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
10use std::fmt;
11
12use futures::future::BoxFuture;
13use indexmap::IndexMap;
14use serde::{Deserialize, Serialize};
15
16use crate::event::{Event, PauseReason, Usage};
17use crate::snapshot::Snapshot;
18use crate::value::Value;
19
20/// Lifecycle status of a stored run.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23#[non_exhaustive]
24pub enum RunStatus {
25    Running,
26    Paused,
27    Succeeded,
28    Failed,
29    Aborted,
30}
31
32impl RunStatus {
33    /// Whether the run reached a final state.
34    pub fn is_terminal(self) -> bool {
35        matches!(self, RunStatus::Succeeded | RunStatus::Failed | RunStatus::Aborted)
36    }
37
38    /// Parse the wire name (`running`, `paused`, ...).
39    pub fn parse(text: &str) -> Option<Self> {
40        match text {
41            "running" => Some(RunStatus::Running),
42            "paused" => Some(RunStatus::Paused),
43            "succeeded" => Some(RunStatus::Succeeded),
44            "failed" => Some(RunStatus::Failed),
45            "aborted" => Some(RunStatus::Aborted),
46            _ => None,
47        }
48    }
49}
50
51/// Persisted summary of one run.
52#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
53pub struct RunRecord {
54    pub run_id: String,
55    /// Name the workflow is served under.
56    pub workflow: String,
57    /// Fingerprint of the workflow graph (resume requires the same graph).
58    pub fingerprint: String,
59    pub status: RunStatus,
60    pub created_ms: u64,
61    pub updated_ms: u64,
62    /// Why the run is paused (empty unless `status == paused`).
63    #[serde(default)]
64    pub pause_reasons: Vec<PauseReason>,
65    #[serde(default)]
66    pub outputs: IndexMap<String, Value>,
67    /// Ordered answer text assembled from response nodes.
68    #[serde(default)]
69    pub answer: String,
70    #[serde(default)]
71    pub error: Option<String>,
72    #[serde(default)]
73    pub error_type: Option<String>,
74    #[serde(default)]
75    pub usage: Usage,
76    /// Events stored so far (may stop growing at the store's cap).
77    #[serde(default)]
78    pub event_count: u64,
79    /// Whether events were dropped because the store's per-run cap was reached.
80    #[serde(default)]
81    pub events_truncated: bool,
82    /// Run inputs as the start node accepted them, secrets masked. Only kept when
83    /// the host opts in (`graphrt serve --store-inputs`).
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub inputs: Option<IndexMap<String, Value>>,
86    /// OpenTelemetry trace id (32 hex digits) of the latest execution, when traced.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub trace_id: Option<String>,
89    /// Span id (16 hex digits) of that execution's root `invoke_workflow` span, so
90    /// later spans (online evaluation scores) can join the same trace.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub span_id: Option<String>,
93    /// Caller-supplied labels for filtering and evaluation (`RunRequest.metadata`).
94    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
95    pub metadata: IndexMap<String, String>,
96    /// Caller's session / conversation id.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub session_id: Option<String>,
99    /// Caller's end-user id.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub user_id: Option<String>,
102    /// Caller-supplied tags.
103    #[serde(default, skip_serializing_if = "Vec::is_empty")]
104    pub tags: Vec<String>,
105}
106
107impl RunRecord {
108    /// A new `running` record.
109    pub fn running(
110        run_id: impl Into<String>,
111        workflow: impl Into<String>,
112        fingerprint: impl Into<String>,
113        now_ms: u64,
114    ) -> Self {
115        Self {
116            run_id: run_id.into(),
117            workflow: workflow.into(),
118            fingerprint: fingerprint.into(),
119            status: RunStatus::Running,
120            created_ms: now_ms,
121            updated_ms: now_ms,
122            pause_reasons: Vec::new(),
123            outputs: IndexMap::new(),
124            answer: String::new(),
125            error: None,
126            error_type: None,
127            usage: Usage::default(),
128            event_count: 0,
129            events_truncated: false,
130            inputs: None,
131            trace_id: None,
132            span_id: None,
133            metadata: IndexMap::new(),
134            session_id: None,
135            user_id: None,
136            tags: Vec::new(),
137        }
138    }
139
140    /// Apply a terminal event (`RunSucceeded`, `RunFailed`, `RunAborted`, `RunPaused`).
141    /// Returns the snapshot of a paused run so the caller can persist it.
142    pub fn apply_terminal(&mut self, event: &Event, now_ms: u64) -> Option<Snapshot> {
143        self.updated_ms = now_ms;
144        match event {
145            Event::RunSucceeded { outputs, usage, .. } => {
146                self.status = RunStatus::Succeeded;
147                self.outputs.clone_from(outputs);
148                self.usage = *usage;
149                self.pause_reasons.clear();
150                None
151            }
152            Event::RunFailed { error, error_type, usage, .. } => {
153                self.status = RunStatus::Failed;
154                self.error = Some(error.clone());
155                self.error_type = Some(error_type.clone());
156                self.usage = *usage;
157                self.pause_reasons.clear();
158                None
159            }
160            Event::RunAborted { reason, .. } => {
161                self.status = RunStatus::Aborted;
162                self.error = Some(reason.clone());
163                self.pause_reasons.clear();
164                None
165            }
166            Event::RunPaused { reasons, snapshot } => {
167                self.status = RunStatus::Paused;
168                self.pause_reasons.clone_from(reasons);
169                self.usage = snapshot.usage;
170                Some((**snapshot).clone())
171            }
172            _ => None,
173        }
174    }
175}
176
177/// Query for [`RunStore::list`].
178#[derive(Clone, Debug, Default, PartialEq, Eq)]
179pub struct RunFilter {
180    pub workflow: Option<String>,
181    pub status: Option<RunStatus>,
182    /// Maximum records returned (stores cap this; 0 means the store default).
183    pub limit: usize,
184    /// Continue after this run id (the `next_cursor` of a previous page).
185    pub cursor: Option<String>,
186}
187
188/// One page of [`RunStore::list`], newest first.
189#[derive(Clone, Debug, Default, PartialEq, Serialize)]
190pub struct RunPage {
191    pub runs: Vec<RunRecord>,
192    pub next_cursor: Option<String>,
193}
194
195/// Store failure.
196#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
197#[non_exhaustive]
198pub enum StoreError {
199    #[error("run `{0}` not found")]
200    NotFound(String),
201    /// The operation conflicts with the run's current state (already exists,
202    /// not paused, already being resumed).
203    #[error("{0}")]
204    Conflict(String),
205    #[error("invalid run id `{0}`")]
206    InvalidId(String),
207    #[error("run store I/O error: {0}")]
208    Io(String),
209    #[error("corrupt run store entry: {0}")]
210    Corrupt(String),
211}
212
213/// Result type of [`RunStore`] operations.
214pub type StoreResult<T> = Result<T, StoreError>;
215
216/// Durable storage of run records, events and snapshots.
217///
218/// Implementations must make [`RunStore::claim_resume`] atomic: of two concurrent
219/// claims on the same paused run, exactly one succeeds.
220pub trait RunStore: Send + Sync + fmt::Debug {
221    /// Insert a new record. Fails with [`StoreError::Conflict`] if the id exists.
222    fn create(&self, record: RunRecord) -> BoxFuture<'_, StoreResult<()>>;
223    /// Insert or replace a record.
224    fn put(&self, record: RunRecord) -> BoxFuture<'_, StoreResult<()>>;
225    fn get<'a>(&'a self, run_id: &'a str) -> BoxFuture<'a, StoreResult<Option<RunRecord>>>;
226    fn list(&self, filter: RunFilter) -> BoxFuture<'_, StoreResult<RunPage>>;
227    /// Remove a run and everything stored for it. Returns whether it existed.
228    fn delete<'a>(&'a self, run_id: &'a str) -> BoxFuture<'a, StoreResult<bool>>;
229    /// Append events (already serialized by [`event_to_stored`], secrets masked).
230    /// Stores may cap the number of events kept per run; they then set
231    /// `events_truncated`.
232    fn append_events<'a>(&'a self, run_id: &'a str, events: Vec<StoredEvent>) -> BoxFuture<'a, StoreResult<()>>;
233    /// Stored events, starting at index `from`.
234    fn events<'a>(&'a self, run_id: &'a str, from: u64) -> BoxFuture<'a, StoreResult<Vec<StoredEvent>>>;
235    fn save_snapshot<'a>(&'a self, run_id: &'a str, snapshot: &'a Snapshot) -> BoxFuture<'a, StoreResult<()>>;
236    fn load_snapshot<'a>(&'a self, run_id: &'a str) -> BoxFuture<'a, StoreResult<Option<Snapshot>>>;
237    /// Atomically move a `paused` run to `running` and return the updated record.
238    /// Fails with [`StoreError::Conflict`] when the run is not paused (including when
239    /// another request claimed it first).
240    fn claim_resume<'a>(&'a self, run_id: &'a str, now_ms: u64) -> BoxFuture<'a, StoreResult<RunRecord>>;
241    /// After a host restart: mark every `running` run as `failed` ("interrupted by
242    /// restart"). Paused runs stay resumable. Returns how many runs were marked.
243    fn recover_interrupted(&self, now_ms: u64) -> BoxFuture<'_, StoreResult<usize>>;
244    /// Delete runs (any status except `running`) last updated before `cutoff_ms`.
245    fn purge_before(&self, cutoff_ms: u64) -> BoxFuture<'_, StoreResult<usize>>;
246}
247
248/// Error message stored on runs interrupted by a host restart.
249pub const INTERRUPTED_BY_RESTART: &str = "interrupted by restart";
250
251/// An event serialized as one JSON object, the form in which stores keep events.
252///
253/// Holding the JSON text instead of a [`serde_json::Value`] tree saves building
254/// a map per event on the way in and re-serializing it on the way out.
255pub type StoredEvent = Box<serde_json::value::RawValue>;
256
257/// Serialize an event for storage: the same JSON as [`event_to_json`], written
258/// straight to text.
259pub fn event_to_stored(event: &Event) -> StoredEvent {
260    let text = match event {
261        // Rare, and the snapshot has to be dropped: go through the tree.
262        Event::RunPaused { .. } => serde_json::to_string(&event_to_json(event)),
263        _ => serde_json::to_string(event),
264    };
265    text.ok()
266        .and_then(|text| serde_json::value::RawValue::from_string(text).ok())
267        .unwrap_or_else(|| serde_json::value::RawValue::NULL.to_owned())
268}
269
270/// The `type` field of a stored event (e.g. `node_started`), if it has one.
271pub fn stored_event_type(event: &StoredEvent) -> Option<&str> {
272    #[derive(Deserialize)]
273    struct TypeOnly<'a> {
274        #[serde(rename = "type", borrow)]
275        kind: Option<&'a str>,
276    }
277    serde_json::from_str::<TypeOnly<'_>>(event.get()).ok().and_then(|t| t.kind)
278}
279
280/// Serialize an event for storage. Secrets are masked by the value serializer; the
281/// snapshot carried by `run_paused` is dropped (stores keep it separately).
282pub fn event_to_json(event: &Event) -> serde_json::Value {
283    let mut json = serde_json::to_value(event).unwrap_or(serde_json::Value::Null);
284    if let Some(obj) = json.as_object_mut()
285        && obj.get("type").and_then(serde_json::Value::as_str) == Some("run_paused")
286    {
287        obj.remove("snapshot");
288    }
289    json
290}
291
292/// Validate a run id used as a storage key: 1–128 chars of `[A-Za-z0-9_.-]`, not
293/// starting with `.`.
294pub fn validate_run_id(run_id: &str) -> StoreResult<()> {
295    let ok = !run_id.is_empty()
296        && run_id.len() <= 128
297        && !run_id.starts_with('.')
298        && run_id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
299    if ok { Ok(()) } else { Err(StoreError::InvalidId(run_id.chars().take(64).collect())) }
300}
301
302/// Current Unix time in milliseconds (0 where no clock exists).
303pub fn now_ms() -> u64 {
304    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
305    {
306        0
307    }
308    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
309    {
310        std::time::SystemTime::now()
311            .duration_since(std::time::UNIX_EPOCH)
312            .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
313            .unwrap_or(0)
314    }
315}
316
317/// Apply `filter` to records already sorted newest first (shared by implementations).
318pub fn page_of(mut sorted: Vec<RunRecord>, filter: &RunFilter, max_limit: usize) -> RunPage {
319    sorted.retain(|r| {
320        filter.workflow.as_deref().is_none_or(|w| r.workflow == w) && filter.status.is_none_or(|s| r.status == s)
321    });
322    let start = match &filter.cursor {
323        Some(cursor) => sorted.iter().position(|r| &r.run_id == cursor).map_or(sorted.len(), |i| i + 1),
324        None => 0,
325    };
326    let limit = if filter.limit == 0 { max_limit } else { filter.limit.min(max_limit) };
327    let runs: Vec<RunRecord> = sorted.into_iter().skip(start).take(limit.saturating_add(1)).collect();
328    let mut runs = runs;
329    let next_cursor = if runs.len() > limit {
330        runs.truncate(limit);
331        runs.last().map(|r| r.run_id.clone())
332    } else {
333        None
334    };
335    RunPage { runs, next_cursor }
336}
337
338/// Sort records newest first (ties broken by id, descending) for [`page_of`].
339pub fn sort_newest_first(records: &mut [RunRecord]) {
340    records.sort_by(|a, b| b.created_ms.cmp(&a.created_ms).then_with(|| b.run_id.cmp(&a.run_id)));
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    fn rec(id: &str, wf: &str, created: u64, status: RunStatus) -> RunRecord {
348        let mut r = RunRecord::running(id, wf, "fp", created);
349        r.status = status;
350        r
351    }
352
353    #[test]
354    fn run_ids_are_validated() {
355        assert!(validate_run_id("run-1a2b_3.c").is_ok());
356        for bad in ["", "../x", ".hidden", "a/b", "a b", &"x".repeat(129)] {
357            assert!(validate_run_id(bad).is_err(), "{bad}");
358        }
359    }
360
361    #[test]
362    fn paging_and_filtering() {
363        let mut all = vec![
364            rec("a", "w1", 1, RunStatus::Succeeded),
365            rec("b", "w1", 2, RunStatus::Paused),
366            rec("c", "w2", 3, RunStatus::Paused),
367            rec("d", "w1", 4, RunStatus::Failed),
368        ];
369        sort_newest_first(&mut all);
370        let page = page_of(all.clone(), &RunFilter { limit: 2, ..Default::default() }, 100);
371        assert_eq!(page.runs.iter().map(|r| r.run_id.as_str()).collect::<Vec<_>>(), ["d", "c"]);
372        assert_eq!(page.next_cursor.as_deref(), Some("c"));
373        let next = page_of(all.clone(), &RunFilter { limit: 2, cursor: page.next_cursor, ..Default::default() }, 100);
374        assert_eq!(next.runs.iter().map(|r| r.run_id.as_str()).collect::<Vec<_>>(), ["b", "a"]);
375        assert_eq!(next.next_cursor, None);
376        let paused = page_of(
377            all.clone(),
378            &RunFilter { status: Some(RunStatus::Paused), workflow: Some("w1".into()), ..Default::default() },
379            100,
380        );
381        assert_eq!(paused.runs.len(), 1);
382        assert_eq!(paused.runs[0].run_id, "b");
383    }
384
385    #[test]
386    fn paused_event_json_drops_snapshot() {
387        let snapshot = Snapshot {
388            format: crate::snapshot::SNAPSHOT_FORMAT,
389            run_id: "r".into(),
390            graph_fingerprint: "fp".into(),
391            elapsed_ms: 0,
392            steps: 0,
393            usage: Usage::default(),
394            handled_errors: 0,
395            root: crate::snapshot::FrameSnapshot::default(),
396        };
397        let event = Event::RunPaused { reasons: Vec::new(), snapshot: Box::new(snapshot) };
398        let json = event_to_json(&event);
399        assert_eq!(json["type"], "run_paused");
400        assert!(json.get("snapshot").is_none());
401        let stored = event_to_stored(&event);
402        assert_eq!(serde_json::from_str::<serde_json::Value>(stored.get()).unwrap(), json);
403        assert_eq!(stored_event_type(&stored), Some("run_paused"));
404    }
405
406    #[test]
407    fn stored_event_text_matches_the_json_tree() {
408        let mut outputs = IndexMap::new();
409        outputs.insert("z".to_owned(), Value::from("last"));
410        outputs.insert("a".to_owned(), Value::Secret(std::sync::Arc::from("sk-live")));
411        outputs.insert("n".to_owned(), Value::from_json(serde_json::json!(1.5)));
412        let event = Event::RunSucceeded { outputs, usage: Usage::default(), handled_errors: 0, elapsed_ms: 7 };
413        let stored = event_to_stored(&event);
414        assert_eq!(stored.get(), event_to_json(&event).to_string());
415        assert!(!stored.get().contains("sk-live"));
416        assert_eq!(stored_event_type(&stored), Some("run_succeeded"));
417    }
418}