1use base::interface::model::ModelEvent;
20
21use super::format::{ChunkRecord, Record, TextRun, ToolArgsRun};
22
23const MIN_RUN: usize = 3;
27
28const 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
65fn 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
84pub 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
93pub 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#[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
194pub 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 #[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 #[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}