Skip to main content

rig_multiagent/
graph.rs

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