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