Skip to main content

graphrt_llm/
replay.rs

1//! Record and replay model responses ("cassettes") for deterministic runs.
2//!
3//! A [`ReplayModel`] sits where a provider would. Each request is normalized
4//! (object keys sorted) and hashed with SHA-256; the hash names a cassette file
5//! `<dir>/<key>.json` holding the request and the streamed response deltas.
6//!
7//! | Mode | Cassette present | Cassette missing |
8//! |---|---|---|
9//! | [`ReplayMode::Replay`] | served, chunk by chunk | error naming the key |
10//! | [`ReplayMode::Record`] | re-recorded from the upstream | recorded from the upstream |
11//! | [`ReplayMode::Auto`] | served | recorded from the upstream |
12//!
13//! Only successful, complete responses are written; a failed or interrupted
14//! upstream stream leaves no cassette behind. Files are written atomically
15//! (temp file + rename), so concurrent recordings of the same request are safe.
16//!
17//! Providers files declare it with `kind: replay` (see [`crate::providers`]);
18//! `GRAPHRT_REPLAY_MODE` overrides the mode of every replay provider.
19//!
20//! Cassettes contain the full prompts and answers: treat them like test
21//! fixtures, and do not record prompts that carry secrets.
22
23use std::path::{Path, PathBuf};
24use std::sync::Arc;
25
26use futures::StreamExt;
27use futures::future::BoxFuture;
28use graphrt_core::event::Usage;
29use serde::{Deserialize, Serialize};
30use sha2::{Digest, Sha256};
31
32use crate::error::LlmError;
33use crate::types::{ChatDelta, ChatModel, ChatRequest, ChatStream, FinishReason};
34
35/// Environment variable overriding the mode of every replay provider.
36pub const REPLAY_MODE_ENV: &str = "GRAPHRT_REPLAY_MODE";
37
38/// Cassette file format version.
39pub const CASSETTE_VERSION: u32 = 1;
40
41/// How a [`ReplayModel`] treats requests.
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
43#[serde(rename_all = "lowercase")]
44pub enum ReplayMode {
45    /// Serve recorded responses only; a request without a cassette is an error.
46    #[default]
47    Replay,
48    /// Always call the upstream provider and (re)write the cassette.
49    Record,
50    /// Serve a recorded response when there is one, otherwise record it.
51    Auto,
52}
53
54impl ReplayMode {
55    /// Parse `replay`, `record` or `auto` (case-insensitive).
56    pub fn parse(text: &str) -> Result<Self, LlmError> {
57        match text.trim().to_ascii_lowercase().as_str() {
58            "replay" => Ok(Self::Replay),
59            "record" => Ok(Self::Record),
60            "auto" => Ok(Self::Auto),
61            other => {
62                Err(LlmError::Config(format!("unknown replay mode `{other}` (expected `replay`, `record` or `auto`)")))
63            }
64        }
65    }
66
67    /// Whether this mode may call the upstream provider.
68    pub fn needs_upstream(self) -> bool {
69        self != Self::Replay
70    }
71}
72
73/// One recorded delta (the serializable mirror of [`ChatDelta`]).
74#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
75#[serde(rename_all = "snake_case")]
76pub enum CassetteDelta {
77    Text(String),
78    Reasoning(String),
79    ToolCall {
80        index: usize,
81        #[serde(default, skip_serializing_if = "Option::is_none")]
82        id: Option<String>,
83        #[serde(default, skip_serializing_if = "Option::is_none")]
84        name: Option<String>,
85        arguments: String,
86    },
87    Usage(Usage),
88    Finish(FinishReason),
89    ProviderState(serde_json::Value),
90    Warning(String),
91}
92
93impl CassetteDelta {
94    /// `None` for a [`ChatDelta::Failover`] report: it tells how this process
95    /// reached a provider, not what the provider answered.
96    fn from_delta(delta: &ChatDelta) -> Option<Self> {
97        Some(match delta {
98            ChatDelta::Text(t) => Self::Text(t.clone()),
99            ChatDelta::Reasoning(t) => Self::Reasoning(t.clone()),
100            ChatDelta::ToolCall { index, id, name, arguments } => {
101                Self::ToolCall { index: *index, id: id.clone(), name: name.clone(), arguments: arguments.clone() }
102            }
103            ChatDelta::Usage(u) => Self::Usage(*u),
104            ChatDelta::Finish(f) => Self::Finish(f.clone()),
105            ChatDelta::ProviderState(s) => Self::ProviderState(s.clone()),
106            ChatDelta::Warning(w) => Self::Warning(w.clone()),
107            ChatDelta::Failover(_) => return None,
108        })
109    }
110
111    fn into_delta(self) -> ChatDelta {
112        match self {
113            Self::Text(t) => ChatDelta::Text(t),
114            Self::Reasoning(t) => ChatDelta::Reasoning(t),
115            Self::ToolCall { index, id, name, arguments } => ChatDelta::ToolCall { index, id, name, arguments },
116            Self::Usage(u) => ChatDelta::Usage(u),
117            Self::Finish(f) => ChatDelta::Finish(f),
118            Self::ProviderState(s) => ChatDelta::ProviderState(s),
119            Self::Warning(w) => ChatDelta::Warning(w),
120        }
121    }
122}
123
124/// A recorded request and its streamed response.
125#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
126pub struct Cassette {
127    pub version: u32,
128    /// The cassette key ([`cassette_key`] of `request`).
129    pub key: String,
130    /// The normalized request, for humans reviewing the fixture.
131    pub request: serde_json::Value,
132    /// Response deltas in the order they were streamed.
133    pub response: Vec<CassetteDelta>,
134}
135
136/// A request in canonical form: the serialized [`ChatRequest`] with every
137/// object's keys sorted, so key order in workflow or schema documents does
138/// not change the key.
139pub fn normalize_request(request: &ChatRequest) -> Result<serde_json::Value, LlmError> {
140    let mut value = serde_json::to_value(request).map_err(|e| LlmError::Config(format!("encoding request: {e}")))?;
141    // What the run's budget left changes from run to run (and with calls at the same
142    // time): it shapes the upstream call, never which recorded answer is replayed.
143    if let Some(fields) = value.as_object_mut() {
144        fields.remove("budget_max_tokens");
145    }
146    Ok(sort_keys(value))
147}
148
149fn sort_keys(value: serde_json::Value) -> serde_json::Value {
150    match value {
151        serde_json::Value::Object(map) => {
152            let mut entries: Vec<(String, serde_json::Value)> = map.into_iter().collect();
153            entries.sort_unstable_by(|a, b| a.0.cmp(&b.0));
154            serde_json::Value::Object(entries.into_iter().map(|(k, v)| (k, sort_keys(v))).collect())
155        }
156        serde_json::Value::Array(items) => serde_json::Value::Array(items.into_iter().map(sort_keys).collect()),
157        other => other,
158    }
159}
160
161/// Stable cassette key of a request: the first 32 hex digits of the SHA-256
162/// of its normalized JSON.
163pub fn cassette_key(request: &ChatRequest) -> Result<String, LlmError> {
164    Ok(key_of(&normalize_request(request)?))
165}
166
167fn key_of(normalized: &serde_json::Value) -> String {
168    let digest = Sha256::digest(normalized.to_string().as_bytes());
169    digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
170}
171
172/// A model that serves (and optionally records) responses from cassette files.
173#[derive(Debug)]
174pub struct ReplayModel {
175    dir: PathBuf,
176    mode: ReplayMode,
177    upstream: Option<Arc<dyn ChatModel>>,
178}
179
180impl ReplayModel {
181    /// Serve cassettes from `dir`. Modes other than [`ReplayMode::Replay`]
182    /// need an `upstream` model to record from.
183    pub fn new(
184        dir: impl Into<PathBuf>,
185        mode: ReplayMode,
186        upstream: Option<Arc<dyn ChatModel>>,
187    ) -> Result<Self, LlmError> {
188        if mode.needs_upstream() && upstream.is_none() {
189            return Err(LlmError::Config(format!(
190                "replay mode `{}` needs an `upstream` provider to record from",
191                mode_name(mode)
192            )));
193        }
194        Ok(Self { dir: dir.into(), mode, upstream })
195    }
196
197    /// The cassette directory.
198    pub fn dir(&self) -> &Path {
199        &self.dir
200    }
201
202    /// The active mode.
203    pub fn mode(&self) -> ReplayMode {
204        self.mode
205    }
206
207    fn cassette_path(&self, key: &str) -> PathBuf {
208        self.dir.join(format!("{key}.json"))
209    }
210
211    async fn serve(&self, request: ChatRequest) -> Result<ChatStream, LlmError> {
212        let normalized = normalize_request(&request)?;
213        let key = key_of(&normalized);
214        let path = self.cassette_path(&key);
215        if self.mode != ReplayMode::Record && path.is_file() {
216            return replay_file(&path);
217        }
218        let Some(upstream) = self.upstream.as_ref().filter(|_| self.mode.needs_upstream()) else {
219            return Err(LlmError::Config(format!(
220                "replay: no cassette for this request (model `{}`, key {key}) in `{}`; record it with \
221                 {REPLAY_MODE_ENV}=record or `mode: auto` and an `upstream` provider. Its last message: {}",
222                request.model,
223                self.dir.display(),
224                last_message(&request)
225            )));
226        };
227        let inner = upstream.chat(request).await?;
228        Ok(record_stream(inner, Recording { path, key, request: normalized }))
229    }
230}
231
232/// The longest part of a request's last message a miss quotes.
233const MISS_QUOTE_CHARS: usize = 2000;
234
235/// The role and the start of `request`'s last message: what differs from the
236/// recorded request when a run went another way (a tool that failed, for
237/// example, sends its error to the model).
238fn last_message(request: &ChatRequest) -> String {
239    let Some(message) = request.messages.last() else { return "none".to_owned() };
240    let text = message.text();
241    let mut quoted: String = text.chars().take(MISS_QUOTE_CHARS).collect();
242    if quoted.len() < text.len() {
243        quoted.push_str("...");
244    }
245    format!("{:?} {quoted:?}", message.role)
246}
247
248fn mode_name(mode: ReplayMode) -> &'static str {
249    match mode {
250        ReplayMode::Replay => "replay",
251        ReplayMode::Record => "record",
252        ReplayMode::Auto => "auto",
253    }
254}
255
256impl ChatModel for ReplayModel {
257    fn chat(&self, request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
258        Box::pin(self.serve(request))
259    }
260}
261
262/// Read a cassette and stream its deltas one by one.
263fn replay_file(path: &Path) -> Result<ChatStream, LlmError> {
264    let text = std::fs::read_to_string(path)
265        .map_err(|e| LlmError::Config(format!("replay: cannot read cassette `{}`: {e}", path.display())))?;
266    let cassette: Cassette = serde_json::from_str(&text)
267        .map_err(|e| LlmError::Config(format!("replay: invalid cassette `{}`: {e}", path.display())))?;
268    if cassette.version != CASSETTE_VERSION {
269        return Err(LlmError::Config(format!(
270            "replay: cassette `{}` has version {}, expected {CASSETTE_VERSION}",
271            path.display(),
272            cassette.version
273        )));
274    }
275    let deltas = cassette.response.into_iter().map(|d| Ok(d.into_delta()));
276    Ok(Box::pin(futures::stream::iter(deltas)))
277}
278
279struct Recording {
280    path: PathBuf,
281    key: String,
282    request: serde_json::Value,
283}
284
285struct RecordState {
286    inner: ChatStream,
287    recording: Option<Recording>,
288    deltas: Vec<CassetteDelta>,
289}
290
291/// Pass the upstream deltas through unchanged while collecting them; write the
292/// cassette when the stream ends cleanly. A write failure surfaces as a final
293/// error item so it is never silent.
294fn record_stream(inner: ChatStream, recording: Recording) -> ChatStream {
295    let state = RecordState { inner, recording: Some(recording), deltas: Vec::new() };
296    Box::pin(futures::stream::unfold(state, |mut state| async move {
297        match state.inner.next().await {
298            Some(Ok(delta)) => {
299                state.deltas.extend(CassetteDelta::from_delta(&delta));
300                Some((Ok(delta), state))
301            }
302            Some(Err(error)) => {
303                state.recording = None;
304                Some((Err(error), state))
305            }
306            None => {
307                let recording = state.recording.take()?;
308                let deltas = std::mem::take(&mut state.deltas);
309                match write_cassette(recording, deltas) {
310                    Ok(()) => None,
311                    Err(error) => Some((Err(error), state)),
312                }
313            }
314        }
315    }))
316}
317
318fn write_cassette(recording: Recording, response: Vec<CassetteDelta>) -> Result<(), LlmError> {
319    let Recording { path, key, request } = recording;
320    let cassette = Cassette { version: CASSETTE_VERSION, key, request, response };
321    let io = |e: std::io::Error| LlmError::Config(format!("replay: cannot write cassette `{}`: {e}", path.display()));
322    // Cassettes hold prompts and answers: owner-only, like every run artifact.
323    if let Some(dir) = path.parent() {
324        graphrt_core::private_fs::create_dir_all(dir).map_err(io)?;
325    }
326    let mut text = serde_json::to_string_pretty(&cassette).map_err(|e| LlmError::Config(e.to_string()))?;
327    text.push('\n');
328    let temp = path.with_extension(format!("json.{}.{:?}.tmp", std::process::id(), std::thread::current().id()));
329    graphrt_core::private_fs::write(&temp, text).map_err(io)?;
330    std::fs::rename(&temp, &path).map_err(|e| {
331        let _cleanup = std::fs::remove_file(&temp);
332        io(e)
333    })
334}
335
336#[cfg(all(test, feature = "mock"))]
337mod tests {
338    #![allow(clippy::unwrap_used, clippy::expect_used)]
339
340    use super::*;
341    use crate::mock::MockModel;
342    use crate::types::{Message, collect};
343
344    fn scratch(name: &str) -> PathBuf {
345        let dir = std::env::temp_dir().join(format!("graphrt-replay-{name}-{}", std::process::id()));
346        let _fresh = std::fs::remove_dir_all(&dir);
347        dir
348    }
349
350    fn block_on<F: std::future::Future>(future: F) -> F::Output {
351        tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(future)
352    }
353
354    async fn ask(model: &dyn ChatModel, text: &str) -> Result<crate::ChatResponse, LlmError> {
355        let stream = model.chat(ChatRequest::new("m", vec![Message::user(text)])).await?;
356        collect(stream, |_| {}).await
357    }
358
359    #[test]
360    fn records_then_replays_chunk_by_chunk_and_misses_clearly() {
361        let dir = scratch("cycle");
362        let upstream = Arc::new(MockModel::new(vec![vec![
363            ChatDelta::Text("Hel".into()),
364            ChatDelta::Text("lo".into()),
365            ChatDelta::Usage(Usage { prompt_tokens: 3, completion_tokens: 2, total_tokens: 5 }),
366            ChatDelta::Finish(FinishReason::Stop),
367        ]]));
368        let recorder = ReplayModel::new(&dir, ReplayMode::Record, Some(upstream.clone())).unwrap();
369        let recorded = block_on(ask(&recorder, "hi")).unwrap();
370        assert_eq!(recorded.text, "Hello");
371        assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
372
373        let player = ReplayModel::new(&dir, ReplayMode::Replay, None).unwrap();
374        let stream = block_on(player.chat(ChatRequest::new("m", vec![Message::user("hi")]))).unwrap();
375        let deltas: Vec<ChatDelta> = block_on(stream.map(|d| d.unwrap()).collect());
376        assert_eq!(deltas.len(), 4, "chunks are replayed one by one");
377        assert_eq!(deltas.first(), Some(&ChatDelta::Text("Hel".into())));
378        let replayed = block_on(ask(&player, "hi")).unwrap();
379        assert_eq!(replayed.text, "Hello");
380        assert_eq!(replayed.usage.total_tokens, 5);
381        assert_eq!(upstream.requests().len(), 1, "replay never calls the upstream");
382
383        let miss = block_on(ask(&player, "something else")).unwrap_err().to_string();
384        assert!(miss.contains("no cassette") && miss.contains("GRAPHRT_REPLAY_MODE"), "{miss}");
385        assert!(miss.contains(r#"Its last message: User "something else""#), "the miss says what was asked: {miss}");
386        let _cleanup = std::fs::remove_dir_all(&dir);
387    }
388
389    #[test]
390    fn auto_records_misses_and_replays_hits() {
391        let dir = scratch("auto");
392        let upstream = Arc::new(MockModel::new(vec![MockModel::text("one"), MockModel::text("two")]));
393        let auto = ReplayModel::new(&dir, ReplayMode::Auto, Some(upstream.clone())).unwrap();
394        assert_eq!(block_on(ask(&auto, "a")).unwrap().text, "one");
395        assert_eq!(block_on(ask(&auto, "a")).unwrap().text, "one", "second call is served from the cassette");
396        assert_eq!(block_on(ask(&auto, "b")).unwrap().text, "two");
397        assert_eq!(upstream.requests().len(), 2);
398        #[cfg(unix)]
399        {
400            use std::os::unix::fs::PermissionsExt;
401            let mode = |path: &std::path::Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777;
402            assert_eq!(mode(&dir), 0o700, "cassette directory");
403            for entry in std::fs::read_dir(&dir).unwrap() {
404                assert_eq!(mode(&entry.unwrap().path()), 0o600, "cassettes hold prompts and answers");
405            }
406        }
407        let _cleanup = std::fs::remove_dir_all(&dir);
408    }
409
410    #[test]
411    fn failed_upstream_streams_are_not_recorded() {
412        let dir = scratch("fail");
413        let upstream = Arc::new(MockModel::new(vec![]));
414        upstream.push_error(LlmError::Network("down".into()));
415        let auto = ReplayModel::new(&dir, ReplayMode::Auto, Some(upstream)).unwrap();
416        assert!(block_on(ask(&auto, "a")).is_err());
417        assert!(!dir.exists() || std::fs::read_dir(&dir).unwrap().count() == 0);
418    }
419
420    #[test]
421    fn keys_ignore_object_key_order_and_modes_need_upstreams() {
422        let mut a = ChatRequest::new("m", vec![Message::user("x")]);
423        a.extra.insert("b".into(), serde_json::json!(1));
424        a.extra.insert("a".into(), serde_json::json!({"y": 1, "x": 2}));
425        let mut b = ChatRequest::new("m", vec![Message::user("x")]);
426        b.extra.insert("a".into(), serde_json::json!({"x": 2, "y": 1}));
427        b.extra.insert("b".into(), serde_json::json!(1));
428        assert_eq!(cassette_key(&a).unwrap(), cassette_key(&b).unwrap());
429        assert_eq!(cassette_key(&a).unwrap().len(), 32);
430        assert_ne!(cassette_key(&a).unwrap(), cassette_key(&ChatRequest::new("other", vec![])).unwrap());
431
432        assert!(ReplayModel::new("x", ReplayMode::Auto, None).is_err());
433        assert_eq!(ReplayMode::parse("RECORD").unwrap(), ReplayMode::Record);
434        assert!(ReplayMode::parse("sometimes").is_err());
435    }
436}