Skip to main content

telemetry/recorder/
pack.rs

1//! Lossless run-length packing for streamed delta chunks.
2//!
3//! Providers emit token-sized deltas, so a recording that stores one line per
4//! chunk spends most of its bytes on JSON envelopes rather than content. This
5//! module folds a run of consecutive same-kind deltas belonging to one call
6//! into a single row and expands rows back into the exact original chunks.
7//!
8//! Two properties the encoder is built around:
9//!
10//! - **Members are never joined.** Token boundaries are evidence — where the
11//!   model paused, which span came back from cache. Keeping each fragment a
12//!   separate array element is also what makes packing correct without tracking
13//!   content-block indices: even a run that spans a block boundary expands to
14//!   the identical chunk sequence, because there is no per-chunk index to
15//!   restore.
16//! - **Anything unrecognized passes through verbatim.** An event the encoder
17//!   cannot classify costs compression, never data.
18
19use base::interface::model::ModelEvent;
20
21use super::format::{ChunkRecord, Record, TextRun, ToolArgsRun};
22
23/// Below this a row's envelope rivals the lines it replaces. A format constant,
24/// not a tunable: both layouts expand identically, so changing it never
25/// invalidates a stored recording.
26const MIN_RUN: usize = 3;
27
28/// Runs split here instead of growing without bound. The packer holds pending
29/// members in memory until a run ends, so an uncapped run would mean a whole
30/// content block buffered — and lost if the process died mid-stream, which is
31/// exactly when the recording matters most.
32const MAX_RUN: usize = 64;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35enum RunKind {
36    Text,
37    Thinking,
38    ToolArgs,
39}
40
41fn classify(chunk: &ChunkRecord) -> Option<RunKind> {
42    match &chunk.chunk {
43        ModelEvent::TextDelta { .. } => Some(RunKind::Text),
44        ModelEvent::ThinkingDelta { .. } => Some(RunKind::Thinking),
45        ModelEvent::ToolArgsDelta { .. } => Some(RunKind::ToolArgs),
46        _ => None,
47    }
48}
49
50fn tool_args_id(chunk: &ChunkRecord) -> Option<&str> {
51    match &chunk.chunk {
52        ModelEvent::ToolArgsDelta { id, .. } => Some(id),
53        _ => None,
54    }
55}
56
57fn payload(chunk: &ChunkRecord) -> String {
58    match &chunk.chunk {
59        ModelEvent::TextDelta { text } | ModelEvent::ThinkingDelta { text } => text.clone(),
60        ModelEvent::ToolArgsDelta { partial_json, .. } => partial_json.clone(),
61        _ => String::new(),
62    }
63}
64
65/// Whether `next` extends a run ending at `prev`.
66///
67/// Adjacency is arrival order into a packer, which only ever sees one call's
68/// stream — deliberately *not* `seq` adjacency. `seq` is a line number handed
69/// out by the writer, and when a parent and its sub-agent record into the same
70/// file their line numbers interleave; requiring them to be consecutive meant
71/// every run broke after one member and packing silently stopped working in
72/// exactly the case it was needed for. Line numbers are assigned to a run when
73/// it is written ([`stamp_seqs`]), so a row's block stays contiguous regardless.
74fn continues(prev: &ChunkRecord, next: &ChunkRecord, kind: RunKind) -> bool {
75    if next.call != prev.call {
76        return false;
77    }
78    if kind == RunKind::ToolArgs && tool_args_id(prev) != tool_args_id(next) {
79        return false;
80    }
81    true
82}
83
84/// How many chunks a record stands for — its share of the line numbering.
85pub fn seq_width(record: &Record) -> usize {
86    match record {
87        Record::TextChunks(run) | Record::ThinkingChunks(run) => run.texts.len(),
88        Record::ToolArgsChunks(run) => run.args.len(),
89        _ => 1,
90    }
91}
92
93/// Assign `record` a block of line numbers starting at `from`.
94///
95/// Called when the record is about to be appended rather than when its chunks
96/// arrived, so a packed row always occupies a contiguous block and `seq0 + k`
97/// keeps naming the k-th member even with another stream writing in between.
98pub fn stamp_seqs(record: &mut Record, from: u64) {
99    match record {
100        Record::Chunk(c) => c.seq = from,
101        Record::TextChunks(run) | Record::ThinkingChunks(run) => run.seq0 = from,
102        Record::ToolArgsChunks(run) => run.seq0 = from,
103        _ => {}
104    }
105}
106
107fn build_row(kind: RunKind, run: &[ChunkRecord]) -> Record {
108    let first = &run[0];
109    let dt: Vec<i64> = run
110        .windows(2)
111        .map(|w| w[1].ts as i64 - w[0].ts as i64)
112        .collect();
113    let members: Vec<String> = run.iter().map(payload).collect();
114    match kind {
115        RunKind::ToolArgs => Record::ToolArgsChunks(ToolArgsRun {
116            seq0: first.seq,
117            ts0: first.ts,
118            call: first.call,
119            id: tool_args_id(first).unwrap_or_default().to_string(),
120            args: members,
121            dt,
122        }),
123        RunKind::Text | RunKind::Thinking => {
124            let run = TextRun {
125                seq0: first.seq,
126                ts0: first.ts,
127                call: first.call,
128                texts: members,
129                dt,
130            };
131            if kind == RunKind::Text {
132                Record::TextChunks(run)
133            } else {
134                Record::ThinkingChunks(run)
135            }
136        }
137    }
138}
139
140/// Incremental packer: feed chunks in arrival order, write out what it returns.
141///
142/// Holding a partial run is what buys the compression, so the packer trades a
143/// bounded write delay (at most [`MAX_RUN`] members) for it. [`RunPacker::flush`]
144/// must be called at the end of a call's stream — otherwise its tail sits in
145/// the buffer and never reaches the file.
146#[derive(Debug, Default)]
147pub struct RunPacker {
148    pending: Vec<ChunkRecord>,
149    kind: Option<RunKind>,
150}
151
152impl RunPacker {
153    pub fn new() -> Self {
154        Self::default()
155    }
156
157    pub fn push(&mut self, chunk: ChunkRecord) -> Vec<Record> {
158        let Some(kind) = classify(&chunk) else {
159            let mut out = self.flush();
160            out.push(Record::Chunk(chunk));
161            return out;
162        };
163
164        let extends = self.kind == Some(kind)
165            && self
166                .pending
167                .last()
168                .is_some_and(|prev| continues(prev, &chunk, kind));
169
170        if !extends {
171            let out = self.flush();
172            self.kind = Some(kind);
173            self.pending.push(chunk);
174            return out;
175        }
176
177        self.pending.push(chunk);
178        if self.pending.len() >= MAX_RUN {
179            return self.flush();
180        }
181        Vec::new()
182    }
183
184    pub fn flush(&mut self) -> Vec<Record> {
185        let kind = self.kind.take();
186        let run = std::mem::take(&mut self.pending);
187        match kind {
188            Some(kind) if run.len() >= MIN_RUN => vec![build_row(kind, &run)],
189            _ => run.into_iter().map(Record::Chunk).collect(),
190        }
191    }
192}
193
194/// Pack a complete batch. Equivalent to feeding every member to a
195/// [`RunPacker`] and flushing.
196pub fn pack(chunks: Vec<ChunkRecord>) -> Vec<Record> {
197    let mut packer = RunPacker::new();
198    let mut out = Vec::new();
199    for chunk in chunks {
200        out.extend(packer.push(chunk));
201    }
202    out.extend(packer.flush());
203    out
204}
205
206#[derive(Debug, thiserror::Error, PartialEq)]
207pub enum PackError {
208    #[error("{tag} row: dt has {dt} gaps for {members} members (expected {expected})")]
209    DtArity {
210        tag: &'static str,
211        dt: usize,
212        members: usize,
213        expected: usize,
214    },
215    #[error("{tag} row: empty member list")]
216    Empty { tag: &'static str },
217    #[error("{tag} row: member timestamp left the representable range")]
218    TimeRange { tag: &'static str },
219}
220
221fn expand_members(
222    tag: &'static str,
223    members: &[String],
224    dt: &[i64],
225    seq0: u64,
226    ts0: u64,
227    call: u64,
228    make: impl Fn(&str) -> ModelEvent,
229) -> Result<Vec<ChunkRecord>, PackError> {
230    if members.is_empty() {
231        return Err(PackError::Empty { tag });
232    }
233    if dt.len() != members.len() - 1 {
234        return Err(PackError::DtArity {
235            tag,
236            dt: dt.len(),
237            members: members.len(),
238            expected: members.len() - 1,
239        });
240    }
241    let mut out = Vec::with_capacity(members.len());
242    let mut ts = ts0 as i64;
243    for (i, member) in members.iter().enumerate() {
244        if i > 0 {
245            ts += dt[i - 1];
246        }
247        if ts < 0 {
248            return Err(PackError::TimeRange { tag });
249        }
250        out.push(ChunkRecord {
251            seq: seq0 + i as u64,
252            ts: ts as u64,
253            call,
254            chunk: make(member),
255        });
256    }
257    Ok(out)
258}
259
260pub fn expand_text_run(run: &TextRun, thinking: bool) -> Result<Vec<ChunkRecord>, PackError> {
261    let tag = if thinking {
262        "thinking_chunks"
263    } else {
264        "text_chunks"
265    };
266    expand_members(tag, &run.texts, &run.dt, run.seq0, run.ts0, run.call, |t| {
267        if thinking {
268            ModelEvent::ThinkingDelta { text: t.into() }
269        } else {
270            ModelEvent::TextDelta { text: t.into() }
271        }
272    })
273}
274
275pub fn expand_tool_args_run(run: &ToolArgsRun) -> Result<Vec<ChunkRecord>, PackError> {
276    expand_members(
277        "tool_args_chunks",
278        &run.args,
279        &run.dt,
280        run.seq0,
281        run.ts0,
282        run.call,
283        |a| ModelEvent::ToolArgsDelta {
284            id: run.id.clone(),
285            partial_json: a.into(),
286        },
287    )
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293    use base::interface::model::Usage;
294
295    fn text(seq: u64, ts: u64, s: &str) -> ChunkRecord {
296        ChunkRecord {
297            seq,
298            ts,
299            call: 0,
300            chunk: ModelEvent::TextDelta { text: s.into() },
301        }
302    }
303
304    fn args(seq: u64, ts: u64, id: &str, s: &str) -> ChunkRecord {
305        ChunkRecord {
306            seq,
307            ts,
308            call: 0,
309            chunk: ModelEvent::ToolArgsDelta {
310                id: id.into(),
311                partial_json: s.into(),
312            },
313        }
314    }
315
316    fn expand_all(records: Vec<Record>) -> Vec<ChunkRecord> {
317        let mut out = Vec::new();
318        for record in records {
319            match record {
320                Record::Chunk(c) => out.push(c),
321                Record::TextChunks(r) => out.extend(expand_text_run(&r, false).unwrap()),
322                Record::ThinkingChunks(r) => out.extend(expand_text_run(&r, true).unwrap()),
323                Record::ToolArgsChunks(r) => out.extend(expand_tool_args_run(&r).unwrap()),
324                other => panic!("unexpected record: {other:?}"),
325            }
326        }
327        out
328    }
329
330    fn assert_round_trip(chunks: Vec<ChunkRecord>) {
331        let expected = format!("{chunks:?}");
332        let packed = pack(chunks);
333        assert_eq!(format!("{:?}", expand_all(packed)), expected);
334    }
335
336    #[test]
337    fn a_run_at_the_minimum_packs_into_one_row() {
338        let chunks = vec![text(0, 100, "a"), text(1, 112, "b"), text(2, 120, "c")];
339        let packed = pack(chunks.clone());
340        assert_eq!(packed.len(), 1);
341        assert!(matches!(packed[0], Record::TextChunks(_)));
342        assert_round_trip(chunks);
343    }
344
345    #[test]
346    fn a_run_below_the_minimum_stays_one_line_each() {
347        let chunks = vec![text(0, 100, "a"), text(1, 112, "b")];
348        let packed = pack(chunks.clone());
349        assert_eq!(packed.len(), 2);
350        assert!(packed.iter().all(|r| matches!(r, Record::Chunk(_))));
351        assert_round_trip(chunks);
352    }
353
354    #[test]
355    fn token_boundaries_survive_packing() {
356        let chunks = vec![
357            text(0, 100, "Hel"),
358            text(1, 112, "lo"),
359            text(2, 120, " wor"),
360            text(3, 135, "ld"),
361        ];
362        let packed = pack(chunks);
363        let Record::TextChunks(run) = &packed[0] else {
364            panic!("expected a packed run")
365        };
366        assert_eq!(run.texts, vec!["Hel", "lo", " wor", "ld"]);
367        assert_eq!(run.dt, vec![12, 8, 15]);
368    }
369
370    #[test]
371    fn a_non_delta_event_breaks_the_run() {
372        let chunks = vec![
373            text(0, 100, "a"),
374            text(1, 110, "b"),
375            text(2, 120, "c"),
376            ChunkRecord {
377                seq: 3,
378                ts: 130,
379                call: 0,
380                chunk: ModelEvent::ContentBlockStop { index: 0 },
381            },
382            text(4, 140, "d"),
383            text(5, 150, "e"),
384            text(6, 160, "f"),
385        ];
386        let packed = pack(chunks.clone());
387        assert_eq!(packed.len(), 3);
388        assert_round_trip(chunks);
389    }
390
391    /// A gap in line numbers means another stream wrote in between, not that
392    /// this call's chunks stopped being consecutive. Breaking the run there is
393    /// what made packing collapse whenever a parent and a sub-agent shared a
394    /// recording — the case packing matters most for.
395    #[test]
396    fn a_gap_in_line_numbers_does_not_break_the_run() {
397        let chunks = vec![text(0, 100, "a"), text(1, 110, "b"), text(9, 120, "c")];
398        let packed = pack(chunks);
399        assert_eq!(packed.len(), 1, "got {packed:?}");
400    }
401
402    /// The row's line numbers are assigned when it is written, so `seq0 + k`
403    /// names the k-th member no matter what the members arrived as.
404    #[test]
405    fn stamping_renumbers_a_row_into_one_contiguous_block() {
406        let mut packed = pack(vec![
407            text(0, 100, "a"),
408            text(1, 110, "b"),
409            text(9, 120, "c"),
410        ]);
411        assert_eq!(seq_width(&packed[0]), 3);
412        stamp_seqs(&mut packed[0], 40);
413        let Record::TextChunks(run) = &packed[0] else {
414            panic!("expected a packed run, got {packed:?}")
415        };
416        let expanded = expand_text_run(run, false).unwrap();
417        assert_eq!(
418            expanded.iter().map(|c| c.seq).collect::<Vec<_>>(),
419            vec![40, 41, 42]
420        );
421    }
422
423    #[test]
424    fn a_different_call_breaks_the_run() {
425        let mut chunks = vec![text(0, 100, "a"), text(1, 110, "b"), text(2, 120, "c")];
426        chunks[2].call = 1;
427        assert_round_trip(chunks);
428    }
429
430    #[test]
431    fn tool_args_with_a_different_id_never_share_a_run() {
432        let chunks = vec![
433            args(0, 100, "t1", "{\"a\":"),
434            args(1, 110, "t1", "1}"),
435            args(2, 120, "t2", "{\"b\":"),
436            args(3, 130, "t2", "2}"),
437        ];
438        let packed = pack(chunks.clone());
439        assert!(packed
440            .iter()
441            .all(|r| matches!(r, Record::Chunk(_) | Record::ToolArgsChunks(_))));
442        assert_round_trip(chunks);
443    }
444
445    #[test]
446    fn tool_args_run_round_trips_with_its_id() {
447        let chunks = vec![
448            args(0, 100, "t1", "{\"path\":"),
449            args(1, 110, "t1", "\"/tmp"),
450            args(2, 120, "t1", "/x\"}"),
451        ];
452        let packed = pack(chunks.clone());
453        assert_eq!(packed.len(), 1);
454        assert_round_trip(chunks);
455    }
456
457    #[test]
458    fn a_run_longer_than_the_cap_splits_and_still_round_trips() {
459        let chunks: Vec<_> = (0..MAX_RUN as u64 * 2 + 5)
460            .map(|i| text(i, 100 + i * 3, &format!("t{i}")))
461            .collect();
462        let packed = pack(chunks.clone());
463        assert!(packed.len() > 1);
464        assert_round_trip(chunks);
465    }
466
467    #[test]
468    fn a_backwards_clock_step_round_trips() {
469        let chunks = vec![text(0, 200, "a"), text(1, 180, "b"), text(2, 210, "c")];
470        let packed = pack(chunks.clone());
471        let Record::TextChunks(run) = &packed[0] else {
472            panic!("expected a packed run")
473        };
474        assert_eq!(run.dt, vec![-20, 30]);
475        assert_round_trip(chunks);
476    }
477
478    #[test]
479    fn mixed_event_kinds_round_trip_in_order() {
480        let chunks = vec![
481            ChunkRecord {
482                seq: 0,
483                ts: 100,
484                call: 0,
485                chunk: ModelEvent::ThinkingDelta { text: "hm".into() },
486            },
487            ChunkRecord {
488                seq: 1,
489                ts: 110,
490                call: 0,
491                chunk: ModelEvent::ThinkingDelta { text: "mm".into() },
492            },
493            ChunkRecord {
494                seq: 2,
495                ts: 120,
496                call: 0,
497                chunk: ModelEvent::ThinkingDelta { text: "!".into() },
498            },
499            ChunkRecord {
500                seq: 3,
501                ts: 130,
502                call: 0,
503                chunk: ModelEvent::ThinkingSignature {
504                    signature: "s".into(),
505                },
506            },
507            text(4, 140, "a"),
508            text(5, 150, "b"),
509            text(6, 160, "c"),
510            ChunkRecord {
511                seq: 7,
512                ts: 170,
513                call: 0,
514                chunk: ModelEvent::EndTurn {
515                    stop_reason: "end_turn".into(),
516                    usage: Usage {
517                        input_tokens: 1,
518                        output_tokens: 2,
519                        ..Default::default()
520                    },
521                },
522            },
523        ];
524        assert_round_trip(chunks);
525    }
526
527    #[test]
528    fn a_malformed_row_fails_loudly_instead_of_dropping_the_run() {
529        let run = TextRun {
530            seq0: 0,
531            ts0: 100,
532            call: 0,
533            texts: vec!["a".into(), "b".into(), "c".into()],
534            dt: vec![10],
535        };
536        assert_eq!(
537            expand_text_run(&run, false).unwrap_err(),
538            PackError::DtArity {
539                tag: "text_chunks",
540                dt: 1,
541                members: 3,
542                expected: 2,
543            }
544        );
545    }
546
547    #[test]
548    fn an_empty_row_fails_loudly() {
549        let run = TextRun {
550            seq0: 0,
551            ts0: 100,
552            call: 0,
553            texts: vec![],
554            dt: vec![],
555        };
556        assert_eq!(
557            expand_text_run(&run, false).unwrap_err(),
558            PackError::Empty { tag: "text_chunks" }
559        );
560    }
561}