Skip to main content

telemetry/recorder/
format.rs

1//! The on-disk vocabulary of `calls.jsonl`.
2//!
3//! One recording is a header line followed by records describing what left for
4//! the model and what came back, in arrival order. A call's request is written
5//! *before* the stream opens, so a recording torn by a crash still answers the
6//! question a crash raises — what was in flight when it died.
7//!
8//! Bulky request parts are [`BlobId`] references (see [`super::blob`]); the
9//! response is stored as the model events themselves rather than a parallel
10//! representation, so there is no second shape that can drift from the first.
11
12use base::interface::model::{Effort, ThinkingMode};
13use base::interface::model::{InputMap, ModelError, ModelErrorKind, ModelEvent, Usage};
14use base::provider::ApiType;
15use serde::{Deserialize, Serialize};
16
17use super::blob::BlobId;
18
19/// Bumped only for a change that makes existing recordings unreadable. Adding
20/// a record type is not such a change — readers skip what they do not know
21/// (see [`Record::Unknown`]).
22pub const FORMAT_VERSION: u32 = 1;
23
24/// One line of `calls.jsonl`.
25#[derive(Debug, Clone, Serialize, Deserialize)]
26#[serde(tag = "type", rename_all = "snake_case")]
27pub enum Record {
28    Recording(Header),
29    /// Boxed: a `CallRecord` is three times the size of a `ChunkRecord`, and a
30    /// `Record` is built once per streamed token — so an unboxed variant would
31    /// make every chunk pay for the largest thing the enum can hold.
32    Call(Box<CallRecord>),
33    Chunk(ChunkRecord),
34    TextChunks(TextRun),
35    ThinkingChunks(TextRun),
36    ToolArgsChunks(ToolArgsRun),
37    End(EndRecord),
38
39    /// A record type this build does not know. A recording is diagnostic data,
40    /// not session state: reading the parts we understand beats refusing the
41    /// whole file. The reader warns with the line number, because a genuinely
42    /// corrupt line lands here too.
43    #[serde(other)]
44    Unknown,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct Header {
49    pub version: u32,
50    pub name: String,
51    pub session_id: String,
52    /// The session that spawned this one. With `created_at` and the per-record
53    /// timestamps, this is what turns a directory of recordings into a single
54    /// tree on one timeline instead of a pile of unrelated files.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub parent: Option<String>,
57    /// Which kind of agent this session runs, when it is a sub-agent.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub agent_type: Option<String>,
60    pub created_at: u64,
61    pub engine_version: String,
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct CallRecord {
66    pub seq: u64,
67    pub ts: u64,
68    /// Which session issued this call. The header names one session, but a
69    /// recording configured with an explicit name holds a parent's calls and
70    /// its sub-agents' interleaved, and replay hands each live session only its
71    /// own — so the file has to say per call, not once at the top.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub session_id: Option<String>,
74    /// The lineage of `session_id`, repeated on every call for the same reason
75    /// `session_id` is: the header can only describe one session, and a
76    /// recording written under an explicit name holds several. Without this a
77    /// sub-agent's parentage is simply absent from any recording but its own.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub parent_session_id: Option<String>,
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub agent_type: Option<String>,
82    /// The turn this call belongs to, as the session's events name it.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub turn_id: Option<String>,
85    pub turn: u32,
86    pub step: u32,
87    /// Present for a call made outside any turn — `compact`, `memory`, and so
88    /// on; the conventional values are
89    /// [`base::interface::model::call_purpose`]'s constants. Absent
90    /// for turn work, where `turn`/`step` are the coordinates that mean
91    /// something. Deliberately not part of the replay divergence check.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub purpose: Option<String>,
94    pub provider: String,
95    pub api_type: ApiType,
96    pub params: RecordedParams,
97    /// One entry per assembled prompt block, in order. Kept per block rather
98    /// than joined: the boundaries are what tell the system prompt, the skills
99    /// inventory, and MCP instructions apart.
100    pub system: Vec<BlobId>,
101    pub tools: BlobId,
102    pub messages: Vec<BlobId>,
103    /// What the turn's user message is made of, as coordinates over
104    /// `messages`. Absent for a call that started no turn, or when compaction
105    /// folded the message away before this call went out.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub input_map: Option<InputMap>,
108}
109
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub struct RecordedParams {
112    pub model: String,
113    pub max_tokens: u32,
114    pub thinking_mode: ThinkingMode,
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub effort: Option<Effort>,
117    #[serde(default, skip_serializing_if = "Vec::is_empty")]
118    pub cache_edits: Vec<String>,
119    /// `StreamParams::provider_search`'s `max_uses`, when the call asked the
120    /// provider to search.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub search_max_uses: Option<u32>,
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct ChunkRecord {
127    pub seq: u64,
128    pub ts: u64,
129    pub call: u64,
130    pub chunk: ModelEvent,
131}
132
133/// A packed run of consecutive text or thinking deltas belonging to one call.
134///
135/// `texts` is never joined — token boundaries are evidence, not noise, and
136/// keeping members separate is what makes the packing lossless regardless of
137/// where content-block boundaries fell.
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct TextRun {
140    pub seq0: u64,
141    pub ts0: u64,
142    pub call: u64,
143    pub texts: Vec<String>,
144    /// Millisecond gaps between consecutive members; one shorter than `texts`.
145    /// Signed because a wall clock can step backwards mid-stream.
146    pub dt: Vec<i64>,
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct ToolArgsRun {
151    pub seq0: u64,
152    pub ts0: u64,
153    pub call: u64,
154    /// The tool_use id every member shares; a run with a mixed id never packs.
155    pub id: String,
156    pub args: Vec<String>,
157    pub dt: Vec<i64>,
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct EndRecord {
162    pub seq: u64,
163    pub ts: u64,
164    pub call: u64,
165    pub outcome: Outcome,
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub stop_reason: Option<String>,
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub usage: Option<Usage>,
170    pub duration_ms: u64,
171}
172
173#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174#[serde(tag = "status", rename_all = "snake_case")]
175pub enum Outcome {
176    Ok,
177    Cancelled,
178    Error {
179        #[serde(flatten)]
180        error: RecordedError,
181    },
182}
183
184/// A [`ModelError`] in a form a recording can hold. `ModelError` itself stays
185/// free of serde so the model interface owes nothing to the recorder; replay
186/// reconstructs the original through [`RecordedError::into_model_error`], which
187/// is what lets a recorded failure — an overload that triggered the fallback
188/// model, say — replay as a failure instead of being silently skipped.
189///
190/// The status is `http_status` because the enclosing [`Outcome`] already
191/// spends `status` on its own tag.
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
193pub struct RecordedError {
194    pub error: ModelErrorKind,
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub http_status: Option<u16>,
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub retry_after_ms: Option<u64>,
199    #[serde(default, skip_serializing_if = "String::is_empty")]
200    pub message: String,
201}
202
203impl From<&ModelError> for RecordedError {
204    fn from(e: &ModelError) -> Self {
205        Self {
206            error: e.kind,
207            http_status: e.status,
208            retry_after_ms: e.retry_after.map(|d| d.as_millis() as u64),
209            message: e.message.clone(),
210        }
211    }
212}
213
214impl RecordedError {
215    pub fn into_model_error(self) -> ModelError {
216        let error = ModelError::new(self.error, self.message)
217            .with_retry_after(self.retry_after_ms.map(std::time::Duration::from_millis));
218        match self.http_status {
219            Some(status) => error.with_status(status),
220            None => error,
221        }
222    }
223}
224
225pub fn now_ms() -> u64 {
226    u64::try_from(base::clock::unix_ms()).unwrap_or(0)
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn unknown_record_type_decodes_as_unknown() {
235        let line = r#"{"type":"something_from_the_future","whatever":1}"#;
236        assert!(matches!(
237            serde_json::from_str::<Record>(line).unwrap(),
238            Record::Unknown
239        ));
240    }
241
242    #[test]
243    fn call_record_round_trips() {
244        let record = Record::Call(Box::new(CallRecord {
245            seq: 3,
246            ts: 1_755_500_000_123,
247            session_id: Some("S1".into()),
248            parent_session_id: None,
249            agent_type: None,
250            turn_id: Some("T1".into()),
251            turn: 2,
252            step: 1,
253            purpose: None,
254            provider: "anthropic".into(),
255            api_type: ApiType::Anthropic,
256            params: RecordedParams {
257                search_max_uses: None,
258                model: "claude-opus-5".into(),
259                max_tokens: 8192,
260                thinking_mode: ThinkingMode::Off,
261                effort: None,
262                cache_edits: vec![],
263            },
264            system: vec![BlobId("aaaaaaaaaaaaaaaa".into())],
265            tools: BlobId("bbbbbbbbbbbbbbbb".into()),
266            messages: vec![BlobId("cccccccccccccccc".into())],
267            input_map: None,
268        }));
269        let json = serde_json::to_string(&record).unwrap();
270        assert!(json.contains(r#""type":"call""#));
271        let back: Record = serde_json::from_str(&json).unwrap();
272        let Record::Call(back) = back else {
273            panic!("expected a call record")
274        };
275        assert_eq!(back.seq, 3);
276        assert_eq!(back.turn_id.as_deref(), Some("T1"));
277        assert_eq!(back.system.len(), 1);
278    }
279
280    #[test]
281    fn every_model_error_survives_the_round_trip() {
282        let errors = [
283            ModelError::overloaded()
284                .with_status(529)
285                .with_retry_after(Some(std::time::Duration::from_millis(1500))),
286            ModelError::auth("bad token"),
287            ModelError::rate_limited(),
288            ModelError::timeout("no response headers"),
289            ModelError::cancelled(),
290            ModelError::protocol("boom"),
291            ModelError::not_recorded("no title call"),
292        ];
293        for error in &errors {
294            let recorded = RecordedError::from(error);
295            let json = serde_json::to_string(&recorded).unwrap();
296            let back: RecordedError = serde_json::from_str(&json).unwrap();
297            assert_eq!(recorded, back);
298            assert_eq!(&back.into_model_error(), error);
299        }
300    }
301
302    #[test]
303    fn model_events_round_trip_through_a_chunk_record() {
304        let events = [
305            ModelEvent::TextDelta { text: "hi".into() },
306            ModelEvent::ThinkingDelta { text: "hmm".into() },
307            ModelEvent::ThinkingSignature {
308                signature: "sig".into(),
309            },
310            ModelEvent::RedactedThinking { data: "enc".into() },
311            ModelEvent::ToolUse {
312                id: "t1".into(),
313                name: "Read".into(),
314                input: serde_json::json!({"path": "/tmp/x"}),
315            },
316            ModelEvent::ContentBlockStop { index: 0 },
317            ModelEvent::EndTurn {
318                stop_reason: "end_turn".into(),
319                usage: Usage {
320                    input_tokens: 10,
321                    output_tokens: 20,
322                    ..Default::default()
323                },
324            },
325        ];
326        for event in events {
327            let record = Record::Chunk(ChunkRecord {
328                seq: 0,
329                ts: 1,
330                call: 0,
331                chunk: event.clone(),
332            });
333            let json = serde_json::to_string(&record).unwrap();
334            let back: Record = serde_json::from_str(&json).unwrap();
335            let Record::Chunk(back) = back else {
336                panic!("expected a chunk record")
337            };
338            assert_eq!(format!("{:?}", back.chunk), format!("{event:?}"));
339        }
340    }
341}