Skip to main content

rusty_agent_runtime/
node.rs

1//! Node abstractions: the unit of computation in the graph.
2//!
3//! A node is an async computation that:
4//!
5//! 1. Receives a [`NodeContext`] — an **immutable snapshot** of the shared
6//!    state as of the start of the current super-step, plus run configuration
7//!    and interrupt/resume helpers.
8//! 2. Returns a [`NodeOutput`] — a *partial* state update (never the whole
9//!    state) plus an optional [`Command`] for dynamic routing.
10//!
11//! Because nodes only ever see the snapshot from the super-step start, nodes
12//! running in the same super-step can never observe each other's writes —
13//! the barrier is what makes shared-state parallelism safe.
14//!
15//! Any async closure `Fn(NodeContext) -> impl Future<Output = Result<NodeOutput>>`
16//! automatically implements [`Node`] via a blanket impl.
17
18use std::collections::HashMap;
19use std::future::Future;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25
26use crate::effects::EffectAdmissionContext;
27use crate::error::{Result, RustyError};
28use crate::middleware::MiddlewareChain;
29use crate::state::State;
30
31/// Per-run, per-node configuration handed to every node invocation.
32///
33/// This is a deliberately small, cloneable value (the LangGraph analog is
34/// `RunnableConfig` + `Runtime`). It is constructed fresh by the executor at
35/// each super-step and embedded in the [`NodeContext`].
36#[derive(Debug, Clone, Default, Serialize, Deserialize)]
37pub struct NodeConfig {
38    /// The thread (session) this run belongs to. Stable across interrupts
39    /// and resumes; namespacing for checkpoints.
40    pub thread_id: String,
41
42    /// Zero-based index of the current super-step. Useful for logging,
43    /// `remaining_steps`-style degradation, and idempotency keys.
44    pub step: usize,
45
46    /// The resume value supplied by the caller when resuming from an
47    /// interrupt (`RunConfig::resume` / `Command::resume`).
48    ///
49    /// Protocol (mirrors LangGraph): a node that previously called
50    /// `interrupt(payload)` is **re-executed from its start**; on the resume
51    /// run, this field carries the caller's value and
52    /// [`NodeContext::resume_value`] returns `Some`. Nodes must therefore be
53    /// idempotent with respect to side effects performed before the
54    /// `interrupt()` call.
55    pub resume: Option<Value>,
56
57    /// Free-form extension point (tags, tracing metadata, user config).
58    #[serde(default)]
59    pub extra: HashMap<String, Value>,
60}
61
62/// The input to every node invocation.
63///
64/// The state snapshot is cloned per node invocation, so snapshot isolation
65/// is structural, not conventional: nodes running in the same super-step
66/// each hold their own owned snapshot and can never observe each other's
67/// writes.
68#[derive(Debug, Clone)]
69pub struct NodeContext {
70    state: State,
71    config: NodeConfig,
72    middleware: MiddlewareChain,
73    effect_admission: Option<EffectAdmissionContext>,
74}
75
76impl NodeContext {
77    /// Build a context from a state snapshot and config. Primarily used by
78    /// the executor; tests may construct it directly. Carries no middleware
79    /// chain — see [`NodeContext::with_middleware`].
80    pub fn new(state: State, config: NodeConfig) -> Self {
81        Self {
82            state,
83            config,
84            middleware: MiddlewareChain::new(),
85            effect_admission: None,
86        }
87    }
88
89    /// The immutable state snapshot as of the start of this super-step.
90    pub fn state(&self) -> &State {
91        &self.state
92    }
93
94    /// The run configuration for this invocation.
95    pub fn config(&self) -> &NodeConfig {
96        &self.config
97    }
98
99    /// Builder-style: attach the run's middleware chain. The executor sets
100    /// this when layers are registered; empty otherwise.
101    pub fn with_middleware(mut self, chain: MiddlewareChain) -> Self {
102        self.middleware = chain;
103        self
104    }
105
106    /// The middleware chain attached to the run's executor (Middleware /
107    /// Interceptor SDK). Node code uses it to propagate interception into
108    /// the boundaries it controls: hand it to
109    /// [`crate::tool::ToolExecutor::with_middleware`] or wrap models in
110    /// [`crate::middleware::MiddlewareChatModel`]. Empty when the executor
111    /// has no layers.
112    pub fn middleware(&self) -> &MiddlewareChain {
113        &self.middleware
114    }
115
116    /// The run-scoped effect boundary attached by an executor that enabled
117    /// admission enforcement. Nodes dispatching tools should pass this to
118    /// [`crate::tool::ToolExecutor::with_effect_admission`]. The prebuilt
119    /// ReAct tools node does so automatically.
120    pub fn effect_admission(&self) -> Option<&EffectAdmissionContext> {
121        self.effect_admission.as_ref()
122    }
123
124    /// Builder-style: attach a run-scoped effect admission boundary.
125    pub fn with_effect_admission(mut self, context: EffectAdmissionContext) -> Self {
126        self.effect_admission = Some(context);
127        self
128    }
129
130    pub(crate) fn with_optional_effect_admission(
131        mut self,
132        context: Option<EffectAdmissionContext>,
133    ) -> Self {
134        self.effect_admission = context;
135        self
136    }
137
138    /// The current thread id (shortcut for `config().thread_id`).
139    pub fn thread_id(&self) -> &str {
140        &self.config.thread_id
141    }
142
143    /// The current super-step index (shortcut for `config().step`).
144    pub fn step(&self) -> usize {
145        self.config.step
146    }
147
148    /// The resume value, if this run is resuming from an interrupt.
149    ///
150    /// Typical pattern inside a resumable node:
151    ///
152    /// ```
153    /// use rusty_agent_runtime::node::{NodeConfig, NodeContext};
154    /// use rusty_agent_runtime::state::State;
155    /// use serde_json::{json, Value};
156    ///
157    /// # fn pattern(ctx: NodeContext) -> rusty_agent_runtime::error::Result<Value> {
158    /// let approved = match ctx.resume_value() {
159    ///     Some(v) => v.clone(),            // resumed: interrupt() "returns" v
160    ///     None => return Err(ctx.interrupt(json!({"question": "approve?"}))),
161    /// };
162    /// # Ok(approved)
163    /// # }
164    /// # let ctx = NodeContext::new(State::new(), NodeConfig::default());
165    /// # assert!(pattern(ctx).unwrap_err().is_interrupt());
166    /// ```
167    pub fn resume_value(&self) -> Option<&Value> {
168        self.config.resume.as_ref()
169    }
170
171    /// Build the interrupt error for a payload.
172    ///
173    /// Returning `Err(ctx.interrupt(payload))` from a node suspends the whole
174    /// run — not just this node. The super-step is transactional: no write of
175    /// the in-flight step survives, not even from sibling nodes that already
176    /// completed. The executor therefore persists a checkpoint that
177    /// re-schedules the **entire active set** of the suspended step — the
178    /// interrupting node plus all of its siblings — and surfaces `payload` in
179    /// [`crate::executor::ExecutionOutcome::Interrupted`]. On resume, every
180    /// node of that set re-executes from its start (node logic must be
181    /// idempotent), with [`NodeContext::resume_value`] set for the first
182    /// super-step.
183    pub fn interrupt(&self, value: Value) -> RustyError {
184        RustyError::Interrupt { value }
185    }
186}
187
188/// The output of a node: partial state updates plus optional dynamic routing.
189#[derive(Debug, Clone, Default)]
190pub struct NodeOutput {
191    /// Partial updates to merge into shared state at the barrier, keyed by
192    /// channel name. Merge semantics come from the channel's
193    /// [`crate::state::Reducer`]. Nodes **must not** return whole state.
194    pub updates: HashMap<String, Value>,
195
196    /// Optional dynamic routing decision (overrides static edges).
197    ///
198    /// `Some(Command::default())` is a no-op in disguise (see
199    /// [`Command::is_noop`]); prefer `None` for "no override".
200    pub command: Option<Command>,
201}
202
203impl NodeOutput {
204    /// An output with no updates and no routing override.
205    pub fn empty() -> Self {
206        Self::default()
207    }
208
209    /// An output carrying a single channel update.
210    pub fn update(channel: impl Into<String>, value: Value) -> Self {
211        let mut updates = HashMap::new();
212        updates.insert(channel.into(), value);
213        Self {
214            updates,
215            command: None,
216        }
217    }
218
219    /// An output carrying multiple channel updates.
220    pub fn updates(updates: HashMap<String, Value>) -> Self {
221        Self {
222            updates,
223            command: None,
224        }
225    }
226
227    /// Alias for [`NodeOutput::updates`] that reads better next to
228    /// [`NodeOutput::update`] / [`NodeOutput::with_update`].
229    pub fn from_updates(updates: HashMap<String, Value>) -> Self {
230        Self::updates(updates)
231    }
232
233    /// An output that only routes (no state updates).
234    ///
235    /// Note that [`Command::default`] is a no-op ([`Command::is_noop`]);
236    /// wrapping one in `Some` here is accepted but has no effect.
237    pub fn route(command: Command) -> Self {
238        Self {
239            updates: HashMap::new(),
240            command: Some(command),
241        }
242    }
243
244    /// Builder-style: attach a routing command.
245    pub fn with_command(mut self, command: Command) -> Self {
246        self.command = Some(command);
247        self
248    }
249
250    /// Builder-style: add one channel update.
251    pub fn with_update(mut self, channel: impl Into<String>, value: Value) -> Self {
252        self.updates.insert(channel.into(), value);
253        self
254    }
255}
256
257/// Dynamic routing + resume directive, unifying state transition and control
258/// flow (the LangGraph `Command`).
259#[derive(Debug, Clone, Default, Serialize, Deserialize)]
260pub struct Command {
261    /// Nodes to activate in the next super-step, overriding the static edge
262    /// set. Names must resolve to graph nodes (validated by the executor).
263    ///
264    /// An empty `goto` with no other information means "no routing override".
265    #[serde(default)]
266    pub goto: Vec<String>,
267
268    /// A resume value. As **input** (`RunConfig::resume`) this is the only
269    /// valid Command pattern: it supplies the value an interrupted node's
270    /// `interrupt()` logically returns.
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub resume: Option<Value>,
273}
274
275impl Command {
276    /// Route to a single node next.
277    pub fn goto(node: impl Into<String>) -> Self {
278        Self {
279            goto: vec![node.into()],
280            resume: None,
281        }
282    }
283
284    /// Route to multiple nodes (parallel activation) next.
285    pub fn goto_many<I, S>(nodes: I) -> Self
286    where
287        I: IntoIterator<Item = S>,
288        S: Into<String>,
289    {
290        Self {
291            goto: nodes.into_iter().map(Into::into).collect(),
292            resume: None,
293        }
294    }
295
296    /// A resume directive (used as run input after an interrupt).
297    pub fn resume(value: Value) -> Self {
298        Self {
299            goto: Vec::new(),
300            resume: Some(value),
301        }
302    }
303
304    /// `true` if this command carries no routing override and no resume
305    /// value — i.e. `Command::default()`. Consumers can use this to treat
306    /// `Some(noop)` the same as `None`.
307    pub fn is_noop(&self) -> bool {
308        self.goto.is_empty() && self.resume.is_none()
309    }
310}
311
312/// The node trait: an async unit of computation over shared state.
313///
314/// Implement this directly for stateful nodes, or just pass an async closure
315/// to [`crate::graph::GraphBuilder::add_node`] — a blanket impl covers any
316/// `Fn(NodeContext) -> impl Future<Output = Result<NodeOutput>> + Send + Sync`.
317///
318/// **Contract** (enforced by the executor, documented here):
319///
320/// - Nodes read state **only** from [`NodeContext::state`] (the super-step
321///   snapshot) and express all state changes via [`NodeOutput::updates`].
322/// - Node logic must be **idempotent**: on interrupt-resume or
323///   partial-failure recovery the node re-executes from its start.
324#[async_trait]
325pub trait Node: Send + Sync {
326    /// Human/log-friendly name. Closure nodes default to `"anonymous"`;
327    /// the graph tracks nodes by the name given to `add_node`, which is the
328    /// authoritative identity.
329    fn name(&self) -> &str {
330        "anonymous"
331    }
332
333    /// The declared default effect classification of this node (Flight
334    /// Recorder, R0.5): recorded on the node's journal events and used by
335    /// retry/replay policy.
336    ///
337    /// The default is [`crate::record::Effect::Pure`] — a plain compute node
338    /// over its state snapshot. **Override honestly**: a node that performs
339    /// I/O or side effects inside `run` is not `Pure`, and misdeclaring it
340    /// weakens replay fidelity (the journal will claim an effect was
341    /// re-derivable when it was not). [`crate::remote::RemoteNode`] and the
342    /// `wasm`-feature `WasmNode` override to `NonIdempotent`.
343    fn effect(&self) -> crate::record::Effect {
344        crate::record::Effect::Pure
345    }
346
347    /// Execute the node against a super-step state snapshot.
348    async fn run(&self, ctx: NodeContext) -> Result<NodeOutput>;
349}
350
351/// Blanket implementation for async closures/functions:
352/// `Fn(NodeContext) -> impl Future<Output = Result<NodeOutput>>`.
353#[async_trait]
354impl<F, Fut> Node for F
355where
356    F: Fn(NodeContext) -> Fut + Send + Sync,
357    Fut: Future<Output = Result<NodeOutput>> + Send,
358{
359    async fn run(&self, ctx: NodeContext) -> Result<NodeOutput> {
360        (self)(ctx).await
361    }
362}
363
364/// Allow `Arc<dyn Node>` itself to be registered as a node (useful for
365/// sharing one node implementation across graphs).
366#[async_trait]
367impl Node for Arc<dyn Node> {
368    fn name(&self) -> &str {
369        self.as_ref().name()
370    }
371
372    async fn run(&self, ctx: NodeContext) -> Result<NodeOutput> {
373        self.as_ref().run(ctx).await
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380    use serde_json::json;
381
382    #[tokio::test]
383    async fn closure_implements_node() {
384        let node = |ctx: NodeContext| async move {
385            assert_eq!(ctx.thread_id(), "t1");
386            Ok(NodeOutput::update("x", json!(ctx.step())))
387        };
388        let ctx = NodeContext::new(
389            State::new(),
390            NodeConfig {
391                thread_id: "t1".into(),
392                step: 3,
393                resume: None,
394                extra: HashMap::new(),
395            },
396        );
397        let out = Node::run(&node, ctx).await.unwrap();
398        assert_eq!(out.updates.get("x"), Some(&json!(3)));
399        assert_eq!(node.name(), "anonymous");
400    }
401
402    #[tokio::test]
403    async fn interrupt_helper_produces_interrupt_error() {
404        let node = |ctx: NodeContext| async move {
405            match ctx.resume_value() {
406                Some(v) => Ok(NodeOutput::update("answer", v.clone())),
407                None => Err(ctx.interrupt(json!({"question": "approve?"}))),
408            }
409        };
410
411        let ctx = NodeContext::new(State::new(), NodeConfig::default());
412        let err = Node::run(&node, ctx).await.unwrap_err();
413        assert!(err.is_interrupt());
414        assert_eq!(
415            err.interrupt_value(),
416            Some(&json!({"question": "approve?"}))
417        );
418
419        let resumed = NodeContext::new(
420            State::new(),
421            NodeConfig {
422                resume: Some(json!(true)),
423                ..NodeConfig::default()
424            },
425        );
426        let out = Node::run(&node, resumed).await.unwrap();
427        assert_eq!(out.updates.get("answer"), Some(&json!(true)));
428    }
429}