Skip to main content

graphrt_core/
event.rs

1//! Events emitted by a run.
2//!
3//! Events are plain serializable data (tagged by `type`), so they can be
4//! streamed over SSE / websockets as-is. Secrets inside values are masked by
5//! [`crate::value::Value`]'s serializer.
6
7use indexmap::IndexMap;
8use serde::{Deserialize, Serialize};
9
10use crate::pool::Selector;
11use crate::snapshot::Snapshot;
12use crate::value::Value;
13use crate::variables::Variables;
14
15/// Identifies an execution frame. The root frame is the empty string; child
16/// frames are `"<container_node>[<index>]"` segments joined by `/`, e.g.
17/// `"iter[2]/loop[0]"`.
18pub type FrameId = std::sync::Arc<str>;
19
20/// Token usage reported by model-calling nodes, and what it cost.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
22pub struct Usage {
23    pub prompt_tokens: u64,
24    pub completion_tokens: u64,
25    pub total_tokens: u64,
26    /// Cost in millionths of the price unit of the providers file: model
27    /// calls with a price, and tools that report one (`image/generate` with a
28    /// `per_image` price). Zero, and left out of JSON, when nothing was priced.
29    #[serde(default, skip_serializing_if = "is_zero")]
30    pub cost_micros: u64,
31}
32
33fn is_zero(value: &u64) -> bool {
34    *value == 0
35}
36
37impl Usage {
38    pub fn add(&mut self, other: &Usage) {
39        self.prompt_tokens = self.prompt_tokens.saturating_add(other.prompt_tokens);
40        self.completion_tokens = self.completion_tokens.saturating_add(other.completion_tokens);
41        self.total_tokens = self.total_tokens.saturating_add(other.total_tokens);
42        self.cost_micros = self.cost_micros.saturating_add(other.cost_micros);
43    }
44
45    /// Each count less `other`'s, not below zero.
46    #[must_use]
47    pub fn saturating_sub(&self, other: &Usage) -> Usage {
48        Usage {
49            prompt_tokens: self.prompt_tokens.saturating_sub(other.prompt_tokens),
50            completion_tokens: self.completion_tokens.saturating_sub(other.completion_tokens),
51            total_tokens: self.total_tokens.saturating_sub(other.total_tokens),
52            cost_micros: self.cost_micros.saturating_sub(other.cost_micros),
53        }
54    }
55
56    /// Each count the larger of this and `other`'s.
57    #[must_use]
58    pub fn at_least(&self, other: &Usage) -> Usage {
59        Usage {
60            prompt_tokens: self.prompt_tokens.max(other.prompt_tokens),
61            completion_tokens: self.completion_tokens.max(other.completion_tokens),
62            total_tokens: self.total_tokens.max(other.total_tokens),
63            cost_micros: self.cost_micros.max(other.cost_micros),
64        }
65    }
66
67    pub fn is_zero(&self) -> bool {
68        self.total_tokens == 0 && self.prompt_tokens == 0 && self.completion_tokens == 0 && self.cost_micros == 0
69    }
70
71    /// The tokens a budget charges: the total, or prompt and completion when
72    /// the provider reported no total (never wrapping on bogus numbers).
73    pub fn billable_tokens(&self) -> u64 {
74        self.total_tokens.max(self.prompt_tokens.saturating_add(self.completion_tokens))
75    }
76}
77
78/// Why a run or node paused.
79#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
80pub struct PauseReason {
81    /// Frame of the node that requested the pause (empty for external pauses).
82    pub frame: FrameId,
83    /// Node that requested the pause, if any.
84    pub node_id: Option<String>,
85    /// Machine-readable kind, e.g. `human_input`, `external`, `approval`.
86    pub kind: String,
87    /// Free-form details (form definition, message, ...).
88    #[serde(default)]
89    pub data: Value,
90}
91
92/// A run event.
93#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
94#[serde(tag = "type", rename_all = "snake_case")]
95#[non_exhaustive]
96pub enum Event {
97    RunStarted {
98        run_id: String,
99        resumed: bool,
100    },
101    NodeStarted {
102        frame: FrameId,
103        node_id: std::sync::Arc<str>,
104        exec_id: std::sync::Arc<str>,
105        kind: std::sync::Arc<str>,
106        title: std::sync::Arc<str>,
107        attempt: u32,
108    },
109    /// Incremental output, e.g. LLM tokens for output `field`.
110    NodeChunk {
111        frame: FrameId,
112        node_id: std::sync::Arc<str>,
113        exec_id: std::sync::Arc<str>,
114        /// Output field the chunk belongs to. Shared: nodes that stream many
115        /// chunks reuse one allocation (see [`crate::NodeContext::chunk_shared`]).
116        field: std::sync::Arc<str>,
117        chunk: String,
118    },
119    /// Structured progress emitted by a node (agent steps, tool calls, iteration progress...).
120    NodeProgress {
121        frame: FrameId,
122        node_id: std::sync::Arc<str>,
123        exec_id: std::sync::Arc<str>,
124        name: String,
125        data: Value,
126    },
127    NodeRetry {
128        frame: FrameId,
129        node_id: std::sync::Arc<str>,
130        exec_id: std::sync::Arc<str>,
131        attempt: u32,
132        error: String,
133        delay_ms: u64,
134    },
135    NodeSucceeded {
136        frame: FrameId,
137        node_id: std::sync::Arc<str>,
138        exec_id: std::sync::Arc<str>,
139        /// The node's outputs, shared with its pool namespace (cloning is cheap).
140        outputs: Variables,
141        /// Selected branch handle for branch nodes.
142        #[serde(skip_serializing_if = "Option::is_none")]
143        branch: Option<String>,
144        #[serde(skip_serializing_if = "Option::is_none")]
145        usage: Option<Usage>,
146        #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
147        metadata: IndexMap<String, Value>,
148        elapsed_ms: u64,
149    },
150    /// A node failed. `handled` is true when its error strategy kept the run going.
151    NodeFailed {
152        frame: FrameId,
153        node_id: std::sync::Arc<str>,
154        exec_id: std::sync::Arc<str>,
155        error: String,
156        error_type: String,
157        handled: bool,
158        /// Outputs committed by the error strategy (`error_message`, defaults...).
159        #[serde(default, skip_serializing_if = "Variables::is_empty")]
160        outputs: Variables,
161        elapsed_ms: u64,
162    },
163    /// The node will not run because every incoming path was skipped.
164    NodeSkipped {
165        frame: FrameId,
166        node_id: std::sync::Arc<str>,
167    },
168    NodePaused {
169        frame: FrameId,
170        node_id: std::sync::Arc<str>,
171        exec_id: std::sync::Arc<str>,
172        reason: PauseReason,
173    },
174    /// A node wrote a variable outside its own outputs (assigner, conversation variable...).
175    VariableUpdated {
176        frame: FrameId,
177        node_id: std::sync::Arc<str>,
178        selector: Selector,
179        value: Value,
180    },
181    RunSucceeded {
182        outputs: IndexMap<String, Value>,
183        usage: Usage,
184        /// Failures handled by an error strategy (non-zero = partial success).
185        handled_errors: u32,
186        elapsed_ms: u64,
187    },
188    RunFailed {
189        error: String,
190        /// Machine-readable category: `invalid_input` (bad run input or resume
191        /// data), `snapshot_mismatch`, `limit_exceeded` (steps / duration / depth),
192        /// `internal`, or the failing node's own error type (e.g. `timeout`,
193        /// `http`, `model`).
194        #[serde(default)]
195        error_type: String,
196        usage: Usage,
197        elapsed_ms: u64,
198    },
199    RunAborted {
200        reason: String,
201        elapsed_ms: u64,
202    },
203    /// The run paused. Persist `snapshot` and pass it back to resume.
204    RunPaused {
205        reasons: Vec<PauseReason>,
206        snapshot: Box<Snapshot>,
207    },
208}
209
210impl Event {
211    /// Whether this is the final event of a run.
212    pub fn is_terminal(&self) -> bool {
213        matches!(
214            self,
215            Event::RunSucceeded { .. } | Event::RunFailed { .. } | Event::RunAborted { .. } | Event::RunPaused { .. }
216        )
217    }
218
219    /// Frame of node-level events.
220    pub fn frame(&self) -> Option<&FrameId> {
221        match self {
222            Event::NodeStarted { frame, .. }
223            | Event::NodeChunk { frame, .. }
224            | Event::NodeProgress { frame, .. }
225            | Event::NodeRetry { frame, .. }
226            | Event::NodeSucceeded { frame, .. }
227            | Event::NodeFailed { frame, .. }
228            | Event::NodeSkipped { frame, .. }
229            | Event::NodePaused { frame, .. }
230            | Event::VariableUpdated { frame, .. } => Some(frame),
231            _ => None,
232        }
233    }
234}