-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathexecute_function_graph.rs
More file actions
1936 lines (1757 loc) · 75.9 KB
/
Copy pathexecute_function_graph.rs
File metadata and controls
1936 lines (1757 loc) · 75.9 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::types::{
evaluate_condition, string_map_to_json, substitute_all, substitute_all_raw, FunctionGraph,
FunctionInput, FunctionNode, 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>,
/// 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,
}
/// 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. `Failure` is a genuine error that propagates to the
/// orchestration result. Encoding break this way means forgetting to propagate it is a
/// compile error rather than a silently-ignored value (see issue #148 / #132).
#[derive(Debug)]
enum NodeError {
/// A `df.break()` signal carrying its (already-stringified) value, caught by the loop.
Break(String),
/// A real failure; propagates to the orchestration's `Err` result.
Failure(String),
}
/// All helper functions (`substitute_all`, `evaluate_condition`) and activity scheduling
/// return `Result<_, String>`. This conversion lets `?` turn those `String` errors into
/// `NodeError::Failure` automatically, so only genuine control flow needs explicit handling.
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>;
/// 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,
}
/// 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>,
}
/// 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`; only `NodeError::Failure` represents a genuine error. This
/// boundary collapses the typed result 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. Callers should treat the returned
/// `Err` strictly as a failure and must not add retry/recovery logic for break.
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 ctx
.schedule_activity(
activities::load_function_graph::NAME,
input.instance_id.clone(),
)
.await
{
Ok(json) => json,
Err(e) => {
// load_function_graph failed (e.g., superuser blocked).
// Mark the instance as failed before propagating.
let status_input = serde_json::json!({
"instance_id": input.instance_id,
"status": "failed"
});
let _ = ctx
.schedule_activity(
activities::update_instance_status::NAME,
status_input.to_string(),
)
.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(),
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::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 with result: {result}"));
let status_input = serde_json::json!({
"instance_id": input.instance_id,
"status": "completed"
});
let _ = ctx
.schedule_activity(
activities::update_instance_status::NAME,
status_input.to_string(),
)
.await;
}
Err(err) => {
ctx.trace_info(format!("Function failed with error: {err}"));
let status_input = serde_json::json!({
"instance_id": input.instance_id,
"status": "failed"
});
let _ = ctx
.schedule_activity(
activities::update_instance_status::NAME,
status_input.to_string(),
)
.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 = serde_json::json!({
"node_id": input.node_id,
"instance_id": input.instance_id,
"status": "failed",
"result": e,
"execution_id": stamp,
});
(status_input.to_string(), 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(),
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`.
// A genuine `Failure` propagates as `Err` across the sub-orchestration boundary.
//
// 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::Failure(e)) => return Err(e),
};
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,
};
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 subtree_instance_id(ctx: &OrchestrationContext, child_root_node_id: &str) -> String {
format!(
"{}::{}::{}",
ctx.instance_id(),
ctx.execution_id(),
child_root_node_id
)
}
/// 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 = serde_json::json!({
"node_id": node_id,
"instance_id": graph.instance_id,
"status": "running",
"execution_id": execution_stamp,
});
let _ = ctx
.schedule_activity(
activities::update_node_status::NAME,
running_input.to_string(),
)
.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. Only `Failure` marks
// the node failed. All three 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::Failure(err)) => ("failed", err.as_str()),
};
let status_input = serde_json::json!({
"node_id": node_id,
"instance_id": graph.instance_id,
"status": status,
"result": status_result,
"execution_id": execution_stamp,
});
let _ = ctx
.schedule_activity(
activities::update_node_status::NAME,
status_input.to_string(),
)
.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).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,
) -> NodeResult {
let query = node
.query
.as_ref()
.ok_or_else(|| format!("SQL node {node_id} has no query"))?;
let final_query = substitute_all(query, results, &exec_ctx.vars, sys_vars)?;
ctx.trace_info(format!("Executing SQL: {final_query}"));
let input = serde_json::json!({
"query": final_query,
"submitted_by": node.submitted_by,
"database": node.database,
});
let result = ctx
.schedule_activity(activities::execute_sql::NAME, input.to_string())
.await?;
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.
Box::pin(execute_function_node_with_vars(
ctx, graph, left_id, results, exec_ctx,
))
.await?;
let right_result = Box::pin(execute_function_node_with_vars(
ctx, graph, right_id, results, exec_ctx,
))
.await?;
store_named_result(ctx, node, &right_result, results, "THEN");
Ok(right_result)
}
async fn execute_sleep_node(
ctx: &OrchestrationContext,
node: &FunctionNode,
node_id: &str,
) -> NodeResult {
let seconds_str = node
.query
.as_ref()
.ok_or_else(|| format!("SLEEP node {node_id} has no duration"))?;
let seconds: u64 = seconds_str
.parse()
.map_err(|_| format!("Invalid sleep duration: {seconds_str}"))?;
ctx.trace_info(format!("Sleeping for {seconds} seconds"));
ctx.schedule_timer(Duration::from_secs(seconds)).await;
Ok(format!(r#"{{"slept": true, "seconds": {seconds}}}"#))
}
async fn execute_wait_schedule_node(
ctx: &OrchestrationContext,
node: &FunctionNode,
node_id: &str,
) -> NodeResult {
let config_str = node
.query
.as_ref()
.ok_or_else(|| format!("WAIT_SCHEDULE node {node_id} has no config"))?;
let config: serde_json::Value = serde_json::from_str(config_str)
.map_err(|e| format!("Invalid WAIT_SCHEDULE config: {e}"))?;
let cron_expr = config["cron_expr"]
.as_str()
.ok_or_else(|| "WAIT_SCHEDULE missing cron_expr".to_string())?;
// A cron schedule is a function of "now", so the next tick MUST be computed
// when this node actually executes — not at df.start() time — so that any
// delay before execution, and every iteration of a recurring `@>` loop,
// targets the correct upcoming tick.
//
// `ctx.utc_now()` is duroxide's deterministic clock (the only sanctioned way
// to read wall-clock time in this deterministic file): the value is recorded
// in history and replayed verbatim. The cron math below is pure given `now`,
// so the whole computation is replay-safe. The "0 " prefix supplies the
// seconds field the `cron` crate expects (mirrors df.wait_for_schedule()).
let now: DateTime<Utc> = ctx
.utc_now()
.await
.map_err(|e| format!("WAIT_SCHEDULE failed to read deterministic clock: {e}"))?
.into();
let cron_with_seconds = format!("0 {cron_expr}");
let schedule = CronSchedule::from_str(&cron_with_seconds)
.map_err(|e| format!("Invalid cron expression '{cron_expr}': {e}"))?;
let next = schedule
.after(&now)
.next()
.ok_or_else(|| format!("No upcoming schedule found for '{cron_expr}'"))?;
// Clamp to zero if the tick is already in the past by the time we get here.
//
// NOTE: once duroxide gains an absolute-deadline timer
// (https://github.com/microsoft/duroxide/issues/34), this `now`-read +
// subtraction can be replaced with `ctx.schedule_timer_until(next)`, which
// targets the absolute tick directly and drops the extra utc_now() syscall.
let wait = (next - now).to_std().unwrap_or(Duration::ZERO);
ctx.trace_info(format!(
"Waiting {}s until next schedule tick {next} (cron: {cron_expr})",
wait.as_secs()
));
ctx.schedule_timer(wait).await;
Ok(r#"{"scheduled": true}"#.to_string())
}
/// Minimum wall-clock duration that every loop iteration must take before
/// `continue_as_new` is called. If the body (plus any while-condition
/// evaluation) completes faster than this, a compensating timer makes up the
/// deficit so an empty-bodied loop can't busy-spin via continue_as_new.
const LOOP_MIN_ITER_DURATION: Duration = Duration::from_secs(1);
/// Maximum loop iterations before the orchestration is forcibly terminated.
/// This prevents runaway infinite loops from consuming resources indefinitely.
/// At the minimum 1-second rate limit, this allows ~27 hours of looping.
const MAX_LOOP_ITERATIONS: u64 = 100_000;
/// Stamp a loop node's status from its *parent* orchestration.
///
/// A non-root loop node is the root of its own child instance, so the child normally owns
/// its status transitions (via `execute_function_node_with_vars`). This helper covers the
/// cases where the child never got far enough to stamp itself — spawn failure, a failed
/// branch future, or a losing RACE branch — and the parent must record a terminal state so
/// the node does not linger as running.
async fn stamp_loop_node(
ctx: &OrchestrationContext,
instance_id: &str,
loop_node_id: &str,
status: &str,
result: Option<&str>,
stamp: &str,
) {
let mut input = serde_json::json!({
"node_id": loop_node_id,
"instance_id": instance_id,
"status": status,
"execution_id": stamp,
});
if let Some(r) = result {
input["result"] = serde_json::Value::String(r.to_string());
}
let _ = ctx
.schedule_activity(activities::update_node_status::NAME, input.to_string())
.await;
}
async fn fail_loop_before_start(
ctx: &OrchestrationContext,
graph: &FunctionGraph,
loop_node_id: &str,
error: String,
) -> NodeResult {
let execution_stamp = format!("{}::{}", ctx.instance_id(), ctx.execution_id());
stamp_loop_node(
ctx,
&graph.instance_id,
loop_node_id,
"failed",
Some(&error),
&execution_stamp,
)
.await;
Err(NodeError::Failure(error))
}
async fn fail_loop_child_future(
ctx: &OrchestrationContext,
graph: &FunctionGraph,
loop_node_id: &str,
error: String,
) -> NodeResult {
let child_stamp = format!("{}::1", subtree_instance_id(ctx, loop_node_id));
stamp_loop_node(
ctx,
&graph.instance_id,
loop_node_id,
"failed",
Some(&error),
&child_stamp,
)
.await;
Err(NodeError::Failure(error))
}
/// Run one iteration of a loop body (and its optional while-condition).
///
/// Shared by both inline loop paths: a loop at the root of the root orchestration and a
/// loop at the root of an `execute_subtree` child.
///
/// Returns `Ok(Some(final_result))` when the loop should exit (a `df.break()` in the body,
/// or the while-condition evaluating false), `Ok(None)` when another iteration is needed,
/// and `Err` when the body or condition fails.
async fn run_loop_iteration(
ctx: &OrchestrationContext,
graph: &FunctionGraph,
node: &FunctionNode,
loop_node_id: &str,
body_id: &str,
results: &mut HashMap<String, String>,
exec_ctx: &ExecutionContext,
) -> Result<Option<String>, String> {
// The loop is where `NodeError::Break` is caught: a break unwinds through the body via
// `?` and is converted here into the loop's normal exit value. A `Failure` propagates
// out of the sub-orchestration unchanged.
let body_result =
match execute_function_node_with_vars(ctx, graph, body_id, results, exec_ctx).await {
Ok(v) => v,
Err(NodeError::Break(break_value)) => {
ctx.trace_info(format!(
"Loop terminated by break with value: {break_value}"
));
store_named_result(ctx, node, &break_value, results, "LOOP");
return Ok(Some(break_value));
}
Err(NodeError::Failure(e)) => return Err(e),
};
// While-condition: if present and false, exit the loop.
if let Some(ref config_str) = node.query {
let config: serde_json::Value = serde_json::from_str(config_str).map_err(|e| {
// M8: Malformed condition config should fail the loop rather than
// silently creating an infinite loop without exit condition.
format!("LOOP node {loop_node_id}: failed to parse condition config: {e}")
})?;
if let Some(condition_node_id) = config["condition_node"].as_str() {
ctx.trace_info("Evaluating loop condition");
let condition_result = match execute_function_node_with_vars(
ctx,
graph,
condition_node_id,
results,
exec_ctx,
)
.await
{
Ok(v) => v,
Err(NodeError::Break(break_value)) => {
store_named_result(ctx, node, &break_value, results, "LOOP");
return Ok(Some(break_value));
}
Err(NodeError::Failure(e)) => return Err(e),
};
// Parse condition result to check truthiness (uses evaluate_condition to extract boolean from SQL result)
let should_continue = evaluate_condition(&condition_result).unwrap_or(false);
ctx.trace_info(format!(
"Loop condition evaluated to: {condition_result} (continue={should_continue})"
));
if !should_continue {
ctx.trace_info("Loop condition false, exiting loop");
store_named_result(ctx, node, &body_result, results, "LOOP");
return Ok(Some(body_result));
}
}
}
Ok(None)
}
/// Execute a loop node inline, driving the *current* orchestration's `continue_as_new`.
///
/// Only a loop sitting at `exec_ctx.subtree_root` reaches this function; a deeper loop is
/// intercepted in `execute_function_node_with_vars` and delegated to a child. Running the
/// root loop inline is safe because there is no upstream prefix to re-execute: re-entering
/// this orchestration from its root lands back on this same loop node each generation.
///
/// Both hosts are handled: the root `execute` orchestration and an `execute_subtree` child
/// rooted at the loop node. They differ only in the input envelope they re-enter with, which
/// `exec_ctx.continuation` selects.
///
/// Note that `ctx.continue_as_new()` returns a future that never resolves, so on a
/// continuing generation this function does not return and the caller's terminal node
/// stamping never runs — the loop node stays `running` until it actually exits.
async fn execute_loop_node(
ctx: &OrchestrationContext,
graph: &FunctionGraph,
node: &FunctionNode,
node_id: &str,
results: &mut HashMap<String, String>,
exec_ctx: &ExecutionContext,
) -> NodeResult {
debug_assert_eq!(
node_id, exec_ctx.subtree_root,
"inline loop must be the current orchestration's root"
);
let body_id = node
.left_node
.as_ref()
.ok_or_else(|| format!("LOOP node {node_id} has no body"))?;
// Capture the iteration start time so we can rate-limit `continue_as_new`
// below. `utc_now()` is duroxide's deterministic clock (recorded in
// history and replayed verbatim), so this remains replay-safe.
let iter_started = ctx.utc_now().await.ok();
ctx.trace_info("Executing loop iteration");
if let Some(final_result) = Box::pin(run_loop_iteration(
ctx, graph, node, node_id, body_id, results, exec_ctx,
))
.await
.map_err(NodeError::Failure)?
{
return Ok(final_result);
}
ctx.trace_info("Continuing as new for next loop iteration");
// M7: Enforce maximum iteration count to prevent runaway infinite loops
let next_iteration = exec_ctx.loop_iteration + 1;
if next_iteration >= MAX_LOOP_ITERATIONS {
return Err(NodeError::Failure(format!(
"Loop exceeded maximum iteration count of {MAX_LOOP_ITERATIONS}. \
Use df.break() to exit the loop or restructure the workflow."
)));
}
// Enforce a minimum per-iteration wall-clock duration to prevent
// busy-looping (e.g. `df.loop(df.sleep(0))`). Compute the elapsed time
// from the deterministic clock; if the iteration finished faster than
// LOOP_MIN_ITER_DURATION, schedule a timer for the deficit so the next
// continue_as_new is gated by at least that much real-clock time.
if let Some(started) = iter_started {
if let Ok(now) = ctx.utc_now().await {
let elapsed = now.duration_since(started).unwrap_or(Duration::ZERO);
if elapsed < LOOP_MIN_ITER_DURATION {
let deficit = LOOP_MIN_ITER_DURATION - elapsed;
ctx.trace_info(format!(
"Loop iteration took {elapsed:?} (< {LOOP_MIN_ITER_DURATION:?}); \
adding {deficit:?} rate-limit delay"
));
ctx.schedule_timer(deficit).await;
}
}
}
// Rebuild this orchestration's own input for the next generation. The root
// orchestration re-enters with a `FunctionInput` (named results are rebuilt from
// scratch, as they always have been); an `execute_subtree` child re-enters with a
// `SubtreeInput` that threads the accumulated named results forward.
// Rebuild this orchestration's own input for the next generation. The root
// orchestration re-enters with a `FunctionInput` (named results are rebuilt from
// scratch, as they always have been); an `execute_subtree` child re-enters with a
// `SubtreeInput` that threads the accumulated named results forward. Both carry the
// graph snapshot forward so no generation re-reads `df.nodes`.
let graph_json =
serde_json::to_string(graph).map_err(|e| format!("Failed to serialize graph: {e}"))?;
let new_input_json = match exec_ctx.continuation {
Continuation::Root => {
let new_input = FunctionInput {
instance_id: graph.instance_id.clone(),
label: exec_ctx.label.clone(),
vars: exec_ctx.vars.clone(),
loop_iteration: next_iteration,
graph: Some(graph_json),
};
serde_json::to_string(&new_input)
.map_err(|e| format!("Failed to serialize loop input: {e}"))?
}
Continuation::Subtree => {
let new_input = SubtreeInput {