Skip to main content

vlo_types/
envelope.rs

1//! The event envelope: kinds, statuses, causes, usage, and the journaled event shape.
2//!
3//! The kernel routes on the header fields alone and never parses `payload`
4//! (see `docs/kernel-protocol.md`).
5
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9/// The five event kinds. Projects cannot add kinds (see `docs/kernel-protocol.md`).
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
11#[serde(rename_all = "snake_case")]
12pub enum Kind {
13    /// An activity executed by a worker.
14    Task,
15    /// A durable timer the host fires at `fire_at_ms`.
16    Timer,
17    /// An external signal delivered to a parked `await_signal` step.
18    Signal,
19    /// A child run spawned by this run.
20    Child,
21    /// Kernel bookkeeping: `start`, `cancel`, `fail`, `complete`, `continue`, `nondeterminism`.
22    Marker,
23}
24
25/// The seven step statuses (see `docs/kernel-protocol.md`).
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
27#[serde(rename_all = "snake_case")]
28pub enum Status {
29    /// Opened, not yet accepted by a worker (timers, children and markers start here too).
30    Scheduled,
31    /// A worker accepted the task.
32    Running,
33    /// Terminal: the step produced a result.
34    Succeeded,
35    /// Terminal: non-retryable cause, attempts exhausted, or `schema_violation`.
36    Failed,
37    /// A retry was planned; the step returns to `scheduled` for the next attempt.
38    Retrying,
39    /// Terminal: cancelled by the run or by the user.
40    Cancelled,
41    /// Parked until a signal is delivered.
42    AwaitingSignal,
43}
44
45impl Status {
46    /// `true` for `succeeded`, `failed` and `cancelled`: the statuses with no outgoing edge.
47    pub fn is_terminal(self) -> bool {
48        matches!(self, Status::Succeeded | Status::Failed | Status::Cancelled)
49    }
50}
51
52/// Failure taxonomy. Retry policy is keyed on this, never on application error text.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
54#[serde(rename_all = "snake_case")]
55pub enum Cause {
56    /// The attempt exceeded its wall-clock budget (`timeout_ms`). Retryable.
57    Timeout,
58    /// The worker stopped heartbeating and its lease expired. Retryable.
59    HeartbeatLost,
60    /// The activity threw. Retryable.
61    AppError,
62    /// The user cancelled the run. Never retried.
63    UserCancel,
64    /// The worker's output failed schema validation. Never retried.
65    SchemaViolation,
66    /// A re-fold diverged from the journal. Never retried.
67    NondeterminismDetected,
68}
69
70/// Resource usage stamped on events and summed into `KernelState`. Integers only,
71/// because `KernelState` is hashed.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
73pub struct Usage {
74    /// CPU time consumed, in milliseconds.
75    #[serde(default)]
76    pub cpu_ms: u64,
77    /// Model tokens consumed.
78    #[serde(default)]
79    pub tokens: u64,
80    /// Cost in micro-USD (1 USD = 1_000_000). Integer so the hash stays float-free.
81    #[serde(default)]
82    pub cost_micro_usd: u64,
83}
84
85impl Usage {
86    /// Add `other` into `self`, saturating on overflow.
87    pub fn add(&mut self, other: &Usage) {
88        self.cpu_ms = self.cpu_ms.saturating_add(other.cpu_ms);
89        self.tokens = self.tokens.saturating_add(other.tokens);
90        self.cost_micro_usd = self.cost_micro_usd.saturating_add(other.cost_micro_usd);
91    }
92}
93
94/// An event as the host submits it, before the kernel assigns `seq` and `state_hash`.
95///
96/// `random` is 32 hex chars of host-generated randomness, journaled so that every
97/// consumer of randomness (retry jitter, reducer `random`) is replay-stable.
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
99pub struct EventInput {
100    /// The run this event belongs to.
101    pub run_id: String,
102    /// The step this event belongs to; `start` for the `started` marker.
103    pub step_id: String,
104    /// Task attempt this event is about (1-based); a `retrying` event names the *next*
105    /// attempt. `0` for every other kind.
106    #[serde(default)]
107    pub attempt: u32,
108    /// Event kind; the kernel routes on `kind`, `status` and `step_id`.
109    pub kind: Kind,
110    /// The step status this event moves the step to.
111    pub status: Status,
112    /// Failure cause on `failed` / `retrying` events; `None` otherwise.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub cause: Option<Cause>,
115    /// Resources this event consumed; banked into `KernelState::usage_total`.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub usage: Option<Usage>,
118    /// Host wall-clock at submission, in milliseconds since the Unix epoch. The reducer's
119    /// only clock.
120    pub ts_ms: u64,
121    /// 32 lowercase hex chars of host-generated randomness, journaled for replay.
122    pub random: String,
123    /// Schema the payload conforms to (`<name>@<content-hash>`), when known.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub schema_ref: Option<String>,
126    /// Inline JSON payload, byte-exact. Exactly one of `payload` / `payload_ref` may be set.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub payload: Option<String>,
129    /// `blob://sha256/<hex>` when the payload was offloaded.
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub payload_ref: Option<String>,
132    /// Free-text error detail for `failed` task events. Never interpreted by the kernel.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub error: Option<String>,
135}
136
137/// A journaled event: `EventInput` plus the kernel-assigned sequence number and the
138/// state hash after folding it (so a re-fold can pinpoint the divergent seq).
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
140pub struct Envelope {
141    /// The submitted event, flattened into the envelope on the wire.
142    #[serde(flatten)]
143    pub input: EventInput,
144    /// Sequence number assigned by the journal writer; strictly increasing per run,
145    /// starting at `1`.
146    pub seq: u64,
147    /// The parent run, when this run was spawned as a child.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub parent_run_id: Option<String>,
150    /// The parent's `spawn` step, when this run was spawned as a child.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub parent_step_id: Option<String>,
153    /// Hash of `(kernel_state, state)` after the transition that produced this event
154    /// (see `docs/kernel-protocol.md`).
155    pub state_hash: String,
156}
157
158/// Well-known step id of the `started` marker event.
159pub const START_STEP_ID: &str = "start";