Runtime, durability, timeouts
Runtime context
Section titled “Runtime context”Pass per-run data that is not part of the state, such as a user id, with RunConfig::with_context.
#[derive(serde::Deserialize)]struct Ctx { user_id: String,}
g.add_node_fn("greet", |_i: Value, ctx: NodeCtx| async move { let c: Ctx = ctx.runtime().context_as()?; Ok::<Value, NodeError>(json!({"who": c.user_id}))})?;
let out = app.invoke(json!({}), RunConfig::new().with_context(json!({"user_id": "user_123"}))).await?;Ways to read it:
ctx.context()returnsOption<&Value>.ctx.runtime()returns aRuntimewithcontext,store,stream_writer,previous,execution_infoandheartbeat().context_as::<T>()deserialises the context. It is an error when no context was given.get_runtime()works anywhere inside a node.
Subgraphs inherit the context. StateGraph::set_context_schema::<C>() rejects a context that does not deserialise into C, before any node runs.
Durability modes
Section titled “Durability modes”Durability decides when checkpoints are written. Set it per run in StreamOpts and use invoke_with or stream:
let opts = StreamOpts { durability: Durability::Sync, ..Default::default() };let out = app.invoke_with(input, cfg, opts).await?;| Mode | Behaviour |
|---|---|
Durability::Sync |
Waits for each checkpoint before the next superstep |
Durability::Async (default) |
Saves checkpoints and task writes on one background chain while the next superstep runs. Joined before the run returns; errors surface from the run. |
Durability::Exit |
Saves once when the run exits. A nested run saves only when it failed, was interrupted or is a persistent subgraph. |
Serde names are sync, async and exit.
Retries
Section titled “Retries”Attach a RetryPolicy to a node with NodeOpts::new().retry(..). It has initial_interval, backoff_factor, max_interval, max_attempts, jitter and retry_on. StateGraph::set_node_defaults sets defaults for all nodes.
g.add_node_with( "flaky", node_fn(|_s: Value, _c: NodeCtx| async move { Ok::<Value, NodeError>(json!({})) }), NodeOpts::new().retry(RetryPolicy { max_attempts: 2, ..Default::default() }),)?;Timeouts
Section titled “Timeouts”A TimeoutPolicy has two limits per attempt:
run_timeout: a hard wall-clock cap, in seconds.idle_timeout: the longest time without observable progress, in seconds.
refresh_on is Auto or Heartbeat. Under Auto, progress is: task writes, ctx.writer() writes, messages and tool events, child tasks, and ctx.heartbeat(). Progress inside a subgraph also refreshes the enclosing node.
Where to set it:
- per node:
NodeOpts::new().timeout(..) - per
Send:SendPacket::with_timeout(..), which overrides the node - per task or entrypoint:
TaskDef::timeout(..),Entrypoint::timeout(..) - as a graph default:
StateGraph::set_default_timeout(..), which also applies to error-handler nodes
TimeoutPolicy converts from a Duration or from seconds as f64. TimeoutPolicy::default().with_idle_timeout(d) builds one step by step.
A fired timeout fails the attempt with NodeError::Timeout. The attempt’s writes are discarded and late writes from tasks it spawned are dropped. The default RetryPolicy retries a timeout. Each attempt gets a fresh clock.
Error-handler nodes
Section titled “Error-handler nodes”An error handler runs when a node fails after its retries are exhausted, timeouts included.
g.add_node_with( "always_failing", node_fn(|_s: Value, _c: NodeCtx| async move { Err::<Value, NodeError>(NodeError::failed("Always fails")) }), NodeOpts::new().error_handler(node_fn(|_input: Value, ctx: NodeCtx| async move { let failure = ctx.node_error().expect("handlers receive the failure"); println!("{} failed: {}", failure.node, failure.error); Ok::<Value, NodeError>(json!({"foo": "handled"})) })),)?;NodeOpts::error_handler(node)adds a node named__error_handler__{node}.StateGraph::set_default_error_handler(node)adds__default_error_handler__for every regular node without its own.- The handler runs in the same superstep with the failed node’s input.
ctx.node_error()returns the failure (NodeFailure { node, error }). - The handler can return an update or route with a
Command. - Sibling nodes keep running.
- Interrupts and parent commands are never routed to a handler. A failing handler fails the run. Handlers never catch other handlers.
- The error is persisted. After a resume the failed node is not re-run, and the handler task is recreated with the same id.
Cache and deferred nodes
Section titled “Cache and deferred nodes”NodeOpts::cache(CachePolicy) caches a node’s result. Pass a cache such as InMemoryCache with CompileOpts::new().cache(..). NodeOpts::defer(true) makes a node fire only after no other node is triggered, for example a tail node that must run after all Send fan-out has settled.
Cancellation
Section titled “Cancellation”Pass a CancellationToken in StreamOpts::cancel to stop a run at the next superstep boundary. See Streaming.
Warpra is open source under Apache-2.0. Made by Liceron.