Skip to main content

telemetry/recorder/
reader.rs

1//! Reads a recording back into calls with their responses attached.
2//!
3//! The read path is deliberately forgiving where the history store is strict.
4//! A session transcript is what `resume` rebuilds a conversation from, so
5//! silently skipping a line there would reconstruct a wrong session and
6//! refusing the file is the safer failure. A recording is diagnostic data:
7//! surfacing the parts that parse beats refusing the whole file, so an
8//! unreadable line is counted, warned about with its line number, and stepped
9//! over. The count is carried on [`Recording`] so a caller can say how much of
10//! a recording it is actually looking at.
11
12use base::interface::model::ModelEvent;
13use std::path::Path;
14
15use super::format::{CallRecord, EndRecord, Header, Record};
16use super::pack::{expand_text_run, expand_tool_args_run};
17
18#[derive(Debug, thiserror::Error)]
19pub enum ReadError {
20    #[error("recording not found: {0}")]
21    NotFound(String),
22    #[error("io error: {0}")]
23    Io(#[from] std::io::Error),
24    #[error("recording has no header line")]
25    MissingHeader,
26    #[error("unsupported recording format version {found} (this build reads {supported})")]
27    UnsupportedVersion { found: u32, supported: u32 },
28}
29
30/// One recorded model call: what went out, what came back, and how it ended.
31#[derive(Debug, Clone)]
32pub struct RecordedCall {
33    pub request: CallRecord,
34    pub response: Vec<ModelEvent>,
35    /// Absent when the recording stops mid-call — the process died while the
36    /// stream was open. Replay reproduces that as a stream that simply ends.
37    pub end: Option<EndRecord>,
38    /// When the first response record of this call was written (ms since the epoch); `None` when none was.
39    pub first_event_at: Option<u64>,
40}
41
42#[derive(Debug, Clone)]
43pub struct Recording {
44    pub header: Header,
45    pub calls: Vec<RecordedCall>,
46    /// Lines that could not be interpreted. Non-zero means this recording is
47    /// being read partially.
48    pub damaged: usize,
49}
50
51pub fn load(dir: &Path) -> Result<Recording, ReadError> {
52    let path = dir.join("calls.jsonl");
53    let content = match std::fs::read_to_string(&path) {
54        Ok(c) => c,
55        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
56            return Err(ReadError::NotFound(path.display().to_string()))
57        }
58        Err(e) => return Err(ReadError::Io(e)),
59    };
60
61    // A last line with no newline is one the writer is still in the middle
62    // of (or died in the middle of), not a damaged one.
63    let complete = match content.rfind('\n') {
64        Some(end) => &content[..=end],
65        None => "",
66    };
67    let mut reading = Reading::default();
68    for (i, line) in complete.lines().enumerate() {
69        let line_no = i + 1;
70        if line.trim().is_empty() {
71            continue;
72        }
73        match serde_json::from_str::<Record>(line) {
74            Ok(record) => reading.take(record, line_no)?,
75            Err(e) => {
76                tracing::warn!(line = line_no, error = %e, "recording: unreadable line, skipped");
77                reading.damaged += 1;
78            }
79        }
80    }
81
82    Ok(Recording {
83        header: reading.header.ok_or(ReadError::MissingHeader)?,
84        calls: reading.calls,
85        damaged: reading.damaged,
86    })
87}
88
89/// A recording as far as its lines have been read.
90#[derive(Default)]
91struct Reading {
92    header: Option<Header>,
93    calls: Vec<RecordedCall>,
94    damaged: usize,
95}
96
97impl Reading {
98    fn take(&mut self, record: Record, line_no: usize) -> Result<(), ReadError> {
99        let (calls, damaged) = (&mut self.calls, &mut self.damaged);
100        match record {
101            Record::Recording(h) => {
102                if h.version > super::format::FORMAT_VERSION {
103                    return Err(ReadError::UnsupportedVersion {
104                        found: h.version,
105                        supported: super::format::FORMAT_VERSION,
106                    });
107                }
108                self.header = Some(h);
109            }
110            Record::Call(request) => calls.push(RecordedCall {
111                request: *request,
112                response: Vec::new(),
113                end: None,
114                first_event_at: None,
115            }),
116            Record::Chunk(c) => push_events(
117                calls,
118                c.call,
119                c.ts,
120                std::iter::once(c.chunk),
121                line_no,
122                damaged,
123            ),
124            Record::TextChunks(run) => push_packed(
125                calls,
126                run.call,
127                run.ts0,
128                expand_text_run(&run, false),
129                line_no,
130                damaged,
131            ),
132            Record::ThinkingChunks(run) => push_packed(
133                calls,
134                run.call,
135                run.ts0,
136                expand_text_run(&run, true),
137                line_no,
138                damaged,
139            ),
140            Record::ToolArgsChunks(run) => push_packed(
141                calls,
142                run.call,
143                run.ts0,
144                expand_tool_args_run(&run),
145                line_no,
146                damaged,
147            ),
148            Record::End(end) => match calls.iter_mut().find(|c| c.request.seq == end.call) {
149                Some(call) => call.end = Some(end),
150                None => {
151                    tracing::warn!(
152                        line = line_no,
153                        call = end.call,
154                        "recording: end record with no matching call, skipped"
155                    );
156                    *damaged += 1;
157                }
158            },
159            Record::Unknown => {
160                tracing::warn!(line = line_no, "recording: unknown record type, skipped");
161                *damaged += 1;
162            }
163        }
164        Ok(())
165    }
166}
167
168/// Loads a recording for replay, applying the hand-written override beside it
169/// if there is one. An override is deliberate, so a broken one fails the
170/// replay instead of being skipped: an edit that silently did nothing is worse
171/// than one that says why it could not.
172pub(super) fn load_for_replay(
173    dir: &Path,
174    name: &str,
175) -> Result<Recording, base::interface::model::ModelError> {
176    use base::interface::model::{ModelError, ModelEvent};
177    let mut recording = load(dir)
178        .map_err(|e| ModelError::protocol(format!("recorder: cannot replay {name:?}: {e}")))?;
179    if recording.damaged > 0 {
180        tracing::warn!(
181            name,
182            damaged = recording.damaged,
183            "recorder: replaying a recording with unreadable lines"
184        );
185    }
186    if let Some(doc) = super::override_doc::load(dir)
187        .map_err(|e| ModelError::protocol(format!("recorder: {name:?}: {e}")))?
188    {
189        let mut responses: Vec<Vec<ModelEvent>> =
190            recording.calls.iter().map(|c| c.response.clone()).collect();
191        super::override_doc::apply(&doc, &mut responses)
192            .map_err(|e| ModelError::protocol(format!("recorder: {name:?}: {e}")))?;
193        for (call, response) in recording.calls.iter_mut().zip(responses) {
194            call.response = response;
195        }
196        tracing::info!(name, "recorder: replaying with an override applied");
197    }
198    Ok(recording)
199}
200
201fn push_packed(
202    calls: &mut [RecordedCall],
203    call_seq: u64,
204    ts: u64,
205    expanded: Result<Vec<super::format::ChunkRecord>, super::pack::PackError>,
206    line_no: usize,
207    damaged: &mut usize,
208) {
209    match expanded {
210        Ok(chunks) => push_events(
211            calls,
212            call_seq,
213            ts,
214            chunks.into_iter().map(|c| c.chunk),
215            line_no,
216            damaged,
217        ),
218        Err(e) => {
219            tracing::warn!(line = line_no, error = %e, "recording: malformed packed run, skipped");
220            *damaged += 1;
221        }
222    }
223}
224
225fn push_events(
226    calls: &mut [RecordedCall],
227    call_seq: u64,
228    ts: u64,
229    events: impl Iterator<Item = ModelEvent>,
230    line_no: usize,
231    damaged: &mut usize,
232) {
233    match calls.iter_mut().find(|c| c.request.seq == call_seq) {
234        Some(call) => {
235            call.first_event_at.get_or_insert(ts);
236            call.response.extend(events);
237        }
238        None => {
239            tracing::warn!(
240                line = line_no,
241                call = call_seq,
242                "recording: chunk with no matching call, skipped"
243            );
244            *damaged += 1;
245        }
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252    use crate::recorder::blob::BlobId;
253    use crate::recorder::format::{now_ms, ChunkRecord, Outcome, RecordedParams, FORMAT_VERSION};
254    use crate::recorder::writer::RecordingWriter;
255    use base::interface::model::ThinkingMode;
256    use base::interface::model::Usage;
257    use base::provider::ApiType;
258
259    fn header() -> Header {
260        Header {
261            version: FORMAT_VERSION,
262            name: "run".into(),
263            session_id: "S1".into(),
264            parent: None,
265            agent_type: None,
266            created_at: now_ms(),
267            engine_version: "test".into(),
268        }
269    }
270
271    fn call_record(seq: u64) -> CallRecord {
272        CallRecord {
273            seq,
274            ts: 1000,
275            session_id: Some("S1".into()),
276            parent_session_id: None,
277            agent_type: None,
278            turn_id: None,
279            turn: 0,
280            step: 0,
281            purpose: None,
282            provider: "anthropic".into(),
283            api_type: ApiType::Anthropic,
284            params: RecordedParams {
285                search_max_uses: None,
286                model: "m".into(),
287                max_tokens: 100,
288                thinking_mode: ThinkingMode::Off,
289                effort: None,
290                cache_edits: vec![],
291            },
292            system: vec![BlobId("a".repeat(16))],
293            tools: BlobId("b".repeat(16)),
294            messages: vec![],
295            input_map: None,
296        }
297    }
298
299    /// Writes a call, three text deltas (which pack into one row), and an end.
300    fn write_one_call(root: &Path) {
301        let writer = RecordingWriter::create(root, header());
302        writer
303            .append(&Record::Call(Box::new(call_record(0))))
304            .unwrap();
305        let chunks: Vec<_> = (0..3)
306            .map(|i| ChunkRecord {
307                seq: i + 1,
308                ts: 1000 + i * 10,
309                call: 0,
310                chunk: ModelEvent::TextDelta {
311                    text: format!("t{i}"),
312                },
313            })
314            .collect();
315        for record in crate::recorder::pack::pack(chunks) {
316            writer.append(&record).unwrap();
317        }
318        writer
319            .append(&Record::End(EndRecord {
320                seq: 4,
321                ts: 1100,
322                call: 0,
323                outcome: Outcome::Ok,
324                stop_reason: Some("end_turn".into()),
325                usage: Some(Usage {
326                    input_tokens: 5,
327                    output_tokens: 6,
328                    ..Default::default()
329                }),
330                duration_ms: 100,
331            }))
332            .unwrap();
333        writer.flush().unwrap();
334    }
335
336    #[test]
337    fn a_written_recording_reads_back_with_its_response_attached() {
338        let root = tempfile::tempdir().unwrap();
339        write_one_call(root.path());
340
341        let recording = load(&root.path().join("run")).unwrap();
342        assert_eq!(recording.damaged, 0);
343        assert_eq!(recording.calls.len(), 1);
344        let call = &recording.calls[0];
345        assert_eq!(call.response.len(), 3);
346        assert!(matches!(
347            &call.response[0],
348            ModelEvent::TextDelta { text } if text == "t0"
349        ));
350        assert!(matches!(call.end.as_ref().unwrap().outcome, Outcome::Ok));
351        assert_eq!(call.first_event_at, Some(1000));
352    }
353
354    #[test]
355    fn an_unknown_record_type_is_skipped_and_counted() {
356        let root = tempfile::tempdir().unwrap();
357        write_one_call(root.path());
358        let path = root.path().join("run").join("calls.jsonl");
359        let mut content = std::fs::read_to_string(&path).unwrap();
360        content.push_str("{\"type\":\"from_the_future\",\"x\":1}\n");
361        std::fs::write(&path, content).unwrap();
362
363        let recording = load(&root.path().join("run")).unwrap();
364        assert_eq!(recording.damaged, 1);
365        assert_eq!(recording.calls.len(), 1);
366        assert_eq!(recording.calls[0].response.len(), 3);
367    }
368
369    #[test]
370    fn an_unparseable_line_is_skipped_and_counted() {
371        let root = tempfile::tempdir().unwrap();
372        write_one_call(root.path());
373        let path = root.path().join("run").join("calls.jsonl");
374        let mut content = std::fs::read_to_string(&path).unwrap();
375        content.push_str("{ this is not json\n");
376        std::fs::write(&path, content).unwrap();
377
378        let recording = load(&root.path().join("run")).unwrap();
379        assert_eq!(recording.damaged, 1);
380        assert_eq!(recording.calls.len(), 1);
381    }
382
383    #[test]
384    fn a_line_still_being_written_is_left_out_rather_than_counted() {
385        let root = tempfile::tempdir().unwrap();
386        write_one_call(root.path());
387        let path = root.path().join("run").join("calls.jsonl");
388        let mut content = std::fs::read_to_string(&path).unwrap();
389        content.push_str("{\"type\":\"chunk\",\"seq\":9,\"ts\":1");
390        std::fs::write(&path, content).unwrap();
391
392        let recording = load(&root.path().join("run")).unwrap();
393        assert_eq!(recording.damaged, 0);
394        assert_eq!(recording.calls.len(), 1);
395    }
396
397    #[test]
398    fn a_call_cut_off_mid_stream_reads_back_without_an_end() {
399        let root = tempfile::tempdir().unwrap();
400        let writer = RecordingWriter::create(root.path(), header());
401        writer
402            .append(&Record::Call(Box::new(call_record(0))))
403            .unwrap();
404        writer
405            .append(&Record::Chunk(ChunkRecord {
406                seq: 1,
407                ts: 1010,
408                call: 0,
409                chunk: ModelEvent::TextDelta {
410                    text: "partial".into(),
411                },
412            }))
413            .unwrap();
414        writer.flush().unwrap();
415
416        let recording = load(&root.path().join("run")).unwrap();
417        assert_eq!(recording.calls.len(), 1);
418        assert_eq!(recording.calls[0].response.len(), 1);
419        assert!(recording.calls[0].end.is_none());
420    }
421
422    #[test]
423    fn a_call_with_no_response_records_has_no_first_event_time() {
424        let root = tempfile::tempdir().unwrap();
425        let writer = RecordingWriter::create(root.path(), header());
426        writer
427            .append(&Record::Call(Box::new(call_record(0))))
428            .unwrap();
429        writer
430            .append(&Record::End(EndRecord {
431                seq: 1,
432                ts: 1100,
433                call: 0,
434                outcome: Outcome::Ok,
435                stop_reason: None,
436                usage: None,
437                duration_ms: 100,
438            }))
439            .unwrap();
440        writer.flush().unwrap();
441
442        let recording = load(&root.path().join("run")).unwrap();
443        assert_eq!(recording.calls[0].first_event_at, None);
444    }
445
446    #[test]
447    fn a_newer_format_version_is_refused_rather_than_misread() {
448        let root = tempfile::tempdir().unwrap();
449        let mut h = header();
450        h.version = FORMAT_VERSION + 1;
451        let writer = RecordingWriter::create(root.path(), h);
452        writer
453            .append(&Record::Call(Box::new(call_record(0))))
454            .unwrap();
455        writer.flush().unwrap();
456
457        assert!(matches!(
458            load(&root.path().join("run")),
459            Err(ReadError::UnsupportedVersion { .. })
460        ));
461    }
462
463    #[test]
464    fn a_missing_recording_is_reported_as_not_found() {
465        let root = tempfile::tempdir().unwrap();
466        assert!(matches!(
467            load(&root.path().join("absent")),
468            Err(ReadError::NotFound(_))
469        ));
470    }
471}