Skip to main content

adk_graph/
executor.rs

1//! Pregel-based execution engine for graphs
2//!
3//! Executes graphs using the Pregel model with super-steps.
4
5#[cfg(feature = "node-cache")]
6use crate::cache::compute_cache_key;
7use crate::checkpoint::Durability;
8use crate::deferred::{FAN_IN_METADATA_KEY, FanInSnapshot, FanInTracker};
9use crate::error::{GraphError, InterruptedExecution, Result};
10use crate::governed::{GovernedDispatch, GovernedRun};
11use crate::graph::{CompiledGraph, Route};
12use crate::interrupt::{GraphToolConfirmationPause, Interrupt};
13use crate::node::{ExecutionConfig, Node, NodeContext};
14use crate::record::{
15    LINEAGE_METADATA_KEY, Lineage, NodeRecord, NodeStatus, OPEN_PAUSES_METADATA_KEY,
16    RUN_METADATA_KEY, RunRecord, STEPS_METADATA_KEY, StepKind, StepRecord, now as record_now,
17};
18use crate::state::{Checkpoint, PendingWrite, State};
19use crate::stream::{StreamEvent, StreamMode};
20use crate::timeout::{OnTimeout, ProgressHandle, execute_with_timeout, item_timeout_budget};
21use futures::stream::{self, StreamExt};
22use std::collections::{BTreeMap, BTreeSet, HashMap};
23use std::sync::Arc;
24use std::time::Instant;
25
26/// Result of a super-step execution
27#[derive(Default)]
28pub struct SuperStepResult {
29    /// Nodes that were executed
30    pub executed_nodes: Vec<String>,
31    /// Every pause of the step with the node it stopped, in node-name order.
32    /// Empty when nothing paused.
33    pub interrupts: Vec<(String, Interrupt)>,
34    /// Stream events generated
35    pub events: Vec<StreamEvent>,
36    /// Nodes that named their own successors, keyed by node name.
37    pub goto: HashMap<String, Vec<String>>,
38    /// Each executed node's own updates, keyed by node name.
39    ///
40    /// A fan-in node records these as the arrival of the predecessor that wrote
41    /// them, so an arrival never embeds the whole state.
42    pub updates: HashMap<String, HashMap<String, serde_json::Value>>,
43}
44
45/// What a completed run produced, and what it asks of its caller.
46#[derive(Debug, Clone)]
47pub struct GraphOutcome {
48    /// The final state.
49    pub state: State,
50    /// Nodes of the parent graph a node asked to run next, if any.
51    ///
52    /// Set by [`NodeOutput::with_goto_parent`](crate::node::NodeOutput::with_goto_parent).
53    /// A graph that is not a subgraph has no parent, so this is ignored.
54    pub goto_parent: Option<Vec<String>>,
55}
56
57/// Pregel-based executor for graphs
58pub struct PregelExecutor<'a> {
59    graph: &'a CompiledGraph,
60    config: ExecutionConfig,
61    /// ADK configuration supplied through an additive direct-graph API.
62    run_config: Option<adk_core::RunConfig>,
63    state: State,
64    step: usize,
65    pending_nodes: Vec<String>,
66    /// Parent nodes a node asked to run next; see `NodeOutput::with_goto_parent`.
67    goto_parent: Option<Vec<String>>,
68    /// Tracks deferred nodes waiting for all upstream paths to complete.
69    pending_deferred: HashMap<String, FanInTracker>,
70    /// Tracks when each deferred node first entered the pending state (for fan-in timeout).
71    deferred_start_times: HashMap<String, Instant>,
72    /// Predecessors a `fan_in_timeout` released a node without, keyed by node. Their
73    /// next arrival is ignored, so the node does not run again for an abandoned branch.
74    abandoned_arrivals: HashMap<String, std::collections::HashSet<String>>,
75    /// Attempts already spent per node, carried through a resume so a retry
76    /// budget is not restarted.
77    attempts: HashMap<String, u32>,
78    /// Outputs of children invoked imperatively, keyed by child path. Shared with
79    /// every node's invoker so a resumed parent serves finished children from it.
80    child_ledger: Arc<std::sync::Mutex<HashMap<String, serde_json::Value>>>,
81    /// The node whose static interrupt this run has already answered.
82    ///
83    /// Restored from the checkpoint on resume and cleared once that node has
84    /// executed, so the gate re-arms for a later arrival through a cycle.
85    cleared_interrupt: Option<String>,
86    /// Whether a thread whose last run finished starts again from its entry
87    /// nodes instead of returning the finished state.
88    restart_completed: bool,
89    /// The step this run started at; the recursion limit counts from here.
90    run_start_step: usize,
91    /// The highest checkpoint version this run knows of for its thread; its next
92    /// checkpoint is one higher.
93    head_version: u64,
94    /// The thread's checkpoints where a run paused and no run has resumed, which every
95    /// checkpoint this run writes lists (`OPEN_PAUSES_METADATA_KEY`).
96    open_pauses: BTreeSet<String>,
97    /// Writes of the nodes that finished in a super-step that has not completed.
98    pending_writes: BTreeMap<String, PendingWrite>,
99    /// A checkpoint being written in the background under `Durability::Async`.
100    inflight: Option<tokio::task::JoinHandle<Result<String>>>,
101    /// Whether a completed super-step has not been checkpointed yet.
102    unsaved: bool,
103    /// Nodes that paused with a dynamic interrupt and have not run since.
104    ///
105    /// Restored from the checkpoint on resume, so the step that resumes them
106    /// hands each its answer from `ExecutionConfig::resume_values`.
107    paused_nodes: BTreeSet<String>,
108    /// The id and answer schema of each paused node's pause, restored from the checkpoint
109    /// on resume, so an answer binds to the pause it was given for.
110    pending_interrupts: BTreeMap<String, PendingInterrupt>,
111    /// The run the next checkpoint belongs to; opened when the run starts from its
112    /// entry nodes and restored on resume.
113    run: Option<RunRecord>,
114    /// Where this thread was forked from, if it was.
115    lineage: Option<Lineage>,
116    /// Steps finished since the last checkpoint was written.
117    unsaved_steps: Vec<StepRecord>,
118    /// Completed runs of each governed node in this thread's lineage.
119    occurrences: BTreeMap<String, u32>,
120    /// The request each governed node paused with, while it waits for a decision.
121    held: BTreeMap<String, adk_core::ToolConfirmationRequest>,
122    /// The id the next checkpoint is written under, known in advance so a governed
123    /// node's effect-log entry can name the checkpoint that records its step.
124    next_checkpoint_id: String,
125    /// How far step labels run ahead of `step`, after a pause at an `interrupt_after` gate.
126    label_offset: usize,
127}
128
129/// Checkpoint metadata naming the nodes a dynamic pause stopped.
130pub(crate) const PAUSED_NODES_METADATA_KEY: &str = "adk.graph.paused_nodes";
131/// Checkpoint metadata holding the id and answer schema of each paused node's pause.
132const PENDING_INTERRUPTS_METADATA_KEY: &str = "adk.graph.pending_interrupts";
133
134/// A dynamic pause waiting for its answer.
135#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
136#[serde(rename_all = "camelCase")]
137struct PendingInterrupt {
138    /// The pause's id ([`Interrupt::id`]).
139    id: String,
140    /// The JSON Schema its answer must satisfy.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    response_schema: Option<serde_json::Value>,
143}
144/// Checkpoint metadata counting each governed node's completed runs in the lineage.
145pub(crate) const OCCURRENCES_METADATA_KEY: &str = "adk.graph.occurrences";
146/// Checkpoint metadata holding the request each waiting governed node paused with.
147const HELD_METADATA_KEY: &str = "adk.graph.held";
148/// Every metadata key a checkpoint's revision by `update_state` carries over.
149const CARRIED_METADATA_KEYS: [&str; 8] = [
150    FAN_IN_METADATA_KEY,
151    PAUSED_NODES_METADATA_KEY,
152    PENDING_INTERRUPTS_METADATA_KEY,
153    RUN_METADATA_KEY,
154    STEPS_METADATA_KEY,
155    LINEAGE_METADATA_KEY,
156    OCCURRENCES_METADATA_KEY,
157    HELD_METADATA_KEY,
158];
159
160/// One node's dispatch within a super-step, as its future reports it.
161struct NodeRun {
162    name: String,
163    /// `None` when the node did not start, because the step had already failed.
164    output: Option<Result<crate::node::NodeOutput>>,
165    started_at: chrono::DateTime<chrono::Utc>,
166    duration_ms: u64,
167    step: usize,
168    attempts: u32,
169    /// The governed bracket's outcome, for a governed node.
170    governed: Option<GovernedRun>,
171}
172
173impl<'a> PregelExecutor<'a> {
174    /// Create a new executor
175    pub fn new(graph: &'a CompiledGraph, config: ExecutionConfig) -> Self {
176        Self::new_with_run_config(graph, config, None)
177    }
178
179    pub(crate) fn new_with_run_config(
180        graph: &'a CompiledGraph,
181        config: ExecutionConfig,
182        run_config: Option<adk_core::RunConfig>,
183    ) -> Self {
184        Self {
185            graph,
186            config,
187            run_config,
188            state: State::new(),
189            step: 0,
190            pending_nodes: vec![],
191            goto_parent: None,
192            pending_deferred: HashMap::new(),
193            deferred_start_times: HashMap::new(),
194            abandoned_arrivals: HashMap::new(),
195            attempts: HashMap::new(),
196            child_ledger: Arc::new(std::sync::Mutex::new(HashMap::new())),
197            cleared_interrupt: None,
198            restart_completed: false,
199            run_start_step: 0,
200            head_version: 0,
201            open_pauses: BTreeSet::new(),
202            pending_writes: BTreeMap::new(),
203            inflight: None,
204            unsaved: false,
205            paused_nodes: BTreeSet::new(),
206            pending_interrupts: BTreeMap::new(),
207            run: None,
208            lineage: None,
209            unsaved_steps: Vec::new(),
210            occurrences: BTreeMap::new(),
211            held: BTreeMap::new(),
212            next_checkpoint_id: uuid::Uuid::new_v4().to_string(),
213            label_offset: 0,
214        }
215    }
216
217    /// Starts a thread whose last run finished again from its entry nodes.
218    ///
219    /// Used by [`GraphAgent`](crate::agent::GraphAgent), where every call is a
220    /// new turn on the session's thread. The finished state carries over and the
221    /// new input is merged on top; a paused thread still resumes where it paused.
222    pub(crate) fn restarting_completed_threads(mut self) -> Self {
223        self.restart_completed = true;
224        self
225    }
226
227    /// Attempt to resume from an existing checkpoint.
228    ///
229    /// If a checkpoint is found (either by explicit `resume_from` ID or by latest
230    /// checkpoint for the thread), restores state, pending_nodes, and step from it,
231    /// then merges the provided input on top. Returns `true` if resumed.
232    ///
233    /// If no checkpoint is found, returns `false` so the caller can proceed with
234    /// fresh-start logic.
235    async fn try_resume_from_checkpoint(&mut self, input: &State) -> Result<bool> {
236        let checkpoint = if let Some(checkpoint_id) = &self.config.resume_from {
237            // Resume from a specific checkpoint by ID
238            if let Some(cp) = self.graph.checkpointer.as_ref() {
239                // Refused before any node runs: starting over instead would run again
240                // the nodes the caller meant to resume after.
241                let Some(checkpoint) = cp.load_by_id(checkpoint_id).await? else {
242                    return Err(GraphError::CheckpointError(format!(
243                        "cannot resume thread '{}' from checkpoint '{checkpoint_id}': no \
244                         checkpoint with that ID is stored. Retention removes a pause's \
245                         checkpoint once a run has resumed it, and deleting the thread removes \
246                         them all; resume from an ID `Checkpointer::list` returns",
247                        self.config.thread_id
248                    )));
249                };
250                Some(checkpoint)
251            } else {
252                None
253            }
254        } else if let Some(cp) = self.graph.checkpointer.as_ref() {
255            // Try to load the latest checkpoint for this thread
256            cp.load(&self.config.thread_id).await?
257        } else {
258            None
259        };
260
261        if let Some(checkpoint) = checkpoint {
262            // The lineage and each governed node's count belong to the thread, so a new
263            // turn on a finished thread keeps them; the run and its waiting requests do not.
264            self.lineage = checkpoint.lineage()?;
265            self.occurrences =
266                read_metadata(&checkpoint, OCCURRENCES_METADATA_KEY)?.unwrap_or_default();
267            let run = checkpoint.run_record()?;
268            let held = read_metadata(&checkpoint, HELD_METADATA_KEY)?.unwrap_or_default();
269            self.label_offset = checkpoint.label_offset();
270            // A fork from an earlier checkpoint continues after the thread's newest.
271            self.head_version = checkpoint.version;
272            let mut open_pauses = checkpoint.open_pauses()?;
273            if self.config.resume_from.is_some()
274                && let Some(cp) = self.graph.checkpointer.as_ref()
275                && let Some(newest) = cp.load(&checkpoint.thread_id).await?
276            {
277                self.head_version = self.head_version.max(newest.version);
278                // The newest lists every open pause, those of other branches included.
279                open_pauses = newest.open_pauses()?;
280            }
281            // Resuming a pause answers it; the thread's other open pauses stay listed.
282            open_pauses.retain(|id| *id != checkpoint.checkpoint_id);
283            self.open_pauses = open_pauses.into_iter().collect();
284            let finished = checkpoint.pending_nodes.is_empty();
285            self.state = checkpoint.state;
286            self.step = checkpoint.step;
287
288            if finished && self.restart_completed && self.config.resume_from.is_none() {
289                // A new turn on a finished thread. The retry budget, child ledger,
290                // gate marker, and fan-in arrivals belonged to the finished run,
291                // so none of them carry over; only the state does.
292                self.pending_nodes = self.entry_frontier()?;
293                self.run_start_step = checkpoint.step;
294            } else {
295                self.pending_nodes = checkpoint.pending_nodes;
296                self.cleared_interrupt = checkpoint.cleared_interrupt;
297                self.attempts = checkpoint.attempts;
298                *self.child_ledger.lock().expect("child ledger") = checkpoint.child_ledger;
299                self.pending_writes = checkpoint.pending_writes;
300                if let Some(snapshot) = FanInSnapshot::from_metadata(&checkpoint.metadata)? {
301                    let restored = snapshot.restore(|node| self.graph.get_upstream_nodes(node));
302                    self.pending_deferred = restored.trackers;
303                    self.deferred_start_times = restored.started;
304                    self.abandoned_arrivals = restored.abandoned;
305                }
306                if let Some(paused) = checkpoint.metadata.get(PAUSED_NODES_METADATA_KEY) {
307                    self.paused_nodes = serde_json::from_value(paused.clone())?;
308                }
309                if let Some(pending) = checkpoint.metadata.get(PENDING_INTERRUPTS_METADATA_KEY) {
310                    self.pending_interrupts = serde_json::from_value(pending.clone())?;
311                }
312                // A paused, failed or interrupted run continues; a checkpoint without a
313                // run, such as a fork's first, opens one.
314                self.run = run;
315                self.held = held;
316            }
317
318            // Merge input on top of restored state
319            for (key, value) in input {
320                self.graph.schema.apply_update(&mut self.state, key, value.clone());
321            }
322
323            Ok(true)
324        } else {
325            Ok(false)
326        }
327    }
328
329    /// Run the graph to completion
330    pub async fn run(&mut self, input: State) -> Result<State> {
331        self.graph.check_governed_nodes()?;
332        // Check for existing checkpoint to resume from
333        let resumed = self.try_resume_from_checkpoint(&input).await?;
334        self.check_resume_answers()?;
335
336        if !resumed {
337            // No checkpoint found — fresh start
338            self.state = self.initialize_state(input).await?;
339            self.pending_nodes = self.entry_frontier()?;
340        }
341        self.open_run();
342
343        // Main execution loop
344        while !self.pending_nodes.is_empty() {
345            // Check recursion limit
346            let steps_taken = self.step.saturating_sub(self.run_start_step);
347            if steps_taken >= self.recursion_limit() {
348                return Err(GraphError::RecursionLimitExceeded(steps_taken));
349            }
350
351            self.flush_before_side_effects().await?;
352
353            // Execute super-step
354            let mut result = match self.execute_super_step().await {
355                Ok(result) => result,
356                Err(error) => {
357                    self.checkpoint_failed_step().await;
358                    return Err(error);
359                }
360            };
361
362            // Handle interrupts
363            if !result.interrupts.is_empty() {
364                self.pause_frontier(&mut result)?;
365                let interrupt = result.interrupts[0].1.clone();
366                let checkpoint_id = self.save_pause_checkpoint().await?;
367                return Err(GraphError::Interrupted(Box::new(
368                    InterruptedExecution::new(
369                        self.config.thread_id.clone(),
370                        checkpoint_id,
371                        interrupt,
372                        self.state.clone(),
373                        self.step,
374                    )
375                    .with_interrupts(
376                        result.interrupts.into_iter().map(|(_, interrupt)| interrupt).collect(),
377                    ),
378                )));
379            }
380
381            // The gate re-arms once its node has run, so a cycle returning to
382            // the same node asks again.
383            if let Some(cleared) = &self.cleared_interrupt
384                && result.executed_nodes.iter().any(|n| n == cleared)
385            {
386                self.cleared_interrupt = None;
387            }
388
389            // Advance the frontier *before* checkpointing. A checkpoint records
390            // what still has to run, so saving while `pending_nodes` still holds
391            // the nodes that just finished would re-execute them on resume.
392            self.pending_nodes = self.advance_frontier(&result, &[])?;
393            self.settle_child_ledger(&[]);
394            self.paused_nodes.retain(|node| !result.executed_nodes.contains(node));
395            self.step += 1;
396
397            // An empty frontier is a terminal checkpoint: resuming it re-reads
398            // the final state instead of restarting the graph.
399            self.checkpoint_step().await?;
400
401            if self.pending_nodes.is_empty() {
402                break;
403            }
404        }
405
406        self.finish_checkpoints().await?;
407        Ok(self.state.clone())
408    }
409
410    /// Run with streaming
411    pub fn run_stream(
412        mut self,
413        input: State,
414        mode: StreamMode,
415    ) -> impl futures::Stream<Item = Result<StreamEvent>> + 'a {
416        async_stream::stream! {
417            if let Err(error) = self.graph.check_governed_nodes() {
418                yield Err(error);
419                return;
420            }
421            // Check for existing checkpoint to resume from
422            let resumed = match self.try_resume_from_checkpoint(&input).await {
423                Ok(r) => r,
424                Err(e) => {
425                    yield Err(e);
426                    return;
427                }
428            };
429            if let Err(error) = self.check_resume_answers() {
430                yield Err(error);
431                return;
432            }
433
434            if resumed {
435                // Emit a resumed event indicating execution was restored from checkpoint
436                yield Ok(StreamEvent::resumed(self.step, self.pending_nodes.clone()));
437            } else {
438                // No checkpoint found — fresh start
439                match self.initialize_state(input).await {
440                    Ok(state) => self.state = state,
441                    Err(e) => {
442                        yield Err(e);
443                        return;
444                    }
445                }
446                match self.entry_frontier() {
447                    Ok(frontier) => self.pending_nodes = frontier,
448                    Err(e) => {
449                        yield Err(e);
450                        return;
451                    }
452                }
453            }
454            self.open_run();
455
456            // Stream initial state if requested
457            if matches!(mode, StreamMode::Values) {
458                yield Ok(StreamEvent::state(self.state.clone(), self.step));
459            }
460
461            // Main execution loop
462            while !self.pending_nodes.is_empty() {
463                // Check recursion limit
464                let steps_taken = self.step.saturating_sub(self.run_start_step);
465                if steps_taken >= self.recursion_limit() {
466                    yield Err(GraphError::RecursionLimitExceeded(steps_taken));
467                    return;
468                }
469
470                if let Err(error) = self.flush_before_side_effects().await {
471                    yield Err(error);
472                    return;
473                }
474
475                // Emit node_start events BEFORE execution (in Debug mode)
476                if matches!(mode, StreamMode::Debug | StreamMode::Custom | StreamMode::Messages) {
477                    for node_name in &self.pending_nodes {
478                        yield Ok(StreamEvent::node_start(node_name, self.step));
479                    }
480                }
481
482                // For Messages mode, stream from nodes directly
483                if matches!(mode, StreamMode::Messages) {
484                    let mut result = SuperStepResult::default();
485
486                    // The same gate `execute_super_step` applies. This loop does
487                    // not call it, so without this the mode ignored every gate.
488                    let gated = self.gate_before(&self.pending_nodes);
489                    // What became of each node, for the step's record.
490                    let mut records: Vec<NodeRecord> = Vec::new();
491                    if let Some(interrupt) = gated.clone() {
492                        records.push(node_record(&interrupt.0, record_now(), 0, NodeStatus::Paused, None, 0));
493                        result.interrupts.push(interrupt);
494                    }
495
496                    // Nodes run one after another here, each applying its updates, so
497                    // a failure restores the state the step started from and keeps
498                    // what finished as pending writes.
499                    let step_start_state = self.state.clone();
500                    let mut step_writes: BTreeMap<String, PendingWrite> = BTreeMap::new();
501
502                    // A gate stops the step before any node runs. A node's own pause
503                    // does not: the other nodes of the step still run, as they do
504                    // when the step runs in parallel, and every pause is reported.
505                    for node_name in self.pending_nodes.clone().iter() {
506                        if gated.is_some() {
507                            break;
508                        }
509                        if let Some(write) = self.pending_writes.get(node_name).cloned() {
510                            records.push(node_record(
511                                node_name,
512                                record_now(),
513                                0,
514                                NodeStatus::Done,
515                                Some(&write.updates),
516                                1,
517                            ));
518                            result.executed_nodes.push(node_name.clone());
519                            if let Some(targets) = write.goto.clone() {
520                                result.goto.insert(node_name.clone(), targets);
521                            }
522                            if let Some(targets) = write.goto_parent.clone() {
523                                self.goto_parent = Some(targets);
524                            }
525                            for (key, value) in &write.updates {
526                                self.graph.schema.apply_update(&mut self.state, key, value.clone());
527                            }
528                            result.updates.insert(node_name.clone(), write.updates.clone());
529                            step_writes.insert(node_name.clone(), write);
530                            continue;
531                        }
532                        if let Some(node) = self.graph.nodes.get(node_name) {
533                            let ctx = self.node_context(node_name);
534                            let started_at = record_now();
535                            let start = std::time::Instant::now();
536
537                            // A governed node runs through its bracket, not as a stream.
538                            if let Some(dispatch) = self.governed_dispatch(node_name, node) {
539                                let run = crate::governed::dispatch(dispatch, &ctx).await;
540                                let duration_ms = start.elapsed().as_millis() as u64;
541                                let mut record =
542                                    node_record(node_name, started_at, duration_ms, run.status, None, 1);
543                                record.effect_key = run.effect_key.clone();
544                                result.events.push(StreamEvent::node_end(node_name, self.step, duration_ms));
545                                match run.output {
546                                    Ok(output) => {
547                                        if let Some(interrupt) = output.interrupt {
548                                            records.push(record);
549                                            // A node that paused itself after its call was
550                                            // approved waits on nothing in the inbox.
551                                            match run.held {
552                                                Some(held) => {
553                                                    self.held.insert(node_name.clone(), held);
554                                                }
555                                                None => {
556                                                    self.held.remove(node_name);
557                                                }
558                                            }
559                                            result.interrupts.push((node_name.clone(), interrupt));
560                                            continue;
561                                        }
562                                        record = node_record(
563                                            node_name,
564                                            started_at,
565                                            duration_ms,
566                                            run.status,
567                                            Some(&output.updates),
568                                            1,
569                                        );
570                                        record.effect_key = run.effect_key;
571                                        records.push(record);
572                                        self.held.remove(node_name);
573                                        result.executed_nodes.push(node_name.clone());
574                                        result.events.extend(output.events);
575                                        if let Some(targets) = output.goto.clone() {
576                                            result.goto.insert(node_name.clone(), targets);
577                                        }
578                                        if let Some(targets) = output.goto_parent.clone() {
579                                            self.goto_parent = Some(targets);
580                                        }
581                                        let mut keys: Vec<String> = output.updates.keys().cloned().collect();
582                                        keys.sort();
583                                        self.ensure_channels_declared(node_name, keys.iter().map(String::as_str))?;
584                                        for key in keys {
585                                            if let Some(value) = output.updates.get(&key) {
586                                                self.graph.schema.apply_update(&mut self.state, &key, value.clone());
587                                            }
588                                        }
589                                        result.updates.insert(node_name.clone(), output.updates.clone());
590                                        step_writes.insert(
591                                            node_name.clone(),
592                                            PendingWrite {
593                                                updates: output.updates,
594                                                goto: output.goto,
595                                                goto_parent: output.goto_parent,
596                                            },
597                                        );
598                                    }
599                                    Err(e) => {
600                                        record.error = Some(e.to_string());
601                                        records.push(record);
602                                        self.held.remove(node_name);
603                                        self.state = step_start_state.clone();
604                                        self.pending_writes = step_writes.clone();
605                                        self.record_step(StepKind::Failed, std::mem::take(&mut records));
606                                        self.checkpoint_failed_step().await;
607                                        yield Err(e);
608                                        return;
609                                    }
610                                }
611                                continue;
612                            }
613
614                            let policy = self.graph.timeout_policy_for(node_name).cloned();
615
616                            // The timeout policy now applies to the streamed
617                            // execution itself. For a stream, "idle" means no
618                            // event was produced within the idle timeout.
619                            let max_attempts = match policy.as_ref().map(|p| &p.on_timeout) {
620                                Some(OnTimeout::Retry { max_attempts }) => (*max_attempts).max(1),
621                                _ => 1,
622                            };
623                            let mut collected_events = Vec::new();
624                            let mut streamed_updates = Vec::new();
625                            let mut streamed_goto: Option<(String, Vec<String>)> = None;
626                            let mut streamed_interrupt: Option<Interrupt> = None;
627                            let mut timed_out_after;
628                            let mut attempt = 0;
629
630                            loop {
631                                attempt += 1;
632                                collected_events.clear();
633                                streamed_updates.clear();
634                                timed_out_after = None;
635                                begin_attempt(&ctx);
636                                let attempt_start = std::time::Instant::now();
637                                let mut node_stream = node.execute_stream(&ctx);
638                                let mut failure = None;
639
640                                loop {
641                                    let budget = policy
642                                        .as_ref()
643                                        .and_then(|p| item_timeout_budget(p, attempt_start.elapsed()));
644                                    let item = match budget {
645                                        Some(budget) => {
646                                            match tokio::time::timeout(budget, node_stream.next()).await {
647                                                Ok(item) => item,
648                                                Err(_) => {
649                                                    timed_out_after = Some(attempt_start.elapsed());
650                                                    break;
651                                                }
652                                            }
653                                        }
654                                        None => node_stream.next().await,
655                                    };
656
657                                    match item {
658                                        Some(Ok(event)) => {
659                                            // Yield Message events immediately
660                                            if matches!(event, StreamEvent::Message { .. }) {
661                                                yield Ok(event.clone());
662                                            }
663                                            // The node reports its state updates on the
664                                            // stream, so they are taken from the single
665                                            // execution that produced these events.
666                                            if let StreamEvent::Updates { ref updates, .. } = event {
667                                                streamed_updates.push(updates.clone());
668                                            }
669                                            // A node that routed itself reports it here.
670                                            if let StreamEvent::RouteDispatched {
671                                                ref source,
672                                                ref targets,
673                                            } = event
674                                            {
675                                                streamed_goto =
676                                                    Some((source.clone(), targets.clone()));
677                                            }
678                                            // As does a node asking to pause.
679                                            if let StreamEvent::NodeInterrupt {
680                                                ref message,
681                                                ref data,
682                                                ref response_schema,
683                                                ..
684                                            } = event
685                                            {
686                                                streamed_interrupt =
687                                                    Some(Interrupt::Dynamic {
688                                                        message: message.clone(),
689                                                        data: data.clone(),
690                                                        id: None,
691                                                        response_schema: response_schema.clone(),
692                                                    });
693                                            }
694                                            collected_events.push(event);
695                                        }
696                                        Some(Err(e)) => {
697                                            failure = Some(e);
698                                            break;
699                                        }
700                                        None => break,
701                                    }
702                                }
703                                drop(node_stream);
704
705                                if let Some(e) = failure {
706                                    let mut record = node_record(
707                                        node_name,
708                                        started_at,
709                                        start.elapsed().as_millis() as u64,
710                                        NodeStatus::Failed,
711                                        None,
712                                        u32::try_from(attempt).unwrap_or(u32::MAX),
713                                    );
714                                    record.error = Some(e.to_string());
715                                    records.push(record);
716                                    self.state = step_start_state.clone();
717                                    self.pending_writes = step_writes.clone();
718                                    self.record_step(StepKind::Failed, std::mem::take(&mut records));
719                                    self.checkpoint_failed_step().await;
720                                    yield Err(e);
721                                    return;
722                                }
723                                if timed_out_after.is_none() || attempt >= max_attempts {
724                                    break;
725                                }
726                            }
727
728                            if let Some(elapsed) = timed_out_after {
729                                let on_timeout =
730                                    policy.as_ref().map(|p| p.on_timeout.clone()).unwrap_or_default();
731                                match on_timeout {
732                                    OnTimeout::Skip => {
733                                        tracing::warn!(
734                                            node = %node_name,
735                                            elapsed = ?elapsed,
736                                            "node timed out while streaming, skipping"
737                                        );
738                                        streamed_updates.clear();
739                                    }
740                                    OnTimeout::Fail | OnTimeout::Retry { .. } => {
741                                        let error = GraphError::NodeTimedOut {
742                                            node: node_name.clone(),
743                                            elapsed,
744                                        };
745                                        let mut record = node_record(
746                                            node_name,
747                                            started_at,
748                                            start.elapsed().as_millis() as u64,
749                                            NodeStatus::Failed,
750                                            None,
751                                            u32::try_from(attempt).unwrap_or(u32::MAX),
752                                        );
753                                        record.error = Some(error.to_string());
754                                        records.push(record);
755                                        self.state = step_start_state.clone();
756                                        self.pending_writes = step_writes.clone();
757                                        self.record_step(StepKind::Failed, std::mem::take(&mut records));
758                                        self.checkpoint_failed_step().await;
759                                        yield Err(error);
760                                        return;
761                                    }
762                                }
763                            }
764
765                            let duration_ms = start.elapsed().as_millis() as u64;
766                            result.events.push(StreamEvent::node_end(node_name, self.step, duration_ms));
767                            result.events.extend(collected_events);
768
769                            let node_interrupt = streamed_interrupt;
770                            if let Some(interrupt) = node_interrupt {
771                                records.push(node_record(
772                                    node_name,
773                                    started_at,
774                                    duration_ms,
775                                    NodeStatus::Paused,
776                                    None,
777                                    u32::try_from(attempt).unwrap_or(u32::MAX),
778                                ));
779                                result.interrupts.push((node_name.clone(), interrupt));
780                            } else {
781                                result.executed_nodes.push(node_name.clone());
782                                let mut write = PendingWrite::default();
783                                if let Some((source, targets)) = streamed_goto {
784                                    write.goto = Some(targets.clone());
785                                    result.goto.insert(source, targets);
786                                }
787                                for updates in &streamed_updates {
788                                    write.updates.extend(updates.clone());
789                                }
790                                records.push(node_record(
791                                    node_name,
792                                    started_at,
793                                    duration_ms,
794                                    NodeStatus::Done,
795                                    Some(&write.updates),
796                                    u32::try_from(attempt).unwrap_or(u32::MAX),
797                                ));
798                                result.updates.insert(node_name.clone(), write.updates.clone());
799                                step_writes.insert(node_name.clone(), write);
800                                for updates in streamed_updates {
801                                    self.ensure_channels_declared(
802                                        node_name,
803                                        updates.keys().map(String::as_str),
804                                    )?;
805                                    for (key, value) in updates {
806                                        self.graph.schema.apply_update(&mut self.state, &key, value);
807                                    }
808                                }
809                            }
810                        }
811                    }
812
813                    // Yield node_end events
814                    for event in &result.events {
815                        if matches!(event, StreamEvent::NodeEnd { .. }) {
816                            yield Ok(event.clone());
817                        }
818                    }
819
820                    // Reported in node-name order, as the parallel path reports them.
821                    result.interrupts.sort_by(|left, right| left.0.cmp(&right.0));
822
823                    // A node that arms a gate on completion stops the run here, unless
824                    // a node already asked to pause itself.
825                    if result.interrupts.is_empty()
826                        && let Some(interrupt) = self.gate_after(&result.executed_nodes)
827                    {
828                        result.interrupts.push(interrupt);
829                    }
830                    self.count_governed_runs(&result.executed_nodes);
831                    let kind =
832                        if result.interrupts.is_empty() { StepKind::Completed } else { StepKind::Paused };
833                    self.record_step(kind, std::mem::take(&mut records));
834
835                    // This branch returns rather than falling through to the shared
836                    // handling below, so the pause is reported here.
837                    if !result.interrupts.is_empty() {
838                        if let Err(error) = self.pause_frontier(&mut result) {
839                            yield Err(error);
840                            return;
841                        }
842                        // Persist before reporting: without this the pause cannot be
843                        // resumed and the work already done is lost.
844                        self.pending_writes.clear();
845                        let checkpoint_id = match self.save_pause_checkpoint().await {
846                            Ok(checkpoint_id) => checkpoint_id,
847                            Err(error) => {
848                                yield Err(error);
849                                return;
850                            }
851                        };
852                        for event in self.pause_events(&result, &checkpoint_id) {
853                            yield Ok(event);
854                        }
855                        return;
856                    }
857
858                    // The gate re-arms once its node has run; see `run`.
859                    if let Some(cleared) = &self.cleared_interrupt
860                        && result.executed_nodes.iter().any(|n| n == cleared)
861                    {
862                        self.cleared_interrupt = None;
863                    }
864
865                    self.pending_nodes = match self.advance_frontier(&result, &[]) {
866                        Ok(nodes) => nodes,
867                        Err(e) => {
868                            yield Err(e);
869                            return;
870                        }
871                    };
872                    self.settle_child_ledger(&[]);
873                    self.paused_nodes.retain(|node| !result.executed_nodes.contains(node));
874                    self.step += 1;
875
876                    self.pending_writes.clear();
877
878                    // The other path checkpoints every super-step. This one did not,
879                    // so a run in this mode left no state to resume from and
880                    // `get_state` reported nothing.
881                    if let Err(e) = self.checkpoint_step().await {
882                        yield Err(e);
883                        return;
884                    }
885                    continue;
886                }
887
888                // Execute super-step (non-streaming)
889                let mut result = match self.execute_super_step().await {
890                    Ok(r) => r,
891                    Err(e) => {
892                        self.checkpoint_failed_step().await;
893                        yield Err(e);
894                        return;
895                    }
896                };
897
898                // Yield events based on mode (node_end and custom events)
899                for event in &result.events {
900                    match (&mode, &event) {
901                        // Skip node_start since we already emitted it above
902                        (StreamMode::Custom | StreamMode::Debug, StreamEvent::NodeStart { .. }) => {}
903                        (StreamMode::Custom, _) => yield Ok(event.clone()),
904                        (StreamMode::Debug, _) => yield Ok(event.clone()),
905                        _ => {}
906                    }
907                }
908
909                // Yield state/updates
910                match mode {
911                    StreamMode::Values => {
912                        yield Ok(StreamEvent::state(self.state.clone(), self.step));
913                    }
914                    StreamMode::Updates => {
915                        yield Ok(StreamEvent::step_complete(
916                            self.step,
917                            result.executed_nodes.clone(),
918                        ));
919                    }
920                    _ => {}
921                }
922
923                // Handle interrupts
924                if !result.interrupts.is_empty() {
925                    if let Err(error) = self.pause_frontier(&mut result) {
926                        yield Err(error);
927                        return;
928                    }
929                    // Persist before reporting: without this the interrupt is
930                    // unresumable, because resuming loads the checkpoint for the
931                    // thread.
932                    let checkpoint_id = match self.save_pause_checkpoint().await {
933                        Ok(checkpoint_id) => checkpoint_id,
934                        Err(error) => {
935                            yield Err(error);
936                            return;
937                        }
938                    };
939                    for event in self.pause_events(&result, &checkpoint_id) {
940                        yield Ok(event);
941                    }
942                    return;
943                }
944
945                // The gate re-arms once its node has run; see `run`.
946                if let Some(cleared) = &self.cleared_interrupt
947                    && result.executed_nodes.iter().any(|n| n == cleared)
948                {
949                    self.cleared_interrupt = None;
950                }
951
952                // Advance the frontier before checkpointing, so the checkpoint
953                // records what still has to run rather than what just finished.
954                //
955                // Reported only on the debug stream, because building it evaluates
956                // each router a second time.
957                if matches!(mode, StreamMode::Debug) {
958                    match self.graph.route_dispatches(&result.executed_nodes, &self.state) {
959                        Ok(dispatches) => {
960                            for (source, targets) in dispatches {
961                                yield Ok(StreamEvent::route_dispatched(&source, targets));
962                            }
963                        }
964                        Err(error) => {
965                            yield Err(error);
966                            return;
967                        }
968                    }
969                }
970
971                self.pending_nodes = match self.advance_frontier(&result, &[]) {
972                    Ok(nodes) => nodes,
973                    Err(e) => {
974                        yield Err(e);
975                        return;
976                    }
977                };
978                self.settle_child_ledger(&[]);
979                self.paused_nodes.retain(|node| !result.executed_nodes.contains(node));
980                self.step += 1;
981
982                if let Err(e) = self.checkpoint_step().await {
983                    yield Err(e);
984                    return;
985                }
986            }
987
988            if let Err(e) = self.finish_checkpoints().await {
989                yield Err(e);
990                return;
991            }
992            yield Ok(StreamEvent::done(self.state.clone(), self.step + 1));
993        }
994    }
995
996    /// Computes the next frontier of a finished super-step, holding fan-in nodes
997    /// that still wait for a predecessor.
998    ///
999    /// `in_flight` names nodes that did not finish and run again, such as the
1000    /// nodes a dynamic pause re-queues; a waiting fan-in node counts them as
1001    /// predecessors that can still run.
1002    ///
1003    /// # Errors
1004    ///
1005    /// Returns the routing error from [`Self::next_frontier`] or the fan-in error
1006    /// from [`Self::filter_deferred_nodes`].
1007    fn advance_frontier(
1008        &mut self,
1009        result: &SuperStepResult,
1010        in_flight: &[String],
1011    ) -> Result<Vec<String>> {
1012        let (candidates, routes) = self.next_frontier(&result.executed_nodes, &result.goto)?;
1013        self.filter_deferred_nodes(candidates, &routes, &result.updates, in_flight)
1014    }
1015
1016    /// The nodes a run starts with.
1017    ///
1018    /// An entry node that is also a fan-in node, reached from `START` and from
1019    /// other nodes, waits like any join: `START` has arrived, and the node runs
1020    /// once the predecessors that can still run in this pass have, so it runs
1021    /// once rather than at the start and again after each predecessor. A node
1022    /// whose other predecessors run only after it, such as a loop's head,
1023    /// starts at once.
1024    ///
1025    /// # Errors
1026    ///
1027    /// Returns the fan-in error from [`Self::filter_deferred_nodes`].
1028    fn entry_frontier(&mut self) -> Result<Vec<String>> {
1029        let graph = self.graph;
1030        let (joins, mut ready): (Vec<String>, Vec<String>) =
1031            graph.get_entry_nodes().into_iter().partition(|node| {
1032                graph.deferred_configs.contains_key(node)
1033                    && !graph.get_upstream_nodes(node).is_empty()
1034            });
1035        if joins.is_empty() {
1036            return Ok(ready);
1037        }
1038        for join in joins {
1039            let upstream = graph.get_upstream_nodes(&join);
1040            self.pending_deferred.insert(
1041                join.clone(),
1042                FanInTracker::new(upstream.iter().map(String::as_str).collect()),
1043            );
1044            self.deferred_start_times.insert(join, Instant::now());
1045        }
1046        // The other entry nodes run next, so they count as running when deciding
1047        // whether a join's predecessors can still arrive.
1048        let released = self.filter_deferred_nodes(Vec::new(), &[], &HashMap::new(), &ready)?;
1049        ready.extend(released);
1050        Ok(ready)
1051    }
1052
1053    /// Filter deferred nodes from the next candidates.
1054    ///
1055    /// A deferred node records an arrival from each node that routed to it in
1056    /// this step: the updates that predecessor wrote, or the value it wrote to a
1057    /// channel named after itself. A predecessor that ran but routed elsewhere
1058    /// does not arrive.
1059    ///
1060    /// Every waiting node is then checked, whether or not anything routed to it
1061    /// in this step. It is released, with its arrivals merged into
1062    /// `{node}_fan_in`, once no predecessor that has not arrived can still run in
1063    /// the current pass. A predecessor can still run when it is reachable along
1064    /// declared edges from a node that runs next, a node that runs again, or
1065    /// another waiting node, without passing through this node or a deferred node
1066    /// that waits on it. A predecessor reached only through this node belongs to
1067    /// the next pass of a loop, so a node re-entered by a back edge, or a merge
1068    /// after a conditional branch, runs with what arrived.
1069    ///
1070    /// When nothing else can run, every waiting node is released, so a run never
1071    /// ends with a join that did not fire.
1072    ///
1073    /// If a deferred node has a `fan_in_timeout` configured and the timeout has
1074    /// elapsed while it still waits:
1075    /// - If at least `min_predecessors` (default one) arrived, proceed with partial results.
1076    /// - Otherwise, return `GraphError::FanInTimedOut`.
1077    fn filter_deferred_nodes(
1078        &mut self,
1079        candidates: Vec<String>,
1080        routes: &[Route],
1081        updates: &HashMap<String, HashMap<String, serde_json::Value>>,
1082        in_flight: &[String],
1083    ) -> Result<Vec<String>> {
1084        let mut ready_nodes = Vec::new();
1085
1086        for candidate in candidates {
1087            if !self.graph.deferred_configs.contains_key(&candidate) {
1088                ready_nodes.push(candidate);
1089                continue;
1090            }
1091            // A branch a timeout released this node without arrives late: that
1092            // arrival is dropped once, rather than running the node again for it.
1093            let abandoned = self.abandoned_arrivals.entry(candidate.clone()).or_default();
1094            let arrivals: Vec<&String> = routes
1095                .iter()
1096                .filter(|(source, target)| target == &candidate && !abandoned.remove(source))
1097                .map(|(source, _)| source)
1098                .collect();
1099            if arrivals.is_empty() && !self.pending_deferred.contains_key(&candidate) {
1100                continue;
1101            }
1102            let upstream = self.graph.get_upstream_nodes(&candidate);
1103            let tracker = self.pending_deferred.entry(candidate.clone()).or_insert_with(|| {
1104                FanInTracker::new(upstream.iter().map(String::as_str).collect())
1105            });
1106            self.deferred_start_times.entry(candidate.clone()).or_insert_with(Instant::now);
1107            for source in arrivals {
1108                tracker.record(source, arrival_output(source, updates.get(source)));
1109            }
1110        }
1111        self.abandoned_arrivals.retain(|_, sources| !sources.is_empty());
1112
1113        if self.pending_deferred.is_empty() {
1114            return Ok(ready_nodes);
1115        }
1116
1117        let graph = self.graph;
1118        let mut waiting: Vec<String> = self.pending_deferred.keys().cloned().collect();
1119        waiting.sort();
1120        let successors = graph.successor_map();
1121        let deferred_upstream: HashMap<&str, Vec<String>> = graph
1122            .deferred_configs
1123            .keys()
1124            .map(|node| (node.as_str(), graph.get_upstream_nodes(node)))
1125            .collect();
1126
1127        let mut released = Vec::new();
1128        for join in &waiting {
1129            // This node, and any deferred node waiting on it, cannot run before it.
1130            let blocked = |node: &str| {
1131                node == join.as_str()
1132                    || deferred_upstream.get(node).is_some_and(|upstream| upstream.contains(join))
1133            };
1134            let sources = ready_nodes
1135                .iter()
1136                .chain(in_flight)
1137                .chain(waiting.iter())
1138                .map(String::as_str)
1139                .filter(|node| !blocked(node));
1140            let reachable = reachable_from(sources, &successors, &blocked);
1141
1142            let tracker = &self.pending_deferred[join];
1143            let still_expected =
1144                tracker.pending_sources().into_iter().any(|source| reachable.contains(source));
1145            if !still_expected {
1146                released.push(join.clone());
1147                continue;
1148            }
1149
1150            let Some(config) = graph.deferred_configs.get(join) else { continue };
1151            let Some(timeout) = config.fan_in_timeout else { continue };
1152            if self.deferred_start_times[join].elapsed() < timeout {
1153                continue;
1154            }
1155            let received = tracker.received_count();
1156            let expected = tracker.expected_count();
1157            // `min_predecessors` decides how many arrivals are enough to release
1158            // the node once the timeout expires.
1159            let required = config.min_predecessors.unwrap_or(1).max(1);
1160            if received < required {
1161                self.pending_deferred.remove(join);
1162                self.deferred_start_times.remove(join);
1163                return Err(GraphError::FanInTimedOut { node: join.clone(), received, expected });
1164            }
1165            tracing::warn!(
1166                node = %join,
1167                received,
1168                expected,
1169                "fan-in timeout expired, proceeding with partial results"
1170            );
1171            let abandoned: std::collections::HashSet<String> = tracker
1172                .pending_sources()
1173                .into_iter()
1174                .filter(|source| reachable.contains(source))
1175                .map(str::to_string)
1176                .collect();
1177            self.release_join(join, false)?;
1178            if !abandoned.is_empty() {
1179                self.abandoned_arrivals.insert(join.clone(), abandoned);
1180            }
1181            ready_nodes.push(join.clone());
1182        }
1183
1184        for join in released {
1185            self.release_join(&join, true)?;
1186            ready_nodes.push(join);
1187        }
1188
1189        // Each waiting node waits on another, and nothing else runs: release
1190        // them together rather than end the run with joins that never fired.
1191        if ready_nodes.is_empty() && in_flight.is_empty() && !self.pending_deferred.is_empty() {
1192            let mut stalled: Vec<String> = self.pending_deferred.keys().cloned().collect();
1193            stalled.sort();
1194            tracing::debug!(nodes = ?stalled, "releasing fan-in nodes that wait only on each other");
1195            for join in stalled {
1196                self.release_join(&join, true)?;
1197                ready_nodes.push(join);
1198            }
1199        }
1200
1201        Ok(ready_nodes)
1202    }
1203
1204    /// Releases a waiting fan-in node, merging its arrivals into `{node}_fan_in`.
1205    ///
1206    /// `check_minimum` applies `min_predecessors` to a node released because its
1207    /// remaining predecessors can no longer run; the timeout path checks its own.
1208    ///
1209    /// # Errors
1210    ///
1211    /// Returns [`GraphError::FanInIncomplete`] when fewer predecessors arrived
1212    /// than `min_predecessors` requires.
1213    fn release_join(&mut self, join: &str, check_minimum: bool) -> Result<()> {
1214        let Some(tracker) = self.pending_deferred.remove(join) else { return Ok(()) };
1215        self.deferred_start_times.remove(join);
1216        // A branch abandoned on an earlier firing that never arrived belongs to
1217        // that firing, not to this one.
1218        self.abandoned_arrivals.remove(join);
1219        let Some(config) = self.graph.deferred_configs.get(join) else { return Ok(()) };
1220        if check_minimum
1221            && !tracker.is_ready()
1222            && let Some(required) = config.min_predecessors
1223            && tracker.received_count() < required
1224        {
1225            return Err(GraphError::FanInIncomplete {
1226                node: join.to_string(),
1227                received: tracker.received_count(),
1228                required,
1229            });
1230        }
1231        let merged = tracker.merge(&config.merge_strategy);
1232        self.graph.schema.apply_update(&mut self.state, &format!("{join}_fan_in"), merged);
1233        Ok(())
1234    }
1235
1236    /// Keeps only the child-ledger entries of nodes that will run this step again.
1237    ///
1238    /// A ledger entry lets a re-executed parent skip a child that already
1239    /// finished. Once a parent's step completes it never re-executes that
1240    /// activation, so its entries are dropped; a parent that paused keeps them
1241    /// for its resume.
1242    fn settle_child_ledger(&self, rerun: &[String]) {
1243        let prefixes: Vec<String> = rerun
1244            .iter()
1245            .map(|node| crate::child::ChildInvoker::activation_prefix(node, self.step))
1246            .collect();
1247        self.child_ledger
1248            .lock()
1249            .expect("child ledger")
1250            .retain(|path, _| prefixes.iter().any(|prefix| path.starts_with(prefix)));
1251    }
1252
1253    /// The context a node runs with in the current step.
1254    ///
1255    /// Carries the run configuration, the graph's schema for a node that projects
1256    /// state, an invoker for the children the node may run, and a progress handle
1257    /// when the node has an idle timeout.
1258    fn node_context(&self, node: &str) -> NodeContext {
1259        let mut ctx = NodeContext::new(self.state.clone(), self.config.clone(), self.step);
1260        // A subgraph's governed nodes key their records by this run's lineage.
1261        ctx.config.lineage_root = Some(self.lineage_root());
1262        if self.graph.is_governed(node) {
1263            ctx.set_governed_call();
1264        }
1265        if let Some(run_config) = self.run_config.clone() {
1266            ctx.set_run_config(run_config);
1267        }
1268        // A node body may invoke other nodes. The invoker carries the graph's
1269        // nodes and the shared ledger, so a resumed parent serves children that
1270        // already finished. These invocations are awaited inline by the parent and
1271        // are deliberately outside the concurrency budget: counting them could
1272        // deadlock, because the parent holds its own slot while waiting.
1273        ctx.set_parent_schema(Arc::new(self.graph.schema.clone()));
1274        // A governed node runs only through its bracket, so a node body cannot invoke it.
1275        let children = if self.graph.governed_nodes.is_empty() {
1276            self.graph.nodes.clone()
1277        } else {
1278            self.graph
1279                .nodes
1280                .iter()
1281                .filter(|(name, _)| !self.graph.is_governed(name))
1282                .map(|(name, node)| (name.clone(), Arc::clone(node)))
1283                .collect()
1284        };
1285        ctx.set_child_invoker(Arc::new(crate::child::ChildInvoker::new(
1286            children,
1287            self.graph.retry_policies.clone(),
1288            Arc::clone(&self.child_ledger),
1289            node,
1290            self.step,
1291        )));
1292        if self.graph.timeout_policy_for(node).is_some_and(|policy| policy.idle_timeout.is_some()) {
1293            ctx.set_progress_handle(ProgressHandle::new());
1294        }
1295        // Only a node resuming its own pause gets an answer, so a node that runs
1296        // again later pauses again rather than reading a stale one.
1297        if self.paused_nodes.contains(node) {
1298            // An answer under the pause's id first; under strict resume, only that.
1299            let by_id = self
1300                .pending_interrupts
1301                .get(node)
1302                .and_then(|pending| self.config.resume_values.get(&pending.id));
1303            let by_node =
1304                (!self.config.strict_resume).then(|| self.config.resume_values.get(node)).flatten();
1305            if let Some(answer) = by_id.or(by_node) {
1306                ctx.set_resume_value(answer.clone());
1307            }
1308        }
1309        ctx
1310    }
1311
1312    /// Initialize state from input and/or checkpoint
1313    async fn initialize_state(&self, input: State) -> Result<State> {
1314        // Start with schema defaults
1315        let mut state = self.graph.schema.initialize_state();
1316
1317        // If resuming from checkpoint, load it
1318        if let Some(checkpoint_id) = &self.config.resume_from {
1319            if let Some(cp) = self.graph.checkpointer.as_ref()
1320                && let Some(checkpoint) = cp.load_by_id(checkpoint_id).await?
1321            {
1322                state = checkpoint.state;
1323            }
1324        } else if let Some(cp) = self.graph.checkpointer.as_ref() {
1325            // Try to load latest checkpoint for thread
1326            if let Some(checkpoint) = cp.load(&self.config.thread_id).await? {
1327                state = checkpoint.state;
1328            }
1329        }
1330
1331        // Merge input into state
1332        for (key, value) in input {
1333            self.graph.schema.apply_update(&mut state, &key, value);
1334        }
1335
1336        Ok(state)
1337    }
1338
1339    /// Execute one super-step (plan -> execute -> update)
1340    async fn execute_super_step(&mut self) -> Result<SuperStepResult> {
1341        let mut result = SuperStepResult::default();
1342
1343        if let Some(gate) = self.gate_before(&self.pending_nodes) {
1344            let record = node_record(&gate.0, record_now(), 0, NodeStatus::Paused, None, 0);
1345            self.record_step(StepKind::Paused, vec![record]);
1346            return Ok(SuperStepResult { interrupts: vec![gate], ..Default::default() });
1347        }
1348
1349        // Collect all updates and check for errors/interrupts
1350        let mut all_updates = Vec::new();
1351        // Each successful node's output, kept as a pending write if the step fails.
1352        let mut step_writes: BTreeMap<String, PendingWrite> = BTreeMap::new();
1353        // What became of each node, for the step's record.
1354        let mut records: Vec<NodeRecord> = Vec::new();
1355
1356        // Nodes that finished before an earlier attempt at this step failed are
1357        // answered from their pending writes instead of running again.
1358        let mut to_run: Vec<String> = Vec::new();
1359        for node_name in &self.pending_nodes {
1360            match self.pending_writes.get(node_name) {
1361                Some(write) => {
1362                    tracing::debug!(node = %node_name, "applying pending write instead of re-running node");
1363                    records.push(node_record(
1364                        node_name,
1365                        record_now(),
1366                        0,
1367                        NodeStatus::Done,
1368                        Some(&write.updates),
1369                        1,
1370                    ));
1371                    result.executed_nodes.push(node_name.clone());
1372                    if let Some(targets) = &write.goto {
1373                        result.goto.insert(node_name.clone(), targets.clone());
1374                    }
1375                    if let Some(targets) = &write.goto_parent {
1376                        self.goto_parent = Some(targets.clone());
1377                    }
1378                    all_updates.push((node_name.clone(), write.updates.clone()));
1379                    result.updates.insert(node_name.clone(), write.updates.clone());
1380                    step_writes.insert(node_name.clone(), write.clone());
1381                }
1382                None => to_run.push(node_name.clone()),
1383            }
1384        }
1385
1386        // Node cache lookups. Every key is computed from the pre-step state, the
1387        // state each node in this step reads, and a hit's updates join the same
1388        // batch as computed ones, so a hit changes nothing a sibling sees and the
1389        // key stored on a miss is the key the next identical lookup computes.
1390        #[cfg(feature = "node-cache")]
1391        let mut miss_keys: HashMap<String, String> = HashMap::new();
1392        #[cfg(feature = "node-cache")]
1393        let mut nodes_to_execute: Vec<String> = Vec::new();
1394        #[cfg(feature = "node-cache")]
1395        for node_name in &to_run {
1396            // A governed node's call goes through its bracket every time, never a cache.
1397            let Some(cache) = self
1398                .graph
1399                .node_caches
1400                .get(node_name)
1401                .filter(|_| !self.graph.is_governed(node_name))
1402            else {
1403                nodes_to_execute.push(node_name.clone());
1404                continue;
1405            };
1406            let cache_key = compute_cache_key(node_name, &self.state);
1407            let cached_value = cache.get(&cache_key).await;
1408            tracing::debug!(
1409                node = %node_name,
1410                cache_hit = cached_value.is_some(),
1411                cache_key = %cache_key,
1412                "node cache lookup"
1413            );
1414            match cached_value {
1415                Some(serde_json::Value::Object(updates)) => {
1416                    result.executed_nodes.push(node_name.clone());
1417                    result.events.push(StreamEvent::node_end(node_name, self.step, 0));
1418                    let updates: HashMap<String, serde_json::Value> = updates.into_iter().collect();
1419                    records.push(node_record(
1420                        node_name,
1421                        record_now(),
1422                        0,
1423                        NodeStatus::Done,
1424                        Some(&updates),
1425                        0,
1426                    ));
1427                    step_writes.insert(node_name.clone(), PendingWrite::new(updates.clone()));
1428                    result.updates.insert(node_name.clone(), updates.clone());
1429                    all_updates.push((node_name.clone(), updates));
1430                }
1431                // A cached value is always the map of a node's updates; anything
1432                // else is unusable, so the node runs.
1433                Some(_) | None => {
1434                    miss_keys.insert(node_name.clone(), cache_key);
1435                    nodes_to_execute.push(node_name.clone());
1436                }
1437            }
1438        }
1439
1440        // Determine which nodes to execute (all if cache feature is disabled).
1441        //
1442        // Sorted so that a bounded dispatch admits nodes in a fixed order rather
1443        // than whatever order the frontier happened to be built in.
1444        #[cfg(feature = "node-cache")]
1445        let pending_for_execution = {
1446            nodes_to_execute.sort();
1447            &nodes_to_execute
1448        };
1449        #[cfg(not(feature = "node-cache"))]
1450        let pending_for_execution = {
1451            to_run.sort();
1452            &to_run
1453        };
1454
1455        // Execute all pending nodes in parallel
1456        let nodes: Vec<_> = pending_for_execution
1457            .iter()
1458            .filter_map(|name| self.graph.nodes.get(name).map(|n| (name.clone(), n.clone())))
1459            .collect();
1460
1461        // Look up timeout and retry policies for each node before spawning futures
1462        let timeout_policies: Vec<_> =
1463            nodes.iter().map(|(name, _)| self.graph.timeout_policy_for(name).cloned()).collect();
1464        let retry_policies: Vec<_> =
1465            nodes.iter().map(|(name, _)| self.graph.retry_policy_for(name).cloned()).collect();
1466        // Attempts already spent, so a resumed run continues its budget rather
1467        // than starting again. adk-python does not persist this.
1468        let prior_attempts: Vec<u32> =
1469            nodes.iter().map(|(name, _)| self.attempts.get(name).copied().unwrap_or(0)).collect();
1470        // A governed node runs through its bracket, once per dispatch.
1471        let dispatches: Vec<Option<GovernedDispatch>> =
1472            nodes.iter().map(|(name, node)| self.governed_dispatch(name, node)).collect();
1473
1474        // Set by the first failure no error handler recovers. A node not yet
1475        // admitted then does not start, and a node waiting to retry stops waiting,
1476        // so the step ends with the work that finished instead of after the longest
1477        // retry chain. A node already running finishes and keeps its write.
1478        let (failed_tx, failed_rx) = tokio::sync::watch::channel(false);
1479        let failed_tx = Arc::new(failed_tx);
1480
1481        let futures: Vec<_> = nodes
1482            .into_iter()
1483            .zip(timeout_policies)
1484            .zip(retry_policies)
1485            .zip(prior_attempts)
1486            .zip(dispatches)
1487            .map(|(((((name, node), policy), retry), spent), dispatch)| {
1488                let ctx = self.node_context(&name);
1489                let step = self.step;
1490                let recoverable = self.graph.error_handler_for(&name).is_some();
1491                let failed_tx = Arc::clone(&failed_tx);
1492                let mut failed = failed_rx.clone();
1493                async move {
1494                    let started_at = record_now();
1495                    if *failed.borrow() {
1496                        return NodeRun {
1497                            name,
1498                            output: None,
1499                            started_at,
1500                            duration_ms: 0,
1501                            step,
1502                            attempts: spent,
1503                            governed: None,
1504                        };
1505                    }
1506                    let start = Instant::now();
1507                    if let Some(dispatch) = dispatch {
1508                        let mut run = crate::governed::dispatch(dispatch, &ctx).await;
1509                        if run.output.is_err() && !recoverable {
1510                            failed_tx.send_replace(true);
1511                        }
1512                        let output = std::mem::replace(&mut run.output, Ok(Default::default()));
1513                        return NodeRun {
1514                            name,
1515                            output: Some(output),
1516                            started_at,
1517                            duration_ms: start.elapsed().as_millis() as u64,
1518                            step,
1519                            attempts: spent + 1,
1520                            governed: Some(run),
1521                        };
1522                    }
1523                    let mut attempts = spent;
1524                    let output = loop {
1525                        begin_attempt(&ctx);
1526                        let result = match policy {
1527                            Some(ref timeout_policy) => {
1528                                execute_with_timeout(node.as_ref(), &ctx, timeout_policy).await
1529                            }
1530                            None => node.execute(&ctx).await,
1531                        };
1532                        attempts += 1;
1533
1534                        let Err(ref error) = result else { break result };
1535                        let Some(ref retry) = retry else { break result };
1536                        if !retry.allows_another_attempt(attempts)
1537                            || !retry.retry_on.should_retry(error)
1538                            || *failed.borrow()
1539                        {
1540                            break result;
1541                        }
1542
1543                        let delay = retry.delay_for_attempt(attempts);
1544                        tracing::warn!(
1545                            node = %name,
1546                            attempt = attempts,
1547                            max_attempts = retry.max_attempts,
1548                            delay_ms = delay.as_millis(),
1549                            error = %error,
1550                            "node failed, retrying after backoff"
1551                        );
1552                        tokio::select! {
1553                            () = tokio::time::sleep(delay) => {}
1554                            _ = failed.wait_for(|failed| *failed) => {
1555                                tracing::debug!(
1556                                    node = %name,
1557                                    "a sibling failed the step, abandoning the retry"
1558                                );
1559                                break result;
1560                            }
1561                        }
1562                    };
1563                    if output.is_err() && !recoverable {
1564                        failed_tx.send_replace(true);
1565                    }
1566                    NodeRun {
1567                        name,
1568                        output: Some(output),
1569                        started_at,
1570                        duration_ms: start.elapsed().as_millis() as u64,
1571                        step,
1572                        attempts,
1573                        governed: None,
1574                    }
1575                }
1576            })
1577            .collect();
1578
1579        // Bound the dispatch. `buffer_unordered` polls futures in the order they
1580        // are produced, and the frontier is sorted above, so admission order does
1581        // not depend on which node finished first.
1582        let concurrency = self
1583            .graph
1584            .max_concurrency
1585            .map_or(pending_for_execution.len(), |limit| limit.min(pending_for_execution.len()))
1586            .max(1);
1587        let mut outputs: Vec<NodeRun> =
1588            stream::iter(futures).buffer_unordered(concurrency).collect().await;
1589        // Completion order is intentionally nondeterministic under parallelism,
1590        // but selecting which of several simultaneous pauses to report cannot
1591        // be. Keep node event order stable and make the first node name win.
1592        outputs.sort_by(|left, right| left.name.cmp(&right.name));
1593
1594        let mut interrupts = Vec::new();
1595        let mut failure = None;
1596
1597        for run in outputs {
1598            let NodeRun {
1599                name: node_name,
1600                output,
1601                started_at,
1602                duration_ms,
1603                step,
1604                attempts,
1605                governed,
1606            } = run;
1607            // Not started, because the step had already failed. It stays in the
1608            // frontier and runs when the step resumes.
1609            let Some(output_result) = output else {
1610                records.push(node_record(
1611                    &node_name,
1612                    started_at,
1613                    0,
1614                    NodeStatus::NotRun,
1615                    None,
1616                    attempts,
1617                ));
1618                continue;
1619            };
1620            // Record the budget spent, so a resumed run does not restart it. A
1621            // node that finally succeeded keeps no entry: its budget is spent
1622            // only while it is failing.
1623            if output_result.is_err() {
1624                self.attempts.insert(node_name.clone(), attempts);
1625            } else {
1626                self.attempts.remove(&node_name);
1627            }
1628            result.events.push(StreamEvent::node_end(&node_name, step, duration_ms));
1629            let (governed_status, effect_key, held) = match governed {
1630                Some(run) => (Some(run.status), run.effect_key, run.held),
1631                None => (None, None, None),
1632            };
1633            let mut record = |status: NodeStatus,
1634                              writes: Option<&HashMap<String, serde_json::Value>>,
1635                              error: Option<String>| {
1636                let mut record =
1637                    node_record(&node_name, started_at, duration_ms, status, writes, attempts);
1638                record.effect_key = effect_key.clone();
1639                record.error = error;
1640                records.push(record);
1641            };
1642
1643            match output_result {
1644                Ok(output) => {
1645                    // Check for dynamic interrupt. Every node that paused is
1646                    // reported, in name order.
1647                    if let Some(node_interrupt) = output.interrupt {
1648                        record(NodeStatus::Paused, None, None);
1649                        // A node that paused itself after its call was approved waits on
1650                        // nothing in the inbox, so the request it was approved for is gone.
1651                        match held {
1652                            Some(held) => {
1653                                self.held.insert(node_name.clone(), held);
1654                            }
1655                            None => {
1656                                self.held.remove(&node_name);
1657                            }
1658                        }
1659                        interrupts.push((node_name, node_interrupt));
1660                        continue;
1661                    }
1662                    record(
1663                        governed_status.unwrap_or(NodeStatus::Done),
1664                        Some(&output.updates),
1665                        None,
1666                    );
1667                    self.held.remove(&node_name);
1668                    result.executed_nodes.push(node_name.clone());
1669
1670                    // Collect custom events
1671                    result.events.extend(output.events);
1672
1673                    // Store result in cache on miss, under the key the lookup used.
1674                    #[cfg(feature = "node-cache")]
1675                    if let Some(cache_key) = miss_keys.get(&node_name)
1676                        && let Some(cache) = self.graph.node_caches.get(&node_name)
1677                    {
1678                        let updates_value = serde_json::to_value(&output.updates)
1679                            .unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
1680                        let ttl = self.graph.cache_policies.get(&node_name).and_then(|p| p.ttl);
1681                        cache.set(cache_key, updates_value, ttl).await;
1682                    }
1683
1684                    step_writes.insert(
1685                        node_name.clone(),
1686                        PendingWrite {
1687                            updates: output.updates.clone(),
1688                            goto: output.goto.clone(),
1689                            goto_parent: output.goto_parent.clone(),
1690                        },
1691                    );
1692                    // A node that named its successors overrides its declared edges.
1693                    if let Some(targets) = output.goto {
1694                        result.goto.insert(node_name.clone(), targets);
1695                    }
1696                    // A node handing control to the graph that holds this one. The
1697                    // run finishes normally; the caller reads this from the outcome.
1698                    if let Some(targets) = output.goto_parent {
1699                        self.goto_parent = Some(targets);
1700                    }
1701
1702                    // Collect updates with their node, so application order can be
1703                    // made independent of which future resolved first.
1704                    result.updates.insert(node_name.clone(), output.updates.clone());
1705                    all_updates.push((node_name.clone(), output.updates));
1706                }
1707                Err(e) => {
1708                    record(
1709                        governed_status.unwrap_or(NodeStatus::Failed),
1710                        None,
1711                        Some(e.to_string()),
1712                    );
1713                    // A refused or failed governed call asks again from the start.
1714                    self.held.remove(&node_name);
1715                    // The retry budget is spent. A handler may record what
1716                    // happened and name a recovery node instead of ending the run.
1717                    // An interrupt never reaches here as a failure.
1718                    match self.graph.error_handler_for(&node_name) {
1719                        Some(handler) if !matches!(e, GraphError::Interrupted(_)) => {
1720                            let recovery = handler(&node_name, &e, &self.state)?;
1721                            step_writes.insert(
1722                                node_name.clone(),
1723                                PendingWrite {
1724                                    updates: recovery.updates.clone(),
1725                                    goto: recovery.goto.clone(),
1726                                    goto_parent: None,
1727                                },
1728                            );
1729                            if let Some(targets) = recovery.goto {
1730                                result.goto.insert(node_name.clone(), targets);
1731                            }
1732                            result.executed_nodes.push(node_name.clone());
1733                            result.updates.insert(node_name.clone(), recovery.updates.clone());
1734                            all_updates.push((node_name, recovery.updates));
1735                        }
1736                        _ => {
1737                            // The first failure in name order is reported; the
1738                            // remaining outputs are still collected as pending writes.
1739                            // An error that already names this node is reported as it
1740                            // is, so a timeout stays a timeout. An agent's failure keeps
1741                            // the agent's error, prefixed with this node's name when it
1742                            // came from a node inside this one, such as a subgraph's.
1743                            if failure.is_none() {
1744                                failure = Some(match e {
1745                                    GraphError::AgentFailed { node: failed, source } => {
1746                                        let node = if failed == node_name {
1747                                            failed
1748                                        } else {
1749                                            format!("{node_name}.{failed}")
1750                                        };
1751                                        GraphError::AgentFailed { node, source }
1752                                    }
1753                                    GraphError::NodeExecutionFailed {
1754                                        node: ref failed, ..
1755                                    }
1756                                    | GraphError::NodeTimedOut { node: ref failed, .. }
1757                                        if *failed == node_name =>
1758                                    {
1759                                        e
1760                                    }
1761                                    other => GraphError::NodeExecutionFailed {
1762                                        node: node_name,
1763                                        message: other.to_string(),
1764                                    },
1765                                });
1766                            }
1767                        }
1768                    }
1769                }
1770            }
1771        }
1772
1773        if let Some(error) = failure {
1774            self.pending_writes = step_writes;
1775            self.record_step(StepKind::Failed, records);
1776            return Err(error);
1777        }
1778        self.pending_writes.clear();
1779
1780        // Apply all updates atomically using reducers.
1781        //
1782        // `buffer_unordered` yields futures as they resolve, so the collected
1783        // order follows timing. A non-commutative reducer — `Append` builds an
1784        // array, so order is the result — would then give a different state for
1785        // the same input depending on which node finished first. Sorting by
1786        // (node, channel) makes the order total and timing-independent: node
1787        // names are unique within a graph, and a node's own updates are held in a
1788        // map whose iteration order is itself unspecified.
1789        all_updates.sort_by(|(left, _), (right, _)| left.cmp(right));
1790        for (node, updates) in all_updates {
1791            let mut keys: Vec<_> = updates.keys().cloned().collect();
1792            keys.sort();
1793            self.ensure_channels_declared(&node, keys.iter().map(String::as_str))?;
1794            for key in keys {
1795                if let Some(value) = updates.get(&key) {
1796                    self.graph.schema.apply_update(&mut self.state, &key, value.clone());
1797                }
1798            }
1799        }
1800
1801        if interrupts.is_empty()
1802            && let Some(gate) = self.gate_after(&result.executed_nodes)
1803        {
1804            interrupts.push(gate);
1805        }
1806        self.count_governed_runs(&result.executed_nodes);
1807        let kind = if interrupts.is_empty() { StepKind::Completed } else { StepKind::Paused };
1808        self.record_step(kind, records);
1809        Ok(SuperStepResult { interrupts, ..result })
1810    }
1811
1812    /// The bracket a governed node's dispatch runs through in this step, or `None` for a
1813    /// node that is not governed.
1814    fn governed_dispatch(&self, name: &str, node: &Arc<dyn Node>) -> Option<GovernedDispatch> {
1815        let governed = *self.graph.governed_nodes.get(name)?;
1816        Some(GovernedDispatch {
1817            node_name: name.to_string(),
1818            node: Arc::clone(node),
1819            governed,
1820            // A governed node that declares nothing is treated as having an effect.
1821            effect: self
1822                .graph
1823                .node_effects
1824                .get(name)
1825                .copied()
1826                .unwrap_or(adk_core::ToolEffect::NonIdempotent),
1827            declaration: self
1828                .graph
1829                .node_shape(name)
1830                .and_then(|shape| serde_json::to_value(shape).ok())
1831                .unwrap_or(serde_json::Value::Null),
1832            root: self.lineage_root(),
1833            run_id: self.run.as_ref().map(|run| run.run_id.clone()).unwrap_or_default(),
1834            occurrence: self.occurrences.get(name).copied().unwrap_or(0) + 1,
1835            // Only the dispatch that resumes the node's own pause binds to its request.
1836            held: if self.paused_nodes.contains(name) {
1837                self.held.get(name).cloned()
1838            } else {
1839                None
1840            },
1841            checkpointer: self.graph.checkpointer.clone(),
1842            thread_id: self.config.thread_id.clone(),
1843            checkpoint_id: self.next_checkpoint_id.clone(),
1844            run_timeout: self.graph.timeout_policy_for(name).and_then(|policy| policy.run_timeout),
1845        })
1846    }
1847
1848    /// The thread this thread's lineage started at: itself, unless it was forked or is a
1849    /// subgraph's run, which takes its parent's.
1850    fn lineage_root(&self) -> String {
1851        match (&self.lineage, &self.config.lineage_root) {
1852            (Some(lineage), _) => lineage.root.clone(),
1853            (None, Some(inherited)) => inherited.clone(),
1854            (None, None) => self.config.thread_id.clone(),
1855        }
1856    }
1857
1858    /// Counts a completed run of each governed node in `executed`, so the next run of
1859    /// the node in this lineage is a new call.
1860    fn count_governed_runs(&mut self, executed: &[String]) {
1861        for node in executed.iter().filter(|node| self.graph.is_governed(node)) {
1862            *self.occurrences.entry(node.clone()).or_insert(0) += 1;
1863        }
1864    }
1865
1866    /// Records the step that is ending, labelled with the step its completed checkpoint
1867    /// carries.
1868    fn record_step(&mut self, kind: StepKind, mut nodes: Vec<NodeRecord>) {
1869        nodes.sort_by(|left, right| left.node.cmp(&right.node));
1870        self.unsaved_steps.push(StepRecord {
1871            step: self.step + 1 + self.label_offset,
1872            kind,
1873            nodes,
1874        });
1875    }
1876
1877    /// Opens a run when none continues: a fresh start, a finished thread that starts
1878    /// again from its entry, or a checkpoint without a run.
1879    fn open_run(&mut self) {
1880        if self.run.is_none() {
1881            let run_id = self.config.parent_context.as_ref().map_or_else(
1882                || uuid::Uuid::new_v4().to_string(),
1883                |parent| parent.invocation_id().to_string(),
1884            );
1885            self.run = Some(RunRecord::new(run_id));
1886        }
1887    }
1888
1889    /// Save a checkpoint
1890    /// Returns the gate a pending node arms, if any.
1891    ///
1892    /// A node whose gate this run has already answered runs instead of
1893    /// interrupting again; without that a resume reaches the same conclusion and
1894    /// the node never executes.
1895    ///
1896    /// Shared by both execution paths. `StreamMode::Messages` runs nodes in its
1897    /// own loop, and when this check lived only in `execute_super_step` that mode
1898    /// ignored every gate.
1899    fn gate_before(&self, pending: &[String]) -> Option<(String, Interrupt)> {
1900        pending
1901            .iter()
1902            .find(|node| {
1903                self.graph.interrupt_before.contains(*node)
1904                    && self.cleared_interrupt.as_deref() != Some(node.as_str())
1905            })
1906            .map(|node| (node.clone(), Interrupt::Before(node.clone())))
1907    }
1908
1909    /// Returns the gate an executed node arms, if any.
1910    fn gate_after(&self, executed: &[String]) -> Option<(String, Interrupt)> {
1911        executed
1912            .iter()
1913            .find(|node| self.graph.interrupt_after.contains(*node))
1914            .map(|node| (node.clone(), Interrupt::After(node.clone())))
1915    }
1916
1917    /// The stream events reporting a paused step: each tool-confirmation pause,
1918    /// then one `Interrupted` event per pause, naming the node it stopped.
1919    /// Refuses the run's resume answers that do not fit the pauses pending in the thread,
1920    /// before any node runs: an answer that does not satisfy its pause's
1921    /// `response_schema`, and under [`ExecutionConfig::strict_resume`] an answer under any
1922    /// key but a pending pause's id.
1923    ///
1924    /// # Errors
1925    ///
1926    /// [`GraphError::ResumeRejected`] naming the key and why.
1927    fn check_resume_answers(&self) -> Result<()> {
1928        let pending: Vec<(&String, &PendingInterrupt)> = self
1929            .pending_interrupts
1930            .iter()
1931            .filter(|(node, _)| self.paused_nodes.contains(*node))
1932            .collect();
1933        if self.config.strict_resume {
1934            for key in self.config.resume_values.keys() {
1935                if pending.iter().any(|(_, interrupt)| interrupt.id == *key) {
1936                    continue;
1937                }
1938                let reason = if pending.iter().any(|(node, _)| *node == key) {
1939                    "a strict resume answers a pause by its interrupt id, not its node's name"
1940                } else {
1941                    "no pause with this id is pending in the thread: it was answered already, \
1942                     or the node asked again with another question"
1943                };
1944                return Err(GraphError::ResumeRejected { key: key.clone(), reason: reason.into() });
1945            }
1946        }
1947        for (node, interrupt) in pending {
1948            let Some(schema) = &interrupt.response_schema else { continue };
1949            let by_node = (!self.config.strict_resume)
1950                .then(|| self.config.resume_values.get(node).map(|answer| (node, answer)))
1951                .flatten();
1952            let Some((key, answer)) = self
1953                .config
1954                .resume_values
1955                .get(&interrupt.id)
1956                .map(|answer| (&interrupt.id, answer))
1957                .or(by_node)
1958            else {
1959                continue;
1960            };
1961            let validator =
1962                jsonschema::validator_for(schema).map_err(|error| GraphError::ResumeRejected {
1963                    key: key.clone(),
1964                    reason: format!(
1965                        "the pause's response_schema is not a valid JSON Schema: {error}"
1966                    ),
1967                })?;
1968            if let Some(error) = validator.iter_errors(answer).next() {
1969                return Err(GraphError::ResumeRejected {
1970                    key: key.clone(),
1971                    reason: format!(
1972                        "the answer does not satisfy the pause's response_schema at '{}': {error}",
1973                        error.instance_path()
1974                    ),
1975                });
1976            }
1977        }
1978        Ok(())
1979    }
1980
1981    fn pause_events(&self, result: &SuperStepResult, checkpoint_id: &str) -> Vec<StreamEvent> {
1982        let mut events: Vec<StreamEvent> = result
1983            .interrupts
1984            .iter()
1985            .filter_map(|(_, interrupt)| {
1986                GraphToolConfirmationPause::from_interrupt(
1987                    interrupt,
1988                    &self.config.thread_id,
1989                    checkpoint_id,
1990                )
1991            })
1992            .map(|pause| {
1993                StreamEvent::custom(
1994                    &pause.node,
1995                    GraphToolConfirmationPause::KIND,
1996                    serde_json::to_value(&pause).unwrap_or(serde_json::Value::Null),
1997                )
1998            })
1999            .collect();
2000        events.extend(result.interrupts.iter().map(|(node, interrupt)| StreamEvent::Interrupted {
2001            node: node.clone(),
2002            message: interrupt.to_string(),
2003            interrupt_id: interrupt.id().map(str::to_string),
2004        }));
2005        events
2006    }
2007
2008    /// Sets the frontier a paused super-step resumes from.
2009    ///
2010    /// | Interrupt | Saved frontier |
2011    /// |-----------|----------------|
2012    /// | `Before` | The frontier that was executing; the gated node produced no updates. |
2013    /// | `After` | The successors of the nodes that ran; the gated node already applied its updates. |
2014    /// | `Dynamic` (including tool confirmation) | The successors of every node that completed, plus each node that paused. |
2015    ///
2016    /// A completed node never re-runs on resume, and its successors and `goto`
2017    /// targets are not lost: they are computed now, while the step's results are
2018    /// still at hand, and arrivals at a fan-in node are recorded for the checkpoint.
2019    ///
2020    /// A node that paused keeps its child-ledger entries, so its children that
2021    /// finished are not run again when it resumes; the nodes that completed drop
2022    /// theirs.
2023    ///
2024    /// # Errors
2025    ///
2026    /// Returns the routing error from [`Self::next_frontier`] or the fan-in error
2027    /// from [`Self::filter_deferred_nodes`].
2028    fn pause_frontier(&mut self, result: &mut SuperStepResult) -> Result<()> {
2029        // Each dynamic pause gets its id, which the caller answers it under and the
2030        // checkpoint keeps with its answer schema.
2031        for (node, interrupt) in &mut result.interrupts {
2032            interrupt.identify(&self.config.thread_id, self.step, node);
2033            if let Some(id) = interrupt.id() {
2034                self.pending_interrupts.insert(
2035                    node.clone(),
2036                    PendingInterrupt {
2037                        id: id.to_string(),
2038                        response_schema: interrupt.response_schema().cloned(),
2039                    },
2040                );
2041            }
2042        }
2043        let executed = &result.executed_nodes;
2044        let Some((_, interrupt)) = result.interrupts.first() else { return Ok(()) };
2045        match interrupt {
2046            Interrupt::Before(node) => {
2047                // Record the gate being answered so the resumed run executes this
2048                // node rather than stopping at it again.
2049                self.cleared_interrupt = Some(node.clone());
2050                return Ok(());
2051            }
2052            Interrupt::After(_) => {
2053                self.pending_nodes = self.advance_frontier(result, &[])?;
2054                self.settle_child_ledger(&[]);
2055            }
2056            Interrupt::Dynamic { .. } => {
2057                let paused: Vec<String> = self
2058                    .pending_nodes
2059                    .iter()
2060                    .filter(|node| !executed.contains(node))
2061                    .cloned()
2062                    .collect();
2063                let mut frontier = self.advance_frontier(result, &paused)?;
2064                self.settle_child_ledger(&paused);
2065                // The nodes that paused; the step that resumes them hands each its
2066                // answer.
2067                self.paused_nodes = paused.iter().cloned().collect();
2068                for node in paused {
2069                    if !frontier.contains(&node) {
2070                        frontier.push(node);
2071                    }
2072                }
2073                self.pending_nodes = frontier;
2074            }
2075        }
2076        // A gate answered earlier re-arms once its node has run, as after an
2077        // uninterrupted step.
2078        if let Some(cleared) = &self.cleared_interrupt
2079            && executed.iter().any(|node| node == cleared)
2080        {
2081            self.cleared_interrupt = None;
2082        }
2083        Ok(())
2084    }
2085
2086    /// Computes the next frontier, letting a node's `goto` stand in for its edges.
2087    ///
2088    /// A node that named successors has its declared edges skipped, so a `goto`
2089    /// replaces an edge rather than adding to one. `END` is accepted and
2090    /// contributes no successor, which is how a branch stops.
2091    ///
2092    /// Returns the frontier and each `(source, target)` route taken, the routes
2093    /// being what a fan-in node counts as arrivals.
2094    ///
2095    /// # Errors
2096    ///
2097    /// Returns [`GraphError::UnknownRouteTarget`] when a `goto` names a node the
2098    /// graph does not hold.
2099    fn next_frontier(
2100        &self,
2101        executed: &[String],
2102        goto: &HashMap<String, Vec<String>>,
2103    ) -> Result<(Vec<String>, Vec<Route>)> {
2104        // A node that routed itself does not also follow its declared edges.
2105        let followed_edges: Vec<String> =
2106            executed.iter().filter(|node| !goto.contains_key(*node)).cloned().collect();
2107        let mut routes = self.graph.routes_from(&followed_edges, &self.state)?;
2108        let mut next: Vec<String> = Vec::new();
2109        for (_, target) in &routes {
2110            if !next.contains(target) {
2111                next.push(target.clone());
2112            }
2113        }
2114
2115        // Sorted, so a multi-target goto admits its nodes in a fixed order.
2116        let mut routed: Vec<(&String, &Vec<String>)> = goto.iter().collect();
2117        routed.sort_by_key(|(node, _)| node.as_str());
2118
2119        for (node, targets) in routed {
2120            for target in targets {
2121                if target == crate::edge::END {
2122                    continue;
2123                }
2124                if self.graph.node(target).is_none() {
2125                    return Err(GraphError::UnknownRouteTarget(format!(
2126                        "node '{node}' routed to '{target}', which is not a node in this graph"
2127                    )));
2128                }
2129                routes.push((node.clone(), target.clone()));
2130                if !next.contains(target) {
2131                    next.push(target.clone());
2132                }
2133            }
2134        }
2135        Ok((next, routes))
2136    }
2137
2138    /// The run's step budget: the config's override, else the graph's own limit.
2139    fn recursion_limit(&self) -> usize {
2140        self.config.recursion_limit.unwrap_or(self.graph.recursion_limit)
2141    }
2142
2143    /// Rejects an update naming a channel the schema does not declare.
2144    ///
2145    /// Inert unless the graph asked for enforcement, and inert when the schema
2146    /// declares no channels, so an existing graph is unaffected either way.
2147    fn ensure_channels_declared<'k>(
2148        &self,
2149        node: &str,
2150        keys: impl IntoIterator<Item = &'k str>,
2151    ) -> Result<()> {
2152        if !self.graph.strict_channels {
2153            return Ok(());
2154        }
2155        match self.graph.schema.first_undeclared(keys) {
2156            Some(channel) => Err(GraphError::UndeclaredChannel {
2157                node: node.to_string(),
2158                channel: channel.to_string(),
2159            }),
2160            None => Ok(()),
2161        }
2162    }
2163
2164    /// Builds the checkpoint of the run as it stands, one version past the head.
2165    fn build_checkpoint(&mut self) -> Checkpoint {
2166        self.head_version += 1;
2167        let mut checkpoint = Checkpoint::new(
2168            &self.config.thread_id,
2169            self.state.clone(),
2170            self.step,
2171            self.pending_nodes.clone(),
2172        )
2173        .with_version(self.head_version);
2174        checkpoint.checkpoint_id =
2175            std::mem::replace(&mut self.next_checkpoint_id, uuid::Uuid::new_v4().to_string());
2176        checkpoint.cleared_interrupt = self.cleared_interrupt.clone();
2177        checkpoint.attempts = self.attempts.clone();
2178        checkpoint.child_ledger = self.child_ledger.lock().expect("child ledger").clone();
2179        checkpoint.pending_writes = self.pending_writes.clone();
2180        // Carried in metadata rather than a field, so every backend persists
2181        // it without a schema change and older checkpoints load as before.
2182        if let Some(snapshot) = FanInSnapshot::capture(
2183            &self.pending_deferred,
2184            &self.deferred_start_times,
2185            &self.abandoned_arrivals,
2186        ) {
2187            checkpoint.metadata.insert(FAN_IN_METADATA_KEY.to_string(), snapshot.to_value());
2188        }
2189        if !self.paused_nodes.is_empty() {
2190            checkpoint.metadata.insert(
2191                PAUSED_NODES_METADATA_KEY.to_string(),
2192                serde_json::to_value(&self.paused_nodes).unwrap_or_default(),
2193            );
2194        }
2195        let pending: BTreeMap<&String, &PendingInterrupt> = self
2196            .pending_interrupts
2197            .iter()
2198            .filter(|(node, _)| self.paused_nodes.contains(*node))
2199            .collect();
2200        if !pending.is_empty() {
2201            checkpoint.metadata.insert(
2202                PENDING_INTERRUPTS_METADATA_KEY.to_string(),
2203                serde_json::to_value(&pending).unwrap_or_default(),
2204            );
2205        }
2206        // Run, step and lineage records (spec 3.3 §12): every step since the last write,
2207        // so a run under `Durability::Exit` keeps the steps it did not checkpoint.
2208        let steps = std::mem::take(&mut self.unsaved_steps);
2209        let records = [
2210            (RUN_METADATA_KEY, self.run.as_ref().map(serde_json::to_value)),
2211            (STEPS_METADATA_KEY, (!steps.is_empty()).then(|| serde_json::to_value(&steps))),
2212            (LINEAGE_METADATA_KEY, self.lineage.as_ref().map(serde_json::to_value)),
2213            (
2214                OCCURRENCES_METADATA_KEY,
2215                (!self.occurrences.is_empty()).then(|| serde_json::to_value(&self.occurrences)),
2216            ),
2217            (HELD_METADATA_KEY, (!self.held.is_empty()).then(|| serde_json::to_value(&self.held))),
2218            (
2219                OPEN_PAUSES_METADATA_KEY,
2220                (!self.open_pauses.is_empty()).then(|| serde_json::to_value(&self.open_pauses)),
2221            ),
2222        ];
2223        for (key, value) in records {
2224            if let Some(Ok(value)) = value {
2225                checkpoint.metadata.insert(key.to_string(), value);
2226            }
2227        }
2228        checkpoint
2229    }
2230
2231    /// Writes the checkpoint of a pause, listed among the thread's open pauses so
2232    /// retention keeps it until a run resumes it.
2233    async fn save_pause_checkpoint(&mut self) -> Result<String> {
2234        self.open_pauses.insert(self.next_checkpoint_id.clone());
2235        self.save_checkpoint().await
2236    }
2237
2238    /// Writes the run's checkpoint now, after any background write finishes.
2239    async fn save_checkpoint(&mut self) -> Result<String> {
2240        self.await_inflight().await?;
2241        let Some(cp) = self.graph.checkpointer.clone() else { return Ok(String::new()) };
2242        let checkpoint = self.build_checkpoint();
2243        self.unsaved = false;
2244        write_checkpoint(cp, self.graph.retention.clone(), checkpoint).await
2245    }
2246
2247    /// Checkpoints a completed super-step as the run's durability mode asks.
2248    async fn checkpoint_step(&mut self) -> Result<()> {
2249        let Some(cp) = self.graph.checkpointer.clone() else { return Ok(()) };
2250        match self.config.durability {
2251            Durability::Sync => {
2252                self.save_checkpoint().await?;
2253            }
2254            Durability::Async => {
2255                // One write at a time, so versions reach the store in order.
2256                self.await_inflight().await?;
2257                let checkpoint = self.build_checkpoint();
2258                self.unsaved = false;
2259                self.inflight = Some(tokio::spawn(write_checkpoint(
2260                    cp,
2261                    self.graph.retention.clone(),
2262                    checkpoint,
2263                )));
2264            }
2265            Durability::Exit => self.unsaved = true,
2266        }
2267        Ok(())
2268    }
2269
2270    /// Waits for a background checkpoint write and reports its failure.
2271    async fn await_inflight(&mut self) -> Result<()> {
2272        if let Some(handle) = self.inflight.take() {
2273            handle.await.map_err(|error| {
2274                GraphError::CheckpointError(format!("background checkpoint write failed: {error}"))
2275            })??;
2276        }
2277        Ok(())
2278    }
2279
2280    /// Makes every completed super-step durable before the run returns.
2281    async fn finish_checkpoints(&mut self) -> Result<()> {
2282        self.await_inflight().await?;
2283        if self.unsaved {
2284            self.save_checkpoint().await?;
2285        }
2286        Ok(())
2287    }
2288
2289    /// Writes every earlier checkpoint before a super-step that runs a
2290    /// non-idempotent node, so a crash during its side effect cannot resume from
2291    /// before an earlier step and repeat that step.
2292    async fn flush_before_side_effects(&mut self) -> Result<()> {
2293        let side_effecting = self.pending_nodes.iter().any(|node| {
2294            self.graph.node_effects.get(node) == Some(&adk_core::ToolEffect::NonIdempotent)
2295                || self.graph.is_governed(node)
2296        });
2297        if side_effecting {
2298            self.finish_checkpoints().await?;
2299        }
2300        Ok(())
2301    }
2302
2303    /// Checkpoints a super-step that failed.
2304    ///
2305    /// The frontier still holds the failed node, so the run resumes at this step:
2306    /// the retry budget already spent is not handed out again, and the nodes that
2307    /// finished are answered from their pending writes instead of re-running. The
2308    /// checkpoint carries the failed step's record, so an observer sees that the run
2309    /// failed rather than a run still working (spec 3.3 §12). A failure to write is
2310    /// logged, not raised, so the node's own error is reported.
2311    async fn checkpoint_failed_step(&mut self) {
2312        let result = self.save_checkpoint().await.map(drop);
2313        if let Err(error) = result {
2314            tracing::warn!(
2315                thread_id = %self.config.thread_id,
2316                step = self.step,
2317                error = %error,
2318                "failed to checkpoint a failing super-step; a resumed run repeats its work"
2319            );
2320        }
2321    }
2322}
2323
2324/// What a predecessor hands a fan-in node: the value it wrote to a channel named
2325/// after itself, or else every update it wrote.
2326///
2327/// Never the whole state: in a loop the state holds the previous pass's
2328/// `{node}_fan_in`, so an arrival that embedded it would double each pass.
2329fn arrival_output(
2330    node: &str,
2331    updates: Option<&HashMap<String, serde_json::Value>>,
2332) -> serde_json::Value {
2333    let Some(updates) = updates else { return serde_json::Value::Object(serde_json::Map::new()) };
2334    if let Some(value) = updates.get(node) {
2335        return value.clone();
2336    }
2337    let mut keys: Vec<&String> = updates.keys().collect();
2338    keys.sort();
2339    serde_json::Value::Object(
2340        keys.into_iter().map(|key| (key.clone(), updates[key].clone())).collect(),
2341    )
2342}
2343
2344/// A node's record in a step, with the keys of `writes` sorted.
2345fn node_record(
2346    node: &str,
2347    started_at: chrono::DateTime<chrono::Utc>,
2348    duration_ms: u64,
2349    status: NodeStatus,
2350    writes: Option<&HashMap<String, serde_json::Value>>,
2351    attempt: u32,
2352) -> NodeRecord {
2353    let mut writes: Vec<String> = writes.map(|w| w.keys().cloned().collect()).unwrap_or_default();
2354    writes.sort();
2355    NodeRecord {
2356        node: node.to_string(),
2357        started_at,
2358        duration_ms,
2359        status,
2360        writes,
2361        attempt,
2362        effect_key: None,
2363        error: None,
2364    }
2365}
2366
2367/// Reads one metadata key of `checkpoint`, `None` when it is absent.
2368fn read_metadata<T: serde::de::DeserializeOwned>(
2369    checkpoint: &Checkpoint,
2370    key: &str,
2371) -> Result<Option<T>> {
2372    checkpoint
2373        .metadata
2374        .get(key)
2375        .map(|value| serde_json::from_value(value.clone()))
2376        .transpose()
2377        .map_err(|error| {
2378            GraphError::SerializationError(format!(
2379                "checkpoint metadata '{key}' is malformed: {error}"
2380            ))
2381        })
2382}
2383
2384/// Every node reachable along `successors` from `sources`, the sources included,
2385/// never entering a node `blocked` rejects.
2386fn reachable_from<'g>(
2387    sources: impl Iterator<Item = &'g str>,
2388    successors: &HashMap<&'g str, Vec<&'g str>>,
2389    blocked: &impl Fn(&str) -> bool,
2390) -> std::collections::HashSet<&'g str> {
2391    let mut seen: std::collections::HashSet<&'g str> = std::collections::HashSet::new();
2392    let mut queue: Vec<&'g str> = sources.collect();
2393    while let Some(node) = queue.pop() {
2394        if !seen.insert(node) {
2395            continue;
2396        }
2397        for next in successors.get(node).into_iter().flatten() {
2398            if !blocked(next) && !seen.contains(next) {
2399                queue.push(next);
2400            }
2401        }
2402    }
2403    seen
2404}
2405
2406/// Starts a new attempt of the node `ctx` belongs to.
2407///
2408/// Children are numbered per attempt, so a retried parent asks for the same
2409/// children under the same identities and is served those that finished.
2410pub(crate) fn begin_attempt(ctx: &NodeContext) {
2411    if let Some(invoker) = ctx.child_invoker() {
2412        invoker.begin_attempt();
2413    }
2414}
2415
2416/// Saves a checkpoint, then trims the thread to its retention policy.
2417async fn write_checkpoint(
2418    cp: Arc<dyn crate::checkpoint::Checkpointer>,
2419    retention: Option<crate::checkpoint::RetentionPolicy>,
2420    checkpoint: Checkpoint,
2421) -> Result<String> {
2422    let id = cp.save(&checkpoint).await?;
2423    // Trimmed as the run proceeds, so the cost stays proportional to the run
2424    // and no external job is needed. After the save, so the newest counts.
2425    if let Some(policy) = &retention {
2426        let removed = cp.prune(&checkpoint.thread_id, policy).await?;
2427        if removed > 0 {
2428            tracing::debug!(thread_id = %checkpoint.thread_id, removed, "pruned old checkpoints");
2429        }
2430    }
2431    Ok(id)
2432}
2433
2434/// Convenience methods for CompiledGraph
2435impl CompiledGraph {
2436    /// Execute the graph synchronously
2437    pub async fn invoke(&self, input: State, config: ExecutionConfig) -> Result<State> {
2438        self.invoke_detailed(input, config).await.map(|outcome| outcome.state)
2439    }
2440
2441    /// Execute with ADK run configuration for agents inside a directly run graph.
2442    ///
2443    /// Use this to resume a tool-confirmation pause with decisions in
2444    /// [`adk_core::RunConfig`]. Existing [`Self::invoke`] callers remain
2445    /// standalone and use default ADK run configuration.
2446    pub async fn invoke_with_run_config(
2447        &self,
2448        input: State,
2449        config: ExecutionConfig,
2450        run_config: adk_core::RunConfig,
2451    ) -> Result<State> {
2452        let mut executor = PregelExecutor::new_with_run_config(self, config, Some(run_config));
2453        executor.run(input).await
2454    }
2455
2456    /// Executes and reports what the run asked of its caller.
2457    ///
2458    /// Only a graph run as a [`SubgraphNode`](crate::subgraph::SubgraphNode) has
2459    /// anything to report beyond its state, so [`Self::invoke`] is the usual
2460    /// entry point.
2461    pub async fn invoke_detailed(
2462        &self,
2463        input: State,
2464        config: ExecutionConfig,
2465    ) -> Result<GraphOutcome> {
2466        let mut executor = PregelExecutor::new(self, config);
2467        let state = executor.run(input).await?;
2468        Ok(GraphOutcome { state, goto_parent: executor.goto_parent })
2469    }
2470
2471    /// Execute with run configuration and retain a subgraph's parent routing outcome.
2472    pub async fn invoke_detailed_with_run_config(
2473        &self,
2474        input: State,
2475        config: ExecutionConfig,
2476        run_config: adk_core::RunConfig,
2477    ) -> Result<GraphOutcome> {
2478        let mut executor = PregelExecutor::new_with_run_config(self, config, Some(run_config));
2479        let state = executor.run(input).await?;
2480        Ok(GraphOutcome { state, goto_parent: executor.goto_parent })
2481    }
2482
2483    /// Execute with streaming
2484    pub fn stream(
2485        &self,
2486        input: State,
2487        config: ExecutionConfig,
2488        mode: StreamMode,
2489    ) -> impl futures::Stream<Item = Result<StreamEvent>> + '_ {
2490        tracing::debug!("CompiledGraph::stream called with mode {:?}", mode);
2491        let executor = PregelExecutor::new(self, config);
2492        executor.run_stream(input, mode)
2493    }
2494
2495    /// Stream with ADK run configuration for agents inside a directly run graph.
2496    ///
2497    /// A resumed tool-confirmation request can be approved or denied by passing
2498    /// [`adk_core::RunConfig::tool_confirmation_decisions`].
2499    pub fn stream_with_run_config(
2500        &self,
2501        input: State,
2502        config: ExecutionConfig,
2503        mode: StreamMode,
2504        run_config: adk_core::RunConfig,
2505    ) -> impl futures::Stream<Item = Result<StreamEvent>> + '_ {
2506        tracing::debug!("CompiledGraph::stream_with_run_config called with mode {:?}", mode);
2507        let executor = PregelExecutor::new_with_run_config(self, config, Some(run_config));
2508        executor.run_stream(input, mode)
2509    }
2510
2511    /// Get current state for a thread
2512    pub async fn get_state(&self, thread_id: &str) -> Result<Option<State>> {
2513        if let Some(cp) = &self.checkpointer {
2514            Ok(cp.load(thread_id).await?.map(|c| c.state))
2515        } else {
2516            Ok(None)
2517        }
2518    }
2519
2520    /// Update state for a thread (for human-in-the-loop)
2521    pub async fn update_state(
2522        &self,
2523        thread_id: &str,
2524        updates: impl IntoIterator<Item = (String, serde_json::Value)>,
2525    ) -> Result<()> {
2526        if let Some(cp) = &self.checkpointer
2527            && let Some(checkpoint) = cp.load(thread_id).await?
2528        {
2529            let mut open_pauses = checkpoint.open_pauses()?;
2530            let revised = checkpoint.checkpoint_id.clone();
2531            let mut state = checkpoint.state;
2532            for (key, value) in updates {
2533                self.schema.apply_update(&mut state, &key, value);
2534            }
2535            let mut new_checkpoint =
2536                Checkpoint::new(thread_id, state, checkpoint.step, checkpoint.pending_nodes)
2537                    .with_version(checkpoint.version + 1);
2538            // Everything a resume restores carries over, so editing state between
2539            // a pause and its resume keeps the answered gate, the retry budget,
2540            // finished children, and the arrivals a waiting join has recorded.
2541            new_checkpoint.cleared_interrupt = checkpoint.cleared_interrupt;
2542            new_checkpoint.attempts = checkpoint.attempts;
2543            new_checkpoint.child_ledger = checkpoint.child_ledger;
2544            new_checkpoint.pending_writes = checkpoint.pending_writes;
2545            for key in CARRIED_METADATA_KEYS {
2546                if let Some(value) = checkpoint.metadata.get(key) {
2547                    new_checkpoint.metadata.insert(key.to_string(), value.clone());
2548                }
2549            }
2550            // The revision of a pause is that pause now: resuming the thread resumes it.
2551            for id in &mut open_pauses {
2552                if *id == revised {
2553                    id.clone_from(&new_checkpoint.checkpoint_id);
2554                }
2555            }
2556            if !open_pauses.is_empty() {
2557                new_checkpoint.metadata.insert(
2558                    OPEN_PAUSES_METADATA_KEY.to_string(),
2559                    serde_json::to_value(&open_pauses)?,
2560                );
2561            }
2562            cp.save(&new_checkpoint).await?;
2563        }
2564        Ok(())
2565    }
2566}
2567
2568#[cfg(test)]
2569mod tests {
2570    use super::*;
2571    use crate::edge::{END, START};
2572    use crate::graph::StateGraph;
2573    use crate::node::NodeOutput;
2574    use serde_json::json;
2575
2576    #[tokio::test]
2577    async fn test_simple_execution() {
2578        let graph = StateGraph::with_channels(&["value"])
2579            .add_node_fn("set_value", |_ctx| async {
2580                Ok(NodeOutput::new().with_update("value", json!(42)))
2581            })
2582            .add_edge(START, "set_value")
2583            .add_edge("set_value", END)
2584            .compile()
2585            .unwrap();
2586
2587        let result = graph.invoke(State::new(), ExecutionConfig::new("test")).await.unwrap();
2588
2589        assert_eq!(result.get("value"), Some(&json!(42)));
2590    }
2591
2592    #[tokio::test]
2593    async fn test_sequential_execution() {
2594        let graph = StateGraph::with_channels(&["value"])
2595            .add_node_fn("step1", |_ctx| async {
2596                Ok(NodeOutput::new().with_update("value", json!(1)))
2597            })
2598            .add_node_fn("step2", |ctx| async move {
2599                let current = ctx.get("value").and_then(|v| v.as_i64()).unwrap_or(0);
2600                Ok(NodeOutput::new().with_update("value", json!(current + 10)))
2601            })
2602            .add_edge(START, "step1")
2603            .add_edge("step1", "step2")
2604            .add_edge("step2", END)
2605            .compile()
2606            .unwrap();
2607
2608        let result = graph.invoke(State::new(), ExecutionConfig::new("test")).await.unwrap();
2609
2610        assert_eq!(result.get("value"), Some(&json!(11)));
2611    }
2612
2613    #[tokio::test]
2614    async fn test_conditional_routing() {
2615        let graph = StateGraph::with_channels(&["path", "result"])
2616            .add_node_fn("router", |ctx| async move {
2617                let path = ctx.get("path").and_then(|v| v.as_str()).unwrap_or("a");
2618                Ok(NodeOutput::new().with_update("route", json!(path)))
2619            })
2620            .add_node_fn("path_a", |_ctx| async {
2621                Ok(NodeOutput::new().with_update("result", json!("went to A")))
2622            })
2623            .add_node_fn("path_b", |_ctx| async {
2624                Ok(NodeOutput::new().with_update("result", json!("went to B")))
2625            })
2626            .add_edge(START, "router")
2627            .add_conditional_edges(
2628                "router",
2629                |state| state.get("route").and_then(|v| v.as_str()).unwrap_or(END).to_string(),
2630                [("a", "path_a"), ("b", "path_b"), (END, END)],
2631            )
2632            .add_edge("path_a", END)
2633            .add_edge("path_b", END)
2634            .compile()
2635            .unwrap();
2636
2637        // Test path A
2638        let mut input = State::new();
2639        input.insert("path".to_string(), json!("a"));
2640        let result = graph.invoke(input, ExecutionConfig::new("test")).await.unwrap();
2641        assert_eq!(result.get("result"), Some(&json!("went to A")));
2642
2643        // Test path B
2644        let mut input = State::new();
2645        input.insert("path".to_string(), json!("b"));
2646        let result = graph.invoke(input, ExecutionConfig::new("test")).await.unwrap();
2647        assert_eq!(result.get("result"), Some(&json!("went to B")));
2648    }
2649
2650    #[tokio::test]
2651    async fn test_cycle_with_limit() {
2652        let graph = StateGraph::with_channels(&["count"])
2653            .add_node_fn("increment", |ctx| async move {
2654                let count = ctx.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
2655                Ok(NodeOutput::new().with_update("count", json!(count + 1)))
2656            })
2657            .add_edge(START, "increment")
2658            .add_conditional_edges(
2659                "increment",
2660                |state| {
2661                    let count = state.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
2662                    if count < 5 { "increment".to_string() } else { END.to_string() }
2663                },
2664                [("increment", "increment"), (END, END)],
2665            )
2666            .compile()
2667            .unwrap();
2668
2669        let result = graph.invoke(State::new(), ExecutionConfig::new("test")).await.unwrap();
2670
2671        assert_eq!(result.get("count"), Some(&json!(5)));
2672    }
2673
2674    #[tokio::test]
2675    async fn test_recursion_limit() {
2676        let graph = StateGraph::with_channels(&["count"])
2677            .add_node_fn("loop", |ctx| async move {
2678                let count = ctx.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
2679                Ok(NodeOutput::new().with_update("count", json!(count + 1)))
2680            })
2681            .add_edge(START, "loop")
2682            .add_edge("loop", "loop") // Infinite loop
2683            .compile()
2684            .unwrap()
2685            .with_recursion_limit(10);
2686
2687        let result = graph.invoke(State::new(), ExecutionConfig::new("test")).await;
2688
2689        // The recursion limit check happens when step >= limit, so it will exceed at step 10
2690        assert!(
2691            matches!(result, Err(GraphError::RecursionLimitExceeded(_))),
2692            "Expected RecursionLimitExceeded error, got: {:?}",
2693            result
2694        );
2695    }
2696}