Skip to main content

graphrt_core/engine/
mod.rs

1//! The execution engine.
2//!
3//! # Model
4//!
5//! - The [`Graph`] is immutable and shared; each run keeps its own per-frame
6//!   node and edge state.
7//! - A node becomes ready once **every** incoming edge is resolved and **at
8//!   least one** is taken. A node whose incoming edges are all skipped is
9//!   skipped too (`NodeSkipped`), and the skip propagates downstream.
10//! - Non-branch nodes take every outgoing edge except `fail-branch` edges.
11//!   Branch nodes take the edges whose handle equals [`NodeOutput::branch`];
12//!   a branch node that selects no handle fails (subject to its error strategy).
13//!   A selected handle with no edges simply skips every outgoing path.
14//! - Response nodes (answer / end) merge their outputs into the frame outputs:
15//!   `answer` is concatenated, other keys overwrite. The root frame outputs are
16//!   the run outputs.
17//! - Nodes of one frame run concurrently (up to [`Limits::max_concurrency`]) as
18//!   futures polled by the run itself. Nothing is spawned, so the engine runs on
19//!   any executor, including single-threaded and wasm ones.
20//!
21//! # Run bootstrap
22//!
23//! The root pool receives `env.*` (document defaults coerced to their declared
24//! types, overridden by [`RunInput::env`]), `conversation.*` (same rule; missing
25//! values get their type's zero value), `sys.*` from [`RunInput::sys`] plus
26//! `sys.run_id`. [`RunInput::inputs`] are written into the **namespace of the
27//! root entry node** (normally the `start` node) before it runs; the start
28//! node validates them and re-emits them as its outputs. Inputs are never
29//! copied into `sys`, so an input cannot shadow a system variable.
30//!
31//! # Failures
32//!
33//! - **Retries** apply to every node kind when `retry.max_retries > 0` and the
34//!   error is [`NodeError::retryable`]. The delay is the larger of the policy
35//!   delay and [`NodeError::retry_after_ms`] (capped at five minutes), awaited
36//!   inside the node's own future, so other nodes keep running. The execution id is stable across
37//!   attempts, and a retry that eventually succeeds is not a handled error.
38//! - **Timeouts** (`timeout_ms`, else [`Limits::default_node_timeout_ms`]) apply
39//!   per attempt when the clock supports timers. The attempt deadline is also
40//!   exposed as [`NodeContext::deadline_ms`](crate::node::NodeContext) so nodes
41//!   that block synchronously can bound themselves.
42//! - After retries, the error strategy applies:
43//!   - `fail`: the frame fails. In the root frame the run ends with `RunFailed`
44//!     and in-flight nodes are dropped. In a container body, the container node
45//!     receives [`SubgraphResult::Failed`](crate::node::SubgraphResult).
46//!   - `fail-branch`: outputs `error_message` / `error_type`; only `fail-branch`
47//!     edges are taken.
48//!   - `default-value`: outputs are the defaults plus `error_message` /
49//!     `error_type`; non-branch nodes then continue as on success. Branch nodes
50//!     follow the handle named by a `branch` default value, or skip every
51//!     outgoing path if there is none.
52//!
53//!   Handled failures are counted in `RunSucceeded::handled_errors`.
54//! - A panicking node fails with error type `panic` (when unwinding is enabled).
55//!
56//! # Limits
57//!
58//! `max_steps` counts every node attempt in every frame and persists across
59//! pause / resume. `max_duration_ms` covers the whole run (including time before
60//! a pause) and is enforced by a timer race. `max_depth` bounds container nesting.
61//!
62//! # Containers
63//!
64//! Container nodes receive [`NodeContext::subgraph`](crate::node::NodeContext),
65//! which runs the container's body as a child frame (`"<parent>/<container>[i]"`)
66//! with the same scheduler, event sink, step budget and control signals. Writes
67//! to namespaces outside the body (container variables, conversation variables)
68//! are returned in `SubgraphResult::Completed::writes`; `broke` reports whether a
69//! `loop-end` node completed. Usage of container nodes themselves is not added
70//! to the run total (their children are already counted).
71//!
72//! # Pause / resume / abort
73//!
74//! - [`RunHandle::pause`] stops scheduling everywhere, lets in-flight nodes
75//!   finish and then ends with `RunPaused` carrying a [`Snapshot`].
76//! - [`RunHandle::preempt`] does not wait: in-flight nodes are cancelled and
77//!   saved as pending (same `exec_id`), so they run again on resume. Execution
78//!   is at-least-once per node; nodes with side effects should be idempotent on
79//!   `run_id` + `exec_id`.
80//! - A node returning [`NodeOutcome::Paused`](crate::node::NodeOutcome) pauses
81//!   only itself: independent branches keep running until nothing else can make
82//!   progress, then the run pauses.
83//! - On resume ([`RunInput::resume`]) the snapshot's graph fingerprint and
84//!   format are verified, env / sys / conversation values from the new
85//!   [`RunInput`] are applied, pending nodes re-run and paused nodes are resumed
86//!   with their saved state plus their entry in [`ResumeFrom::inputs`].
87//!   Inputs are looked up by the frame-qualified key `"<frame>/<node_id>"`
88//!   first (e.g. `"review[2]/approve"` for a node paused inside the third
89//!   item of iteration `review`; the frame is [`PauseReason::frame`]), then by
90//!   the plain node id, which applies to every frame.
91//! - [`RunHandle::abort`] drops every in-flight node future immediately.
92
93mod control;
94mod frame;
95mod ids;
96mod root;
97
98use std::collections::VecDeque;
99use std::pin::Pin;
100use std::sync::atomic::{AtomicBool, Ordering};
101use std::sync::{Arc, Mutex, PoisonError};
102use std::task::{Context, Poll};
103
104use futures::future::BoxFuture;
105use futures::task::AtomicWaker;
106use futures::{FutureExt, Stream, StreamExt};
107use indexmap::IndexMap;
108
109use self::control::{Control, Stop};
110use crate::event::{Event, PauseReason};
111use crate::graph::Graph;
112use crate::node::{Clock, EventSink, Services, default_clock};
113use crate::pool::Selector;
114use crate::snapshot::Snapshot;
115use crate::value::Value;
116
117#[cfg(doc)]
118use crate::node::{NodeError, NodeOutput};
119
120/// Resource limits for a run.
121#[derive(Clone, Debug, PartialEq)]
122pub struct Limits {
123    /// Maximum node executions (including retries and container bodies). Default 10 000.
124    pub max_steps: u64,
125    /// Wall-clock budget for the whole run. Enforced only with a timer-capable clock.
126    pub max_duration_ms: Option<u64>,
127    /// Maximum container nesting depth. Default 8.
128    pub max_depth: u32,
129    /// Timeout applied to nodes without their own `timeout_ms`.
130    pub default_node_timeout_ms: Option<u64>,
131    /// Maximum nodes executing concurrently within one frame. Default 64.
132    pub max_concurrency: usize,
133    /// Total tokens (prompt and completion) the run may use, child runs
134    /// included. Charged after every model response. Default none.
135    pub max_total_tokens: Option<u64>,
136    /// Cost the run may reach, in millionths of the price unit of the
137    /// providers file (prices per model). Default none.
138    pub max_cost_micros: Option<u64>,
139}
140
141impl Default for Limits {
142    fn default() -> Self {
143        Self {
144            max_steps: 10_000,
145            max_duration_ms: None,
146            max_depth: 8,
147            default_node_timeout_ms: None,
148            max_concurrency: 64,
149            max_total_tokens: None,
150            max_cost_micros: None,
151        }
152    }
153}
154
155/// Input for a run.
156#[derive(Clone, Debug, Default)]
157pub struct RunInput {
158    /// Values for the start node's declared variables (written into the entry node's namespace).
159    pub inputs: IndexMap<String, Value>,
160    /// System variables (`sys.*`), e.g. `query`, `files`, `user_id`, `conversation_id`.
161    pub sys: IndexMap<String, Value>,
162    /// Environment variables (`env.*`); override document defaults. Never persisted.
163    pub env: IndexMap<String, Value>,
164    /// Conversation variables (`conversation.*`); override document defaults.
165    pub conversation: IndexMap<String, Value>,
166    /// Explicit run id (generated when absent).
167    pub run_id: Option<String>,
168    /// Resume a paused run.
169    pub resume: Option<ResumeFrom>,
170    /// A token budget for this run, below the engine's
171    /// ([`Limits::max_total_tokens`]): the lower of the two applies.
172    pub max_total_tokens: Option<u64>,
173    /// A cost budget for this run in micro units, below the engine's
174    /// ([`Limits::max_cost_micros`]): the lower of the two applies.
175    pub max_cost_micros: Option<u64>,
176}
177
178impl RunInput {
179    pub fn new() -> Self {
180        Self::default()
181    }
182
183    /// Add a start input.
184    pub fn input(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
185        self.inputs.insert(name.into(), value.into());
186        self
187    }
188
189    /// Add a system variable.
190    pub fn sys(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
191        self.sys.insert(name.into(), value.into());
192        self
193    }
194
195    /// Add an environment variable.
196    pub fn env(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
197        self.env.insert(name.into(), value.into());
198        self
199    }
200
201    /// Resume from a snapshot.
202    pub fn resume(mut self, snapshot: Snapshot, inputs: IndexMap<String, Value>) -> Self {
203        self.resume = Some(ResumeFrom::new(snapshot, inputs));
204        self
205    }
206}
207
208/// Resume information.
209#[derive(Clone, Debug)]
210pub struct ResumeFrom {
211    pub snapshot: Snapshot,
212    /// Host input for paused nodes (e.g. a submitted human-input form), keyed by
213    /// `"<frame>/<node_id>"` for one specific frame or by plain node id for any
214    /// frame. Root-frame nodes use the plain node id.
215    pub inputs: IndexMap<String, Value>,
216    /// Plaintext for secrets outside `env.*` (e.g. secret-typed start inputs or
217    /// conversation variables), keyed by dotted selector (`"start.api_key"`).
218    /// Snapshots never store secret plaintext: such values are restored as
219    /// redacted secrets ([`Value::redacted_secret`]) and nodes that need them fail
220    /// until they are re-supplied here. Only selectors that currently hold a
221    /// redacted secret are overwritten.
222    pub secrets: IndexMap<String, Value>,
223}
224
225impl ResumeFrom {
226    /// Resume `snapshot` with host input for paused nodes.
227    pub fn new(snapshot: Snapshot, inputs: IndexMap<String, Value>) -> Self {
228        Self { snapshot, inputs, secrets: IndexMap::new() }
229    }
230
231    /// Re-supply a secret that is not an environment variable.
232    pub fn secret(mut self, selector: impl Into<String>, value: impl Into<String>) -> Self {
233        self.secrets.insert(selector.into(), Value::Secret(Arc::from(value.into())));
234        self
235    }
236}
237
238/// Executes runs of one graph.
239#[derive(Clone, Debug)]
240pub struct Engine {
241    graph: Arc<Graph>,
242    services: Arc<Services>,
243    clock: Arc<dyn Clock>,
244    limits: Limits,
245    /// Workflows its nodes may start as child runs, by name.
246    #[cfg(feature = "subagents")]
247    linked: Arc<IndexMap<String, LinkedWorkflow>>,
248    /// The fingerprint with the linked graphs, made when they are linked
249    /// (`None` without links: the graph's own).
250    #[cfg(feature = "subagents")]
251    linked_fingerprint: Option<Arc<str>>,
252    /// Env the host refuses this workflow (see [`Engine::with_refused_env`]).
253    #[cfg(feature = "bundle-env")]
254    refused_env: Option<Arc<RefusedEnv>>,
255}
256
257/// Env variables a host does not give a workflow it did not write (a
258/// bundle's), with how the host gives them: a run that needs one fails at
259/// its start instead of running without it.
260#[cfg(feature = "bundle-env")]
261#[derive(Clone, Debug, PartialEq, Eq)]
262pub struct RefusedEnv {
263    /// The refused names the workflow declares without a default.
264    pub names: Vec<String>,
265    /// How the host gives one (`pass --bundle-env NAME`), for the error.
266    pub hint: String,
267}
268
269#[cfg(feature = "bundle-env")]
270impl RefusedEnv {
271    /// The start error of a run that needs a refused name, `None` when none is needed.
272    pub(crate) fn failure(&self) -> Option<String> {
273        let name = self.names.first()?;
274        Some(format!(
275            "the workflow needs env `{name}`, which the host does not give it ({}): {}",
276            self.names.join(", "),
277            self.hint.replace("NAME", name)
278        ))
279    }
280}
281
282/// A workflow linked to an engine's runs ([`Engine::with_linked`]): its graph,
283/// the environment its child runs see (its own, not the parent's, resolved
284/// against its `env` declarations) and the services its host gives it.
285#[cfg(feature = "subagents")]
286#[derive(Clone, Debug)]
287pub struct LinkedWorkflow {
288    graph: Arc<Graph>,
289    env: IndexMap<String, Value>,
290    services: Option<Arc<Services>>,
291    #[cfg(feature = "bundle-env")]
292    refused_env: Option<Arc<RefusedEnv>>,
293}
294
295#[cfg(feature = "subagents")]
296impl LinkedWorkflow {
297    /// `graph` with an empty environment and the parent run's services.
298    pub fn new(graph: Arc<Graph>) -> Self {
299        Self {
300            graph,
301            env: IndexMap::new(),
302            services: None,
303            #[cfg(feature = "bundle-env")]
304            refused_env: None,
305        }
306    }
307
308    /// Env its child runs need and the host refuses: a child run fails at its start.
309    #[cfg(feature = "bundle-env")]
310    pub fn with_refused_env(mut self, refused: Option<Arc<RefusedEnv>>) -> Self {
311        self.refused_env = refused;
312        self
313    }
314
315    /// The `env.*` values its child runs see, before its declarations apply.
316    pub fn with_env(mut self, env: IndexMap<String, Value>) -> Self {
317        self.env = env;
318        self
319    }
320
321    /// The services its child runs use (its memory scope, skills, tools),
322    /// instead of the parent run's.
323    pub fn with_services(mut self, services: Arc<Services>) -> Self {
324        self.services = Some(services);
325        self
326    }
327
328    pub fn graph(&self) -> &Arc<Graph> {
329        &self.graph
330    }
331
332    pub fn env(&self) -> &IndexMap<String, Value> {
333        &self.env
334    }
335
336    pub fn services(&self) -> Option<&Arc<Services>> {
337        self.services.as_ref()
338    }
339
340    /// Check what a host can check when it links: the environment against the
341    /// workflow's `env` declarations, and start variables a model can supply.
342    ///
343    /// @throws String - what is wrong, for the host's start error.
344    pub fn check(&self) -> Result<(), String> {
345        self.declared_env()?;
346        frame::start_schema(&self.graph).map(|_| ())
347    }
348
349    /// The environment resolved against the workflow's declarations: defaults
350    /// apply and a `secret` declaration makes a secret.
351    pub(crate) fn resolved_env(&self) -> Result<Vec<(String, Value)>, String> {
352        self.declared_env()
353    }
354
355    /// Why a child run cannot start: env it needs that the host refuses
356    /// (`env_refused`). A host checks it at the child's start, never when it
357    /// links (the link is fine, the child is not given what it needs).
358    #[cfg(feature = "bundle-env")]
359    pub(crate) fn refused(&self) -> Option<String> {
360        self.refused_env.as_deref().and_then(RefusedEnv::failure)
361    }
362
363    fn declared_env(&self) -> Result<Vec<(String, Value)>, String> {
364        root::resolve_decls(&self.graph.workflow().env, &self.env, true).map_err(|why| format!("environment: {why}"))
365    }
366}
367
368impl Engine {
369    pub fn new(graph: Arc<Graph>) -> Self {
370        Self {
371            graph,
372            services: Arc::new(Services::new()),
373            clock: default_clock(),
374            limits: Limits::default(),
375            #[cfg(feature = "subagents")]
376            linked: Arc::new(IndexMap::new()),
377            #[cfg(feature = "subagents")]
378            linked_fingerprint: None,
379            #[cfg(feature = "bundle-env")]
380            refused_env: None,
381        }
382    }
383
384    /// Env the workflow needs and the host refuses it (a bundle's): a run fails
385    /// at its start with `env_refused`, naming the variable and how to give it.
386    #[cfg(feature = "bundle-env")]
387    pub fn with_refused_env(mut self, refused: Option<Arc<RefusedEnv>>) -> Self {
388        self.refused_env = refused.filter(|refused| !refused.names.is_empty());
389        self
390    }
391
392    /// What [`Engine::with_refused_env`] set.
393    #[cfg(feature = "bundle-env")]
394    pub fn refused_env(&self) -> Option<Arc<RefusedEnv>> {
395        self.refused_env.clone()
396    }
397
398    /// The workflows linked to this engine's runs, by name.
399    #[cfg(feature = "subagents")]
400    pub fn linked(&self) -> impl Iterator<Item = (&str, &LinkedWorkflow)> {
401        self.linked.iter().map(|(name, link)| (name.as_str(), link))
402    }
403
404    /// Workflows the nodes of this engine's runs may start as child runs
405    /// ([`crate::node::ChildRuns`]), by name. A snapshot covers them: a run is
406    /// not resumed against a changed child workflow.
407    ///
408    /// It replaces the set given before, and a later entry replaces an
409    /// earlier one of the same name. A host links only what the
410    /// engine's agents list (and what those list in turn): every linked
411    /// workflow is in the fingerprint, so linking more would refuse a resume
412    /// whenever an unrelated workflow changed.
413    #[cfg(feature = "subagents")]
414    pub fn with_linked(mut self, linked: impl IntoIterator<Item = (String, LinkedWorkflow)>) -> Self {
415        self.linked = Arc::new(linked.into_iter().collect());
416        self.linked_fingerprint = (!self.linked.is_empty()).then(|| {
417            // Each name is prefixed with its length, so no two link sets give the same text.
418            let mut linked: Vec<String> = self
419                .linked
420                .iter()
421                .map(|(name, link)| format!("{}:{name}={}", name.len(), link.graph.fingerprint()))
422                .collect();
423            linked.sort();
424            Arc::from(format!("{}+{}", self.graph.fingerprint(), linked.join(",")))
425        });
426        self
427    }
428
429    /// The fingerprint a snapshot of this engine's runs carries: the graph's,
430    /// and the linked graphs' when there are any. Hosts compare a snapshot
431    /// with this, not with the graph's own fingerprint.
432    pub fn fingerprint(&self) -> &str {
433        #[cfg(feature = "subagents")]
434        if let Some(linked) = &self.linked_fingerprint {
435            return linked;
436        }
437        self.graph.fingerprint()
438    }
439
440    pub fn with_services(mut self, services: Services) -> Self {
441        self.services = Arc::new(services);
442        self
443    }
444
445    /// Share an existing services registry.
446    pub fn with_shared_services(mut self, services: Arc<Services>) -> Self {
447        self.services = services;
448        self
449    }
450
451    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
452        self.clock = clock;
453        self
454    }
455
456    pub fn with_limits(mut self, limits: Limits) -> Self {
457        self.limits = limits;
458        self
459    }
460
461    pub fn graph(&self) -> &Arc<Graph> {
462        &self.graph
463    }
464
465    /// The services this engine's runs use.
466    pub fn services(&self) -> &Arc<Services> {
467        &self.services
468    }
469
470    pub fn limits(&self) -> &Limits {
471        &self.limits
472    }
473
474    /// Start a run. The returned stream drives execution when polled (no task is
475    /// spawned), so it works on any executor. The final item is always a terminal
476    /// event (`RunSucceeded`, `RunFailed`, `RunAborted` or `RunPaused`).
477    pub fn run(&self, input: RunInput) -> RunStream {
478        let queue = Arc::new(EventQueue::default());
479        let control = Arc::new(Control::default());
480        let sink_queue = Arc::clone(&queue);
481        let sink: EventSink = Arc::new(move |event| sink_queue.push(event));
482        let driver = root::run_root(self.clone(), input, control.clone(), sink).boxed();
483        RunStream { driver: Some(driver), queue, finished: false, handle: RunHandle { control } }
484    }
485
486    /// Run to completion and return the terminal event, discarding the others.
487    pub async fn run_to_end(&self, input: RunInput) -> Event {
488        let mut stream = self.run(input);
489        let mut last = None;
490        while let Some(event) = stream.next().await {
491            last = Some(event);
492        }
493        last.unwrap_or(Event::RunFailed {
494            error: "run produced no events".to_owned(),
495            error_type: "internal".to_owned(),
496            usage: Default::default(),
497            elapsed_ms: 0,
498        })
499    }
500}
501
502/// The reason [`RunHandle::pause`] and [`RunHandle::preempt`] report.
503fn external_reason(reason: String) -> PauseReason {
504    PauseReason { frame: Arc::from(""), node_id: None, kind: "external".to_owned(), data: Value::from(reason) }
505}
506
507/// Events waiting for the stream's consumer.
508///
509/// Most events are produced while [`RunStream::poll_next`] polls the driver, on
510/// the consumer's own task; nodes may also emit from tasks of their own (e.g. a
511/// plugin's reader), which the waker covers. A `VecDeque` reuses its buffer, so
512/// unlike a channel no allocation is made per event.
513#[derive(Default)]
514struct EventQueue {
515    events: Mutex<VecDeque<Event>>,
516    waker: AtomicWaker,
517    /// Set when the stream is dropped: later events are discarded, not queued.
518    closed: AtomicBool,
519}
520
521impl EventQueue {
522    fn push(&self, event: Event) {
523        if self.closed.load(Ordering::Acquire) {
524            return;
525        }
526        self.events.lock().unwrap_or_else(PoisonError::into_inner).push_back(event);
527        self.waker.wake();
528    }
529
530    fn pop(&self) -> Option<Event> {
531        self.events.lock().unwrap_or_else(PoisonError::into_inner).pop_front()
532    }
533}
534
535/// Stream of run events. `Send + 'static`. Dropping it cancels the run.
536pub struct RunStream {
537    driver: Option<BoxFuture<'static, ()>>,
538    queue: Arc<EventQueue>,
539    finished: bool,
540    handle: RunHandle,
541}
542
543impl Drop for RunStream {
544    fn drop(&mut self) {
545        self.queue.closed.store(true, Ordering::Release);
546    }
547}
548
549impl std::fmt::Debug for RunStream {
550    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
551        f.debug_struct("RunStream").field("finished", &self.finished).finish_non_exhaustive()
552    }
553}
554
555impl RunStream {
556    /// A handle for controlling the run from elsewhere.
557    pub fn handle(&self) -> RunHandle {
558        self.handle.clone()
559    }
560}
561
562impl Stream for RunStream {
563    type Item = Event;
564
565    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Event>> {
566        if self.finished {
567            return Poll::Ready(None);
568        }
569        if let Some(driver) = self.driver.as_mut()
570            && driver.as_mut().poll(cx).is_ready()
571        {
572            self.driver = None;
573        }
574        let event = match self.queue.pop() {
575            Some(event) => Some(event),
576            None if self.driver.is_none() => None,
577            None => {
578                // Only register when about to sleep (registering on every poll makes
579                // events pushed by this very task wake it again), then look once more
580                // so an event pushed from another task in between is not missed.
581                self.queue.waker.register(cx.waker());
582                match self.queue.pop() {
583                    Some(event) => Some(event),
584                    None => return Poll::Pending,
585                }
586            }
587        };
588        match event {
589            Some(event) => {
590                if event.is_terminal() {
591                    self.finished = true;
592                }
593                Poll::Ready(Some(event))
594            }
595            None => {
596                // Every event is sent synchronously, so a finished driver with an
597                // empty queue means the run is over.
598                self.finished = true;
599                Poll::Ready(None)
600            }
601        }
602    }
603}
604
605/// Controls a running run. Cheap to clone, `Send + Sync`.
606#[derive(Clone, Debug)]
607pub struct RunHandle {
608    control: Arc<Control>,
609}
610
611impl RunHandle {
612    /// Cancel immediately: in-flight nodes are dropped. Ends with `RunAborted`.
613    pub fn abort(&self, reason: impl Into<String>) {
614        self.control.stop(Stop::Abort(reason.into()));
615    }
616
617    /// Stop scheduling new nodes, let in-flight nodes finish, then end with `RunPaused`
618    /// (or `RunSucceeded` if nothing was left to run).
619    pub fn pause(&self, reason: impl Into<String>) {
620        self.pause_with(external_reason(reason.into()));
621    }
622
623    /// [`RunHandle::pause`] with a caller-chosen reason (reported in `RunPaused`).
624    pub fn pause_with(&self, reason: PauseReason) {
625        self.control.request_pause(Some(reason));
626    }
627
628    /// Stop now: cancel in-flight nodes (dropping their futures), then end with
629    /// `RunPaused`. A cancelled node is saved as pending and runs again on resume,
630    /// with the same `exec_id` and attempt number, so execution is at-least-once
631    /// per node: hosts should key side effects on `run_id` + `exec_id`. Container
632    /// bodies are preempted too and resume where they stopped. Escalates an
633    /// earlier [`RunHandle::pause`]. Use it when the host cannot wait for nodes to
634    /// finish (a shutdown grace period shorter than an LLM call).
635    pub fn preempt(&self, reason: impl Into<String>) {
636        self.preempt_with(Some(external_reason(reason.into())));
637    }
638
639    /// [`RunHandle::preempt`] with a caller-chosen reason, or none to escalate an
640    /// earlier pause without reporting a second reason.
641    pub fn preempt_with(&self, reason: Option<PauseReason>) {
642        self.control.request_preempt(reason);
643    }
644
645    /// Whether the run was asked to stop: aborted, paused or preempted (by the
646    /// host or by one of its nodes). A host that holds back the run's stream
647    /// (backpressure) lets it through once this is true, so the stop is never
648    /// delayed.
649    pub fn stop_requested(&self) -> bool {
650        self.control.is_stopped() || self.control.pause_requested()
651    }
652
653    /// Write a variable into the root frame (applied between node completions).
654    pub fn update_variable(&self, selector: Selector, value: Value) {
655        self.control.push_update(selector, value);
656    }
657}