Skip to main content

graphrt_core/
response.rs

1//! Ordered response streaming.
2//!
3//! The engine emits raw events as soon as they happen: tokens from parallel
4//! LLM nodes interleave, and nodes finish in any order. A chat-style consumer
5//! wants something different: the text of each response node (`answer`, and
6//! optionally `end`) rendered in template order, with model tokens streamed
7//! through as early as it is safe to do so.
8//!
9//! [`ResponseAssembler`] is a consumer-side transducer that does exactly that:
10//!
11//! ```ignore
12//! let mut assembler = ResponseAssembler::new(engine.graph());
13//! while let Some(event) = run.next().await {
14//!     for chunk in assembler.push(&event) {
15//!         print!("{}", chunk.text);
16//!     }
17//! }
18//! ```
19//!
20//! ## Rules
21//!
22//! - Only response nodes of the **root scope** are assembled. Events from child
23//!   frames (iteration / loop bodies) are ignored, unless
24//!   [`ResponseAssembler::pass_through_unreferenced`] is enabled, in which case
25//!   their chunks are forwarded verbatim.
26//! - At most one response is *active* at a time. Responses are activated in the
27//!   order they become **certain** to execute (ties broken by topological
28//!   order). Certainty is a linear-time fixpoint over the graph — never a path
29//!   enumeration:
30//!   - a node that started or finished is certain, and so is the root entry;
31//!   - a node is certain when one incoming edge comes from a certain source and
32//!     that edge will be taken if the source succeeds: every edge of a
33//!     non-branching node (except `fail-branch` edges), or the edge matching the
34//!     handle a finished branch node selected. Node failures are not anticipated,
35//!     except that an unfinished node with the `fail-branch` strategy makes none
36//!     of its edges certain (either side may be taken).
37//! - While a response is active, its template is drained left to right:
38//!   literal text is emitted immediately; a variable produced by a graph node
39//!   emits that node's buffered stream chunks for the variable's field as they
40//!   arrive; once the node finishes, a variable that never streamed is emitted
41//!   whole (`Value::to_text`). Variables of skipped or failed nodes render as
42//!   nothing. Variables outside graph nodes (`sys.*`, `conversation.*`, ...)
43//!   are resolved from values given via [`ResponseAssembler::with_value`] /
44//!   [`ResponseAssembler::with_pool`], or render as nothing.
45//! - `end` nodes do not stream by default (their outputs are structured data,
46//!   delivered in `RunSucceeded`). Enable [`ResponseAssembler::include_end`] to
47//!   render them as their output values joined by newlines.
48//! - **Retries and handled failures never mix attempts.** A source node whose
49//!   policy allows retries (`retry.max_retries > 0`) or handles errors
50//!   (`on_error` other than `fail`) is *not* streamed live: its chunks are
51//!   buffered and emitted only once the node finishes. A `node_retry` event
52//!   discards the buffered chunks of the failed attempt. On success the final
53//!   attempt's text is emitted; after a handled `default-value` failure the
54//!   default output is emitted instead of any partial text; after a
55//!   `fail-branch` failure (or an unhandled one) nothing is emitted for the
56//!   variable. The trade-off: such nodes lose token-by-token streaming in
57//!   exchange for an answer that always matches the node's final output.
58//! - Ordering after handled failures follows the engine: a non-branch node with
59//!   `default-value` continues along its regular edges, a `fail-branch` node
60//!   along its `fail-branch` edges, and a branch node with `default-value`
61//!   along the handle named by its `branch` default value (no edge if absent).
62//! - `RunSucceeded` and `RunAborted` flush everything that can still be
63//!   rendered, as does [`ResponseAssembler::finish`].
64//! - `RunFailed` renders nothing more, and takes back what was rendered ahead
65//!   of time: text is emitted as soon as a response node is certain to run,
66//!   which does not anticipate failures. Chunks already handed out cannot be
67//!   recalled, but [`ResponseAssembler::text_so_far`] then holds only the text
68//!   of response nodes that ran, so the answer kept for a failed run never
69//!   quotes a node that did not execute.
70
71use std::collections::{HashMap, HashSet, VecDeque};
72use std::sync::Arc;
73
74use serde::Deserialize;
75
76use crate::dsl::ErrorStrategy;
77use crate::event::Event;
78use crate::graph::{FAIL_BRANCH, Graph, NodeIx};
79use crate::node::NodeRole;
80use crate::pool::{Selector, VariablePool};
81use crate::snapshot::{EdgeStatus, FrameSnapshot, NodeStatus};
82use crate::template::{Part, Template};
83use crate::value::Value;
84
85/// A piece of ordered response text.
86#[derive(Clone, Debug, PartialEq, Eq)]
87pub struct ResponseChunk {
88    /// Response node the text belongs to (or, for passed-through chunks, the
89    /// node that produced them). Shared with the graph, so a chunk does not
90    /// copy it.
91    pub node_id: Arc<str>,
92    pub text: String,
93    /// `true` exactly once per response node, on an empty chunk marking that
94    /// its template is fully rendered.
95    pub is_final: bool,
96}
97
98impl ResponseChunk {
99    fn text(node_id: &Arc<str>, text: String) -> Self {
100        Self { node_id: Arc::clone(node_id), text, is_final: false }
101    }
102
103    fn done(node_id: &Arc<str>) -> Self {
104        Self { node_id: Arc::clone(node_id), text: String::new(), is_final: true }
105    }
106}
107
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109enum Status {
110    Unknown,
111    Started,
112    Succeeded,
113    /// Failed but kept going through its error strategy.
114    Handled,
115    /// Failed without an error strategy: outputs never appear.
116    Failed,
117    Skipped,
118}
119
120impl Status {
121    fn finished(self) -> bool {
122        matches!(self, Status::Succeeded | Status::Handled | Status::Failed | Status::Skipped)
123    }
124}
125
126#[derive(Debug)]
127struct Response {
128    node: NodeIx,
129    id: Arc<str>,
130    parts: Vec<Part>,
131    queued: bool,
132    done: bool,
133}
134
135#[derive(Debug, Default)]
136struct StreamBuf {
137    text: String,
138}
139
140/// Stream buffers by node id, then field (a node has few referenced fields).
141type Streams = HashMap<Arc<str>, Vec<(Arc<str>, StreamBuf)>>;
142
143fn stream_buf<'a>(streams: &'a Streams, node: &str, field: &str) -> Option<&'a StreamBuf> {
144    streams.get(node)?.iter().find(|(f, _)| f.as_ref() == field).map(|(_, buf)| buf)
145}
146
147#[derive(Debug)]
148struct Active {
149    response: usize,
150    part: usize,
151    /// Byte offset already emitted from the current variable's stream buffer.
152    offset: usize,
153}
154
155#[derive(Deserialize)]
156struct EndOutput {
157    value_selector: Selector,
158}
159
160/// Turns raw run events into ordered response text. See the module docs.
161#[derive(Debug)]
162pub struct ResponseAssembler {
163    graph: Arc<Graph>,
164    responses: Vec<Response>,
165    status: Vec<Status>,
166    branch: Vec<Option<String>>,
167    /// Nodes whose streams are buffered until they finish (retry / handled-error policy).
168    deferred: Vec<bool>,
169    /// Edge states restored from a snapshot (indexed like `Graph::edges`).
170    edge_state: Vec<Option<EdgeStatus>>,
171    /// Response nodes fully rendered before a pause (restored via `resume_from`).
172    rendered: Vec<bool>,
173    /// Stream buffers of the `(node id, field)` pairs templates reference, by
174    /// node id. Looked up by `&str`, so a chunk costs no allocation.
175    streams: Streams,
176    /// Namespaces templates reference: only their outputs are kept in `pool`.
177    referenced: HashSet<Arc<str>>,
178    pool: VariablePool,
179    queue: VecDeque<usize>,
180    active: Option<Active>,
181    emitted: String,
182    /// The pieces `emitted` is made of, in order: the response (an index into
183    /// `responses`) and the byte length of its text.
184    segments: Vec<(usize, usize)>,
185    pass_through: bool,
186    include_end: bool,
187    finished: bool,
188    /// Certainty of each node, maintained incrementally between events.
189    certain: Vec<bool>,
190    /// Whether `certain` reflects the current state (false after construction / resume).
191    certain_valid: bool,
192    /// Root nodes whose status changed since the last certainty refresh.
193    changed: Vec<NodeIx>,
194}
195
196impl ResponseAssembler {
197    /// Build an assembler for runs of `graph`.
198    pub fn new(graph: &Arc<Graph>) -> Self {
199        let mut this = Self {
200            graph: Arc::clone(graph),
201            responses: Vec::new(),
202            status: vec![Status::Unknown; graph.nodes().len()],
203            branch: vec![None; graph.nodes().len()],
204            deferred: graph
205                .nodes()
206                .iter()
207                .map(|n| n.policy.retry.max_retries > 0 || !matches!(n.policy.on_error, ErrorStrategy::Fail))
208                .collect(),
209            edge_state: vec![None; graph.edges().len()],
210            rendered: vec![false; graph.nodes().len()],
211            streams: Streams::new(),
212            referenced: HashSet::new(),
213            pool: VariablePool::new(),
214            queue: VecDeque::new(),
215            active: None,
216            emitted: String::new(),
217            segments: Vec::new(),
218            pass_through: false,
219            include_end: false,
220            finished: false,
221            certain: vec![false; graph.nodes().len()],
222            certain_valid: false,
223            changed: Vec::new(),
224        };
225        this.rebuild_responses();
226        this
227    }
228
229    /// Forward chunks that no template references (and child-frame chunks) verbatim.
230    pub fn pass_through_unreferenced(mut self, enabled: bool) -> Self {
231        self.pass_through = enabled;
232        self
233    }
234
235    /// Also render `end` nodes (their outputs joined by newlines).
236    pub fn include_end(mut self, enabled: bool) -> Self {
237        self.include_end = enabled;
238        self.rebuild_responses();
239        self
240    }
241
242    /// Provide a value for a non-node variable such as `sys.query`.
243    pub fn with_value(mut self, selector: &Selector, value: Value) -> Self {
244        self.pool.set(selector, value);
245        self
246    }
247
248    /// Provide non-node variables in bulk (e.g. the run's `sys` / `conversation` values).
249    pub fn with_pool(mut self, pool: VariablePool) -> Self {
250        for (ns, name, value) in pool.iter() {
251            self.pool.insert(ns, name, value.clone());
252        }
253        self
254    }
255
256    /// Continue assembling a resumed run from the root frame snapshot carried by
257    /// `RunPaused` (`snapshot.root`).
258    ///
259    /// Restores every variable value of the snapshot (node outputs included, so
260    /// templates can reference nodes that will not run again), node and edge
261    /// states (for correct ordering), and marks response nodes that already
262    /// succeeded before the pause as rendered, so they are not emitted twice.
263    /// A response that was only partially rendered when the run paused is
264    /// rendered again from the start.
265    pub fn resume_from(mut self, snapshot: &FrameSnapshot) -> Self {
266        let restored = VariablePool::from_snapshot(snapshot.pool.clone());
267        for (ns, name, value) in restored.iter() {
268            self.pool.insert(ns, name, value.clone());
269        }
270        for (ix, edge) in self.graph.edges().iter().enumerate() {
271            if let (Some(state), Some(slot)) = (snapshot.edges.get(edge.id.as_ref()), self.edge_state.get_mut(ix)) {
272                *slot = Some(*state);
273            }
274        }
275        for (node_id, node) in &snapshot.nodes {
276            let Some(ix) = self.root_node(node_id) else { continue };
277            let status = match node.status {
278                NodeStatus::Succeeded => Status::Succeeded,
279                NodeStatus::Skipped => Status::Skipped,
280                NodeStatus::Failed if self.has_taken_outgoing(ix) => Status::Handled,
281                NodeStatus::Failed => Status::Failed,
282                NodeStatus::Paused => Status::Started,
283                NodeStatus::Pending => Status::Unknown,
284            };
285            if let Some(slot) = self.status.get_mut(ix) {
286                *slot = status;
287            }
288            if let Some(slot) = self.rendered.get_mut(ix) {
289                *slot = status == Status::Succeeded;
290            }
291        }
292        self.certain_valid = false;
293        self.rebuild_responses();
294        self
295    }
296
297    fn has_taken_outgoing(&self, ix: NodeIx) -> bool {
298        self.graph.outgoing(ix).iter().any(|&ex| self.edge_state.get(ex).copied().flatten() == Some(EdgeStatus::Taken))
299    }
300
301    /// All response text emitted so far, concatenated.
302    pub fn text_so_far(&self) -> &str {
303        &self.emitted
304    }
305
306    /// Feed one event; returns the response chunks it unlocks.
307    pub fn push(&mut self, event: &Event) -> Vec<ResponseChunk> {
308        let mut out = Vec::new();
309        self.push_into(event, &mut out);
310        out
311    }
312
313    /// [`ResponseAssembler::push`] appending to `out` instead of returning a
314    /// new list, so a consumer can reuse one buffer for a whole run.
315    ///
316    /// ```
317    /// # use std::sync::Arc;
318    /// # use graphrt_core::{Graph, Registry, response::ResponseAssembler};
319    /// # let graph = Arc::new(Graph::from_text(r#"{"graph": {"nodes": [{"id": "start", "type": "start"}], "edges": []}}"#, &Registry::with_builtins()).unwrap());
320    /// # let events: Vec<graphrt_core::Event> = Vec::new();
321    /// let mut assembler = ResponseAssembler::new(&graph);
322    /// let mut chunks = Vec::new();
323    /// for event in &events {
324    ///     assembler.push_into(event, &mut chunks);
325    ///     for chunk in chunks.drain(..) {
326    ///         print!("{}", chunk.text);
327    ///     }
328    /// }
329    /// ```
330    pub fn push_into(&mut self, event: &Event, out: &mut Vec<ResponseChunk>) {
331        if self.finished {
332            return;
333        }
334        match event {
335            Event::NodeStarted { frame, node_id, .. } if frame.is_empty() => {
336                self.set_status(node_id, Status::Started);
337            }
338            Event::NodeChunk { frame, node_id, field, chunk, .. } => {
339                let buf = match self.streams.get_mut(node_id.as_ref()) {
340                    Some(fields) if frame.is_empty() => fields.iter_mut().find(|(f, _)| f == field),
341                    _ => None,
342                };
343                let buffered = match buf {
344                    Some((_, buf)) => {
345                        buf.text.push_str(chunk);
346                        true
347                    }
348                    None => {
349                        if self.pass_through && !chunk.is_empty() {
350                            out.push(ResponseChunk::text(node_id, chunk.clone()));
351                        }
352                        false
353                    }
354                };
355                if self.certain_valid {
356                    // A chunk changes no node status: at most the active response advances.
357                    if buffered {
358                        self.drain(false, out);
359                    }
360                    return;
361                }
362            }
363            Event::NodeSucceeded { frame, node_id, outputs, branch, .. } if frame.is_empty() => {
364                if self.referenced.contains(node_id.as_ref()) {
365                    self.pool.set_outputs(node_id, outputs);
366                }
367                if let Some(ix) = self.root_node(node_id)
368                    && let Some(b) = self.branch.get_mut(ix)
369                {
370                    b.clone_from(branch);
371                }
372                self.set_status(node_id, Status::Succeeded);
373            }
374            Event::NodeFailed { frame, node_id, handled, outputs, .. } if frame.is_empty() => {
375                if *handled && self.referenced.contains(node_id.as_ref()) {
376                    self.pool.set_outputs(node_id, outputs);
377                }
378                self.set_status(node_id, if *handled { Status::Handled } else { Status::Failed });
379            }
380            Event::NodeSkipped { frame, node_id } if frame.is_empty() => {
381                self.set_status(node_id, Status::Skipped);
382            }
383            Event::NodeRetry { frame, node_id, .. } if frame.is_empty() => {
384                // The failed attempt's partial output must never reach the answer.
385                if let Some(fields) = self.streams.get_mut(node_id.as_ref()) {
386                    fields.iter_mut().for_each(|(_, buf)| buf.text.clear());
387                }
388                return;
389            }
390            Event::RunSucceeded { .. } | Event::RunAborted { .. } => {
391                self.finish_into(out);
392                return;
393            }
394            Event::RunFailed { .. } => {
395                // Nothing more is rendered: what is left belongs to nodes that will not run.
396                self.keep_text_of_nodes_that_ran();
397                self.finished = true;
398                return;
399            }
400            _ => return,
401        }
402        self.refresh_certainty();
403        self.drain(false, out);
404    }
405
406    /// Flush: treat every pending variable as resolved and render what is
407    /// available. Idempotent.
408    pub fn finish(&mut self) -> Vec<ResponseChunk> {
409        let mut out = Vec::new();
410        self.finish_into(&mut out);
411        out
412    }
413
414    fn finish_into(&mut self, out: &mut Vec<ResponseChunk>) {
415        if self.finished {
416            return;
417        }
418        self.refresh_certainty();
419        self.drain(true, out);
420        self.finished = true;
421    }
422
423    /// Drop from the emitted text what was rendered for response nodes that
424    /// never executed (they were certain to run until the run failed).
425    fn keep_text_of_nodes_that_ran(&mut self) {
426        let mut kept = String::with_capacity(self.emitted.len());
427        let mut segments = Vec::with_capacity(self.segments.len());
428        let mut start = 0;
429        for &(response, len) in &self.segments {
430            let end = start + len;
431            let ran = self
432                .responses
433                .get(response)
434                .and_then(|r| self.status.get(r.node))
435                .is_some_and(|status| matches!(status, Status::Succeeded | Status::Handled));
436            if ran && let Some(text) = self.emitted.get(start..end) {
437                kept.push_str(text);
438                segments.push((response, len));
439            }
440            start = end;
441        }
442        self.emitted = kept;
443        self.segments = segments;
444    }
445
446    fn rebuild_responses(&mut self) {
447        let Some(scope) = self.graph.root_scope() else {
448            return;
449        };
450        let mut responses = Vec::new();
451        for &ix in &scope.nodes {
452            let Some(node) = self.graph.node(ix) else { continue };
453            if node.role != NodeRole::Response {
454                continue;
455            }
456            let parts = match &*node.kind {
457                "answer" => node
458                    .doc
459                    .config
460                    .get("answer")
461                    .and_then(serde_json::Value::as_str)
462                    .map(|s| Template::parse(s).parts().to_vec())
463                    .unwrap_or_default(),
464                "end" if self.include_end => end_parts(&node.doc.config),
465                _ => continue,
466            };
467            let rendered = self.rendered.get(ix).copied().unwrap_or(false);
468            responses.push(Response { node: ix, id: node.id.clone(), parts, queued: rendered, done: rendered });
469        }
470        let mut old = std::mem::take(&mut self.streams);
471        self.referenced.clear();
472        for sel in responses.iter().flat_map(|r| r.parts.iter()).filter_map(|p| match p {
473            Part::Var(sel) => Some(sel),
474            Part::Text(_) => None,
475        }) {
476            let node: Arc<str> = Arc::from(sel.namespace());
477            self.referenced.insert(Arc::clone(&node));
478            if !sel.path().is_empty() {
479                continue;
480            }
481            let fields = self.streams.entry(node).or_default();
482            if fields.iter().any(|(f, _)| f.as_ref() == sel.name()) {
483                continue;
484            }
485            // Keep text already buffered for the pair, if any.
486            let buf = old
487                .get_mut(sel.namespace())
488                .and_then(|v| v.iter_mut().find(|(f, _)| f.as_ref() == sel.name()))
489                .map(|(_, buf)| std::mem::take(buf))
490                .unwrap_or_default();
491            fields.push((Arc::from(sel.name()), buf));
492        }
493        self.responses = responses;
494    }
495
496    fn root_node(&self, id: &str) -> Option<NodeIx> {
497        self.graph.index_of(id).filter(|&ix| self.graph.node(ix).is_some_and(|n| n.parent.is_none()))
498    }
499
500    fn set_status(&mut self, node_id: &str, status: Status) {
501        if let Some(ix) = self.root_node(node_id)
502            && let Some(s) = self.status.get_mut(ix)
503        {
504            // Never downgrade a finished node back to "started" (retries reuse the id).
505            if !(s.finished() && status == Status::Started) {
506                if *s != status {
507                    self.changed.push(ix);
508                }
509                *s = status;
510            }
511        }
512    }
513
514    fn status_of(&self, ix: NodeIx) -> Status {
515        self.status.get(ix).copied().unwrap_or(Status::Unknown)
516    }
517
518    /// Whether `ix` is certain to run, given the certainty of its predecessors.
519    fn compute_certain(&self, ix: NodeIx, entry: NodeIx, certain: &[bool]) -> bool {
520        match self.status_of(ix) {
521            Status::Skipped => false,
522            Status::Unknown => ix == entry || self.has_certain_edge(ix, certain),
523            _ => true,
524        }
525    }
526
527    /// Bring the certain set up to date and enqueue newly certain responses.
528    ///
529    /// Certainty only grows as a run progresses, so after one full pass each
530    /// status change is propagated forward from the changed node: O(affected
531    /// nodes) per event instead of O(graph). A node losing certainty (not
532    /// expected in practice) falls back to a full recomputation.
533    fn refresh_certainty(&mut self) {
534        let Some(scope) = self.graph.root_scope() else {
535            return;
536        };
537        let entry = scope.entry;
538        let mut certain = std::mem::take(&mut self.certain);
539        certain.resize(self.graph.nodes().len(), false);
540        // The change list doubles as the work list; its buffer is handed back below.
541        let mut work = std::mem::take(&mut self.changed);
542        let mut full = !self.certain_valid;
543        if !full {
544            while let Some(ix) = work.pop() {
545                let now = self.compute_certain(ix, entry, &certain);
546                let before = certain.get(ix).copied().unwrap_or(false);
547                if before && !now {
548                    full = true;
549                    break;
550                }
551                if now != before
552                    && let Some(c) = certain.get_mut(ix)
553                {
554                    *c = now;
555                }
556                // Even when `ix` itself was already certain, its outgoing edges may
557                // have become certain (e.g. a branch picked its handle).
558                if now {
559                    for &ex in self.graph.outgoing(ix) {
560                        if let Some(edge) = self.graph.edge(ex)
561                            && !certain.get(edge.target).copied().unwrap_or(false)
562                            && self.compute_certain(edge.target, entry, &certain)
563                        {
564                            if let Some(c) = certain.get_mut(edge.target) {
565                                *c = true;
566                            }
567                            work.push(edge.target);
568                        }
569                    }
570                }
571            }
572        }
573        work.clear();
574        self.changed = work;
575        if full {
576            certain.iter_mut().for_each(|c| *c = false);
577            for &ix in &scope.nodes {
578                let is_certain = self.compute_certain(ix, entry, &certain);
579                if let Some(c) = certain.get_mut(ix) {
580                    *c = is_certain;
581                }
582            }
583        }
584        for (i, r) in self.responses.iter_mut().enumerate() {
585            if !r.queued && certain.get(r.node).copied().unwrap_or(false) {
586                r.queued = true;
587                self.queue.push_back(i);
588            }
589        }
590        self.certain = certain;
591        self.certain_valid = true;
592    }
593
594    /// Whether an incoming edge of `ix` will be taken given its (certain) source.
595    fn has_certain_edge(&self, ix: NodeIx, certain: &[bool]) -> bool {
596        self.graph.incoming(ix).iter().filter_map(|&ex| self.graph.edge(ex).map(|e| (ex, e))).any(|(ex, edge)| {
597            if !certain.get(edge.source).copied().unwrap_or(false) {
598                return false;
599            }
600            // States restored from a snapshot are authoritative.
601            match self.edge_state.get(ex).copied().flatten() {
602                Some(EdgeStatus::Taken) => return true,
603                Some(EdgeStatus::Skipped) => return false,
604                Some(EdgeStatus::Unknown) | None => {}
605            }
606            let Some(src) = self.graph.node(edge.source) else { return false };
607            let status = self.status_of(edge.source);
608            let fail_branch = matches!(src.policy.on_error, ErrorStrategy::FailBranch);
609            match status {
610                Status::Failed | Status::Skipped => false,
611                Status::Handled if fail_branch => edge.handle.as_ref() == FAIL_BRANCH,
612                Status::Handled if src.role == NodeRole::Branch => {
613                    default_branch(&src.policy.on_error).as_deref() == Some(edge.handle.as_ref())
614                }
615                Status::Handled => edge.handle.as_ref() != FAIL_BRANCH,
616                Status::Succeeded if src.role == NodeRole::Branch => {
617                    self.branch.get(edge.source).and_then(Option::as_deref) == Some(edge.handle.as_ref())
618                }
619                _ if src.role == NodeRole::Branch => false,
620                // Unfinished fail-branch node: which side it takes is not known yet.
621                _ if fail_branch => false,
622                _ => edge.handle.as_ref() != FAIL_BRANCH,
623            }
624        })
625    }
626
627    /// Render as much as possible. With `flush`, pending variables are treated as resolved.
628    fn drain(&mut self, flush: bool, out: &mut Vec<ResponseChunk>) {
629        loop {
630            if self.active.is_none() {
631                match self.queue.pop_front() {
632                    Some(response) => self.active = Some(Active { response, part: 0, offset: 0 }),
633                    None => return,
634                }
635            }
636            let Some(active) = self.active.as_mut() else { return };
637            let Some(response) = self.responses.get(active.response) else {
638                self.active = None;
639                continue;
640            };
641            // A response node that ended up skipped renders nothing.
642            if self.status.get(response.node).copied() == Some(Status::Skipped) {
643                self.finish_active(None, out);
644                continue;
645            }
646            // Parts are borrowed, not cloned: this runs for every streamed chunk.
647            match response.parts.get(active.part) {
648                None => {
649                    let id = Arc::clone(&response.id);
650                    self.finish_active(Some(&id), out);
651                }
652                Some(Part::Text(text)) => {
653                    let piece = Piece { response: active.response, id: &response.id };
654                    emit(&mut self.emitted, &mut self.segments, out, &piece, text.clone());
655                    active.part += 1;
656                    active.offset = 0;
657                }
658                Some(Part::Var(sel)) => {
659                    let sources = Sources {
660                        graph: &self.graph,
661                        status: &self.status,
662                        deferred: &self.deferred,
663                        streams: &self.streams,
664                        pool: &self.pool,
665                    };
666                    let step = resolve_var(&sources, sel, active.offset, flush);
667                    if !step.text.is_empty() {
668                        let piece = Piece { response: active.response, id: &response.id };
669                        emit(&mut self.emitted, &mut self.segments, out, &piece, step.text);
670                    }
671                    active.offset = step.offset;
672                    if step.complete {
673                        active.part += 1;
674                        active.offset = 0;
675                    } else {
676                        return;
677                    }
678                }
679            }
680        }
681    }
682
683    fn finish_active(&mut self, id: Option<&Arc<str>>, out: &mut Vec<ResponseChunk>) {
684        if let Some(active) = self.active.take() {
685            if let Some(r) = self.responses.get_mut(active.response) {
686                r.done = true;
687            }
688            if let Some(id) = id {
689                out.push(ResponseChunk::done(id));
690            }
691        }
692    }
693}
694
695struct Step {
696    text: String,
697    offset: usize,
698    complete: bool,
699}
700
701/// Read-only view of the state a template variable is resolved from.
702struct Sources<'a> {
703    graph: &'a Graph,
704    status: &'a [Status],
705    deferred: &'a [bool],
706    streams: &'a Streams,
707    pool: &'a VariablePool,
708}
709
710fn resolve_var(sources: &Sources<'_>, sel: &Selector, offset: usize, flush: bool) -> Step {
711    let Sources { graph, status, deferred, streams, pool } = *sources;
712    let node_ix = graph.index_of(sel.namespace()).filter(|&ix| graph.node(ix).is_some_and(|n| n.parent.is_none()));
713    let Some(ix) = node_ix else {
714        // Not produced by a root graph node: host-provided value (or nothing).
715        return Step { text: pool.get(sel).map(|v| v.to_text()).unwrap_or_default(), offset: 0, complete: true };
716    };
717    let node_status = status.get(ix).copied().unwrap_or(Status::Unknown);
718
719    let is_deferred = deferred.get(ix).copied().unwrap_or(false);
720    let buffered = if sel.path().is_empty() {
721        stream_buf(streams, sel.namespace(), sel.name()).filter(|b| !b.text.is_empty())
722    } else {
723        None
724    };
725
726    if is_deferred {
727        // Emitted only once the node has finished, from its final attempt.
728        let text = match node_status {
729            Status::Succeeded => match buffered {
730                Some(buf) => buf.text.clone(),
731                None => pool.get(sel).map(|v| v.to_text()).unwrap_or_default(),
732            },
733            // Default-value outputs (or nothing on fail-branch, whose outputs are only error fields).
734            Status::Handled => pool.get(sel).map(|v| v.to_text()).unwrap_or_default(),
735            _ => String::new(),
736        };
737        return Step { text, offset: 0, complete: node_status.finished() || flush };
738    }
739
740    // Live streaming: emit whatever was buffered beyond `offset`.
741    let mut text = String::new();
742    let mut new_offset = offset;
743    let streamed = buffered.is_some();
744    if let Some(buf) = buffered
745        && let Some(rest) = buf.text.get(offset..)
746    {
747        text.push_str(rest);
748        new_offset = buf.text.len();
749    }
750
751    let complete = match node_status {
752        Status::Skipped | Status::Failed => true,
753        Status::Succeeded | Status::Handled => {
754            if !streamed && let Some(v) = pool.get(sel) {
755                text.push_str(&v.to_text());
756            }
757            true
758        }
759        Status::Unknown | Status::Started => {
760            if flush
761                && !streamed
762                && let Some(v) = pool.get(sel)
763            {
764                text.push_str(&v.to_text());
765            }
766            flush
767        }
768    };
769    Step { text, offset: new_offset, complete }
770}
771
772/// Handle named by a `branch` entry of a `default-value` strategy.
773fn default_branch(strategy: &ErrorStrategy) -> Option<String> {
774    match strategy {
775        ErrorStrategy::DefaultValue { values } => values.get("branch").and_then(Value::as_str).map(str::to_owned),
776        _ => None,
777    }
778}
779
780/// The response a piece of text is emitted for.
781struct Piece<'a> {
782    /// Its index in `ResponseAssembler::responses`.
783    response: usize,
784    id: &'a Arc<str>,
785}
786
787fn emit(
788    emitted: &mut String,
789    segments: &mut Vec<(usize, usize)>,
790    out: &mut Vec<ResponseChunk>,
791    piece: &Piece<'_>,
792    text: String,
793) {
794    if text.is_empty() {
795        return;
796    }
797    emitted.push_str(&text);
798    match segments.last_mut() {
799        Some((response, len)) if *response == piece.response => *len += text.len(),
800        _ => segments.push((piece.response, text.len())),
801    }
802    out.push(ResponseChunk::text(piece.id, text));
803}
804
805fn end_parts(config: &serde_json::Map<String, serde_json::Value>) -> Vec<Part> {
806    let outputs: Vec<EndOutput> = config
807        .get("outputs")
808        .cloned()
809        .and_then(|v| serde_json::from_value::<Vec<serde_json::Value>>(v).ok())
810        .unwrap_or_default()
811        .into_iter()
812        .filter_map(|v| serde_json::from_value(v).ok())
813        .collect();
814    let mut parts = Vec::with_capacity(outputs.len() * 2);
815    for (i, o) in outputs.into_iter().enumerate() {
816        if i > 0 {
817            parts.push(Part::Text("\n".to_owned()));
818        }
819        parts.push(Part::Var(o.value_selector));
820    }
821    parts
822}