Skip to main content

rig_multiagent/
graph.rs

1//! Nodes run along edges, in parallel where they can.
2
3use std::any::{Any, TypeId};
4use std::collections::HashMap;
5use std::fmt::Write as _;
6use std::sync::Arc;
7use std::time::{Duration, Instant};
8
9use futures::StreamExt;
10use futures::stream::FuturesUnordered;
11use rig_core::completion::Usage;
12use rig_core::wasm_compat::{WasmBoxedFuture, WasmBoxedStream, WasmCompatSend, WasmCompatSync};
13use serde::{Deserialize, Serialize};
14use tracing::Instrument;
15
16use crate::BuildError;
17use crate::checkpoint::{CheckpointError, Checkpoints, Saving};
18use crate::events::{Emit, events};
19use crate::human::{Clock, Question};
20use crate::node::{Node, NodeError, NodeIo, NodeOutput};
21use crate::swarm::DEFAULT_MAX_TURNS;
22
23/// An edge's condition.
24#[cfg(not(target_family = "wasm"))]
25type Condition = Arc<dyn Fn(&GraphState) -> bool + Send + Sync>;
26/// An edge's condition (browser wasm: no `Send + Sync`, no threads).
27#[cfg(target_family = "wasm")]
28type Condition = Arc<dyn Fn(&GraphState) -> bool>;
29
30/// Nodes (agents, swarms, graphs, functions) connected by edges.
31///
32/// A run starts with the [entry](GraphBuilder::entry) nodes, by default the
33/// ones without incoming edges, on the task. Then, batch by batch: the nodes
34/// of a batch run in parallel; a node that finished follows each of its
35/// outgoing edges whose condition holds, and the nodes those edges reach make
36/// the next batch. A node reached from several nodes of a batch runs once.
37/// A node gets the task when nothing led to it, and otherwise the task with
38/// the outputs of every finished node with an edge to it that holds.
39///
40/// A node that fails does not follow its edges, so its branch stops; the
41/// other branches carry on, and the run then fails with what it got.
42///
43/// With cycles, a node can run again (a reviewer sending work back to a
44/// writer, say), seeing the newest outputs before it; such a graph needs
45/// [`max_node_executions`](GraphBuilder::max_node_executions).
46///
47/// Cloning is cheap; clones share the nodes.
48#[derive(Clone)]
49pub struct Graph {
50    inner: Arc<Inner>,
51}
52
53struct Inner {
54    nodes: Vec<GraphNode>,
55    edges: Vec<Edge>,
56    entries: Vec<usize>,
57    max_node_executions: Option<usize>,
58    max_turns: usize,
59    execution_timeout: Duration,
60    node_timeout: Duration,
61    checkpoints: Option<Checkpoints>,
62}
63
64struct GraphNode {
65    id: String,
66    node: Box<dyn Node>,
67}
68
69struct Edge {
70    from: usize,
71    to: usize,
72    condition: Option<Condition>,
73}
74
75impl Edge {
76    fn holds(&self, state: &GraphState) -> bool {
77        self.condition
78            .as_ref()
79            .is_none_or(|condition| condition(state))
80    }
81}
82
83/// Builds a [`Graph`].
84#[must_use]
85pub struct GraphBuilder {
86    nodes: Vec<(String, Box<dyn Node>)>,
87    edges: Vec<(String, String, Option<Condition>)>,
88    entries: Vec<String>,
89    max_node_executions: Option<usize>,
90    max_turns: usize,
91    execution_timeout: Duration,
92    node_timeout: Duration,
93    checkpoints: Option<Checkpoints>,
94}
95
96impl Graph {
97    /// Start building a graph.
98    pub fn builder() -> GraphBuilder {
99        GraphBuilder {
100            nodes: Vec::new(),
101            edges: Vec::new(),
102            entries: Vec::new(),
103            max_node_executions: None,
104            max_turns: DEFAULT_MAX_TURNS,
105            execution_timeout: Duration::from_secs(15 * 60),
106            node_timeout: Duration::from_secs(5 * 60),
107            checkpoints: None,
108        }
109    }
110}
111
112impl GraphBuilder {
113    /// Add a node: a Rig agent, a [`Swarm`](crate::Swarm), another
114    /// [`Graph`], a [`node_fn`](crate::node_fn), or any [`Node`].
115    pub fn node(mut self, id: impl Into<String>, node: impl Node + 'static) -> Self {
116        self.nodes.push((id.into(), Box::new(node)));
117        self
118    }
119
120    /// Run `to` after `from`.
121    pub fn edge(mut self, from: impl Into<String>, to: impl Into<String>) -> Self {
122        self.edges.push((from.into(), to.into(), None));
123        self
124    }
125
126    /// Run `to` after `from` when `condition` holds on the run so far.
127    ///
128    /// ```
129    /// # use rig_multiagent::{Graph, GraphState, node_fn};
130    /// # let review = node_fn(|_: String| async { Ok("APPROVED".to_owned()) });
131    /// # let publish = node_fn(|text: String| async { Ok(text) });
132    /// let graph = Graph::builder()
133    ///     .node("review", review)
134    ///     .node("publish", publish)
135    ///     .edge_if("review", "publish", |state: &GraphState| {
136    ///         state.output("review").is_some_and(|verdict| verdict.contains("APPROVED"))
137    ///     })
138    ///     .build()?;
139    /// # Ok::<(), rig_multiagent::BuildError>(())
140    /// ```
141    pub fn edge_if(
142        mut self,
143        from: impl Into<String>,
144        to: impl Into<String>,
145        condition: impl Fn(&GraphState) -> bool + WasmCompatSend + WasmCompatSync + 'static,
146    ) -> Self {
147        self.edges
148            .push((from.into(), to.into(), Some(Arc::new(condition))));
149        self
150    }
151
152    /// Start the run with this node (call it again for several). Defaults to
153    /// every node without incoming edges.
154    pub fn entry(mut self, id: impl Into<String>) -> Self {
155        self.entries.push(id.into());
156        self
157    }
158
159    /// How many node runs, in all, a graph run may make. Required when the
160    /// graph has a cycle; unbounded otherwise.
161    pub fn max_node_executions(mut self, max: usize) -> Self {
162        self.max_node_executions = Some(max);
163        self
164    }
165
166    /// How many model calls one agent node's run may make, counting the first
167    /// call and every follow-up after a tool call. An agent whose own
168    /// `default_max_turns` is higher keeps its own. Defaults to 8; zero fails
169    /// the build with [`BuildError::ZeroTurns`]. Nodes that are swarms or
170    /// functions are not affected.
171    pub fn max_turns_per_agent(mut self, max_turns: usize) -> Self {
172        self.max_turns = max_turns;
173        self
174    }
175
176    /// How long a whole run may take. Defaults to 15 minutes.
177    pub fn execution_timeout(mut self, timeout: Duration) -> Self {
178        self.execution_timeout = timeout;
179        self
180    }
181
182    /// How long one node may take. Defaults to 5 minutes.
183    #[doc(alias = "agent_timeout")]
184    pub fn node_timeout(mut self, timeout: Duration) -> Self {
185        self.node_timeout = timeout;
186        self
187    }
188
189    /// Keep the progress of runs started with [`run_as`](Graph::run_as) or
190    /// [`stream_as`](Graph::stream_as) in `store` (any rig-memory store: a
191    /// `DirStore`, a database), so a run that stopped resumes where it was.
192    pub fn checkpoints(
193        mut self,
194        store: impl rig_memory::AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
195    ) -> Self {
196        self.checkpoints = Some(Checkpoints::new(store, "graph"));
197        self
198    }
199
200    /// Check the nodes and edges.
201    pub fn build(self) -> Result<Graph, BuildError> {
202        if self.nodes.is_empty() {
203            return Err(BuildError::Empty);
204        }
205        if self.max_turns == 0 {
206            return Err(BuildError::ZeroTurns);
207        }
208        let mut nodes: Vec<GraphNode> = Vec::with_capacity(self.nodes.len());
209        for (id, node) in self.nodes {
210            if nodes.iter().any(|other| other.id == id) {
211                return Err(BuildError::DuplicateName(id));
212            }
213            nodes.push(GraphNode { id, node });
214        }
215        let index = |id: &str| {
216            nodes
217                .iter()
218                .position(|node| node.id == id)
219                .ok_or_else(|| BuildError::UnknownName(id.to_owned()))
220        };
221        let mut edges = Vec::with_capacity(self.edges.len());
222        for (from, to, condition) in self.edges {
223            edges.push(Edge {
224                from: index(&from)?,
225                to: index(&to)?,
226                condition,
227            });
228        }
229        let entries = if self.entries.is_empty() {
230            let starts: Vec<usize> = (0..nodes.len())
231                .filter(|&node| !edges.iter().any(|edge| edge.to == node))
232                .collect();
233            if starts.is_empty() {
234                return Err(BuildError::NoEntry);
235            }
236            starts
237        } else {
238            let mut entries = Vec::new();
239            for id in &self.entries {
240                let entry = index(id)?;
241                if !entries.contains(&entry) {
242                    entries.push(entry);
243                }
244            }
245            entries
246        };
247        if self.max_node_executions.is_none() && has_cycle(nodes.len(), &edges) {
248            return Err(BuildError::UnboundedCycle);
249        }
250        Ok(Graph {
251            inner: Arc::new(Inner {
252                nodes,
253                edges,
254                entries,
255                max_node_executions: self.max_node_executions,
256                max_turns: self.max_turns,
257                execution_timeout: self.execution_timeout,
258                node_timeout: self.node_timeout,
259                checkpoints: self.checkpoints,
260            }),
261        })
262    }
263}
264
265/// Whether following edges (conditions aside) can come back to a node.
266fn has_cycle(nodes: usize, edges: &[Edge]) -> bool {
267    // Kahn's algorithm: a graph is acyclic when every node can be peeled off
268    // once nothing points to it any more.
269    let mut incoming = vec![0usize; nodes];
270    for edge in edges {
271        if let Some(count) = incoming.get_mut(edge.to) {
272            *count += 1;
273        }
274    }
275    let mut free: Vec<usize> = incoming
276        .iter()
277        .enumerate()
278        .filter(|(_, count)| **count == 0)
279        .map(|(node, _)| node)
280        .collect();
281    let mut peeled = 0;
282    while let Some(node) = free.pop() {
283        peeled += 1;
284        for edge in edges.iter().filter(|edge| edge.from == node) {
285            if let Some(count) = incoming.get_mut(edge.to) {
286                *count -= 1;
287                if *count == 0 {
288                    free.push(edge.to);
289                }
290            }
291        }
292    }
293    peeled < nodes
294}
295
296/// Request-scoped values a run is given when it starts: a user id, a tenant,
297/// a database handle. Nodes, [`edge_if`](GraphBuilder::edge_if) conditions
298/// and [`node_fn_with_state`](crate::node_fn_with_state) functions read them
299/// through [`GraphState::run_state`] or [`NodeIo::run_state`](crate::NodeIo::run_state).
300///
301/// Values are typed: one value per type, read back by type. They are never
302/// sent to a model: an agent node gets only its input text, and the tools of
303/// an agent cannot read them (Rig gives a tool only the serializable
304/// `ToolContext`). They are not saved in checkpoints either, so a run resumed
305/// with [`run_as_with_state`](Graph::run_as_with_state) or
306/// [`stream_as_with_state`](Graph::stream_as_with_state) must be given the
307/// state again.
308///
309/// ```
310/// use rig_multiagent::RunState;
311/// struct TenantId(String);
312/// let state = RunState::new().with(TenantId("acme".to_owned()));
313/// assert_eq!(state.get::<TenantId>().map(|tenant| tenant.0.as_str()), Some("acme"));
314/// ```
315#[derive(Clone, Default)]
316pub struct RunState {
317    values: Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
318}
319
320impl RunState {
321    /// An empty state.
322    pub fn new() -> Self {
323        Self::default()
324    }
325
326    /// Store `value`, replacing an earlier value of the same type.
327    #[must_use]
328    pub fn with<T: Any + Send + Sync>(mut self, value: T) -> Self {
329        Arc::make_mut(&mut self.values).insert(TypeId::of::<T>(), Arc::new(value));
330        self
331    }
332
333    /// The stored value of type `T`, if there is one.
334    pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
335        let value: &(dyn Any + Send + Sync) = self.values.get(&TypeId::of::<T>())?.as_ref();
336        value.downcast_ref::<T>()
337    }
338}
339
340impl std::fmt::Debug for RunState {
341    /// Shows how many values there are, never the values themselves.
342    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343        write!(f, "RunState({} values)", self.values.len())
344    }
345}
346
347// `RunState` is read-only after construction: `with` consumes it and nothing
348// mutates the map once a run holds it. Observing it after a caught panic
349// therefore cannot see a broken invariant. The trait objects it stores are not
350// `RefUnwindSafe`, which would otherwise make `GraphState` and `GraphRun` lose
351// the auto traits they had before this type existed.
352impl std::panic::UnwindSafe for RunState {}
353impl std::panic::RefUnwindSafe for RunState {}
354
355/// A run so far, as edge conditions see it.
356#[derive(Debug, Clone, Default, Serialize, Deserialize)]
357pub struct GraphState {
358    task: String,
359    outputs: HashMap<String, String>,
360    runs: HashMap<String, usize>,
361    /// How many times each node finished, which numbers its next run.
362    #[serde(default)]
363    finished: HashMap<String, usize>,
364    order: Vec<String>,
365    /// The request-scoped state the run was given. Never saved.
366    #[serde(skip)]
367    run: RunState,
368}
369
370impl GraphState {
371    /// The task the run started with.
372    pub fn task(&self) -> &str {
373        &self.task
374    }
375
376    /// The request-scoped state the run was given, see [`RunState`].
377    pub fn run_state(&self) -> &RunState {
378        &self.run
379    }
380
381    /// The newest output of node `id`, once it has finished.
382    pub fn output(&self, id: &str) -> Option<&str> {
383        self.outputs.get(id).map(String::as_str)
384    }
385
386    /// How many times node `id` has run, failures included.
387    pub fn runs(&self, id: &str) -> usize {
388        self.runs.get(id).copied().unwrap_or(0)
389    }
390
391    /// The nodes that have run, in order, failures included.
392    pub fn order(&self) -> &[String] {
393        &self.order
394    }
395}
396
397/// A graph run, whole or (in a [`GraphError`]) partial.
398#[derive(Debug, Clone)]
399#[non_exhaustive]
400pub struct GraphRun {
401    /// What the run did.
402    pub state: GraphState,
403    /// The nodes of the last batch that finished, in order.
404    pub last: Vec<String>,
405    /// The model tokens the nodes that finished spent.
406    pub usage: Usage,
407    /// How long the run took.
408    pub elapsed: Duration,
409}
410
411impl GraphRun {
412    /// The newest output of node `id`.
413    pub fn output(&self, id: &str) -> Option<&str> {
414        self.state.output(id)
415    }
416
417    /// The run's answer: the output of the last node to finish, or, when
418    /// the last batch had several, each one under its node's name.
419    pub fn answer(&self) -> String {
420        match self.last.as_slice() {
421            [only] => self.output(only).unwrap_or_default().to_owned(),
422            last => {
423                let mut text = String::new();
424                for id in last {
425                    let _ = write!(
426                        text,
427                        "From {id}:\n{}\n\n",
428                        self.output(id).unwrap_or_default()
429                    );
430                }
431                text.trim_end().to_owned()
432            }
433        }
434    }
435}
436
437/// A graph run in which something failed, with what the rest produced.
438#[derive(Debug, thiserror::Error)]
439#[non_exhaustive]
440pub struct GraphError {
441    /// What failed, in order.
442    pub failures: Vec<GraphFailure>,
443    /// What the run did.
444    pub run: GraphRun,
445}
446
447impl std::fmt::Display for GraphError {
448    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
449        match self.failures.as_slice() {
450            [] => f.write_str("the graph run failed"),
451            [only] => only.fmt(f),
452            [first, rest @ ..] => write!(f, "{first} (and {} more failures)", rest.len()),
453        }
454    }
455}
456
457/// What a [streamed](Graph::stream) graph run reports, as it happens.
458#[derive(Debug)]
459#[non_exhaustive]
460pub enum GraphEvent {
461    /// The run resumed from its checkpoint: the first event of a resumed
462    /// [`stream_as`](Graph::stream_as) run.
463    Resumed {
464        /// The nodes that had run, in order.
465        done: Vec<String>,
466    },
467    /// A node started.
468    NodeStarted {
469        /// The node.
470        node: String,
471    },
472    /// Text a node wrote: what an agent's model streams, or a nested swarm's
473    /// or graph's. Nodes with nothing to stream report only their output.
474    Text {
475        /// The node.
476        node: String,
477        /// The new text.
478        text: String,
479    },
480    /// A node finished.
481    NodeFinished {
482        /// The node.
483        node: String,
484        /// Its output.
485        output: String,
486    },
487    /// A node failed or ran out of time; its branch stops.
488    NodeFailed {
489        /// The node.
490        node: String,
491        /// Why.
492        error: String,
493    },
494    /// A node asks a person; the node waits for the [answer](Question::answer),
495    /// and the run's timeouts stop meanwhile.
496    Question(Question),
497    /// The run ended: the last event. Boxed, so the many text events stay small.
498    Finished(Box<Result<GraphRun, GraphError>>),
499}
500
501/// A run's checkpoint: what it did, and the batch that comes next.
502#[derive(Serialize, Deserialize)]
503struct Saved {
504    finished: bool,
505    state: GraphState,
506    usage: Usage,
507    last: Vec<String>,
508    executions: usize,
509    /// The nodes of the batch still to run, or the next batch.
510    ready: Vec<String>,
511    /// The nodes of the batch that had finished.
512    #[serde(default)]
513    batch_done: Vec<String>,
514    /// Nodes that failed, to run again.
515    failed: Vec<String>,
516    active_ms: u64,
517    elapsed_ms: u64,
518}
519
520fn millis(duration: Duration) -> u64 {
521    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
522}
523
524/// Something that went wrong in a graph run.
525#[derive(Debug, thiserror::Error)]
526#[non_exhaustive]
527pub enum GraphFailure {
528    /// A node failed.
529    #[error("node {node:?} failed: {source}")]
530    Node {
531        /// The node.
532        node: String,
533        /// Its error.
534        #[source]
535        source: NodeError,
536    },
537    /// A node ran out of time.
538    #[error("node {node:?} did not finish in time")]
539    NodeTimeout {
540        /// The node.
541        node: String,
542    },
543    /// The checkpoint could not be read or written.
544    #[error("checkpoint: {error}")]
545    Checkpoint {
546        /// What went wrong.
547        #[source]
548        error: CheckpointError,
549    },
550    /// The run used up [`GraphBuilder::execution_timeout`] before its next batch.
551    #[error("the graph ran out of time")]
552    Timeout,
553    /// The next batch would go past [`GraphBuilder::max_node_executions`].
554    #[error("the graph reached its limit of {limit} node runs")]
555    MaxNodeExecutions {
556        /// The limit.
557        limit: usize,
558    },
559}
560
561/// The span a graph run is in. Its totals are recorded when the run ends:
562/// tokens under `graph.usage.*` (not `gen_ai.usage.*`, which the model calls
563/// under it carry, so backends do not count them twice).
564fn run_span(run_id: Option<&str>) -> tracing::Span {
565    tracing::info_span!(
566        "graph.run",
567        graph.run_id = run_id,
568        graph.node_runs = tracing::field::Empty,
569        graph.usage.input_tokens = tracing::field::Empty,
570        graph.usage.output_tokens = tracing::field::Empty,
571        otel.status_code = tracing::field::Empty,
572        error.type = tracing::field::Empty,
573    )
574}
575
576/// Record how a run ended on its span.
577fn record_outcome(span: &tracing::Span, outcome: &Result<GraphRun, GraphError>) {
578    let run = match outcome {
579        Ok(run) => run,
580        Err(error) => {
581            span.record("otel.status_code", "ERROR");
582            if let Some(failure) = error.failures.first() {
583                span.record("error.type", failure.kind());
584            }
585            &error.run
586        }
587    };
588    span.record("graph.node_runs", run.state.order().len());
589    if let Some(tokens) = run.usage.input_tokens {
590        span.record("graph.usage.input_tokens", tokens);
591    }
592    if let Some(tokens) = run.usage.output_tokens {
593        span.record("graph.usage.output_tokens", tokens);
594    }
595}
596
597/// Mark a node's span failed when it failed or ran out of time.
598fn record_node<T>(span: &tracing::Span, outcome: &Option<Result<T, NodeError>>) {
599    let kind = match outcome {
600        Some(Ok(_)) => return,
601        Some(Err(_)) => "node_failed",
602        None => "timeout",
603    };
604    span.record("otel.status_code", "ERROR");
605    span.record("error.type", kind);
606}
607
608impl GraphFailure {
609    /// A short, stable name for the failure, for `error.type`.
610    fn kind(&self) -> &'static str {
611        match self {
612            Self::Node { .. } => "node_failed",
613            Self::NodeTimeout { .. } => "node_timeout",
614            Self::Timeout => "timeout",
615            Self::MaxNodeExecutions { .. } => "max_node_executions",
616            Self::Checkpoint { .. } => "checkpoint",
617        }
618    }
619}
620
621impl Graph {
622    /// Run the graph on `task`.
623    pub async fn run(&self, task: impl Into<String>) -> Result<GraphRun, GraphError> {
624        self.run_with_state(task, RunState::default()).await
625    }
626
627    /// [`run`](Self::run) with the request-scoped `state` every node, edge
628    /// condition and [`node_fn_with_state`](crate::node_fn_with_state)
629    /// function of the run can read. See [`RunState`].
630    pub async fn run_with_state(
631        &self,
632        task: impl Into<String>,
633        state: RunState,
634    ) -> Result<GraphRun, GraphError> {
635        let span = run_span(None);
636        let outcome = self
637            .run_task(task.into(), None, false, None, state)
638            .instrument(span.clone())
639            .await;
640        record_outcome(&span, &outcome);
641        outcome
642    }
643
644    /// Run the graph as run `run_id`: resume it from its last checkpoint if
645    /// it has one and did not finish, or else start it on `task`. Progress
646    /// is saved as each node finishes and at the end, so a run that stopped
647    /// runs only the nodes that had not finished, and a run that ended with
648    /// failed nodes runs those nodes again.
649    ///
650    /// Agent nodes keep a journal of their tool results, which a node run
651    /// again replays rather than executing the tools twice; swarm and graph
652    /// nodes keep their own progress and resume inside too.
653    ///
654    /// Needs [`checkpoints`](GraphBuilder::checkpoints); without them it is
655    /// [`run`](Self::run). A `run_id` is 1-128 of `[A-Za-z0-9_-]`.
656    pub async fn run_as(
657        &self,
658        run_id: &str,
659        task: impl Into<String>,
660    ) -> Result<GraphRun, GraphError> {
661        self.run_as_with_state(run_id, task, RunState::default())
662            .await
663    }
664
665    /// [`run_as`](Self::run_as) with the request-scoped `state` of the run.
666    /// A resumed run needs the state passed again: it is not in the
667    /// checkpoint. See [`RunState`].
668    pub async fn run_as_with_state(
669        &self,
670        run_id: &str,
671        task: impl Into<String>,
672        state: RunState,
673    ) -> Result<GraphRun, GraphError> {
674        let span = run_span(Some(run_id));
675        let outcome = self
676            .run_task(task.into(), self.saving(Some(run_id)), false, None, state)
677            .instrument(span.clone())
678            .await;
679        record_outcome(&span, &outcome);
680        outcome
681    }
682
683    /// [`stream`](Self::stream) as run `run_id`, resuming it as
684    /// [`run_as`](Self::run_as) does. A resumed run starts with
685    /// [`GraphEvent::Resumed`].
686    pub fn stream_as<'a>(
687        &'a self,
688        run_id: &'a str,
689        task: impl Into<String>,
690    ) -> WasmBoxedStream<'a, GraphEvent> {
691        self.stream_events(task.into(), Some(run_id), RunState::default())
692    }
693
694    /// [`stream_as`](Self::stream_as) with the request-scoped `state` of the
695    /// run; a resumed run needs it passed again. See [`RunState`].
696    pub fn stream_as_with_state<'a>(
697        &'a self,
698        run_id: &'a str,
699        task: impl Into<String>,
700        state: RunState,
701    ) -> WasmBoxedStream<'a, GraphEvent> {
702        self.stream_events(task.into(), Some(run_id), state)
703    }
704
705    /// Run the graph on `task`, reporting each node as it starts, writes and
706    /// finishes, and the outcome last.
707    ///
708    /// The run makes progress only while the stream is polled, and stops
709    /// when the stream is dropped.
710    pub fn stream(&self, task: impl Into<String>) -> WasmBoxedStream<'_, GraphEvent> {
711        self.stream_events(task.into(), None, RunState::default())
712    }
713
714    /// [`stream`](Self::stream) with the request-scoped `state` of the run.
715    /// See [`RunState`].
716    pub fn stream_with_state(
717        &self,
718        task: impl Into<String>,
719        state: RunState,
720    ) -> WasmBoxedStream<'_, GraphEvent> {
721        self.stream_events(task.into(), None, state)
722    }
723
724    fn stream_events<'a>(
725        &'a self,
726        task: String,
727        run_id: Option<&'a str>,
728        state: RunState,
729    ) -> WasmBoxedStream<'a, GraphEvent> {
730        let span = run_span(run_id);
731        events(
732            move |sender| async move {
733                let emit = move |event| {
734                    let _ = sender.send(event);
735                };
736                let outcome = self
737                    .run_task(task, self.saving(run_id), false, Some(&emit), state)
738                    .instrument(span.clone())
739                    .await;
740                record_outcome(&span, &outcome);
741                outcome
742            },
743            |outcome| GraphEvent::Finished(Box::new(outcome)),
744        )
745    }
746
747    /// Where run `run_id` keeps its progress, if the graph has a store.
748    fn saving(&self, run_id: Option<&str>) -> Option<Saving> {
749        run_id
750            .zip(self.inner.checkpoints.clone())
751            .map(|(id, checkpoints)| Saving::new(checkpoints, id))
752    }
753
754    /// Run `task`, saving to `saving`. A `nested` run (a graph node) that
755    /// finished before answers as it did, rather than starting over: its
756    /// graph lost track of it.
757    async fn run_task(
758        &self,
759        task: String,
760        saving: Option<Saving>,
761        nested: bool,
762        emit: Option<Emit<'_, GraphEvent>>,
763        run_state: RunState,
764    ) -> Result<GraphRun, GraphError> {
765        let inner = &*self.inner;
766        let started = Instant::now();
767        let checkpoints = saving
768            .as_ref()
769            .map(|saving| (saving.run_id.as_str(), &saving.checkpoints));
770        let fail = |error: CheckpointError, state: GraphState, before: Duration| GraphError {
771            failures: vec![GraphFailure::Checkpoint { error }],
772            run: GraphRun {
773                state,
774                last: Vec::new(),
775                usage: Usage::default(),
776                elapsed: before + started.elapsed(),
777            },
778        };
779        let index_of = |id: &str| inner.nodes.iter().position(|node| node.id == id);
780        let saved = match checkpoints {
781            Some((id, checkpoints)) => match checkpoints.load::<Saved>(id).await {
782                Ok(Some(saved)) if saved.finished && nested => {
783                    return Ok(GraphRun {
784                        state: saved.state,
785                        last: saved.last,
786                        usage: saved.usage,
787                        elapsed: Duration::from_millis(saved.elapsed_ms),
788                    });
789                }
790                Ok(saved) => saved.filter(|saved| !saved.finished),
791                Err(error) => return Err(fail(error, GraphState::default(), Duration::ZERO)),
792            },
793            None => None,
794        };
795        let mut state;
796        let mut usage;
797        let mut last;
798        let mut executions;
799        let mut ready = Vec::new();
800        // Nodes of the batch the run stopped in that had finished.
801        let mut carried = Vec::new();
802        let clock;
803        let before;
804        match saved {
805            None => {
806                state = GraphState {
807                    task,
808                    ..GraphState::default()
809                };
810                state.run = run_state.clone();
811                usage = Usage::default();
812                last = Vec::new();
813                executions = 0;
814                ready = inner.entries.clone();
815                clock = Clock::resumed(Duration::ZERO);
816                before = Duration::ZERO;
817            }
818            Some(saved) => {
819                before = Duration::from_millis(saved.elapsed_ms);
820                // The nodes it had not run yet, and those that failed, run.
821                for (ids, into) in [
822                    (
823                        saved.ready.iter().chain(&saved.failed).collect::<Vec<_>>(),
824                        &mut ready,
825                    ),
826                    (saved.batch_done.iter().collect(), &mut carried),
827                ] {
828                    for id in ids {
829                        let Some(index) = index_of(id) else {
830                            let error = CheckpointError::UnknownNode(id.clone());
831                            return Err(fail(error, saved.state, before));
832                        };
833                        if !into.contains(&index) {
834                            into.push(index);
835                        }
836                    }
837                }
838                tracing::info!(done = saved.state.order.len(), "graph run resumed");
839                if let Some(emit) = emit {
840                    emit(GraphEvent::Resumed {
841                        done: saved.state.order.clone(),
842                    });
843                }
844                clock = Clock::resumed(Duration::from_millis(saved.active_ms));
845                state = saved.state;
846                state.run = run_state.clone();
847                usage = saved.usage;
848                last = saved.last;
849                executions = saved.executions;
850            }
851        }
852        let clock = &clock;
853        let mut failures = Vec::new();
854        let names = |indices: &[usize]| -> Vec<String> {
855            indices
856                .iter()
857                .filter_map(|&index| inner.nodes.get(index))
858                .map(|node| node.id.clone())
859                .collect()
860        };
861        let snapshot = |state: &GraphState,
862                        usage: &Usage,
863                        last: &[String],
864                        executions: usize,
865                        ready: &[usize],
866                        batch_done: &[usize],
867                        failures: &[GraphFailure]| Saved {
868            finished: ready.is_empty() && batch_done.is_empty() && failures.is_empty(),
869            state: state.clone(),
870            usage: *usage,
871            last: last.to_vec(),
872            executions,
873            ready: names(ready),
874            batch_done: names(batch_done),
875            failed: failures
876                .iter()
877                .filter_map(|failure| match failure {
878                    GraphFailure::Node { node, .. } | GraphFailure::NodeTimeout { node } => {
879                        Some(node.clone())
880                    }
881                    _ => None,
882                })
883                .collect(),
884            active_ms: millis(clock.active()),
885            elapsed_ms: millis(before + started.elapsed()),
886        };
887        'run: while !ready.is_empty() || !carried.is_empty() {
888            let mut finished = std::mem::take(&mut carried);
889            if !ready.is_empty() {
890                if let Some((id, checkpoints)) = checkpoints {
891                    let saved = snapshot(
892                        &state, &usage, &last, executions, &ready, &finished, &failures,
893                    );
894                    if let Err(error) = checkpoints.save(id, &saved).await {
895                        failures.push(GraphFailure::Checkpoint { error });
896                        break 'run;
897                    }
898                }
899                if let Some(limit) = inner.max_node_executions
900                    && executions + ready.len() > limit
901                {
902                    failures.push(GraphFailure::MaxNodeExecutions { limit });
903                    break 'run;
904                }
905                let remaining = inner.execution_timeout.saturating_sub(clock.active());
906                if remaining.is_zero() {
907                    failures.push(GraphFailure::Timeout);
908                    break 'run;
909                }
910                let budget = inner.node_timeout.min(remaining);
911                executions += ready.len();
912                let mut batch: FuturesUnordered<_> = ready
913                    .iter()
914                    .filter_map(|&index| Some((index, inner.nodes.get(index)?)))
915                    .map(|(index, node)| {
916                        let input = self.input(index, &state);
917                        // The node's n-th successful run: a failed run that
918                        // runs again keeps the same part, journal included.
919                        let part = state.finished.get(&node.id).copied().unwrap_or(0) + 1;
920                        let saving = saving
921                            .as_ref()
922                            .map(|saving| saving.part("node", &node.id, part));
923                        let span = tracing::info_span!(
924                            "graph.node",
925                            graph.node = %node.id,
926                            otel.status_code = tracing::field::Empty,
927                            error.type = tracing::field::Empty,
928                        );
929                        let run_state = run_state.clone();
930                        async move {
931                            let Some(emit) = emit else {
932                                let io = NodeIo::quiet(&node.id)
933                                    .saving_to(saving)
934                                    .with_turns(inner.max_turns)
935                                    .with_run_state(run_state.clone());
936                                let run = node.node.run(input, &io).instrument(span.clone());
937                                let outcome = clock.within(budget, run).await;
938                                record_node(&span, &outcome);
939                                return (index, node, outcome);
940                            };
941                            emit(GraphEvent::NodeStarted {
942                                node: node.id.clone(),
943                            });
944                            let on_text = |text: &str| {
945                                emit(GraphEvent::Text {
946                                    node: node.id.clone(),
947                                    text: text.to_owned(),
948                                })
949                            };
950                            let on_question = |question: Question| {
951                                // The text stays out of telemetry, as Rig keeps
952                                // prompts out unless content recording is on.
953                                tracing::info!(graph.node = %node.id, "human.question");
954                                emit(GraphEvent::Question(question.pausing(clock)))
955                            };
956                            let io = NodeIo::streaming(&node.id, &on_text, &on_question)
957                                .saving_to(saving)
958                                .with_turns(inner.max_turns)
959                                .with_run_state(run_state.clone());
960                            let run = node.node.run(input, &io).instrument(span.clone());
961                            let outcome = clock.within(budget, run).await;
962                            record_node(&span, &outcome);
963                            let id = node.id.clone();
964                            emit(match &outcome {
965                                Some(Ok(output)) => GraphEvent::NodeFinished {
966                                    node: id,
967                                    output: output.text.clone(),
968                                },
969                                Some(Err(error)) => GraphEvent::NodeFailed {
970                                    node: id,
971                                    error: error.to_string(),
972                                },
973                                None => GraphEvent::NodeFailed {
974                                    node: id,
975                                    error: "did not finish in time".to_owned(),
976                                },
977                            });
978                            (index, node, outcome)
979                        }
980                    })
981                    .collect();
982                let mut remaining = ready.clone();
983                while let Some((index, node, outcome)) = batch.next().await {
984                    remaining.retain(|&other| other != index);
985                    let id = node.id.clone();
986                    *state.runs.entry(id.clone()).or_default() += 1;
987                    state.order.push(id.clone());
988                    match outcome {
989                        Some(Ok(output)) => {
990                            let NodeOutput {
991                                text, usage: spent, ..
992                            } = output;
993                            usage += spent;
994                            *state.finished.entry(id.clone()).or_default() += 1;
995                            state.outputs.insert(id, text);
996                            finished.push(index);
997                        }
998                        Some(Err(source)) => {
999                            tracing::warn!(graph.node = %id, kind = "node_failed", "graph node failed");
1000                            failures.push(GraphFailure::Node { node: id, source });
1001                        }
1002                        None => failures.push(GraphFailure::NodeTimeout { node: id }),
1003                    }
1004                    // Saved as each node ends, so a stop mid-batch runs only
1005                    // the nodes still running. The batch's end is saved by
1006                    // the next batch's start, or the run's end.
1007                    if !remaining.is_empty()
1008                        && let Some((id, checkpoints)) = checkpoints
1009                    {
1010                        let counted = executions - remaining.len();
1011                        let saved = snapshot(
1012                            &state, &usage, &last, counted, &remaining, &finished, &failures,
1013                        );
1014                        if checkpoints.save(id, &saved).await.is_err() {
1015                            tracing::warn!(
1016                                kind = "checkpoint",
1017                                "could not save a finished graph node"
1018                            );
1019                        }
1020                    }
1021                }
1022            }
1023            if !finished.is_empty() {
1024                last = names(&finished);
1025            }
1026            ready = Vec::new();
1027            for edge in &inner.edges {
1028                if finished.contains(&edge.from) && !ready.contains(&edge.to) && edge.holds(&state)
1029                {
1030                    ready.push(edge.to);
1031                }
1032            }
1033        }
1034        if let Some((id, checkpoints)) = checkpoints
1035            && !failures
1036                .iter()
1037                .any(|failure| matches!(failure, GraphFailure::Checkpoint { .. }))
1038        {
1039            // Finished, or the failed nodes to run again next time.
1040            let saved = snapshot(&state, &usage, &last, executions, &[], &[], &failures);
1041            if checkpoints.save(id, &saved).await.is_err() {
1042                tracing::warn!(kind = "checkpoint", "could not save the graph run's end");
1043            }
1044        }
1045        let run = GraphRun {
1046            state,
1047            last,
1048            usage,
1049            elapsed: before + started.elapsed(),
1050        };
1051        if failures.is_empty() {
1052            Ok(run)
1053        } else {
1054            Err(GraphError { failures, run })
1055        }
1056    }
1057
1058    /// The input of node `index`: the task, and the outputs that lead to it.
1059    fn input(&self, index: usize, state: &GraphState) -> String {
1060        let inner = &*self.inner;
1061        let mut sources: Vec<(&str, &str)> = Vec::new();
1062        for edge in inner.edges.iter().filter(|edge| edge.to == index) {
1063            let Some(from) = inner.nodes.get(edge.from) else {
1064                continue;
1065            };
1066            let from = from.id.as_str();
1067            if let Some(output) = state.outputs.get(from)
1068                && !sources.iter().any(|(seen, _)| *seen == from)
1069                && edge.holds(state)
1070            {
1071                sources.push((from, output));
1072            }
1073        }
1074        if sources.is_empty() {
1075            return state.task.clone();
1076        }
1077        let mut text = format!(
1078            "Original task: {}\n\nInputs from previous nodes:\n",
1079            state.task
1080        );
1081        for (from, output) in sources {
1082            let _ = write!(text, "\nFrom {from}:\n{output}\n");
1083        }
1084        text.trim_end().to_owned()
1085    }
1086}
1087
1088impl Node for Graph {
1089    /// Streams the text of its nodes and passes on their questions. In a
1090    /// checkpointed graph run, the inner graph keeps its own progress (in
1091    /// its store, or else the outer graph's), so it resumes inside too.
1092    fn run<'a>(
1093        &'a self,
1094        input: String,
1095        io: &'a NodeIo<'a>,
1096    ) -> WasmBoxedFuture<'a, Result<NodeOutput, NodeError>> {
1097        Box::pin(async move {
1098            let saving = io.saving().map(|saving| {
1099                let checkpoints = self.inner.checkpoints.clone();
1100                let checkpoints =
1101                    checkpoints.unwrap_or_else(|| saving.checkpoints.with_kind("graph"));
1102                Saving::new(checkpoints, saving.run_id.clone())
1103            });
1104            let emit = |event| match event {
1105                GraphEvent::Text { text, .. } => io.text(&text),
1106                GraphEvent::Question(question) => io.forward(question),
1107                _ => {}
1108            };
1109            let emit: Option<Emit<'_, GraphEvent>> = io.is_streaming().then_some(&emit);
1110            let run = self
1111                .run_task(input, saving, true, emit, io.run_state().clone())
1112                .await?;
1113            Ok(NodeOutput::new(run.answer()).with_usage(run.usage))
1114        })
1115    }
1116}