gadk_engine/workflow/state.rs
1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! `NodeStatus`, `NodeState` and `RunState`.
17
18use std::collections::{HashMap, HashSet};
19
20use serde_json::{Map, Value};
21
22/// The lifecycle status of a node in the workflow graph.
23///
24/// The status is the engine's single source of truth for what a node is doing. It mediates
25/// between the trigger buffer (what wants to run), the in-process task table (what is currently
26/// running), and the persisted node history (what has run).
27#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
28pub enum NodeStatus {
29 /// The node has not been touched yet. This is the zero value.
30 #[default]
31 Inactive,
32 /// The node is ready to run. It may be queued because its input has arrived (consumed from
33 /// the trigger buffer) or because it is being retried after a failure. The scheduler may keep
34 /// a pending node from starting if the engine's max-concurrency cap is reached.
35 Pending,
36 /// The engine has started a task for this node. The task is in flight in the current
37 /// process. A running entry that has no live task in the run state (e.g. after a process
38 /// restart) must be re-scheduled.
39 Running,
40 /// The node finished and produced its output. This is a terminal status for normal
41 /// execution, but a completed node may still be re-triggered by a fresh entry in the trigger
42 /// buffer (this is what enables loops as graph cycles).
43 Completed,
44 /// The node is paused. Two cases share this status: human-in-the-loop (the node yielded a
45 /// RequestInput and is blocked until a function-response payload resumes it), and fan-in
46 /// (`wait_for_output`, e.g. JoinNode: the node ran but did not yet produce its final output
47 /// because not all predecessors have triggered it). While any node is waiting the workflow
48 /// does not finalize.
49 Waiting,
50 /// The node returned an error and the retry policy (if any) has been exhausted. Terminal.
51 Failed,
52 /// The node was cancelled: either because a sibling node failed and the engine cancelled all
53 /// running tasks, or because the invocation was cancelled from outside the engine. Terminal in
54 /// both cases — the two are told apart by whether the run reports an error, not by this status.
55 Cancelled,
56}
57
58/// The per-node lifecycle record. A [`RunState`] holds one of
59/// these for every node the engine has touched.
60#[derive(Debug, Clone, Default)]
61pub struct NodeState {
62 /// The current lifecycle position.
63 pub status: NodeStatus,
64 /// The value most recently handed to the node's `run`. Set when the node is scheduled.
65 pub input: Option<Value>,
66 /// The value the node emitted via the event output. Set when status transitions to
67 /// `Completed`.
68 pub output: Option<Value>,
69 /// The name of the upstream node that produced the current input. Empty for the initial
70 /// START activation.
71 pub triggered_by: String,
72 /// The composite branch string assigned to this activation at scheduling time. Empty for
73 /// nodes that inherit the root branch (single-successor chains); populated for nodes scheduled
74 /// after a fan-out and for JoinNodes resolving the common branch prefix of their predecessors.
75 /// Persisted so resume can reconstruct the same branch tree on re-entry.
76 pub branch: String,
77 /// The long-running tool call IDs the node is waiting on; lets resume match a human's
78 /// FunctionResponse to the node. Non-empty for a node waiting on long-running interrupts, and
79 /// also while status is `Pending` for a partially resumed re-entry node. A node parked by
80 /// `wait_for_output` reaches `Waiting` with this field empty.
81 pub interrupts: Vec<String>,
82 /// The number of times this node has failed.
83 pub attempt: i32,
84 /// Accumulated response payloads for re-entry-mode nodes that yield RequestInput more than
85 /// once during a single activation lifecycle, keyed by interrupt ID. Cleared when the node
86 /// transitions to `Completed`; `None` for handoff-mode nodes.
87 pub resumed_inputs: Option<Map<String, Value>>,
88 /// Maps an interrupt ID to its declared response schema, re-extracted from the pause event
89 /// during rehydration. Not persisted; consumed by resume to validate the payload.
90 pub(crate) interrupt_schemas: HashMap<String, Value>,
91 /// True when this node's interrupt was resolved by a user response that appeared in history
92 /// for the first time on the current resume turn. Not persisted; rebuilt each turn.
93 pub(crate) answered_this_turn: bool,
94}
95
96/// The per-invocation lifecycle state for a workflow run. A resume
97/// turn rebuilds it by scanning session event history.
98#[derive(Debug, Clone, Default)]
99pub struct RunState {
100 /// The per-node lifecycle map. Absent entries are inactive.
101 pub nodes: HashMap<String, NodeState>,
102 /// Names of nodes that already produced an output in session history. Reconstructed from
103 /// history and used by resume for idempotency. Not persisted.
104 pub(crate) completed: HashSet<String>,
105}
106
107impl RunState {
108 /// An empty state.
109 pub fn new() -> Self {
110 Self::default()
111 }
112
113 /// The `NodeState` for `name`, creating an inactive entry if
114 /// none exists. The returned reference may be mutated in place.
115 pub fn ensure_node(&mut self, name: &str) -> &mut NodeState {
116 self.nodes.entry(name.to_owned()).or_default()
117 }
118}