Skip to main content

graphrt_core/
store.rs

1//! Durable run records for hosts that serve many runs (an HTTP server, a job queue).
2//!
3//! A [`RunStore`] keeps, per run: a [`RunRecord`] (status, outputs, pause
4//! reasons...), the run's events as JSON, and the [`Snapshot`] of a paused run, so
5//! a run can be resumed by id after the client went away or the host restarted.
6//!
7//! Nothing secret is persisted: event values serialize with secrets masked, and
8//! snapshots never contain secret plaintext (see [`crate::snapshot`]).
9//!
10//! # Writes that can be retried
11//!
12//! A host that writes through a network (a gateway in front of agents, an
13//! object store) must be able to retry any write without corrupting the run:
14//!
15//! - [`RunStore::append_events`] takes the index of the first event of the
16//!   batch. A batch that is already stored (a retry after a lost reply) is
17//!   accepted without storing it twice; a batch that would leave a gap, or that
18//!   differs from the events already stored at those indices, is refused.
19//! - [`RunStore::put_if`] replaces a record only while its [`RunRecord::epoch`]
20//!   is still the expected one, so a stale writer (a zombie replica, an
21//!   execution that was taken over) cannot overwrite a newer one.
22//! - Every claim ([`RunStore::claim_resume`], [`RunStore::claim_dispatch`])
23//!   increments the epoch.
24
25use std::fmt;
26
27use futures::future::BoxFuture;
28use indexmap::IndexMap;
29use serde::{Deserialize, Serialize};
30
31use crate::event::{Event, PauseReason, Usage};
32use crate::snapshot::Snapshot;
33use crate::value::Value;
34
35/// Lifecycle status of a stored run.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38#[non_exhaustive]
39pub enum RunStatus {
40    /// Accepted but not dispatched to an executor yet (a gateway's queue).
41    Queued,
42    Running,
43    Paused,
44    Succeeded,
45    Failed,
46    Aborted,
47}
48
49impl RunStatus {
50    /// Whether the run reached a final state.
51    pub fn is_terminal(self) -> bool {
52        matches!(self, RunStatus::Succeeded | RunStatus::Failed | RunStatus::Aborted)
53    }
54
55    /// Parse the wire name (`running`, `paused`, ...).
56    pub fn parse(text: &str) -> Option<Self> {
57        match text {
58            "queued" => Some(RunStatus::Queued),
59            "running" => Some(RunStatus::Running),
60            "paused" => Some(RunStatus::Paused),
61            "succeeded" => Some(RunStatus::Succeeded),
62            "failed" => Some(RunStatus::Failed),
63            "aborted" => Some(RunStatus::Aborted),
64            _ => None,
65        }
66    }
67}
68
69/// Persisted summary of one run.
70///
71/// The struct is `#[non_exhaustive]`: build one with [`RunRecord::running`] or
72/// [`RunRecord::queued`] and set fields afterwards.
73#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
74#[non_exhaustive]
75pub struct RunRecord {
76    pub run_id: String,
77    /// Name the workflow is served under.
78    pub workflow: String,
79    /// Fingerprint of the workflow graph (resume requires the same graph).
80    pub fingerprint: String,
81    pub status: RunStatus,
82    pub created_ms: u64,
83    pub updated_ms: u64,
84    /// Why the run is paused (empty unless `status == paused`).
85    #[serde(default)]
86    pub pause_reasons: Vec<PauseReason>,
87    #[serde(default)]
88    pub outputs: IndexMap<String, Value>,
89    /// Ordered answer text assembled from response nodes.
90    #[serde(default)]
91    pub answer: String,
92    #[serde(default)]
93    pub error: Option<String>,
94    #[serde(default)]
95    pub error_type: Option<String>,
96    #[serde(default)]
97    pub usage: Usage,
98    /// Index of the run's next event: how many events were appended so far. Stores
99    /// keep at most their per-run cap of them (see `events_truncated`); the count
100    /// keeps growing past it so event indices (and SSE `id:`s) stay stable.
101    #[serde(default)]
102    pub event_count: u64,
103    /// Whether events were dropped because the store's per-run cap was reached.
104    #[serde(default)]
105    pub events_truncated: bool,
106    /// Run inputs as the start node accepted them, secrets masked. Only kept when
107    /// the host opts in (`graphrt serve --store-inputs`).
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub inputs: Option<IndexMap<String, Value>>,
110    /// OpenTelemetry trace id (32 hex digits) of the latest execution, when traced.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub trace_id: Option<String>,
113    /// Span id (16 hex digits) of that execution's root `invoke_workflow` span, so
114    /// later spans (online evaluation scores) can join the same trace.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub span_id: Option<String>,
117    /// Caller-supplied labels for filtering and evaluation (`RunRequest.metadata`).
118    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
119    pub metadata: IndexMap<String, String>,
120    /// Caller's session / conversation id.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub session_id: Option<String>,
123    /// Caller's end-user id.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub user_id: Option<String>,
126    /// Whether `user_id` is the verified subject of an end-user token (the
127    /// host checked its signature) rather than a label the caller sent. Only
128    /// a verified owner may act on the run as that user (rate it, for example).
129    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
130    pub user_verified: bool,
131    /// Caller-supplied tags.
132    #[serde(default, skip_serializing_if = "Vec::is_empty")]
133    pub tags: Vec<String>,
134    /// Deployment the run belongs to (the namespace of a gateway's store); `None`
135    /// on a standalone server.
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub deployment: Option<String>,
138    /// Immutable version of that deployment the run executes (resume needs the
139    /// same workflow graph).
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub deployment_version: Option<String>,
142    /// Execution epoch: 0 when created, incremented by every claim (dispatch,
143    /// resume). Conditional writes ([`RunStore::put_if`]) compare it, and an
144    /// executor refuses work for an epoch other than the one it was given.
145    #[serde(default)]
146    pub epoch: u64,
147    /// Who executes the current epoch (a replica id), when known.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub owner: Option<String>,
150}
151
152impl RunRecord {
153    /// A new `running` record.
154    pub fn running(
155        run_id: impl Into<String>,
156        workflow: impl Into<String>,
157        fingerprint: impl Into<String>,
158        now_ms: u64,
159    ) -> Self {
160        Self {
161            run_id: run_id.into(),
162            workflow: workflow.into(),
163            fingerprint: fingerprint.into(),
164            status: RunStatus::Running,
165            created_ms: now_ms,
166            updated_ms: now_ms,
167            pause_reasons: Vec::new(),
168            outputs: IndexMap::new(),
169            answer: String::new(),
170            error: None,
171            error_type: None,
172            usage: Usage::default(),
173            event_count: 0,
174            events_truncated: false,
175            inputs: None,
176            trace_id: None,
177            span_id: None,
178            metadata: IndexMap::new(),
179            session_id: None,
180            user_id: None,
181            user_verified: false,
182            tags: Vec::new(),
183            deployment: None,
184            deployment_version: None,
185            epoch: 0,
186            owner: None,
187        }
188    }
189
190    /// A new `queued` record (epoch 0) of `deployment`, waiting to be dispatched
191    /// with [`RunStore::claim_dispatch`].
192    pub fn queued(
193        run_id: impl Into<String>,
194        workflow: impl Into<String>,
195        fingerprint: impl Into<String>,
196        deployment: Option<String>,
197        now_ms: u64,
198    ) -> Self {
199        let mut record = Self::running(run_id, workflow, fingerprint, now_ms);
200        record.status = RunStatus::Queued;
201        record.deployment = deployment;
202        record
203    }
204
205    /// Apply a terminal event (`RunSucceeded`, `RunFailed`, `RunAborted`, `RunPaused`).
206    /// Returns the snapshot of a paused run so the caller can persist it.
207    pub fn apply_terminal(&mut self, event: &Event, now_ms: u64) -> Option<Snapshot> {
208        self.updated_ms = now_ms;
209        match event {
210            Event::RunSucceeded { outputs, usage, .. } => {
211                self.status = RunStatus::Succeeded;
212                self.outputs.clone_from(outputs);
213                self.usage = *usage;
214                self.pause_reasons.clear();
215                None
216            }
217            Event::RunFailed { error, error_type, usage, .. } => {
218                self.status = RunStatus::Failed;
219                self.error = Some(error.clone());
220                self.error_type = Some(error_type.clone());
221                self.usage = *usage;
222                self.pause_reasons.clear();
223                None
224            }
225            Event::RunAborted { reason, .. } => {
226                self.status = RunStatus::Aborted;
227                self.error = Some(reason.clone());
228                self.pause_reasons.clear();
229                None
230            }
231            Event::RunPaused { reasons, snapshot } => {
232                self.status = RunStatus::Paused;
233                self.pause_reasons.clone_from(reasons);
234                self.usage = snapshot.usage;
235                Some((**snapshot).clone())
236            }
237            _ => None,
238        }
239    }
240}
241
242/// Query for [`RunStore::list`].
243#[derive(Clone, Debug, Default, PartialEq, Eq)]
244pub struct RunFilter {
245    pub workflow: Option<String>,
246    pub status: Option<RunStatus>,
247    /// Maximum records returned (stores cap this; 0 means the store default).
248    pub limit: usize,
249    /// Continue after this run id (the `next_cursor` of a previous page).
250    pub cursor: Option<String>,
251}
252
253/// One page of [`RunStore::list`], newest first.
254#[derive(Clone, Debug, Default, PartialEq, Serialize)]
255pub struct RunPage {
256    pub runs: Vec<RunRecord>,
257    pub next_cursor: Option<String>,
258}
259
260/// Store failure.
261#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
262#[non_exhaustive]
263pub enum StoreError {
264    #[error("run `{0}` not found")]
265    NotFound(String),
266    /// The operation conflicts with the run's current state (already exists,
267    /// not paused, already being resumed).
268    #[error("{0}")]
269    Conflict(String),
270    #[error("invalid run id `{0}`")]
271    InvalidId(String),
272    /// A conditional write found another epoch than the expected one (another
273    /// writer got there first).
274    #[error("{0}")]
275    Precondition(String),
276    #[error("run store I/O error: {0}")]
277    Io(String),
278    #[error("corrupt run store entry: {0}")]
279    Corrupt(String),
280}
281
282/// Result type of [`RunStore`] operations.
283pub type StoreResult<T> = Result<T, StoreError>;
284
285/// Durable storage of run records, events and snapshots.
286///
287/// Implementations must make [`RunStore::claim_resume`] and [`RunStore::put_if`]
288/// atomic: of two concurrent claims (or conditional writes) on the same run,
289/// exactly one succeeds. [`RunStore::append_events`] must be idempotent per
290/// index range (see the module docs). The `store-conformance` feature of this
291/// crate ships an abstract test suite every implementation should pass.
292pub trait RunStore: Send + Sync + fmt::Debug {
293    /// Insert a new record. Fails with [`StoreError::Conflict`] if the id exists.
294    fn create(&self, record: RunRecord) -> BoxFuture<'_, StoreResult<()>>;
295    /// Insert or replace a record, unconditionally. Hosts with more than one
296    /// writer use [`RunStore::put_if`] instead.
297    fn put(&self, record: RunRecord) -> BoxFuture<'_, StoreResult<()>>;
298    /// Replace the record of an existing run only while its stored `epoch` is
299    /// `expected_epoch`. Fails with [`StoreError::Precondition`] otherwise, and
300    /// with [`StoreError::NotFound`] when the run does not exist. The store keeps
301    /// its own event counters, as with `put`.
302    fn put_if(&self, record: RunRecord, expected_epoch: u64) -> BoxFuture<'_, StoreResult<()>>;
303    fn get<'a>(&'a self, run_id: &'a str) -> BoxFuture<'a, StoreResult<Option<RunRecord>>>;
304    fn list(&self, filter: RunFilter) -> BoxFuture<'_, StoreResult<RunPage>>;
305    /// Remove a run and everything stored for it. Returns whether it existed.
306    fn delete<'a>(&'a self, run_id: &'a str) -> BoxFuture<'a, StoreResult<bool>>;
307    /// Append events (already serialized by [`event_to_stored`], secrets masked)
308    /// whose first one has index `first_index`, and return the run's new
309    /// [`RunRecord::event_count`].
310    ///
311    /// Idempotent: events at indices already stored must equal the stored ones
312    /// and are skipped (a retried batch is not stored twice). Fails with
313    /// [`StoreError::Conflict`] when `first_index` is past the run's event count
314    /// (a gap) or an overlapping event differs. Stores may cap the number of
315    /// events kept per run; they then set `events_truncated` and keep counting.
316    fn append_events<'a>(
317        &'a self,
318        run_id: &'a str,
319        first_index: u64,
320        events: &'a [StoredEvent],
321    ) -> BoxFuture<'a, StoreResult<u64>>;
322    /// Stored events, starting at index `from`.
323    fn events<'a>(&'a self, run_id: &'a str, from: u64) -> BoxFuture<'a, StoreResult<Vec<StoredEvent>>>;
324    fn save_snapshot<'a>(&'a self, run_id: &'a str, snapshot: &'a Snapshot) -> BoxFuture<'a, StoreResult<()>>;
325    fn load_snapshot<'a>(&'a self, run_id: &'a str) -> BoxFuture<'a, StoreResult<Option<Snapshot>>>;
326    /// Atomically move a `paused` run to `running`, increment its epoch and
327    /// return the updated record. Fails with [`StoreError::Conflict`] when the
328    /// run is not paused (including when another request claimed it first).
329    fn claim_resume<'a>(&'a self, run_id: &'a str, now_ms: u64) -> BoxFuture<'a, StoreResult<RunRecord>>;
330    /// Compare-and-set a `queued` or `paused` run at `expected_epoch` to
331    /// `running` at `expected_epoch + 1`, executed by `owner`, before the run is
332    /// handed to that executor. Fails with [`StoreError::Precondition`] when the
333    /// epoch moved, [`StoreError::Conflict`] when the run is in another status.
334    ///
335    /// The default implementation is `get` + [`RunStore::put_if`], which is
336    /// atomic as long as `put_if` is.
337    fn claim_dispatch<'a>(
338        &'a self,
339        run_id: &'a str,
340        expected_epoch: u64,
341        owner: Option<String>,
342        now_ms: u64,
343    ) -> BoxFuture<'a, StoreResult<RunRecord>> {
344        Box::pin(async move {
345            let mut record = self.get(run_id).await?.ok_or_else(|| StoreError::NotFound(run_id.to_owned()))?;
346            if !matches!(record.status, RunStatus::Queued | RunStatus::Paused) {
347                return Err(StoreError::Conflict(format!("run `{run_id}` is not queued or paused")));
348            }
349            check_epoch(&record, expected_epoch)?;
350            record.status = RunStatus::Running;
351            record.epoch = expected_epoch.saturating_add(1);
352            record.owner = owner;
353            record.updated_ms = now_ms;
354            self.put_if(record.clone(), expected_epoch).await?;
355            Ok(record)
356        })
357    }
358    /// After a host restart: mark every `running` run as `failed` ("interrupted by
359    /// restart"). Paused and queued runs are kept. Returns how many runs were marked.
360    fn recover_interrupted(&self, now_ms: u64) -> BoxFuture<'_, StoreResult<usize>>;
361    /// Delete runs (any status except `running` and `queued`) last updated before
362    /// `cutoff_ms`.
363    fn purge_before(&self, cutoff_ms: u64) -> BoxFuture<'_, StoreResult<usize>>;
364}
365
366/// [`StoreError::Precondition`] unless `record` is at `expected_epoch`.
367pub fn check_epoch(record: &RunRecord, expected_epoch: u64) -> StoreResult<()> {
368    if record.epoch == expected_epoch {
369        Ok(())
370    } else {
371        Err(StoreError::Precondition(format!(
372            "run `{}` is at epoch {}, expected {expected_epoch}",
373            record.run_id, record.epoch
374        )))
375    }
376}
377
378/// How a batch passed to [`RunStore::append_events`] lines up with the events a
379/// store already holds (shared by implementations).
380#[derive(Clone, Copy, Debug, PartialEq, Eq)]
381pub struct AppendPlan {
382    /// Leading events of the batch that are already stored (a retry); they must
383    /// equal the stored ones at `first_index..first_index + overlap`.
384    pub overlap: usize,
385    /// The run's event count after the append.
386    pub new_count: u64,
387}
388
389/// Plan an append of `batch_len` events at `first_index` to a run holding
390/// `event_count` events. Fails with [`StoreError::Conflict`] on a gap.
391pub fn plan_append(run_id: &str, event_count: u64, first_index: u64, batch_len: usize) -> StoreResult<AppendPlan> {
392    if first_index > event_count {
393        return Err(StoreError::Conflict(format!(
394            "run `{run_id}`: events must be appended at index {event_count}, not {first_index}"
395        )));
396    }
397    let batch = u64::try_from(batch_len).unwrap_or(u64::MAX);
398    let overlap = (event_count - first_index).min(batch);
399    Ok(AppendPlan {
400        overlap: usize::try_from(overlap).unwrap_or(usize::MAX),
401        new_count: event_count.max(first_index.saturating_add(batch)),
402    })
403}
404
405/// [`StoreError::Conflict`] for a retried event that differs from the stored one.
406pub fn append_mismatch(run_id: &str, index: u64) -> StoreError {
407    StoreError::Conflict(format!("run `{run_id}`: event {index} differs from the one already stored"))
408}
409
410/// Error message stored on runs interrupted by a host restart.
411pub const INTERRUPTED_BY_RESTART: &str = "interrupted by restart";
412
413/// An event serialized as one JSON object, the form in which stores keep events.
414///
415/// Holding the JSON text instead of a [`serde_json::Value`] tree saves building
416/// a map per event on the way in and re-serializing it on the way out.
417pub type StoredEvent = Box<serde_json::value::RawValue>;
418
419/// Serialize an event for storage: the same JSON as [`event_to_json`], written
420/// straight to text.
421pub fn event_to_stored(event: &Event) -> StoredEvent {
422    let text = match event {
423        // Rare, and the snapshot has to be dropped: go through the tree.
424        Event::RunPaused { .. } => serde_json::to_string(&event_to_json(event)),
425        _ => serde_json::to_string(event),
426    };
427    text.ok()
428        .and_then(|text| serde_json::value::RawValue::from_string(text).ok())
429        .unwrap_or_else(|| serde_json::value::RawValue::NULL.to_owned())
430}
431
432/// The `type` field of a stored event (e.g. `node_started`), if it has one.
433pub fn stored_event_type(event: &StoredEvent) -> Option<&str> {
434    #[derive(Deserialize)]
435    struct TypeOnly<'a> {
436        #[serde(rename = "type", borrow)]
437        kind: Option<&'a str>,
438    }
439    serde_json::from_str::<TypeOnly<'_>>(event.get()).ok().and_then(|t| t.kind)
440}
441
442/// Serialize an event for storage. Secrets are masked by the value serializer; the
443/// snapshot carried by `run_paused` is dropped (stores keep it separately).
444pub fn event_to_json(event: &Event) -> serde_json::Value {
445    let mut json = serde_json::to_value(event).unwrap_or(serde_json::Value::Null);
446    if let Some(obj) = json.as_object_mut()
447        && obj.get("type").and_then(serde_json::Value::as_str) == Some("run_paused")
448    {
449        obj.remove("snapshot");
450    }
451    json
452}
453
454/// Validate a run id used as a storage key: 1–128 chars of `[A-Za-z0-9_.-]`, not
455/// starting with `.`.
456pub fn validate_run_id(run_id: &str) -> StoreResult<()> {
457    let ok = !run_id.is_empty()
458        && run_id.len() <= 128
459        && !run_id.starts_with('.')
460        && run_id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
461    if ok { Ok(()) } else { Err(StoreError::InvalidId(run_id.chars().take(64).collect())) }
462}
463
464/// Current Unix time in milliseconds (0 where no clock exists).
465pub fn now_ms() -> u64 {
466    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
467    {
468        0
469    }
470    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
471    {
472        std::time::SystemTime::now()
473            .duration_since(std::time::UNIX_EPOCH)
474            .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
475            .unwrap_or(0)
476    }
477}
478
479/// Apply `filter` to records already sorted newest first (shared by implementations).
480pub fn page_of(mut sorted: Vec<RunRecord>, filter: &RunFilter, max_limit: usize) -> RunPage {
481    sorted.retain(|r| {
482        filter.workflow.as_deref().is_none_or(|w| r.workflow == w) && filter.status.is_none_or(|s| r.status == s)
483    });
484    let start = match &filter.cursor {
485        Some(cursor) => sorted.iter().position(|r| &r.run_id == cursor).map_or(sorted.len(), |i| i + 1),
486        None => 0,
487    };
488    let limit = if filter.limit == 0 { max_limit } else { filter.limit.min(max_limit) };
489    let runs: Vec<RunRecord> = sorted.into_iter().skip(start).take(limit.saturating_add(1)).collect();
490    let mut runs = runs;
491    let next_cursor = if runs.len() > limit {
492        runs.truncate(limit);
493        runs.last().map(|r| r.run_id.clone())
494    } else {
495        None
496    };
497    RunPage { runs, next_cursor }
498}
499
500/// Sort records newest first (ties broken by id, descending) for [`page_of`].
501pub fn sort_newest_first(records: &mut [RunRecord]) {
502    records.sort_unstable_by(|a, b| b.created_ms.cmp(&a.created_ms).then_with(|| b.run_id.cmp(&a.run_id)));
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508
509    fn rec(id: &str, wf: &str, created: u64, status: RunStatus) -> RunRecord {
510        let mut r = RunRecord::running(id, wf, "fp", created);
511        r.status = status;
512        r
513    }
514
515    #[test]
516    fn run_ids_are_validated() {
517        assert!(validate_run_id("run-1a2b_3.c").is_ok());
518        for bad in ["", "../x", ".hidden", "a/b", "a b", &"x".repeat(129)] {
519            assert!(validate_run_id(bad).is_err(), "{bad}");
520        }
521    }
522
523    #[test]
524    fn paging_and_filtering() {
525        let mut all = vec![
526            rec("a", "w1", 1, RunStatus::Succeeded),
527            rec("b", "w1", 2, RunStatus::Paused),
528            rec("c", "w2", 3, RunStatus::Paused),
529            rec("d", "w1", 4, RunStatus::Failed),
530        ];
531        sort_newest_first(&mut all);
532        let page = page_of(all.clone(), &RunFilter { limit: 2, ..Default::default() }, 100);
533        assert_eq!(page.runs.iter().map(|r| r.run_id.as_str()).collect::<Vec<_>>(), ["d", "c"]);
534        assert_eq!(page.next_cursor.as_deref(), Some("c"));
535        let next = page_of(all.clone(), &RunFilter { limit: 2, cursor: page.next_cursor, ..Default::default() }, 100);
536        assert_eq!(next.runs.iter().map(|r| r.run_id.as_str()).collect::<Vec<_>>(), ["b", "a"]);
537        assert_eq!(next.next_cursor, None);
538        let paused = page_of(
539            all.clone(),
540            &RunFilter { status: Some(RunStatus::Paused), workflow: Some("w1".into()), ..Default::default() },
541            100,
542        );
543        assert_eq!(paused.runs.len(), 1);
544        assert_eq!(paused.runs[0].run_id, "b");
545    }
546
547    #[test]
548    fn paused_event_json_drops_snapshot() {
549        let snapshot = Snapshot {
550            format: crate::snapshot::SNAPSHOT_FORMAT,
551            run_id: "r".into(),
552            graph_fingerprint: "fp".into(),
553            elapsed_ms: 0,
554            steps: 0,
555            usage: Usage::default(),
556            handled_errors: 0,
557            root: crate::snapshot::FrameSnapshot::default(),
558        };
559        let event = Event::RunPaused { reasons: Vec::new(), snapshot: Box::new(snapshot) };
560        let json = event_to_json(&event);
561        assert_eq!(json["type"], "run_paused");
562        assert!(json.get("snapshot").is_none());
563        let stored = event_to_stored(&event);
564        assert_eq!(serde_json::from_str::<serde_json::Value>(stored.get()).unwrap(), json);
565        assert_eq!(stored_event_type(&stored), Some("run_paused"));
566    }
567
568    #[test]
569    fn stored_event_text_matches_the_json_tree() {
570        let mut outputs = IndexMap::new();
571        outputs.insert("z".to_owned(), Value::from("last"));
572        outputs.insert("a".to_owned(), Value::Secret(std::sync::Arc::from("sk-live")));
573        outputs.insert("n".to_owned(), Value::from_json(serde_json::json!(1.5)));
574        let event = Event::RunSucceeded { outputs, usage: Usage::default(), handled_errors: 0, elapsed_ms: 7 };
575        let stored = event_to_stored(&event);
576        assert_eq!(stored.get(), event_to_json(&event).to_string());
577        assert!(!stored.get().contains("sk-live"));
578        assert_eq!(stored_event_type(&stored), Some("run_succeeded"));
579    }
580}