Repository navigation
Expand file tree
/
Copy pathexecute_function_graph.rs
More file actions
2702 lines (2459 loc) · 105 KB
/
Copy pathexecute_function_graph.rs
File metadata and controls
2702 lines (2459 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the PostgreSQL License.
//! ExecuteFunctionGraph orchestration - the main durable function executor
//!
//! ⚠️ DETERMINISTIC CODE ONLY in this file!
//! - No I/O except through activities
//! - No random numbers, current time, or other non-deterministic sources
//! - Same input must always produce the same scheduling decisions
use std::collections::HashMap;
use std::str::FromStr;
use std::time::Duration;
use chrono::{DateTime, Utc};
use cron::Schedule as CronSchedule;
use duroxide::OrchestrationContext;
use crate::activities;
use crate::activities::load_function_graph::{TransactionAwareLoadInput, TransactionGraphProbe};
use crate::types::{
evaluate_condition, string_map_to_json, substitute_all_raw, substitute_all_with_options,
FunctionGraph, FunctionInput, FunctionNode, LoopConfig, SqlQuotingVersion, SystemVars,
};
/// Orchestration name for ExecuteFunctionGraph
pub const NAME: &str = "pg_durable::orchestration::execute-function-graph";
/// Orchestration name for ExecuteSubtree (used for parallel JOIN/RACE)
pub const SUBTREE_NAME: &str = "pg_durable::orchestration::execute-subtree";
/// Execution context containing vars and metadata
#[derive(Clone)]
struct ExecutionContext {
vars: HashMap<String, String>,
label: Option<String>,
/// Whether an enclosing loop may consume application failures from this subtree.
failure_isolated: bool,
/// Loop iteration counter (persisted across continue_as_new generations).
loop_iteration: u64,
/// Node id at the root of the *current* orchestration's node tree: `graph.root_node_id`
/// for `execute`, the branch/loop node id for `execute_subtree`. A loop sitting on this
/// node runs inline and drives this orchestration's own `continue_as_new`; any deeper
/// loop is spawned as a child so its `continue_as_new` cannot re-execute an upstream
/// prefix (#227).
subtree_root: String,
/// Shape of the input this orchestration re-enters itself with on loop `continue_as_new`.
continuation: Continuation,
}
/// Which input envelope an inline loop must rebuild when it calls `continue_as_new`.
///
/// Both orchestrations that can host an inline loop re-enter themselves, but they are
/// registered with different input shapes, so the loop node handler picks the right one.
#[derive(Clone, Copy)]
enum Continuation {
/// The root `execute` orchestration, whose input is a `FunctionInput`.
Root,
/// An `execute_subtree` child, whose input is a `SubtreeInput`.
Subtree,
}
/// Input envelope for `execute_subtree`.
///
/// Carries the serialized graph inline. A subtree therefore runs against the same immutable
/// snapshot its parent already validated, and an inline loop re-emits that snapshot across
/// `continue_as_new` — so `df.nodes` is read exactly once per instance and a post-start
/// tamper cannot change the identity a node executes under. Role deletion and privilege
/// revocation are still enforced on every node execution (`execute_sql` connects *as*
/// `submitted_by`; the HTTP activities re-check `EXECUTE` privilege per request).
///
/// `instance_id` is retained alongside the graph so a startup failure can still stamp the
/// subtree root even when the graph itself fails to parse. `iteration` is threaded across
/// `continue_as_new` when the subtree root is a loop.
#[derive(serde::Serialize, serde::Deserialize)]
struct SubtreeInput {
instance_id: String,
node_id: String,
/// Serialized `FunctionGraph` snapshot inherited from the parent.
graph: String,
/// JSON-encoded named-results map inherited from the parent.
results: String,
/// JSON-encoded workflow vars map.
#[serde(default)]
vars: Option<String>,
#[serde(default)]
label: Option<String>,
#[serde(default)]
iteration: u64,
#[serde(default, skip_serializing_if = "is_false")]
failure_isolated: bool,
}
fn is_false(value: &bool) -> bool {
!*value
}
/// Control-flow-aware error type returned by every node handler.
///
/// `Break` is **not** a failure: it unwinds through compound nodes (THEN, IF, JOIN,
/// RACE, and the subtree boundary) via the `?` operator until the nearest enclosing
/// `execute_loop_node` catches it. `Application` is an expected body-activity failure;
/// `Failure` is a graph, protocol, or runtime fault. Encoding these distinctions in the
/// type prevents a broad catch from consuming failures it does not recognize.
#[derive(Debug)]
enum NodeError {
/// A `df.break()` signal carrying its (already-stringified) value, caught by the loop.
Break(String),
/// An expected application failure returned by a workflow activity.
Application(String),
/// A real failure; propagates to the orchestration's `Err` result.
Failure(String),
}
impl NodeError {
fn message(&self) -> &str {
match self {
NodeError::Break(value) | NodeError::Application(value) | NodeError::Failure(value) => {
value
}
}
}
}
/// All helper functions (`substitute_all`, `evaluate_condition`) and activity scheduling
/// return `Result<_, String>`. This conversion lets `?` turn structural/configuration errors
/// into `NodeError::Failure` automatically. Activity failures are mapped explicitly to
/// `NodeError::Application` at their scheduling boundaries.
impl From<String> for NodeError {
fn from(e: String) -> Self {
NodeError::Failure(e)
}
}
/// Mirrors `From<String>` for the many `.ok_or("literal")?` sites that yield `&str` errors,
/// preserving the ergonomics those calls had when handlers returned `Result<_, String>`.
impl From<&str> for NodeError {
fn from(e: &str) -> Self {
NodeError::Failure(e.to_string())
}
}
/// Result type for node handlers: `Ok` value string, or a typed control-flow/failure error.
type NodeResult = Result<String, NodeError>;
const INITIAL_TRANSACTION_POLL_MS: u64 = 100;
const MAX_TRANSACTION_POLL_MS: u64 = 5_000;
const GRAPH_WAIT_POLLS_PER_EXECUTION: u32 = 64;
/// Bound on how many transient `Retry` outcomes (DB errors, query timeouts,
/// snapshot-visibility lag - see `probe_transaction`) a single graph admission
/// will absorb before failing the orchestration outright. Unlike waiting on
/// the caller's own open transaction (`InProgress`, legitimately unbounded),
/// these retries indicate the worker's own machinery is unhealthy, and
/// polling forever would hide a permanent problem behind misleading
/// "waiting on transaction" logs.
const MAX_GRAPH_RETRY_ATTEMPTS: u32 = 20;
/// Bound on how many times a *terminal* `df.instances` status write
/// (`completed`/`failed`) is durably retried before the orchestration gives up.
/// The engine execution is already terminal at these sites, so a dropped write
/// would leave `df.status()` / `df.await_instance()` trusting a stale
/// non-terminal row indefinitely. Retrying across durable timers lets a
/// transient management-plane outage self-heal once the database recovers,
/// while the bound still prevents an unhealthy worker from spinning forever.
const MAX_STATUS_FINALIZE_ATTEMPTS: u32 = 20;
fn transaction_poll_delay(attempt: u32) -> Duration {
let multiplier = 1u64 << attempt.min(6);
Duration::from_millis(
INITIAL_TRANSACTION_POLL_MS
.saturating_mul(multiplier)
.min(MAX_TRANSACTION_POLL_MS),
)
}
fn should_compact_graph_wait(polls_in_execution: u32) -> bool {
polls_in_execution >= GRAPH_WAIT_POLLS_PER_EXECUTION
}
/// Whether the bounded transient-retry budget for graph admission has been
/// exhausted. Pure so the boundary (`== MAX_GRAPH_RETRY_ATTEMPTS` vs `>`) has
/// direct unit coverage.
fn graph_retry_budget_exceeded(retry_attempt: u32) -> bool {
retry_attempt > MAX_GRAPH_RETRY_ATTEMPTS
}
fn graph_wait_continuation(
input: &FunctionInput,
next_wait_attempt: u32,
next_retry_attempt: u32,
) -> Result<String, serde_json::Error> {
let mut continuation = input.clone();
continuation.graph_wait_attempt = next_wait_attempt;
continuation.graph_retry_attempt = next_retry_attempt;
serde_json::to_string(&continuation)
}
async fn load_initial_graph(
ctx: &OrchestrationContext,
input: &FunctionInput,
) -> Result<String, String> {
let Some(origin_xid) = input.origin_xid.as_ref() else {
// Replay compatibility: historical FunctionInput payloads have no xid.
// They must schedule the original activity name with the exact original
// raw instance-id input bytes.
return ctx
.schedule_activity(
activities::load_function_graph::NAME,
input.instance_id.clone(),
)
.await;
};
let probe_input = serde_json::to_string(&TransactionAwareLoadInput {
instance_id: input.instance_id.clone(),
origin_xid: origin_xid.clone(),
})
.map_err(|e| format!("Failed to serialize transaction-aware graph probe: {e}"))?;
let mut wait_attempt = input.graph_wait_attempt;
let mut retry_attempt = input.graph_retry_attempt;
let mut polls_in_execution = 0u32;
loop {
let raw = ctx
.schedule_activity(
activities::load_function_graph::TRANSACTION_AWARE_NAME,
probe_input.clone(),
)
.await?;
let probe: TransactionGraphProbe = serde_json::from_str(&raw)
.map_err(|e| format!("Failed to parse transaction-aware graph probe result: {e}"))?;
match probe {
TransactionGraphProbe::Ready { graph } => return Ok(graph),
TransactionGraphProbe::InProgress => {
let delay = transaction_poll_delay(wait_attempt);
ctx.trace_info(format!(
"Instance {} graph is waiting on origin transaction {}; retrying in {:?}",
input.instance_id, origin_xid, delay
));
ctx.schedule_timer(delay).await;
wait_attempt = wait_attempt.saturating_add(1);
polls_in_execution = polls_in_execution.saturating_add(1);
if should_compact_graph_wait(polls_in_execution) {
let continuation_json =
graph_wait_continuation(input, wait_attempt, retry_attempt).map_err(
|e| format!("Failed to serialize graph-wait continuation: {e}"),
)?;
ctx.trace_info(format!(
"Compacting graph-admission history for instance {} after {} polls",
input.instance_id, polls_in_execution
));
return ctx.continue_as_new(continuation_json).await;
}
}
TransactionGraphProbe::Retry => {
retry_attempt = retry_attempt.saturating_add(1);
if graph_retry_budget_exceeded(retry_attempt) {
return Err(format!(
"Instance {} graph admission for origin transaction {} failed: \
exceeded {MAX_GRAPH_RETRY_ATTEMPTS} transient retries",
input.instance_id, origin_xid
));
}
let delay = transaction_poll_delay(retry_attempt);
ctx.trace_info(format!(
"Instance {} graph admission for origin transaction {} hit a transient \
failure ({}/{MAX_GRAPH_RETRY_ATTEMPTS}); retrying in {:?}",
input.instance_id, origin_xid, retry_attempt, delay
));
ctx.schedule_timer(delay).await;
polls_in_execution = polls_in_execution.saturating_add(1);
if should_compact_graph_wait(polls_in_execution) {
let continuation_json =
graph_wait_continuation(input, wait_attempt, retry_attempt).map_err(
|e| format!("Failed to serialize graph-wait continuation: {e}"),
)?;
ctx.trace_info(format!(
"Compacting graph-admission history for instance {} after {} polls",
input.instance_id, polls_in_execution
));
return ctx.continue_as_new(continuation_json).await;
}
}
TransactionGraphProbe::Aborted => {
return Err(format!(
"Instance {} origin transaction {} aborted before its graph became visible",
input.instance_id, origin_xid
))
}
TransactionGraphProbe::CommittedMissing => {
return Err(format!(
"Instance {} origin transaction {} committed but its instance graph is absent \
(the start may have been rolled back to a savepoint)",
input.instance_id, origin_xid
))
}
}
}
}
/// Distinguishes a normal subtree result from one that unwound via `df.break()`.
///
/// Stored as `Option<SubtreeControl>` in the envelope (see `SubtreeEnvelope::control`): a
/// missing field deserializes to `None`, which unambiguously marks an envelope recorded by a
/// pre-#148 binary (`<= v0.2.2`, no control field). A new binary always writes an explicit
/// `Some(Normal)` / `Some(Break)`, so the legacy break-sentinel fallback can be gated to
/// `None` only — keeping a user payload from impersonating control flow on a fresh envelope.
#[derive(serde::Serialize, serde::Deserialize)]
enum SubtreeControl {
Normal,
Break,
}
#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(
tag = "pg_durable_subtree_failure",
content = "message",
rename_all = "snake_case"
)]
enum SubtreeFailure {
Application(String),
}
fn encode_subtree_application_failure(message: &str) -> String {
serde_json::to_string(&SubtreeFailure::Application(message.to_string()))
.expect("SubtreeFailure serialization cannot fail")
}
fn decode_subtree_application_failure(error: &str) -> Option<String> {
let failure: SubtreeFailure = serde_json::from_str(error).ok()?;
match failure {
SubtreeFailure::Application(message) => Some(message),
}
}
fn classify_subtree_failure(error: String) -> NodeError {
match decode_subtree_application_failure(&error) {
Some(message) => NodeError::Application(message),
None => NodeError::Failure(error),
}
}
fn contextualize_subtree_failure(context: &str, error: String) -> NodeError {
match classify_subtree_failure(error) {
NodeError::Application(message) => NodeError::Application(format!("{context}: {message}")),
NodeError::Failure(message) => NodeError::Failure(format!("{context}: {message}")),
NodeError::Break(_) => unreachable!("subtree failures cannot carry break control flow"),
}
}
fn retain_higher_priority_join_error(
selected: &mut Option<(NodeError, Option<String>)>,
candidate: NodeError,
loop_node_id: Option<String>,
) {
let priority = |error: &NodeError| match error {
NodeError::Application(_) => 0,
NodeError::Break(_) => 1,
NodeError::Failure(_) => 2,
};
let should_replace = selected
.as_ref()
.map(|(current, _)| priority(&candidate) > priority(current))
.unwrap_or(true);
if should_replace {
*selected = Some((candidate, loop_node_id));
}
}
#[derive(Debug, PartialEq, Eq)]
enum FailureIsolatedBodyOutcome {
Succeeded(String),
ApplicationFailed,
Break(String),
}
fn classify_isolated_body_result(
result: Result<String, String>,
results: &mut HashMap<String, String>,
) -> Result<FailureIsolatedBodyOutcome, NodeError> {
match result {
Ok(raw) => match parse_subtree_envelope(&raw, "LOOP iteration", results) {
Ok(body_result) => Ok(FailureIsolatedBodyOutcome::Succeeded(body_result)),
Err(NodeError::Break(value)) => Ok(FailureIsolatedBodyOutcome::Break(value)),
Err(error) => Err(error),
},
Err(error) => match decode_subtree_application_failure(&error) {
Some(_) => Ok(FailureIsolatedBodyOutcome::ApplicationFailed),
None => Err(NodeError::Failure(error)),
},
}
}
/// Envelope returned by `execute_subtree` containing the SQL result and the updated
/// named-results map so the parent orchestration can merge any new entries after join/race.
/// `control` carries a `df.break()` signal back across the sub-orchestration boundary so the
/// parent can re-raise it as `NodeError::Break` rather than smuggling a sentinel in `result`.
#[derive(serde::Serialize, serde::Deserialize)]
struct SubtreeEnvelope {
/// `None` only when deserialized from a pre-#148 envelope that had no `control` field; a
/// new binary always serializes `Some(..)`. `parse_subtree_envelope` relies on this to run
/// the legacy break-sentinel fallback exclusively on old envelopes.
#[serde(default)]
control: Option<SubtreeControl>,
result: String,
#[serde(serialize_with = "crate::types::serialize_string_map")]
results: HashMap<String, String>,
}
/// Durably drive a *terminal* `df.instances` status write to completion.
///
/// The engine execution is already terminal when this is called, so a
/// best-effort write that is silently dropped on a transient database/pool
/// failure would leave `df.status()` / `df.await_instance()` trusting a stale
/// non-terminal (`pending`/`running`) row while the engine is finished — the
/// two status surfaces diverging indefinitely. Retry the update activity across
/// durable timers so a transient management-plane outage self-heals once the
/// database recovers. The retry budget is bounded (`MAX_STATUS_FINALIZE_ATTEMPTS`)
/// so a persistently unhealthy worker cannot spin forever; on exhaustion the
/// divergence is at least surfaced in the trace rather than hidden.
///
/// This is deterministic: activity results and timer fires are recorded in
/// history, so replay follows the same attempt sequence.
async fn finalize_instance_status(ctx: &OrchestrationContext, instance_id: &str, status: &str) {
let status_input = serde_json::json!({
"instance_id": instance_id,
"status": status,
})
.to_string();
let mut attempt = 0u32;
loop {
match ctx
.schedule_activity(
activities::update_instance_status::NAME,
status_input.clone(),
)
.await
{
Ok(_) => return,
Err(e) => {
if attempt >= MAX_STATUS_FINALIZE_ATTEMPTS {
ctx.trace_info(format!(
"Instance {instance_id}: giving up finalizing status to '{status}' after \
{MAX_STATUS_FINALIZE_ATTEMPTS} attempts; df.instances may remain \
non-terminal while the engine execution is terminal: {e}"
));
return;
}
let delay = transaction_poll_delay(attempt);
ctx.trace_info(format!(
"Instance {instance_id}: finalizing status to '{status}' failed \
(attempt {attempt}/{MAX_STATUS_FINALIZE_ATTEMPTS}); retrying in {delay:?}: {e}"
));
ctx.schedule_timer(delay).await;
attempt = attempt.saturating_add(1);
}
}
}
}
/// Execute a complete function graph — the entry point for a durable function.
///
/// # Control flow
/// Internally every node handler returns `NodeResult`, where `NodeError::Break` is
/// **intentional control flow** (a `df.break()` signal), not a failure. Break unwinds
/// through compound nodes via `?` and is caught by the nearest enclosing
/// `execute_loop_node`; `NodeError::Application` distinguishes activity failures that an
/// opted-in loop may consume, while `NodeError::Failure` carries graph, protocol, and runtime
/// faults. This boundary collapses both failure variants back to `Result<String, String>`:
/// a `Break` that reaches here was used outside `df.loop()`, so it is surfaced as a clear
/// failure rather than completing with a control-flow value.
pub async fn execute(ctx: OrchestrationContext, input_json: String) -> Result<String, String> {
let input: FunctionInput = serde_json::from_str(&input_json)
.map_err(|e| format!("Invalid orchestration input: {e}"))?;
let label_info = input
.label
.as_ref()
.map(|l| format!(" ({l})"))
.unwrap_or_default();
ctx.trace_info(format!(
"Starting ExecuteFunctionGraph for instance: {}{}",
input.instance_id, label_info
));
if !input.vars.is_empty() {
// Sort keys for deterministic logging
let mut keys: Vec<_> = input.vars.keys().collect();
keys.sort();
ctx.trace_info(format!("Workflow vars: {keys:?}"));
}
// Generation 0 loads the graph from the database; a root loop continuing as new carries
// it inline, so an instance reads `df.nodes` exactly once however many iterations it runs.
// That load is also the admission check (`submitted_by` resolution plus the superuser
// guard), which belongs at instance start rather than on every iteration — re-reading
// mid-flight would make a post-start tamper of `df.nodes.submitted_by` take effect
// instead of being ignored.
let graph_json = match input.graph.clone() {
Some(json) => json,
None => match load_initial_graph(&ctx, &input).await {
Ok(json) => json,
Err(e) => {
// load_function_graph failed (e.g., superuser blocked).
// Mark the instance as failed before propagating. The engine
// execution is about to end terminally, so this terminal write
// is retried durably rather than dropped — otherwise the row
// would stay non-terminal while the engine is failed.
finalize_instance_status(&ctx, &input.instance_id, "failed").await;
return Err(e);
}
},
};
let graph: FunctionGraph = serde_json::from_str(&graph_json)
.map_err(|e| format!("Failed to parse function graph: {e}"))?;
ctx.trace_info(format!(
"Executing function with {} nodes, root: {}",
graph.nodes.len(),
graph.root_node_id
));
// Mark the instance as running now that we have loaded the graph and are
// about to execute. This call is idempotent: on continue_as_new the
// instance is already 'running', so re-issuing the update is harmless.
let running_input = serde_json::json!({
"instance_id": input.instance_id,
"status": "running"
});
let _ = ctx
.schedule_activity(
activities::update_instance_status::NAME,
running_input.to_string(),
)
.await;
let mut results: HashMap<String, String> = HashMap::new();
// Create execution context with vars
let exec_ctx = ExecutionContext {
vars: input.vars.clone(),
label: input.label.clone(),
failure_isolated: false,
loop_iteration: input.loop_iteration,
subtree_root: graph.root_node_id.clone(),
continuation: Continuation::Root,
};
let function_outcome =
execute_function_node_with_vars(&ctx, &graph, &graph.root_node_id, &mut results, &exec_ctx)
.await;
// Normalize the typed node result into the orchestration's String boundary. A `Break`
// that reaches this point was never caught by a loop, i.e. `df.break()` was used outside
// of `df.loop()` — surface it as a clear, actionable failure rather than completing with a
// control-flow value as the function's result.
let function_result: Result<String, String> = match function_outcome {
Ok(result) => Ok(result),
Err(NodeError::Application(err)) | Err(NodeError::Failure(err)) => Err(err),
Err(NodeError::Break(_)) => Err(
"df.break() was called outside of a loop. df.break() may only be used inside df.loop()."
.to_string(),
),
};
match &function_result {
Ok(result) => {
ctx.trace_info(format!(
"Function completed (result size: {} bytes)",
result.len()
));
finalize_instance_status(&ctx, &input.instance_id, "completed").await;
}
Err(err) => {
ctx.trace_info(format!("Function failed with error: {err}"));
finalize_instance_status(&ctx, &input.instance_id, "failed").await;
}
}
function_result
}
/// Execute a subtree of a function graph rooted at `node_id`.
///
/// Used for JOIN/RACE branches and for any non-root `df.loop()`. Structurally this mirrors
/// `execute`: it roots an `ExecutionContext` at its own node and — when that node is a loop —
/// lets the loop drive `continue_as_new` on *this* orchestration. Because the subtree has no
/// upstream prefix, re-entering from its root lands back on the same loop node each
/// generation, exactly as it does for a root loop in `execute`.
///
/// Unlike `execute`, this never loads the graph (the parent passes it inline) and never
/// touches instance-level status: the parent owns that.
pub async fn execute_subtree(
ctx: OrchestrationContext,
input_json: String,
) -> Result<String, String> {
let input: SubtreeInput = serde_json::from_str(&input_json)
.map_err(|e| format!("Failed to parse ExecuteSubtree input: {e}"))?;
// The subtree root is owned by this child instance, so stamp it failed on any startup
// error. Without this a child that dies before `execute_function_node_with_vars` runs
// would leave its root node stuck in a non-terminal state (the parent does not stamp
// branch roots).
let fail = |ctx: &OrchestrationContext, e: String| {
let stamp = format!("{}::{}", ctx.instance_id(), ctx.execution_id());
let status_input = serialize_node_status_input(
&input.node_id,
&input.instance_id,
"failed",
Some(&e),
&stamp,
);
(status_input, e)
};
ctx.trace_info(format!(
"ExecuteSubtree: executing node {} (iteration {})",
input.node_id, input.iteration
));
// The graph arrives inline from the parent — no database read here. The subtree runs
// against the snapshot the parent already validated, and an inline loop re-emits it on
// `continue_as_new`, so nothing re-reads `df.nodes` mid-flight.
let parsed = serde_json::from_str::<FunctionGraph>(&input.graph)
.map_err(|e| format!("Failed to parse graph in ExecuteSubtree: {e}"))
.and_then(|graph| {
let results: HashMap<String, String> = serde_json::from_str(&input.results)
.map_err(|e| format!("Failed to parse results in ExecuteSubtree: {e}"))?;
let vars: HashMap<String, String> = match input.vars.as_deref() {
Some(vars_json) => serde_json::from_str(vars_json)
.map_err(|e| format!("Failed to parse vars in ExecuteSubtree: {e}"))?,
None => HashMap::new(),
};
Ok((graph, results, vars))
});
let (graph, mut results, vars) = match parsed {
Ok(parsed) => parsed,
Err(e) => {
let (status_input, e) = fail(&ctx, e);
let _ = ctx
.schedule_activity(activities::update_node_status::NAME, status_input)
.await;
return Err(e);
}
};
let exec_ctx = ExecutionContext {
vars,
label: input.label.clone(),
failure_isolated: input.failure_isolated,
loop_iteration: input.iteration,
subtree_root: input.node_id.clone(),
continuation: Continuation::Subtree,
};
// Build the envelope carrying the result, the updated named-results map, and a typed
// control signal. A `Break` inside the subtree is re-encoded as `control: Break` (not a
// sentinel smuggled inside `result`) so the parent can re-raise it as `NodeError::Break`.
// An expected activity failure is encoded as a typed application-failure payload before
// crossing the sub-orchestration boundary. Other failures remain unrecognized strings so
// callers cannot accidentally consume graph, protocol, collision, or runtime faults.
//
// When the root node is a loop that needs another iteration it calls `continue_as_new`,
// whose future never resolves — so none of the arms below run for a continuing
// generation, and no envelope is produced until the loop actually exits.
let envelope = match execute_function_node_with_vars(
&ctx,
&graph,
&input.node_id,
&mut results,
&exec_ctx,
)
.await
{
Ok(result) => {
ctx.trace_info(format!("ExecuteSubtree: node {} completed", input.node_id));
SubtreeEnvelope {
control: Some(SubtreeControl::Normal),
result,
results,
}
}
Err(NodeError::Break(value)) => {
ctx.trace_info(format!(
"ExecuteSubtree: node {} broke (propagating)",
input.node_id
));
SubtreeEnvelope {
control: Some(SubtreeControl::Break),
result: value,
results,
}
}
Err(NodeError::Application(error)) => {
return Err(encode_subtree_application_failure(&error));
}
Err(NodeError::Failure(error)) => return Err(error),
};
serde_json::to_string(&envelope)
.map_err(|e| format!("Failed to serialize subtree envelope: {e}"))
}
/// Build the `execute_subtree` input for a child rooted at `node_id`.
///
/// Shared by JOIN/RACE branch scheduling and by non-root loop spawning — all three are the
/// same operation now: run this node in its own durable instance.
fn build_subtree_input(
graph: &FunctionGraph,
node_id: &str,
results: &HashMap<String, String>,
exec_ctx: &ExecutionContext,
) -> Result<String, String> {
let input = SubtreeInput {
instance_id: graph.instance_id.clone(),
node_id: node_id.to_string(),
graph: serde_json::to_string(graph)
.map_err(|e| format!("Failed to serialize graph: {e}"))?,
results: string_map_to_json(results)
.map_err(|e| format!("Failed to serialize results: {e}"))?,
vars: Some(
string_map_to_json(&exec_ctx.vars)
.map_err(|e| format!("Failed to serialize vars: {e}"))?,
),
label: exec_ctx.label.clone(),
iteration: 0,
failure_isolated: exec_ctx.failure_isolated,
};
serde_json::to_string(&input).map_err(|e| format!("Failed to serialize subtree input: {e}"))
}
/// Compose the deterministic instance id for a JOIN/RACE branch sub-orchestration.
///
/// `schedule_sub_orchestration_with_id` uses this value verbatim (no parent prefix), so we
/// build `{parent_instance_id}::{parent_execution_id}::{child_root_node_id}`. This guarantees
/// a complete parent-to-child lineage and per-generation uniqueness: the parent execution id
/// advances on every loop `continue_as_new`, while the child root node id distinguishes sibling
/// branches. df.instance_nodes() and the write fence walk the full composed lineage.
fn compose_subtree_instance_id(
parent_instance_id: &str,
parent_execution_id: &str,
child_root_node_id: &str,
) -> String {
format!("{parent_instance_id}::{parent_execution_id}::{child_root_node_id}")
}
fn subtree_instance_id(ctx: &OrchestrationContext, child_root_node_id: &str) -> String {
let parent_instance_id = ctx.instance_id();
let parent_execution_id = ctx.execution_id().to_string();
compose_subtree_instance_id(
&parent_instance_id,
&parent_execution_id,
child_root_node_id,
)
}
fn serialize_node_status_input(
node_id: &str,
instance_id: &str,
status: &str,
result: Option<&str>,
execution_id: &str,
) -> String {
// Preserve the recorded field order for byte-for-byte replay compatibility.
// Parent-loop stamps use a different order and must not use this serializer.
#[derive(serde::Serialize)]
struct NodeStatusInput<'a> {
node_id: &'a str,
instance_id: &'a str,
status: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
result: Option<&'a str>,
execution_id: &'a str,
}
serde_json::to_string(&NodeStatusInput {
node_id,
instance_id,
status,
result,
execution_id,
})
.expect("NodeStatusInput serialization cannot fail")
}
/// Recursively execute function nodes with vars support
async fn execute_function_node_with_vars(
ctx: &OrchestrationContext,
graph: &FunctionGraph,
node_id: &str,
results: &mut HashMap<String, String>,
exec_ctx: &ExecutionContext,
) -> NodeResult {
let node = graph
.nodes
.get(node_id)
.ok_or_else(|| format!("Node not found: {node_id}"))?;
ctx.trace_info(format!(
"Executing node {} (type: {})",
node_id, node.node_type
));
// A loop that is NOT the root of the current orchestration's node tree runs as a child
// sub-orchestration, so its `continue_as_new` restarts only the loop body rather than
// re-executing the upstream prefix (#227), and a loop nested in a parallel branch gets
// its own durable instance (#233). The parent does NOT stamp such a loop node
// running/terminal: the child owns the node as its root and stamps it there. Intercept
// here, before any status stamping.
//
// A loop that IS this orchestration's root falls through and runs inline via
// `execute_loop_node`, driving `continue_as_new` on this orchestration. That is safe
// precisely because there is no upstream prefix to re-execute: re-entering from the root
// lands back on this same loop node. This holds identically for the root `execute`
// orchestration and for an `execute_subtree` child rooted at a loop.
if node.node_type.eq_ignore_ascii_case("loop") && node_id != exec_ctx.subtree_root {
return execute_loop_suborchestration(ctx, graph, node, node_id, results, exec_ctx).await;
}
// Stamp identifying which orchestration generation is transitioning this
// node: "{orchestration_instance_id}::{execution_id}". For the root
// orchestration this is "{df_instance_id}::{loop_generation}"; for a JOIN/RACE
// sub-orchestration the instance id already carries the composed lineage (see
// `subtree_instance_id`). df.instance_nodes() and update_node_status walk the
// lineage generations to infer superseded nodes and fence stale writes. Both
// reads are deterministic (instance_id/execution_id are stable within an execution).
let execution_stamp = format!("{}::{}", ctx.instance_id(), ctx.execution_id());
// Mark node as running
let running_input = serialize_node_status_input(
node_id,
&graph.instance_id,
"running",
None,
&execution_stamp,
);
let _ = ctx
.schedule_activity(activities::update_node_status::NAME, running_input)
.await;
let execute_result = execute_node_inner(ctx, graph, node_id, node, results, exec_ctx).await;
// Update node with final status and result. A `Break` is control flow rather than a
// failure: record the node as completed (carrying the break value) so observability is
// unchanged from when break travelled as a normal `Ok` sentinel. Both failure variants
// mark the node failed. All arms schedule exactly one `update_node_status`, so collapse
// them to a single (status, result) pair to keep the recorded history identical.
let (status, status_result) = match &execute_result {
Ok(result) => ("completed", result.as_str()),
Err(NodeError::Break(value)) => ("completed", value.as_str()),
Err(NodeError::Application(err)) | Err(NodeError::Failure(err)) => ("failed", err.as_str()),
};
let status_input = serialize_node_status_input(
node_id,
&graph.instance_id,
status,
Some(status_result),
&execution_stamp,
);
let _ = ctx
.schedule_activity(activities::update_node_status::NAME, status_input)
.await;
execute_result
}
/// Inner function that actually executes the node logic
async fn execute_node_inner(
ctx: &OrchestrationContext,
graph: &FunctionGraph,
node_id: &str,
node: &FunctionNode,
results: &mut HashMap<String, String>,
exec_ctx: &ExecutionContext,
) -> NodeResult {
// Build system vars
let sys_vars = SystemVars {
instance_id: graph.instance_id.clone(),
label: exec_ctx.label.clone(),
};
match node.node_type.to_lowercase().as_str() {
"sql" => {
execute_sql_node(
ctx,
node,
node_id,
results,
exec_ctx,
&sys_vars,
graph.sql_quoting_version,
)
.await
}
"then" => execute_then_node(ctx, graph, node, node_id, results, exec_ctx).await,
"sleep" => execute_sleep_node(ctx, node, node_id).await,
"wait_schedule" => execute_wait_schedule_node(ctx, node, node_id).await,
"loop" => execute_loop_node(ctx, graph, node, node_id, results, exec_ctx).await,
"if" => execute_if_node(ctx, graph, node, node_id, results, exec_ctx).await,
"join" => execute_join_node(ctx, graph, node, node_id, results, exec_ctx).await,
"race" => execute_race_node(ctx, graph, node, node_id, results, exec_ctx).await,
"http" => execute_http_node(ctx, node, node_id, results, exec_ctx, &sys_vars).await,
"http_multipart" => {
execute_http_multipart_node(ctx, node, node_id, results, exec_ctx, &sys_vars).await
}
"signal" => execute_signal_node(ctx, node, node_id, results).await,
"break" => execute_break_node(ctx, node, node_id).await,
other => Err(NodeError::Failure(format!("Unknown node type: {other}"))),
}
}
// ============================================================================
// Node Type Handlers
// ============================================================================
async fn execute_sql_node(
ctx: &OrchestrationContext,
node: &FunctionNode,
node_id: &str,
results: &mut HashMap<String, String>,
exec_ctx: &ExecutionContext,
sys_vars: &SystemVars,
sql_quoting_version: SqlQuotingVersion,
) -> NodeResult {
let query = node
.query
.as_ref()
.ok_or_else(|| format!("SQL node {node_id} has no query"))?;
let final_query = substitute_all_with_options(
query,
results,
&exec_ctx.vars,
sys_vars,
Some(sql_quoting_version),
)?;
// The substituted text is not traced here: the execute_sql activity logs it
// under pg_durable.log_workflow_sql, and an orchestration must not read a
// GUC to decide what to emit.
ctx.trace_info(format!("Executing SQL node {node_id}"));
let input = serde_json::to_string(&activities::execute_sql::ExecuteSqlInput {
query: final_query,
submitted_by: node.submitted_by.clone(),
database: node.database.clone(),
sql_quoting_version,
})
.map_err(|e| format!("Failed to serialize execute_sql input: {e}"))?;
let result = ctx
.schedule_activity(activities::execute_sql::NAME, input)
.await
.map_err(NodeError::Application)?;
if let Some(name) = &node.result_name {
ctx.trace_info(format!("Storing result as ${name}"));
results.insert(name.clone(), result.clone());
}
Ok(result)
}
fn store_named_result(
ctx: &OrchestrationContext,
node: &FunctionNode,
result: &str,
results: &mut HashMap<String, String>,
node_label: &str,
) {
if let Some(name) = &node.result_name {
ctx.trace_info(format!("Storing {node_label} result as ${name}"));
results.insert(name.clone(), result.to_string());
}
}
async fn execute_then_node(
ctx: &OrchestrationContext,
graph: &FunctionGraph,
node: &FunctionNode,
node_id: &str,
results: &mut HashMap<String, String>,
exec_ctx: &ExecutionContext,
) -> NodeResult {
let left_id = node
.left_node
.as_ref()
.ok_or_else(|| format!("THEN node {node_id} has no left_node"))?;
let right_id = node
.right_node
.as_ref()
.ok_or_else(|| format!("THEN node {node_id} has no right_node"))?;
// A `df.break()` anywhere in the left branch propagates automatically via `?` to the
// enclosing loop, skipping the right branch — no explicit sentinel check needed.