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}
134
135impl Default for Limits {
136 fn default() -> Self {
137 Self {
138 max_steps: 10_000,
139 max_duration_ms: None,
140 max_depth: 8,
141 default_node_timeout_ms: None,
142 max_concurrency: 64,
143 }
144 }
145}
146
147/// Input for a run.
148#[derive(Clone, Debug, Default)]
149pub struct RunInput {
150 /// Values for the start node's declared variables (written into the entry node's namespace).
151 pub inputs: IndexMap<String, Value>,
152 /// System variables (`sys.*`), e.g. `query`, `files`, `user_id`, `conversation_id`.
153 pub sys: IndexMap<String, Value>,
154 /// Environment variables (`env.*`); override document defaults. Never persisted.
155 pub env: IndexMap<String, Value>,
156 /// Conversation variables (`conversation.*`); override document defaults.
157 pub conversation: IndexMap<String, Value>,
158 /// Explicit run id (generated when absent).
159 pub run_id: Option<String>,
160 /// Resume a paused run.
161 pub resume: Option<ResumeFrom>,
162}
163
164impl RunInput {
165 pub fn new() -> Self {
166 Self::default()
167 }
168
169 /// Add a start input.
170 pub fn input(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
171 self.inputs.insert(name.into(), value.into());
172 self
173 }
174
175 /// Add a system variable.
176 pub fn sys(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
177 self.sys.insert(name.into(), value.into());
178 self
179 }
180
181 /// Add an environment variable.
182 pub fn env(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
183 self.env.insert(name.into(), value.into());
184 self
185 }
186
187 /// Resume from a snapshot.
188 pub fn resume(mut self, snapshot: Snapshot, inputs: IndexMap<String, Value>) -> Self {
189 self.resume = Some(ResumeFrom::new(snapshot, inputs));
190 self
191 }
192}
193
194/// Resume information.
195#[derive(Clone, Debug)]
196pub struct ResumeFrom {
197 pub snapshot: Snapshot,
198 /// Host input for paused nodes (e.g. a submitted human-input form), keyed by
199 /// `"<frame>/<node_id>"` for one specific frame or by plain node id for any
200 /// frame. Root-frame nodes use the plain node id.
201 pub inputs: IndexMap<String, Value>,
202 /// Plaintext for secrets outside `env.*` (e.g. secret-typed start inputs or
203 /// conversation variables), keyed by dotted selector (`"start.api_key"`).
204 /// Snapshots never store secret plaintext: such values are restored as
205 /// redacted secrets ([`Value::redacted_secret`]) and nodes that need them fail
206 /// until they are re-supplied here. Only selectors that currently hold a
207 /// redacted secret are overwritten.
208 pub secrets: IndexMap<String, Value>,
209}
210
211impl ResumeFrom {
212 /// Resume `snapshot` with host input for paused nodes.
213 pub fn new(snapshot: Snapshot, inputs: IndexMap<String, Value>) -> Self {
214 Self { snapshot, inputs, secrets: IndexMap::new() }
215 }
216
217 /// Re-supply a secret that is not an environment variable.
218 pub fn secret(mut self, selector: impl Into<String>, value: impl Into<String>) -> Self {
219 self.secrets.insert(selector.into(), Value::Secret(Arc::from(value.into())));
220 self
221 }
222}
223
224/// Executes runs of one graph.
225#[derive(Clone, Debug)]
226pub struct Engine {
227 graph: Arc<Graph>,
228 services: Arc<Services>,
229 clock: Arc<dyn Clock>,
230 limits: Limits,
231}
232
233impl Engine {
234 pub fn new(graph: Arc<Graph>) -> Self {
235 Self { graph, services: Arc::new(Services::new()), clock: default_clock(), limits: Limits::default() }
236 }
237
238 pub fn with_services(mut self, services: Services) -> Self {
239 self.services = Arc::new(services);
240 self
241 }
242
243 /// Share an existing services registry.
244 pub fn with_shared_services(mut self, services: Arc<Services>) -> Self {
245 self.services = services;
246 self
247 }
248
249 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
250 self.clock = clock;
251 self
252 }
253
254 pub fn with_limits(mut self, limits: Limits) -> Self {
255 self.limits = limits;
256 self
257 }
258
259 pub fn graph(&self) -> &Arc<Graph> {
260 &self.graph
261 }
262
263 pub fn limits(&self) -> &Limits {
264 &self.limits
265 }
266
267 /// Start a run. The returned stream drives execution when polled (no task is
268 /// spawned), so it works on any executor. The final item is always a terminal
269 /// event (`RunSucceeded`, `RunFailed`, `RunAborted` or `RunPaused`).
270 pub fn run(&self, input: RunInput) -> RunStream {
271 let queue = Arc::new(EventQueue::default());
272 let control = Arc::new(Control::default());
273 let sink_queue = Arc::clone(&queue);
274 let sink: EventSink = Arc::new(move |event| sink_queue.push(event));
275 let driver = root::run_root(self.clone(), input, control.clone(), sink).boxed();
276 RunStream { driver: Some(driver), queue, finished: false, handle: RunHandle { control } }
277 }
278
279 /// Run to completion and return the terminal event, discarding the others.
280 pub async fn run_to_end(&self, input: RunInput) -> Event {
281 let mut stream = self.run(input);
282 let mut last = None;
283 while let Some(event) = stream.next().await {
284 last = Some(event);
285 }
286 last.unwrap_or(Event::RunFailed {
287 error: "run produced no events".to_owned(),
288 error_type: "internal".to_owned(),
289 usage: Default::default(),
290 elapsed_ms: 0,
291 })
292 }
293}
294
295/// The reason [`RunHandle::pause`] and [`RunHandle::preempt`] report.
296fn external_reason(reason: String) -> PauseReason {
297 PauseReason { frame: Arc::from(""), node_id: None, kind: "external".to_owned(), data: Value::from(reason) }
298}
299
300/// Events waiting for the stream's consumer.
301///
302/// Most events are produced while [`RunStream::poll_next`] polls the driver, on
303/// the consumer's own task; nodes may also emit from tasks of their own (e.g. a
304/// plugin's reader), which the waker covers. A `VecDeque` reuses its buffer, so
305/// unlike a channel no allocation is made per event.
306#[derive(Default)]
307struct EventQueue {
308 events: Mutex<VecDeque<Event>>,
309 waker: AtomicWaker,
310 /// Set when the stream is dropped: later events are discarded, not queued.
311 closed: AtomicBool,
312}
313
314impl EventQueue {
315 fn push(&self, event: Event) {
316 if self.closed.load(Ordering::Acquire) {
317 return;
318 }
319 self.events.lock().unwrap_or_else(PoisonError::into_inner).push_back(event);
320 self.waker.wake();
321 }
322
323 fn pop(&self) -> Option<Event> {
324 self.events.lock().unwrap_or_else(PoisonError::into_inner).pop_front()
325 }
326}
327
328/// Stream of run events. `Send + 'static`. Dropping it cancels the run.
329pub struct RunStream {
330 driver: Option<BoxFuture<'static, ()>>,
331 queue: Arc<EventQueue>,
332 finished: bool,
333 handle: RunHandle,
334}
335
336impl Drop for RunStream {
337 fn drop(&mut self) {
338 self.queue.closed.store(true, Ordering::Release);
339 }
340}
341
342impl std::fmt::Debug for RunStream {
343 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344 f.debug_struct("RunStream").field("finished", &self.finished).finish_non_exhaustive()
345 }
346}
347
348impl RunStream {
349 /// A handle for controlling the run from elsewhere.
350 pub fn handle(&self) -> RunHandle {
351 self.handle.clone()
352 }
353}
354
355impl Stream for RunStream {
356 type Item = Event;
357
358 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Event>> {
359 if self.finished {
360 return Poll::Ready(None);
361 }
362 if let Some(driver) = self.driver.as_mut()
363 && driver.as_mut().poll(cx).is_ready()
364 {
365 self.driver = None;
366 }
367 let event = match self.queue.pop() {
368 Some(event) => Some(event),
369 None if self.driver.is_none() => None,
370 None => {
371 // Only register when about to sleep (registering on every poll makes
372 // events pushed by this very task wake it again), then look once more
373 // so an event pushed from another task in between is not missed.
374 self.queue.waker.register(cx.waker());
375 match self.queue.pop() {
376 Some(event) => Some(event),
377 None => return Poll::Pending,
378 }
379 }
380 };
381 match event {
382 Some(event) => {
383 if event.is_terminal() {
384 self.finished = true;
385 }
386 Poll::Ready(Some(event))
387 }
388 None => {
389 // Every event is sent synchronously, so a finished driver with an
390 // empty queue means the run is over.
391 self.finished = true;
392 Poll::Ready(None)
393 }
394 }
395 }
396}
397
398/// Controls a running run. Cheap to clone, `Send + Sync`.
399#[derive(Clone, Debug)]
400pub struct RunHandle {
401 control: Arc<Control>,
402}
403
404impl RunHandle {
405 /// Cancel immediately: in-flight nodes are dropped. Ends with `RunAborted`.
406 pub fn abort(&self, reason: impl Into<String>) {
407 self.control.stop(Stop::Abort(reason.into()));
408 }
409
410 /// Stop scheduling new nodes, let in-flight nodes finish, then end with `RunPaused`
411 /// (or `RunSucceeded` if nothing was left to run).
412 pub fn pause(&self, reason: impl Into<String>) {
413 self.pause_with(external_reason(reason.into()));
414 }
415
416 /// [`RunHandle::pause`] with a caller-chosen reason (reported in `RunPaused`).
417 pub fn pause_with(&self, reason: PauseReason) {
418 self.control.request_pause(Some(reason));
419 }
420
421 /// Stop now: cancel in-flight nodes (dropping their futures), then end with
422 /// `RunPaused`. A cancelled node is saved as pending and runs again on resume,
423 /// with the same `exec_id` and attempt number, so execution is at-least-once
424 /// per node: hosts should key side effects on `run_id` + `exec_id`. Container
425 /// bodies are preempted too and resume where they stopped. Escalates an
426 /// earlier [`RunHandle::pause`]. Use it when the host cannot wait for nodes to
427 /// finish (a shutdown grace period shorter than an LLM call).
428 pub fn preempt(&self, reason: impl Into<String>) {
429 self.preempt_with(Some(external_reason(reason.into())));
430 }
431
432 /// [`RunHandle::preempt`] with a caller-chosen reason, or none to escalate an
433 /// earlier pause without reporting a second reason.
434 pub fn preempt_with(&self, reason: Option<PauseReason>) {
435 self.control.request_preempt(reason);
436 }
437
438 /// Write a variable into the root frame (applied between node completions).
439 pub fn update_variable(&self, selector: Selector, value: Value) {
440 self.control.push_update(selector, value);
441 }
442}