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}
253
254/// A workflow linked to an engine's runs ([`Engine::with_linked`]): its graph,
255/// the environment its child runs see (its own, not the parent's, resolved
256/// against its `env` declarations) and the services its host gives it.
257#[cfg(feature = "subagents")]
258#[derive(Clone, Debug)]
259pub struct LinkedWorkflow {
260 graph: Arc<Graph>,
261 env: IndexMap<String, Value>,
262 services: Option<Arc<Services>>,
263}
264
265#[cfg(feature = "subagents")]
266impl LinkedWorkflow {
267 /// `graph` with an empty environment and the parent run's services.
268 pub fn new(graph: Arc<Graph>) -> Self {
269 Self { graph, env: IndexMap::new(), services: None }
270 }
271
272 /// The `env.*` values its child runs see, before its declarations apply.
273 pub fn with_env(mut self, env: IndexMap<String, Value>) -> Self {
274 self.env = env;
275 self
276 }
277
278 /// The services its child runs use (its memory scope, skills, tools),
279 /// instead of the parent run's.
280 pub fn with_services(mut self, services: Arc<Services>) -> Self {
281 self.services = Some(services);
282 self
283 }
284
285 pub fn graph(&self) -> &Arc<Graph> {
286 &self.graph
287 }
288
289 pub fn env(&self) -> &IndexMap<String, Value> {
290 &self.env
291 }
292
293 pub fn services(&self) -> Option<&Arc<Services>> {
294 self.services.as_ref()
295 }
296
297 /// Check what a host can check when it links: the environment against the
298 /// workflow's `env` declarations, and start variables a model can supply.
299 ///
300 /// @throws String - what is wrong, for the host's start error.
301 pub fn check(&self) -> Result<(), String> {
302 self.resolved_env()?;
303 frame::start_schema(&self.graph).map(|_| ())
304 }
305
306 /// The environment resolved against the workflow's declarations: defaults
307 /// apply and a `secret` declaration makes a secret.
308 pub(crate) fn resolved_env(&self) -> Result<Vec<(String, Value)>, String> {
309 root::resolve_decls(&self.graph.workflow().env, &self.env, true).map_err(|why| format!("environment: {why}"))
310 }
311}
312
313impl Engine {
314 pub fn new(graph: Arc<Graph>) -> Self {
315 Self {
316 graph,
317 services: Arc::new(Services::new()),
318 clock: default_clock(),
319 limits: Limits::default(),
320 #[cfg(feature = "subagents")]
321 linked: Arc::new(IndexMap::new()),
322 #[cfg(feature = "subagents")]
323 linked_fingerprint: None,
324 }
325 }
326
327 /// Workflows the nodes of this engine's runs may start as child runs
328 /// ([`crate::node::ChildRuns`]), by name. A snapshot covers them: a run is
329 /// not resumed against a changed child workflow.
330 ///
331 /// It replaces the set given before, and a later entry replaces an
332 /// earlier one of the same name. A host links only what the
333 /// engine's agents list (and what those list in turn): every linked
334 /// workflow is in the fingerprint, so linking more would refuse a resume
335 /// whenever an unrelated workflow changed.
336 #[cfg(feature = "subagents")]
337 pub fn with_linked(mut self, linked: impl IntoIterator<Item = (String, LinkedWorkflow)>) -> Self {
338 self.linked = Arc::new(linked.into_iter().collect());
339 self.linked_fingerprint = (!self.linked.is_empty()).then(|| {
340 // Each name is prefixed with its length, so no two link sets give the same text.
341 let mut linked: Vec<String> = self
342 .linked
343 .iter()
344 .map(|(name, link)| format!("{}:{name}={}", name.len(), link.graph.fingerprint()))
345 .collect();
346 linked.sort();
347 Arc::from(format!("{}+{}", self.graph.fingerprint(), linked.join(",")))
348 });
349 self
350 }
351
352 /// The fingerprint a snapshot of this engine's runs carries: the graph's,
353 /// and the linked graphs' when there are any. Hosts compare a snapshot
354 /// with this, not with the graph's own fingerprint.
355 pub fn fingerprint(&self) -> &str {
356 #[cfg(feature = "subagents")]
357 if let Some(linked) = &self.linked_fingerprint {
358 return linked;
359 }
360 self.graph.fingerprint()
361 }
362
363 pub fn with_services(mut self, services: Services) -> Self {
364 self.services = Arc::new(services);
365 self
366 }
367
368 /// Share an existing services registry.
369 pub fn with_shared_services(mut self, services: Arc<Services>) -> Self {
370 self.services = services;
371 self
372 }
373
374 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
375 self.clock = clock;
376 self
377 }
378
379 pub fn with_limits(mut self, limits: Limits) -> Self {
380 self.limits = limits;
381 self
382 }
383
384 pub fn graph(&self) -> &Arc<Graph> {
385 &self.graph
386 }
387
388 /// The services this engine's runs use.
389 pub fn services(&self) -> &Arc<Services> {
390 &self.services
391 }
392
393 pub fn limits(&self) -> &Limits {
394 &self.limits
395 }
396
397 /// Start a run. The returned stream drives execution when polled (no task is
398 /// spawned), so it works on any executor. The final item is always a terminal
399 /// event (`RunSucceeded`, `RunFailed`, `RunAborted` or `RunPaused`).
400 pub fn run(&self, input: RunInput) -> RunStream {
401 let queue = Arc::new(EventQueue::default());
402 let control = Arc::new(Control::default());
403 let sink_queue = Arc::clone(&queue);
404 let sink: EventSink = Arc::new(move |event| sink_queue.push(event));
405 let driver = root::run_root(self.clone(), input, control.clone(), sink).boxed();
406 RunStream { driver: Some(driver), queue, finished: false, handle: RunHandle { control } }
407 }
408
409 /// Run to completion and return the terminal event, discarding the others.
410 pub async fn run_to_end(&self, input: RunInput) -> Event {
411 let mut stream = self.run(input);
412 let mut last = None;
413 while let Some(event) = stream.next().await {
414 last = Some(event);
415 }
416 last.unwrap_or(Event::RunFailed {
417 error: "run produced no events".to_owned(),
418 error_type: "internal".to_owned(),
419 usage: Default::default(),
420 elapsed_ms: 0,
421 })
422 }
423}
424
425/// The reason [`RunHandle::pause`] and [`RunHandle::preempt`] report.
426fn external_reason(reason: String) -> PauseReason {
427 PauseReason { frame: Arc::from(""), node_id: None, kind: "external".to_owned(), data: Value::from(reason) }
428}
429
430/// Events waiting for the stream's consumer.
431///
432/// Most events are produced while [`RunStream::poll_next`] polls the driver, on
433/// the consumer's own task; nodes may also emit from tasks of their own (e.g. a
434/// plugin's reader), which the waker covers. A `VecDeque` reuses its buffer, so
435/// unlike a channel no allocation is made per event.
436#[derive(Default)]
437struct EventQueue {
438 events: Mutex<VecDeque<Event>>,
439 waker: AtomicWaker,
440 /// Set when the stream is dropped: later events are discarded, not queued.
441 closed: AtomicBool,
442}
443
444impl EventQueue {
445 fn push(&self, event: Event) {
446 if self.closed.load(Ordering::Acquire) {
447 return;
448 }
449 self.events.lock().unwrap_or_else(PoisonError::into_inner).push_back(event);
450 self.waker.wake();
451 }
452
453 fn pop(&self) -> Option<Event> {
454 self.events.lock().unwrap_or_else(PoisonError::into_inner).pop_front()
455 }
456}
457
458/// Stream of run events. `Send + 'static`. Dropping it cancels the run.
459pub struct RunStream {
460 driver: Option<BoxFuture<'static, ()>>,
461 queue: Arc<EventQueue>,
462 finished: bool,
463 handle: RunHandle,
464}
465
466impl Drop for RunStream {
467 fn drop(&mut self) {
468 self.queue.closed.store(true, Ordering::Release);
469 }
470}
471
472impl std::fmt::Debug for RunStream {
473 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474 f.debug_struct("RunStream").field("finished", &self.finished).finish_non_exhaustive()
475 }
476}
477
478impl RunStream {
479 /// A handle for controlling the run from elsewhere.
480 pub fn handle(&self) -> RunHandle {
481 self.handle.clone()
482 }
483}
484
485impl Stream for RunStream {
486 type Item = Event;
487
488 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Event>> {
489 if self.finished {
490 return Poll::Ready(None);
491 }
492 if let Some(driver) = self.driver.as_mut()
493 && driver.as_mut().poll(cx).is_ready()
494 {
495 self.driver = None;
496 }
497 let event = match self.queue.pop() {
498 Some(event) => Some(event),
499 None if self.driver.is_none() => None,
500 None => {
501 // Only register when about to sleep (registering on every poll makes
502 // events pushed by this very task wake it again), then look once more
503 // so an event pushed from another task in between is not missed.
504 self.queue.waker.register(cx.waker());
505 match self.queue.pop() {
506 Some(event) => Some(event),
507 None => return Poll::Pending,
508 }
509 }
510 };
511 match event {
512 Some(event) => {
513 if event.is_terminal() {
514 self.finished = true;
515 }
516 Poll::Ready(Some(event))
517 }
518 None => {
519 // Every event is sent synchronously, so a finished driver with an
520 // empty queue means the run is over.
521 self.finished = true;
522 Poll::Ready(None)
523 }
524 }
525 }
526}
527
528/// Controls a running run. Cheap to clone, `Send + Sync`.
529#[derive(Clone, Debug)]
530pub struct RunHandle {
531 control: Arc<Control>,
532}
533
534impl RunHandle {
535 /// Cancel immediately: in-flight nodes are dropped. Ends with `RunAborted`.
536 pub fn abort(&self, reason: impl Into<String>) {
537 self.control.stop(Stop::Abort(reason.into()));
538 }
539
540 /// Stop scheduling new nodes, let in-flight nodes finish, then end with `RunPaused`
541 /// (or `RunSucceeded` if nothing was left to run).
542 pub fn pause(&self, reason: impl Into<String>) {
543 self.pause_with(external_reason(reason.into()));
544 }
545
546 /// [`RunHandle::pause`] with a caller-chosen reason (reported in `RunPaused`).
547 pub fn pause_with(&self, reason: PauseReason) {
548 self.control.request_pause(Some(reason));
549 }
550
551 /// Stop now: cancel in-flight nodes (dropping their futures), then end with
552 /// `RunPaused`. A cancelled node is saved as pending and runs again on resume,
553 /// with the same `exec_id` and attempt number, so execution is at-least-once
554 /// per node: hosts should key side effects on `run_id` + `exec_id`. Container
555 /// bodies are preempted too and resume where they stopped. Escalates an
556 /// earlier [`RunHandle::pause`]. Use it when the host cannot wait for nodes to
557 /// finish (a shutdown grace period shorter than an LLM call).
558 pub fn preempt(&self, reason: impl Into<String>) {
559 self.preempt_with(Some(external_reason(reason.into())));
560 }
561
562 /// [`RunHandle::preempt`] with a caller-chosen reason, or none to escalate an
563 /// earlier pause without reporting a second reason.
564 pub fn preempt_with(&self, reason: Option<PauseReason>) {
565 self.control.request_preempt(reason);
566 }
567
568 /// Whether the run was asked to stop: aborted, paused or preempted (by the
569 /// host or by one of its nodes). A host that holds back the run's stream
570 /// (backpressure) lets it through once this is true, so the stop is never
571 /// delayed.
572 pub fn stop_requested(&self) -> bool {
573 self.control.is_stopped() || self.control.pause_requested()
574 }
575
576 /// Write a variable into the root frame (applied between node completions).
577 pub fn update_variable(&self, selector: Selector, value: Value) {
578 self.control.push_update(selector, value);
579 }
580}