Skip to main content

telemetry/recorder/
rerun.rs

1//! Rerun — send a recording's requests to a real provider and diff the answers.
2//!
3//! Replay proves a run is reproducible. It cannot answer the other question a
4//! recording invites: *what would the model have said if the prompt were
5//! different?* Replay compares blob **ids** and hands back the recorded
6//! response, so editing a blob changes nothing it observes, and the response it
7//! returns was never a function of the request anyway.
8//!
9//! Rerun reads the request back out of the blobs — which is where a hand edit
10//! takes effect — issues it for real, and reports what moved. The recording is
11//! the input; nothing here writes to it.
12//!
13//! Workflow this exists for: record a session, edit one system block or drop
14//! one message, rerun, read the diff.
15
16use base::interface::model::{
17    CallOrigin, Model, ModelError, ModelEvent, ModelMessage, StreamParams, ToolDef,
18};
19use base::prompt::PromptBlock;
20use futures::StreamExt;
21use std::path::Path;
22use std::sync::Arc;
23use tokio_util::sync::CancellationToken;
24
25use super::blob::{BlobId, BlobStore};
26use super::format::CallRecord;
27use super::reader::{self, RecordedCall, Recording};
28
29#[derive(Debug, thiserror::Error)]
30pub enum RerunError {
31    #[error("cannot read recording: {0}")]
32    Read(#[from] super::reader::ReadError),
33    #[error("call #{index} is missing blob {id} — the recording directory is incomplete")]
34    MissingBlob { index: usize, id: BlobId },
35    #[error("call #{index}: blob {id} no longer parses as {what}: {source}")]
36    UnreadableBlob {
37        index: usize,
38        id: BlobId,
39        what: &'static str,
40        source: std::io::Error,
41    },
42    #[error("recording has {len} call(s), asked for #{index}")]
43    NoSuchCall { index: usize, len: usize },
44}
45
46/// One request, loaded back from a recording and ready to send again.
47pub struct LoadedRequest {
48    pub prompt_blocks: Vec<PromptBlock>,
49    pub tools: Vec<ToolDef>,
50    pub messages: Vec<ModelMessage>,
51    pub params: StreamParams,
52    /// What the model said the first time, for comparison.
53    pub recorded_response: Vec<ModelEvent>,
54    /// The `call` record this was rebuilt from — session, turn, purpose.
55    ///
56    /// Carried here rather than left for the caller to fetch separately: a
57    /// second `load` plus index-matching is a parallel array waiting to go out
58    /// of step, and it would go out of step by panicking on an index.
59    pub record: CallRecord,
60}
61
62/// Rebuild call `index`'s request from the recording in `dir`.
63///
64/// Blob content is read, not just referenced — that is the whole point, and it
65/// is what makes an edited blob take effect.
66pub fn load_request(dir: &Path, index: usize) -> Result<LoadedRequest, RerunError> {
67    request_in(&reader::load(dir)?, &BlobStore::new(dir), index)
68}
69
70/// [`load_request`] over a recording the caller has already read.
71pub fn request_in(
72    recording: &Recording,
73    blobs: &BlobStore,
74    index: usize,
75) -> Result<LoadedRequest, RerunError> {
76    let call = recording.calls.get(index).ok_or(RerunError::NoSuchCall {
77        index,
78        len: recording.calls.len(),
79    })?;
80    request_of(blobs, index, call)
81}
82
83/// Every call of the recording, in order.
84pub fn load_all(dir: &Path) -> Result<Vec<LoadedRequest>, RerunError> {
85    let recording = reader::load(dir)?;
86    let blobs = BlobStore::new(dir);
87    recording
88        .calls
89        .iter()
90        .enumerate()
91        .map(|(i, call)| request_of(&blobs, i, call))
92        .collect()
93}
94
95fn request_of(
96    blobs: &BlobStore,
97    index: usize,
98    call: &RecordedCall,
99) -> Result<LoadedRequest, RerunError> {
100    let request = &call.request;
101    let prompt_blocks = request
102        .system
103        .iter()
104        .map(|id| fetch(blobs, index, id, "a prompt block"))
105        .collect::<Result<Vec<PromptBlock>, _>>()?;
106    let tools: Vec<ToolDef> = fetch(blobs, index, &request.tools, "a tool table")?;
107    let messages = request
108        .messages
109        .iter()
110        .map(|id| fetch(blobs, index, id, "a message"))
111        .collect::<Result<Vec<ModelMessage>, _>>()?;
112
113    Ok(LoadedRequest {
114        prompt_blocks,
115        tools,
116        messages,
117        params: params_of(request),
118        recorded_response: call.response.clone(),
119        record: request.clone(),
120    })
121}
122
123fn fetch<T: serde::de::DeserializeOwned>(
124    blobs: &BlobStore,
125    index: usize,
126    id: &BlobId,
127    what: &'static str,
128) -> Result<T, RerunError> {
129    blobs
130        .get::<T>(id)
131        .map_err(|source| RerunError::UnreadableBlob {
132            index,
133            id: id.clone(),
134            what,
135            source,
136        })?
137        .ok_or_else(|| RerunError::MissingBlob {
138            index,
139            id: id.clone(),
140        })
141}
142
143fn params_of(request: &CallRecord) -> StreamParams {
144    StreamParams {
145        model: request.params.model.clone(),
146        max_tokens: request.params.max_tokens,
147        thinking_mode: request.params.thinking_mode.clone(),
148        effort: request.params.effort,
149        cache_edits: request.params.cache_edits.clone(),
150        // Attributed to the session that made it originally, and marked as a
151        // rerun so a recorder downstream does not mistake it for turn work.
152        origin: request
153            .session_id
154            .as_ref()
155            .map(|id| CallOrigin::auxiliary(id, "rerun")),
156        input_map: request.input_map.clone(),
157        provider_search: request
158            .params
159            .search_max_uses
160            .map(|max_uses| base::interface::model::ProviderSearch { max_uses }),
161        usage_tap: Default::default(),
162    }
163}
164
165/// One tool call, as the comparison sees it.
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct ToolCall {
168    pub name: String,
169    /// Argument keys and their canonical JSON, sorted so two calls that differ
170    /// only in key order compare equal.
171    pub args: Vec<(String, String)>,
172}
173
174/// How one argument key compared.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct ArgDiff {
177    pub key: String,
178    pub recorded: Option<String>,
179    pub live: Option<String>,
180}
181
182impl ArgDiff {
183    pub fn matches(&self) -> bool {
184        self.recorded == self.live
185    }
186}
187
188/// One position in the tool-call sequence.
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub enum ToolStep {
191    /// Same tool, same arguments.
192    Same { name: String },
193    /// Same tool, at least one argument differs.
194    ArgsDiffer { name: String, args: Vec<ArgDiff> },
195    /// A different tool was called here, or one side had no call at all.
196    NameDiffers {
197        recorded: Option<String>,
198        live: Option<String>,
199    },
200}
201
202impl ToolStep {
203    pub fn matches(&self) -> bool {
204        matches!(self, ToolStep::Same { .. })
205    }
206}
207
208/// The deterministic half of the comparison.
209///
210/// Tool calls are *acts*, not prose. `Write(path="src/main.c")` and
211/// `Write(path="src/Main.c")` are not "roughly the same thing", and a semantic
212/// judge asked to compare them will say they are — which is exactly the class
213/// of regression worth catching. So nothing here is judged: names, arguments
214/// and `stop_reason` compare exactly, and a mismatch is a failure.
215///
216/// The consequence is deliberate and known: a `Write` whose `content` is a
217/// generated source file will differ on every run, and so will a free-text
218/// `description`. That is reported as a failure with the offending key named,
219/// leaving a human to tell benign drift from a real regression — rather than a
220/// judge quietly deciding for them.
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct ToolDiff {
223    pub steps: Vec<ToolStep>,
224    pub recorded_stop_reason: Option<String>,
225    pub live_stop_reason: Option<String>,
226}
227
228impl ToolDiff {
229    pub fn matches(&self) -> bool {
230        self.steps.iter().all(ToolStep::matches)
231            && self.recorded_stop_reason == self.live_stop_reason
232    }
233
234    /// Keys that differed, as `Tool.key` — the summary a reader triages from.
235    pub fn offending_keys(&self) -> Vec<String> {
236        let mut out = Vec::new();
237        for step in &self.steps {
238            match step {
239                ToolStep::Same { .. } => {}
240                ToolStep::ArgsDiffer { name, args } => out.extend(
241                    args.iter()
242                        .filter(|a| !a.matches())
243                        .map(|a| format!("{name}.{}", a.key)),
244                ),
245                ToolStep::NameDiffers { recorded, live } => out.push(format!(
246                    "<tool {} → {}>",
247                    recorded.as_deref().unwrap_or("none"),
248                    live.as_deref().unwrap_or("none")
249                )),
250            }
251        }
252        out
253    }
254}
255
256/// What changed between the recorded response and a fresh one.
257///
258/// Split in two because the two halves want opposite treatment: the tool half
259/// is decided here and exactly, the text half is left for a judge that
260/// understands wording drift (see the `judge` module in the test runner).
261#[derive(Debug, Clone, PartialEq, Eq)]
262pub struct ResponseDiff {
263    pub recorded_text: String,
264    pub live_text: String,
265    pub recorded_events: usize,
266    pub live_events: usize,
267    pub tools: ToolDiff,
268}
269
270impl ResponseDiff {
271    /// Whether the text is byte-identical — the cheap filter that decides
272    /// whether a judge needs to be asked at all.
273    pub fn text_identical(&self) -> bool {
274        self.recorded_text == self.live_text
275    }
276
277    /// Nothing moved on either half. No judge needed, no report needed.
278    pub fn identical(&self) -> bool {
279        self.text_identical() && self.tools.matches()
280    }
281
282    /// A short human-readable summary, empty when nothing moved.
283    pub fn report(&self) -> String {
284        let mut out = String::new();
285        if !self.tools.matches() {
286            if self.recorded_stop_reason_differs() {
287                out.push_str(&format!(
288                    "stop_reason: recorded {:?}, live {:?}\n",
289                    self.tools.recorded_stop_reason, self.tools.live_stop_reason
290                ));
291            }
292            for step in &self.tools.steps {
293                match step {
294                    ToolStep::Same { .. } => {}
295                    ToolStep::NameDiffers { recorded, live } => {
296                        out.push_str(&format!("tool: recorded {:?}, live {:?}\n", recorded, live))
297                    }
298                    ToolStep::ArgsDiffer { name, args } => {
299                        out.push_str(&format!("{name}: arguments differ\n"));
300                        for a in args {
301                            let mark = if a.matches() { "✓" } else { "✗" };
302                            out.push_str(&format!(
303                                "    {mark} {:<12} recorded {}, live {}\n",
304                                a.key,
305                                describe(a.recorded.as_deref()),
306                                describe(a.live.as_deref()),
307                            ));
308                        }
309                    }
310                }
311            }
312        }
313        if !self.text_identical() {
314            out.push_str(&format!(
315                "text: recorded {} chars, live {} chars\n  recorded: {}\n  live:     {}\n",
316                self.recorded_text.len(),
317                self.live_text.len(),
318                elide(&self.recorded_text),
319                elide(&self.live_text),
320            ));
321        }
322        out
323    }
324
325    fn recorded_stop_reason_differs(&self) -> bool {
326        self.tools.recorded_stop_reason != self.tools.live_stop_reason
327    }
328}
329
330/// A value's size rather than the value: an argument can be a whole source
331/// file, and a summary line is not the place to paste one.
332fn describe(value: Option<&str>) -> String {
333    match value {
334        None => "(absent)".into(),
335        Some(v) if v.len() <= 40 => v.to_string(),
336        Some(v) => format!("{} chars", v.len()),
337    }
338}
339
340fn elide(s: &str) -> String {
341    const MAX: usize = 160;
342    let flat = s.replace('\n', "\\n");
343    match flat.char_indices().nth(MAX) {
344        Some((cut, _)) => format!("{}…", &flat[..cut]),
345        None => flat,
346    }
347}
348
349fn text_of(events: &[ModelEvent]) -> String {
350    events
351        .iter()
352        .filter_map(|e| match e {
353            ModelEvent::TextDelta { text } => Some(text.as_str()),
354            _ => None,
355        })
356        .collect()
357}
358
359fn tools_of(events: &[ModelEvent]) -> Vec<ToolCall> {
360    events
361        .iter()
362        .filter_map(|e| match e {
363            ModelEvent::ToolUse { name, input, .. } => Some(ToolCall {
364                name: name.clone(),
365                args: canonical_args(input),
366            }),
367            _ => None,
368        })
369        .collect()
370}
371
372/// A tool's arguments as sorted `(key, canonical JSON)` pairs.
373///
374/// Sorted because argument order is a serialization detail the model does not
375/// control; canonical JSON because `1.0` and `1` are the same argument even
376/// though the bytes differ.
377fn canonical_args(input: &serde_json::Value) -> Vec<(String, String)> {
378    let Some(object) = input.as_object() else {
379        return vec![(String::new(), input.to_string())];
380    };
381    let mut out: Vec<(String, String)> = object
382        .iter()
383        .map(|(k, v)| (k.clone(), v.to_string()))
384        .collect();
385    out.sort_by(|a, b| a.0.cmp(&b.0));
386    out
387}
388
389fn stop_reason_of(events: &[ModelEvent]) -> Option<String> {
390    events.iter().rev().find_map(|e| match e {
391        ModelEvent::EndTurn { stop_reason, .. } => Some(stop_reason.clone()),
392        _ => None,
393    })
394}
395
396fn compare_tools(recorded: &[ToolCall], live: &[ToolCall]) -> Vec<ToolStep> {
397    let mut steps = Vec::new();
398    for i in 0..recorded.len().max(live.len()) {
399        match (recorded.get(i), live.get(i)) {
400            (Some(r), Some(l)) if r.name == l.name => {
401                let mut keys: Vec<&String> = r.args.iter().chain(&l.args).map(|(k, _)| k).collect();
402                keys.sort();
403                keys.dedup();
404                let args: Vec<ArgDiff> = keys
405                    .into_iter()
406                    .map(|key| ArgDiff {
407                        key: key.clone(),
408                        recorded: lookup(&r.args, key),
409                        live: lookup(&l.args, key),
410                    })
411                    .collect();
412                if args.iter().all(ArgDiff::matches) {
413                    steps.push(ToolStep::Same {
414                        name: r.name.clone(),
415                    });
416                } else {
417                    steps.push(ToolStep::ArgsDiffer {
418                        name: r.name.clone(),
419                        args,
420                    });
421                }
422            }
423            (r, l) => steps.push(ToolStep::NameDiffers {
424                recorded: r.map(|c| c.name.clone()),
425                live: l.map(|c| c.name.clone()),
426            }),
427        }
428    }
429    steps
430}
431
432fn lookup(args: &[(String, String)], key: &str) -> Option<String> {
433    args.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone())
434}
435
436pub fn diff(recorded: &[ModelEvent], live: &[ModelEvent]) -> ResponseDiff {
437    ResponseDiff {
438        recorded_text: text_of(recorded),
439        live_text: text_of(live),
440        recorded_events: recorded.len(),
441        live_events: live.len(),
442        tools: ToolDiff {
443            steps: compare_tools(&tools_of(recorded), &tools_of(live)),
444            recorded_stop_reason: stop_reason_of(recorded),
445            live_stop_reason: stop_reason_of(live),
446        },
447    }
448}
449
450/// What one rerun got back.
451pub struct Rerun {
452    pub diff: ResponseDiff,
453    /// The model's events in order: all of them, or up to `error`. A routed
454    /// model's `served` event is not among them — a recorded response never
455    /// carries one, so keeping it would make every rerun differ by an event.
456    pub live: Vec<ModelEvent>,
457    /// Provider and model the call went to, when the model was a routed one.
458    pub served: Option<(String, String)>,
459    /// Why the call did not open, or what ended its stream early.
460    pub error: Option<ModelError>,
461    pub ttft: Option<std::time::Duration>,
462    pub duration: std::time::Duration,
463}
464
465/// Send `request` to `model` and diff the answer against the recorded one.
466///
467/// `model` must be a real provider, not a `RecorderModel` in replay mode —
468/// replaying the request would just hand back the recorded response and make
469/// every diff empty. A call that fails, to open or partway, is diffed as far
470/// as it got.
471pub async fn rerun_one(
472    model: &Arc<dyn Model>,
473    request: LoadedRequest,
474    cancel: CancellationToken,
475) -> Rerun {
476    let started = std::time::Instant::now();
477    let opened = model
478        .stream(
479            request.prompt_blocks,
480            request.tools,
481            request.messages,
482            request.params,
483            cancel,
484        )
485        .await;
486
487    let mut live = Vec::new();
488    let mut served = None;
489    let mut ttft = None;
490    let mut error = None;
491    match opened {
492        Err(e) => error = Some(e),
493        Ok(mut stream) => {
494            while let Some(event) = stream.next().await {
495                match event {
496                    Ok(ModelEvent::Served { provider, model }) => served = Some((provider, model)),
497                    Ok(event) => {
498                        ttft.get_or_insert_with(|| started.elapsed());
499                        live.push(event);
500                    }
501                    Err(e) => {
502                        error = Some(e);
503                        break;
504                    }
505                }
506            }
507        }
508    }
509    Rerun {
510        diff: diff(&request.recorded_response, &live),
511        live,
512        served,
513        error,
514        ttft,
515        duration: started.elapsed(),
516    }
517}
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522    use crate::recorder::format::{now_ms, Header, Record, RecordedParams, FORMAT_VERSION};
523    use crate::recorder::writer::RecordingWriter;
524    use base::interface::model::ThinkingMode;
525    use base::provider::ApiType;
526
527    fn write_one_call(dir: &Path) {
528        let writer = RecordingWriter::create(dir.parent().unwrap(), {
529            Header {
530                version: FORMAT_VERSION,
531                name: dir.file_name().unwrap().to_string_lossy().into_owned(),
532                session_id: "S1".into(),
533                parent: None,
534                agent_type: None,
535                created_at: now_ms(),
536                engine_version: "test".into(),
537            }
538        });
539        let blobs = writer.blobs();
540        let system = vec![blobs.put(&PromptBlock::system("you are a bot")).unwrap()];
541        let tools = blobs.put(&Vec::<ToolDef>::new()).unwrap();
542        let messages = vec![blobs
543            .put(&ModelMessage {
544                role: base::interface::model::MessageRole::User,
545                content: vec![base::interface::model::ModelContentBlock::Text {
546                    text: "hi".into(),
547                }],
548            })
549            .unwrap()];
550
551        writer
552            .append(&Record::Call(Box::new(CallRecord {
553                seq: 0,
554                ts: now_ms(),
555                session_id: Some("S1".into()),
556                parent_session_id: None,
557                agent_type: None,
558                turn_id: None,
559                turn: 1,
560                step: 0,
561                purpose: None,
562                provider: "anthropic".into(),
563                api_type: ApiType::Anthropic,
564                params: RecordedParams {
565                    search_max_uses: None,
566                    model: "claude-opus-5".into(),
567                    max_tokens: 4096,
568                    thinking_mode: ThinkingMode::Off,
569                    effort: None,
570                    cache_edits: vec![],
571                },
572                system,
573                tools,
574                messages,
575                input_map: None,
576            })))
577            .unwrap();
578        writer
579            .append(&Record::Chunk(crate::recorder::format::ChunkRecord {
580                seq: 1,
581                ts: now_ms(),
582                call: 0,
583                chunk: ModelEvent::TextDelta {
584                    text: "recorded answer".into(),
585                },
586            }))
587            .unwrap();
588        writer.flush().unwrap();
589    }
590
591    #[test]
592    fn a_request_comes_back_out_of_the_blobs() {
593        let root = tempfile::tempdir().unwrap();
594        let dir = root.path().join("run");
595        write_one_call(&dir);
596
597        let loaded = load_request(&dir, 0).unwrap();
598        assert_eq!(loaded.prompt_blocks.len(), 1);
599        assert_eq!(loaded.prompt_blocks[0].content, "you are a bot");
600        assert_eq!(loaded.messages.len(), 1);
601        assert_eq!(loaded.params.model, "claude-opus-5");
602        assert_eq!(text_of(&loaded.recorded_response), "recorded answer");
603    }
604
605    /// The point of the mode: an edited blob changes what gets sent. Replay
606    /// cannot do this, because it never reads a blob's content.
607    #[test]
608    fn editing_a_blob_changes_the_request_that_comes_back() {
609        let root = tempfile::tempdir().unwrap();
610        let dir = root.path().join("run");
611        write_one_call(&dir);
612
613        let id = &reader::load(&dir).unwrap().calls[0].request.system[0].clone();
614        let path = dir.join("blobs").join(&id.0);
615        let edited = std::fs::read_to_string(&path)
616            .unwrap()
617            .replace("you are a bot", "you are a poet");
618        std::fs::write(&path, edited).unwrap();
619
620        let loaded = load_request(&dir, 0).unwrap();
621        assert_eq!(loaded.prompt_blocks[0].content, "you are a poet");
622    }
623
624    #[test]
625    fn a_missing_blob_names_the_call_and_the_blob() {
626        let root = tempfile::tempdir().unwrap();
627        let dir = root.path().join("run");
628        write_one_call(&dir);
629        let id = reader::load(&dir).unwrap().calls[0].request.system[0].clone();
630        std::fs::remove_file(dir.join("blobs").join(&id.0)).unwrap();
631
632        assert!(matches!(
633            load_request(&dir, 0),
634            Err(RerunError::MissingBlob { index: 0, .. })
635        ));
636    }
637
638    #[test]
639    fn asking_past_the_end_says_how_many_there_are() {
640        let root = tempfile::tempdir().unwrap();
641        let dir = root.path().join("run");
642        write_one_call(&dir);
643        assert!(matches!(
644            load_request(&dir, 5),
645            Err(RerunError::NoSuchCall { index: 5, len: 1 })
646        ));
647    }
648
649    /// The whole workflow, end to end: record, edit the prompt, rerun, read the
650    /// diff. The stub model answers from whatever system prompt it is given, so
651    /// a different answer proves the edit reached the provider.
652    #[tokio::test]
653    async fn editing_the_prompt_and_rerunning_shows_a_different_answer() {
654        struct EchoSystem;
655        #[async_trait::async_trait]
656        impl Model for EchoSystem {
657            fn api_type(&self) -> ApiType {
658                ApiType::Anthropic
659            }
660            async fn stream(
661                &self,
662                prompt_blocks: Vec<PromptBlock>,
663                _: Vec<ToolDef>,
664                _: Vec<ModelMessage>,
665                _: StreamParams,
666                _: CancellationToken,
667            ) -> Result<base::interface::model::ModelStream, ModelError> {
668                let text = prompt_blocks
669                    .first()
670                    .map(|b| b.content.clone())
671                    .unwrap_or_default();
672                Ok(Box::new(futures::stream::iter(vec![Ok(
673                    ModelEvent::TextDelta { text },
674                )])))
675            }
676        }
677
678        let root = tempfile::tempdir().unwrap();
679        let dir = root.path().join("run");
680        write_one_call(&dir);
681
682        let id = reader::load(&dir).unwrap().calls[0].request.system[0].clone();
683        let path = dir.join("blobs").join(&id.0);
684        let edited = std::fs::read_to_string(&path)
685            .unwrap()
686            .replace("you are a bot", "you are a poet");
687        std::fs::write(&path, edited).unwrap();
688
689        let model: Arc<dyn Model> = Arc::new(EchoSystem);
690        let request = load_request(&dir, 0).unwrap();
691        let Rerun { diff, live, .. } = rerun_one(&model, request, CancellationToken::new()).await;
692
693        assert_eq!(text_of(&live), "you are a poet");
694        assert!(!diff.identical());
695        assert_eq!(diff.recorded_text, "recorded answer");
696        assert_eq!(diff.live_text, "you are a poet");
697
698        // And the recording is still the recording.
699        assert_eq!(
700            text_of(&reader::load(&dir).unwrap().calls[0].response),
701            "recorded answer"
702        );
703    }
704
705    /// A routed model names its provider first; a stream that fails partway
706    /// still answers with what came before the failure.
707    #[tokio::test]
708    async fn a_stream_cut_short_keeps_what_arrived_and_names_where_it_went() {
709        struct CutShort;
710        #[async_trait::async_trait]
711        impl Model for CutShort {
712            fn api_type(&self) -> ApiType {
713                ApiType::Anthropic
714            }
715            async fn stream(
716                &self,
717                _: Vec<PromptBlock>,
718                _: Vec<ToolDef>,
719                _: Vec<ModelMessage>,
720                _: StreamParams,
721                _: CancellationToken,
722            ) -> Result<base::interface::model::ModelStream, ModelError> {
723                Ok(Box::new(futures::stream::iter(vec![
724                    Ok(ModelEvent::Served {
725                        provider: "p1".into(),
726                        model: "m1".into(),
727                    }),
728                    Ok(ModelEvent::TextDelta {
729                        text: "recorded".into(),
730                    }),
731                    Err(ModelError::overloaded()),
732                ])))
733            }
734        }
735
736        let root = tempfile::tempdir().unwrap();
737        let dir = root.path().join("run");
738        write_one_call(&dir);
739        let model: Arc<dyn Model> = Arc::new(CutShort);
740        let rerun = rerun_one(
741            &model,
742            load_request(&dir, 0).unwrap(),
743            CancellationToken::new(),
744        )
745        .await;
746
747        assert_eq!(rerun.served, Some(("p1".into(), "m1".into())));
748        assert_eq!(rerun.live.len(), 1);
749        assert_eq!(rerun.diff.live_events, 1);
750        assert_eq!(rerun.diff.live_text, "recorded");
751        assert!(rerun.error.is_some());
752        assert!(rerun.ttft.is_some());
753    }
754
755    #[test]
756    fn an_unchanged_answer_reports_nothing() {
757        let events = vec![ModelEvent::TextDelta {
758            text: "same".into(),
759        }];
760        let d = diff(&events, &events);
761        assert!(d.identical());
762        assert_eq!(d.report(), "");
763    }
764
765    #[test]
766    fn a_changed_answer_reports_both_sides() {
767        let recorded = vec![ModelEvent::TextDelta {
768            text: "the old answer".into(),
769        }];
770        let live = vec![
771            ModelEvent::TextDelta {
772                text: "a new answer".into(),
773            },
774            ModelEvent::ToolUse {
775                id: "t1".into(),
776                name: "Read".into(),
777                input: serde_json::json!({}),
778            },
779        ];
780        let d = diff(&recorded, &live);
781        assert!(!d.identical());
782        let report = d.report();
783        assert!(report.contains("the old answer"), "{report}");
784        assert!(report.contains("a new answer"), "{report}");
785        assert!(report.contains("Read"), "{report}");
786    }
787
788    fn tool(name: &str, input: serde_json::Value) -> ModelEvent {
789        ModelEvent::ToolUse {
790            id: "t".into(),
791            name: name.into(),
792            input,
793        }
794    }
795
796    /// Argument order is a serialization detail the model does not control.
797    #[test]
798    fn argument_order_is_not_a_difference() {
799        let a = vec![tool(
800            "Write",
801            serde_json::json!({"path":"a.c","content":"x"}),
802        )];
803        let b = vec![tool(
804            "Write",
805            serde_json::json!({"content":"x","path":"a.c"}),
806        )];
807        assert!(diff(&a, &b).tools.matches());
808    }
809
810    /// The case this whole tier exists for: a judge would call these "the same
811    /// thing". They are not — one of them builds, the other does not.
812    #[test]
813    fn a_one_character_path_change_is_a_failure_not_a_nuance() {
814        let recorded = vec![tool("Write", serde_json::json!({"path":"src/main.c"}))];
815        let live = vec![tool("Write", serde_json::json!({"path":"src/Main.c"}))];
816        let d = diff(&recorded, &live);
817        assert!(!d.tools.matches());
818        assert_eq!(d.tools.offending_keys(), vec!["Write.path"]);
819    }
820
821    /// The known cost of judging every argument exactly: generated file content
822    /// never reproduces. It fails, and the report names the key so a human can
823    /// see at a glance that it is `content` and not `path`.
824    #[test]
825    fn drifting_file_content_fails_but_names_itself() {
826        let recorded = vec![tool(
827            "Write",
828            serde_json::json!({"path":"a.c","content":"int main(){return 0;}"}),
829        )];
830        let live = vec![tool(
831            "Write",
832            serde_json::json!({"path":"a.c","content":"int main(void){return 0;}"}),
833        )];
834        let d = diff(&recorded, &live);
835        assert!(!d.tools.matches());
836        assert_eq!(d.tools.offending_keys(), vec!["Write.content"]);
837        let report = d.report();
838        assert!(
839            report.contains("✓ path"),
840            "path should show as matching: {report}"
841        );
842        assert!(report.contains("✗ content"), "{report}");
843    }
844
845    #[test]
846    fn calling_a_different_tool_is_reported_as_such() {
847        let recorded = vec![tool("Write", serde_json::json!({}))];
848        let live = vec![tool("Bash", serde_json::json!({}))];
849        let d = diff(&recorded, &live);
850        assert!(!d.tools.matches());
851        assert!(d.tools.offending_keys()[0].contains("Write"));
852        assert!(d.tools.offending_keys()[0].contains("Bash"));
853    }
854
855    #[test]
856    fn an_extra_tool_call_is_a_difference() {
857        let recorded = vec![tool("Read", serde_json::json!({}))];
858        let live = vec![
859            tool("Read", serde_json::json!({})),
860            tool("Bash", serde_json::json!({})),
861        ];
862        assert!(!diff(&recorded, &live).tools.matches());
863    }
864
865    #[test]
866    fn a_changed_stop_reason_is_a_difference() {
867        let end = |r: &str| ModelEvent::EndTurn {
868            stop_reason: r.into(),
869            usage: Default::default(),
870        };
871        let d = diff(&[end("tool_use")], &[end("end_turn")]);
872        assert!(!d.tools.matches());
873        assert!(d.report().contains("stop_reason"), "{}", d.report());
874    }
875
876    /// Identical text needs no judge — this is the filter that keeps the judge
877    /// (and its cost, and its own non-determinism) off the common path.
878    #[test]
879    fn identical_text_is_detected_without_a_judge() {
880        let same = vec![ModelEvent::TextDelta { text: "hi".into() }];
881        assert!(diff(&same, &same).text_identical());
882        let other = vec![ModelEvent::TextDelta {
883            text: "hello".into(),
884        }];
885        assert!(!diff(&same, &other).text_identical());
886    }
887}