1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
27
28use serde_json::{json, Map, Value};
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Requires {
33 CompleteOrClosedMessage,
36}
37
38#[derive(Debug, Clone, Copy)]
40pub struct DropRule {
41 pub name: &'static str,
42 pub line_type: &'static str,
44 pub requires: Requires,
45}
46
47pub const DROP_RULES: &[DropRule] = &[DropRule { name: "stream_event_of_complete_message", line_type: "stream_event", requires: Requires::CompleteOrClosedMessage }];
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum Action {
53 Keep,
54 Drop,
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum WindowEnd {
60 Open,
63 Final,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct Synth {
71 pub after: usize,
73 pub message_id: String,
74 pub line: String,
75}
76
77#[derive(Debug, Clone, Default, PartialEq, Eq)]
79pub struct Stats {
80 pub lines: usize,
81 pub kept: usize,
82 pub dropped_fragments: usize,
83 pub interrupted_lines: usize,
84 pub unproven_fragments: usize,
86 pub unproven_by_cause: BTreeMap<&'static str, usize>,
88 pub pending_fragments: usize,
90 pub orphan_fragments: usize,
92 pub unknown_kinds: BTreeMap<String, usize>,
95}
96
97impl Stats {
98 pub fn absorb(&mut self, s: &Stats) {
100 self.lines += s.lines;
101 self.kept += s.kept;
102 self.dropped_fragments += s.dropped_fragments;
103 self.interrupted_lines += s.interrupted_lines;
104 self.unproven_fragments += s.unproven_fragments;
105 for (why, n) in &s.unproven_by_cause {
106 *self.unproven_by_cause.entry(why).or_default() += n;
107 }
108 self.pending_fragments += s.pending_fragments;
109 self.orphan_fragments += s.orphan_fragments;
110 for (kind, n) in &s.unknown_kinds {
111 if self.unknown_kinds.len() < 32 || self.unknown_kinds.contains_key(kind) {
113 *self.unknown_kinds.entry(kind.clone()).or_default() += n;
114 }
115 }
116 }
117}
118
119#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct Plan {
122 pub actions: Vec<Action>,
123 pub synth: Vec<Synth>,
124 pub stats: Stats,
125}
126
127impl Plan {
128 pub fn apply<S: AsRef<str>>(&self, old: &[S]) -> Vec<String> {
131 let mut out = Vec::with_capacity(old.len());
132 let mut synth = self.synth.iter().peekable();
133 for (i, line) in old.iter().enumerate() {
134 if self.actions[i] == Action::Keep {
135 out.push(line.as_ref().to_string());
136 }
137 while let Some(s) = synth.next_if(|s| s.after == i) {
138 out.push(s.line.clone());
139 }
140 }
141 out
142 }
143
144 pub fn sources(&self) -> Vec<usize> {
147 let mut out = Vec::with_capacity(self.actions.len());
148 let mut synth = self.synth.iter().peekable();
149 for (i, action) in self.actions.iter().enumerate() {
150 if *action == Action::Keep {
151 out.push(i);
152 }
153 while synth.next_if(|s| s.after == i).is_some() {
154 out.push(i);
155 }
156 }
157 out
158 }
159}
160
161#[derive(Debug, Clone, Default)]
163struct StreamBlock {
164 start: Value,
165 kind: String,
166 text: String,
167 thinking: String,
168 signature: String,
169 partial_json: String,
170 unknown: bool,
172 deltas: usize,
174 citations: Vec<Value>,
177}
178
179impl StreamBlock {
180 fn new(start: &Value) -> Self {
181 let kind = start.get("type").and_then(Value::as_str).unwrap_or("").to_string();
182 let unknown = !matches!(kind.as_str(), "text" | "thinking" | "tool_use" | "server_tool_use" | "mcp_tool_use");
183 let take = |k: &str| start.get(k).and_then(Value::as_str).unwrap_or("").to_string();
184 StreamBlock {
185 text: if kind == "text" { take("text") } else { String::new() },
186 thinking: if kind == "thinking" { take("thinking") } else { String::new() },
187 signature: if kind == "thinking" { take("signature") } else { String::new() },
188 start: start.clone(),
189 kind,
190 unknown,
191 partial_json: String::new(),
192 deltas: 0,
193 citations: Vec::new(),
194 }
195 }
196
197 fn input(&self) -> Option<Value> {
199 if self.partial_json.is_empty() {
200 return Some(Value::Object(Map::new()));
201 }
202 serde_json::from_str(&self.partial_json).ok()
203 }
204
205 fn matches(&self, complete: &Value) -> bool {
207 if self.unknown {
210 return self.deltas == 0 && complete == &self.start;
211 }
212 if complete.get("type").and_then(Value::as_str) != Some(self.kind.as_str()) {
213 return false;
214 }
215 let s = |k: &str| complete.get(k).and_then(Value::as_str);
216 match self.kind.as_str() {
217 "text" => s("text") == Some(self.text.as_str()) && (self.citations.is_empty() || complete.get("citations").and_then(Value::as_array) == Some(&self.citations)),
219 "thinking" => s("thinking") == Some(self.thinking.as_str()) && (self.signature.is_empty() || s("signature") == Some(self.signature.as_str())),
220 "tool_use" | "server_tool_use" | "mcp_tool_use" => {
221 s("id") == self.start.get("id").and_then(Value::as_str)
222 && s("name") == self.start.get("name").and_then(Value::as_str)
223 && self.input().is_some_and(|i| complete.get("input") == Some(&i))
224 }
225 _ => false,
226 }
227 }
228
229 fn as_content(&self) -> Value {
231 match self.kind.as_str() {
232 "text" => json!({ "type": "text", "text": self.text }),
233 "thinking" => {
234 let mut b = json!({ "type": "thinking", "thinking": self.thinking });
235 if !self.signature.is_empty() {
236 b["signature"] = Value::String(self.signature.clone());
237 }
238 b
239 }
240 _ => {
241 let mut b = json!({
242 "type": "tool_use",
243 "id": self.start.get("id").cloned().unwrap_or(Value::Null),
244 "name": self.start.get("name").cloned().unwrap_or(Value::Null),
245 });
246 match self.input() {
247 Some(i) => b["input"] = i,
248 None => {
249 b["input"] = Value::Object(Map::new());
250 b["partial_input_json"] = Value::String(self.partial_json.clone());
251 }
252 }
253 b
254 }
255 }
256 }
257}
258
259#[derive(Debug, Default)]
260struct Msg {
261 fragment_lines: Vec<usize>,
262 blocks: BTreeMap<u64, StreamBlock>,
263 complete: Vec<Value>,
265 has_complete: bool,
266 unproven: bool,
268 why: Option<&'static str>,
270 closed: bool,
271 kinds: BTreeSet<String>,
273 stopped: bool,
275 session_id: Option<Value>,
276 parent: Option<Value>,
277}
278
279fn field<'a>(v: &'a Value, path: &[&str]) -> Option<&'a Value> {
280 path.iter().try_fold(v, |v, k| v.get(*k))
281}
282
283fn line_type(v: &Value) -> &str {
284 v.get("type").and_then(Value::as_str).unwrap_or("")
285}
286
287fn is_boundary(v: &Value) -> bool {
289 match line_type(v) {
290 "result" => true,
291 "system" => v.get("subtype").and_then(Value::as_str) == Some("init"),
292 _ => false,
293 }
294}
295
296pub fn last_quiet_line<S: AsRef<str>>(lines: &[S]) -> Option<usize> {
300 let mut scan = Scan::default();
301 let mut open: HashSet<String> = HashSet::new();
302 let mut last = None;
303 for (i, raw) in lines.iter().enumerate() {
304 if scan.line(i, raw.as_ref()) == Seen::Boundary {
305 open.clear();
306 } else {
307 if let Some(id) = scan.superseded.take() {
308 open.remove(&id);
309 }
310 if let Some(id) = scan.touched.take() {
311 let m = &scan.msgs[&id];
314 if !m.fragment_lines.is_empty() && !(m.has_complete && m.stopped) {
315 open.insert(id);
316 } else {
317 open.remove(&id);
318 }
319 }
320 }
321 if open.is_empty() {
322 last = Some(i);
323 }
324 }
325 last
326}
327
328pub fn is_turn_boundary(line: &str) -> bool {
330 if !line.starts_with('{') {
331 return false;
332 }
333 serde_json::from_str::<Value>(line).is_ok_and(|v| is_boundary(&v))
334}
335
336impl Msg {
337 fn take_event(&mut self, ev: &str, event: &Value) {
339 let index = event.get("index").and_then(Value::as_u64);
340 match ev {
341 "content_block_start" => match (index, event.get("content_block")) {
342 (Some(ix), Some(b)) => {
343 self.blocks.insert(ix, StreamBlock::new(b));
344 }
345 _ => self.mark_unproven("block_start_without_index_or_block"),
346 },
347 "content_block_delta" => self.take_delta(index, event.get("delta")),
348 "message_stop" => self.stopped = true,
349 "content_block_stop" | "message_delta" | "ping" => {}
350 "error" => self.mark_unproven("error_event"),
352 other => self.name_kind(format!("event:{other}")),
355 }
356 }
357
358 fn name_kind(&mut self, name: String) {
359 if self.kinds.len() < 8 {
361 self.kinds.insert(name.chars().take(64).collect());
362 }
363 }
364
365 fn mark_unproven(&mut self, why: &'static str) {
366 self.unproven = true;
367 self.why.get_or_insert(why);
368 }
369
370 fn take_delta(&mut self, index: Option<u64>, delta: Option<&Value>) {
371 let (Some(ix), Some(delta)) = (index, delta) else {
372 self.mark_unproven("delta_without_index_or_body");
373 return;
374 };
375 let Some(b) = self.blocks.get_mut(&ix) else {
376 self.mark_unproven("delta_for_a_block_never_started");
377 return;
378 };
379 let s = |k: &str| delta.get(k).and_then(Value::as_str).unwrap_or("");
380 b.deltas += 1;
381 match (delta.get("type").and_then(Value::as_str), b.kind.as_str()) {
382 (Some("text_delta"), "text") => b.text.push_str(s("text")),
383 (Some("citations_delta"), "text") => b.citations.push(delta.get("citation").cloned().unwrap_or(Value::Null)),
386 (Some("thinking_delta"), "thinking") => b.thinking.push_str(s("thinking")),
387 (Some("signature_delta"), "thinking") => b.signature.push_str(s("signature")),
388 (Some("input_json_delta"), "tool_use" | "server_tool_use" | "mcp_tool_use") => b.partial_json.push_str(s("partial_json")),
389 (kind, _) => {
390 b.unknown = true;
391 let name = format!("delta:{}", kind.unwrap_or(""));
392 self.name_kind(name);
393 self.mark_unproven("unknown_delta_kind");
394 }
395 }
396 }
397}
398
399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
401enum Seen {
402 Fragment,
403 Complete,
405 Boundary,
407 Other,
408}
409
410#[derive(Default)]
412struct Scan {
413 msgs: HashMap<String, Msg>,
414 order: Vec<String>,
415 current: HashMap<String, Option<String>>,
417 orphan: Vec<usize>,
419 touched: Option<String>,
421 superseded: Option<String>,
423}
424
425impl Scan {
426 fn msg(&mut self, id: &str) -> &mut Msg {
427 if !self.msgs.contains_key(id) {
428 self.order.push(id.to_string());
429 }
430 self.msgs.entry(id.to_string()).or_default()
431 }
432
433 fn line(&mut self, i: usize, raw: &str) -> Seen {
435 if !raw.starts_with('{') {
437 return Seen::Other;
438 }
439 let Ok(v) = serde_json::from_str::<Value>(raw) else { return Seen::Other };
440 let key = match v.get("parent_tool_use_id") {
441 Some(Value::String(s)) => s.clone(),
442 _ => String::new(),
443 };
444 match line_type(&v) {
445 "stream_event" => {
446 self.fragment(i, &v, key);
447 Seen::Fragment
448 }
449 "assistant" => {
450 self.complete_line(&v);
451 Seen::Complete
452 }
453 _ if is_boundary(&v) => {
454 for m in self.msgs.values_mut() {
455 m.closed = true;
456 }
457 self.current.clear();
458 Seen::Boundary
459 }
460 _ => Seen::Other,
461 }
462 }
463
464 fn fragment(&mut self, i: usize, v: &Value, key: String) {
465 let Some(event) = v.get("event") else {
466 self.orphan.push(i);
467 return;
468 };
469 let ev = event.get("type").and_then(Value::as_str).unwrap_or("");
470 if ev == "message_start" {
471 self.message_start(i, v, event, key);
472 return;
473 }
474 let Some(id) = self.current.get(&key).cloned().flatten() else {
475 self.orphan.push(i);
476 return;
477 };
478 let Some(m) = self.msgs.get_mut(&id) else {
479 self.orphan.push(i);
480 return;
481 };
482 m.fragment_lines.push(i);
483 m.take_event(ev, event);
484 self.touched = Some(id);
485 }
486
487 fn message_start(&mut self, i: usize, v: &Value, event: &Value, key: String) {
488 let id = field(event, &["message", "id"]).and_then(Value::as_str).map(str::to_string);
489 let previous = self.current.insert(key, id.clone()).flatten();
490 self.superseded = previous.filter(|p| Some(p) != id.as_ref());
491 let Some(id) = id else {
492 self.orphan.push(i);
493 return;
494 };
495 self.touched = Some(id.clone());
496 let m = self.msg(&id);
497 m.fragment_lines.push(i);
498 m.session_id = m.session_id.take().or_else(|| v.get("session_id").cloned());
499 m.parent = m.parent.take().or_else(|| v.get("parent_tool_use_id").cloned());
500 if field(event, &["message", "role"]).and_then(Value::as_str) != Some("assistant") {
502 m.mark_unproven("message_of_another_role");
503 }
504 }
505
506 fn complete_line(&mut self, v: &Value) {
507 if v.get("partial").and_then(Value::as_bool) == Some(true) {
508 return;
509 }
510 let Some(id) = field(v, &["message", "id"]).and_then(Value::as_str) else { return };
511 self.touched = Some(id.to_string());
512 let m = self.msg(id);
513 m.has_complete = true;
514 if let Some(Value::Array(blocks)) = field(v, &["message", "content"]) {
515 m.complete.extend(blocks.iter().cloned());
516 }
517 }
518}
519
520enum Fate {
522 Unproven(&'static str),
524 Pending,
526 Drop(Option<String>),
528}
529
530fn fate(id: &str, m: &Msg, end: WindowEnd) -> Fate {
531 if m.unproven {
532 return Fate::Unproven(m.why.unwrap_or("unproven"));
533 }
534 if m.blocks.is_empty() {
535 return Fate::Unproven("no_blocks");
536 }
537 let mut used = vec![false; m.complete.len()];
539 let mut unmatched: Vec<&StreamBlock> = Vec::new();
540 for b in m.blocks.values() {
541 match m.complete.iter().enumerate().find(|(j, c)| !used[*j] && b.matches(c)) {
542 Some((j, _)) => used[j] = true,
543 None => unmatched.push(b),
544 }
545 }
546 if unmatched.is_empty() {
547 return if m.has_complete { Fate::Drop(None) } else { Fate::Unproven("no_complete_line") };
549 }
550 if !m.closed && end == WindowEnd::Open {
551 return Fate::Pending;
552 }
553 if unmatched.iter().any(|b| b.unknown || !matches!(b.kind.as_str(), "text" | "thinking" | "tool_use")) {
554 return Fate::Unproven("cut_off_block_of_unknown_kind");
555 }
556 if unmatched.iter().any(|b| !b.citations.is_empty()) {
557 return Fate::Unproven("cut_off_block_with_citations");
558 }
559 if !m.kinds.is_empty() {
561 return Fate::Unproven("cut_off_message_with_unknown_event");
562 }
563 Fate::Drop(Some(interrupted_line(id, m, &unmatched)))
564}
565
566fn interrupted_line(id: &str, m: &Msg, unmatched: &[&StreamBlock]) -> String {
568 let content: Vec<Value> = unmatched.iter().map(|b| b.as_content()).collect();
569 let mut line = json!({
570 "type": "assistant",
571 "interrupted": true,
572 "message": { "id": id, "type": "message", "role": "assistant", "content": content, "stop_reason": Value::Null },
573 });
574 if let Some(s) = &m.session_id {
575 line["session_id"] = s.clone();
576 }
577 if let Some(p) = &m.parent {
578 line["parent_tool_use_id"] = p.clone();
579 }
580 line.to_string()
581}
582
583pub fn plan_window<S: AsRef<str>>(lines: &[S], end: WindowEnd) -> Plan {
585 let mut scan = Scan::default();
586 for (i, raw) in lines.iter().enumerate() {
587 let _ = scan.line(i, raw.as_ref());
588 }
589 let mut actions = vec![Action::Keep; lines.len()];
590 let mut stats = Stats { lines: lines.len(), orphan_fragments: scan.orphan.len(), ..Stats::default() };
591 let mut synth = Vec::new();
592 for id in &scan.order {
593 let m = &scan.msgs[id];
594 let n = m.fragment_lines.len();
595 if n == 0 {
596 continue;
597 }
598 for kind in &m.kinds {
599 *stats.unknown_kinds.entry(kind.clone()).or_default() += 1;
600 }
601 match fate(id, m, end) {
602 Fate::Unproven(why) => {
603 stats.unproven_fragments += n;
604 *stats.unproven_by_cause.entry(why).or_default() += n;
605 }
606 Fate::Pending => stats.pending_fragments += n,
607 Fate::Drop(interrupted) => {
608 for &i in &m.fragment_lines {
609 actions[i] = Action::Drop;
610 }
611 stats.dropped_fragments += n;
612 if let Some(line) = interrupted {
613 synth.push(Synth { after: *m.fragment_lines.last().expect("non-empty"), message_id: id.clone(), line });
614 }
615 }
616 }
617 }
618 synth.sort_by_key(|s| s.after);
619 stats.interrupted_lines = synth.len();
620 stats.kept = actions.iter().filter(|a| **a == Action::Keep).count();
621 Plan { actions, synth, stats }
622}
623
624pub fn compact_lines<S: AsRef<str>>(lines: &[S], end: WindowEnd) -> (Vec<String>, Plan) {
626 let plan = plan_window(lines, end);
627 (plan.apply(lines), plan)
628}
629
630#[derive(Debug, Clone, PartialEq, Eq)]
632pub enum Emit {
633 Interrupted(String),
635 Fragment(String),
637}
638
639impl Emit {
640 pub fn line(&self) -> &str {
641 match self {
642 Emit::Interrupted(l) | Emit::Fragment(l) => l,
643 }
644 }
645}
646
647fn leftovers(scan: &Scan, raw: &[String]) -> Vec<Emit> {
650 let mut out: Vec<(usize, Emit)> = scan.orphan.iter().map(|&i| (i, Emit::Fragment(raw[i].clone()))).collect();
651 for id in &scan.order {
652 let m = &scan.msgs[id];
653 let Some(&last) = m.fragment_lines.last() else { continue };
654 match fate(id, m, WindowEnd::Final) {
655 Fate::Drop(None) => {}
656 Fate::Drop(Some(line)) => out.push((last, Emit::Interrupted(line))),
657 Fate::Unproven(_) | Fate::Pending => out.extend(m.fragment_lines.iter().map(|&i| (i, Emit::Fragment(raw[i].clone())))),
658 }
659 }
660 out.sort_by_key(|(i, _)| *i);
661 out.into_iter().map(|(_, e)| e).collect()
662}
663
664#[derive(Default)]
668pub struct LiveReply {
669 scan: Scan,
670 raw: Vec<String>,
672}
673
674#[derive(Debug, Clone, PartialEq, Eq)]
676pub struct Before {
677 pub fragment: bool,
679 pub emits: Vec<Emit>,
681 pub ended: bool,
683}
684
685impl LiveReply {
686 pub fn new() -> Self {
687 Self::default()
688 }
689
690 pub fn before(&mut self, line: &str) -> Before {
693 let i = self.raw.len();
694 let seen = self.scan.line(i, line);
695 let fragment = seen == Seen::Fragment;
696 self.raw.push(if fragment { line.to_string() } else { String::new() });
697 if seen != Seen::Boundary {
698 return Before { fragment, emits: Vec::new(), ended: false };
699 }
700 let ended = self.holds_fragments();
701 let emits = leftovers(&self.scan, &self.raw);
702 *self = Self::default();
703 Before { fragment, emits, ended }
704 }
705
706 pub fn settled(&self) -> bool {
710 self.scan.orphan.is_empty()
711 && self.scan.order.iter().all(|id| {
712 let m = &self.scan.msgs[id];
713 m.fragment_lines.is_empty() || (m.stopped && matches!(fate(id, m, WindowEnd::Open), Fate::Drop(None)))
714 })
715 }
716
717 pub fn holds_fragments(&self) -> bool {
719 !self.scan.orphan.is_empty() || self.scan.msgs.values().any(|m| !m.fragment_lines.is_empty())
720 }
721
722 pub fn reset(&mut self) {
723 *self = Self::default();
724 }
725}
726
727pub fn recover_live<S: AsRef<str>, T: AsRef<str>>(tail: &[S], live: &[T]) -> Vec<Emit> {
731 let mut r = LiveReply::new();
732 for l in tail {
733 if let Some(v) = parse(l.as_ref()).filter(|v| line_type(v) == "assistant") {
735 r.scan.complete_line(&v);
736 }
737 }
738 for l in live {
739 let _ = r.before(l.as_ref());
740 }
741 for m in r.scan.msgs.values_mut() {
742 m.closed = true;
743 }
744 leftovers(&r.scan, &r.raw)
745}
746
747#[derive(Debug, Clone, PartialEq, Eq)]
749pub enum CheckFailure {
750 L1 { detail: String },
752 L2 { detail: String },
754 L3 { detail: String },
756}
757
758impl std::fmt::Display for CheckFailure {
759 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
760 match self {
761 CheckFailure::L1 { detail } => write!(f, "L1: {detail}"),
762 CheckFailure::L2 { detail } => write!(f, "L2: {detail}"),
763 CheckFailure::L3 { detail } => write!(f, "L3: {detail}"),
764 }
765 }
766}
767
768fn parse(line: &str) -> Option<Value> {
769 if line.starts_with('{') {
770 serde_json::from_str(line).ok()
771 } else {
772 None
773 }
774}
775
776fn is_fragment(line: &str) -> bool {
777 parse(line).is_some_and(|v| line_type(&v) == "stream_event")
778}
779
780fn is_interrupted(line: &str) -> bool {
781 parse(line).is_some_and(|v| line_type(&v) == "assistant" && v.get("interrupted").and_then(Value::as_bool) == Some(true))
782}
783
784fn ids_of(v: &Value, out: &mut HashSet<String>) {
786 if let Some(s) = v.get("session_id").and_then(Value::as_str) {
787 out.insert(format!("session:{s}"));
788 }
789 let mut blocks = |content: Option<&Value>| {
790 if let Some(Value::Array(bs)) = content {
791 for b in bs {
792 match b.get("type").and_then(Value::as_str) {
793 Some("tool_use") => {
794 if let Some(id) = b.get("id").and_then(Value::as_str) {
795 out.insert(format!("tool:{id}"));
796 }
797 }
798 Some("tool_result") => {
799 if let Some(id) = b.get("tool_use_id").and_then(Value::as_str) {
800 out.insert(format!("tool:{id}"));
801 }
802 }
803 _ => {}
804 }
805 }
806 }
807 };
808 blocks(field(v, &["message", "content"]));
809 if line_type(v) == "stream_event" {
810 if let Some(b) = field(v, &["event", "content_block"]) {
811 if b.get("type").and_then(Value::as_str) == Some("tool_use") {
812 if let Some(id) = b.get("id").and_then(Value::as_str) {
813 out.insert(format!("tool:{id}"));
814 }
815 }
816 }
817 }
818}
819
820type VBlock = (String, String, String, String, bool);
823
824fn add_citation(extra: &mut String, citation: Option<&Value>) {
826 let mut all: Vec<Value> = serde_json::from_str(extra).unwrap_or_default();
827 all.push(citation.cloned().unwrap_or(Value::Null));
828 *extra = Value::Array(all).to_string();
829}
830
831struct Split<'a> {
833 plain: Vec<&'a str>,
835 synth: Vec<&'a str>,
837 dropped: Vec<&'a str>,
839}
840
841fn check_l1<'a, S: AsRef<str>, T: AsRef<str>>(old: &'a [S], new: &'a [T]) -> Result<Split<'a>, CheckFailure> {
843 let old_other: Vec<&str> = old.iter().map(AsRef::as_ref).filter(|l| !is_fragment(l)).collect();
844 let mut old_interrupted: HashMap<&str, usize> = HashMap::new();
846 for l in old.iter().map(AsRef::as_ref).filter(|l| is_interrupted(l)) {
847 *old_interrupted.entry(l).or_insert(0) += 1;
848 }
849 let (mut plain, mut synth): (Vec<&str>, Vec<&str>) = (Vec::new(), Vec::new());
850 for l in new.iter().map(AsRef::as_ref) {
851 match old_interrupted.get_mut(l) {
852 Some(n) if *n > 0 => {
853 *n -= 1;
854 plain.push(l);
855 }
856 _ if is_interrupted(l) => synth.push(l),
857 _ => plain.push(l),
858 }
859 }
860 let new_other: Vec<&str> = plain.iter().copied().filter(|l| !is_fragment(l)).collect();
861 if old_other != new_other {
862 let first = old_other.iter().zip(new_other.iter()).position(|(a, b)| a != b).unwrap_or(old_other.len().min(new_other.len()));
863 return Err(CheckFailure::L1 { detail: format!("lines other than fragments differ from position {first} (old {}, new {})", old_other.len(), new_other.len()) });
864 }
865 let old_frag: Vec<&str> = old.iter().map(AsRef::as_ref).filter(|l| is_fragment(l)).collect();
866 let new_frag: Vec<&str> = plain.iter().copied().filter(|l| is_fragment(l)).collect();
867 let mut it = old_frag.iter();
868 for f in &new_frag {
869 if !it.any(|o| o == f) {
870 return Err(CheckFailure::L1 { detail: "a kept fragment is not, in order, one of the old fragments".into() });
871 }
872 }
873 let mut dropped = Vec::new();
875 let mut kept = new_frag.iter().peekable();
876 for o in &old_frag {
877 if kept.peek().is_some_and(|k| *k == o) {
878 kept.next();
879 } else {
880 dropped.push(*o);
881 }
882 }
883 Ok(Split { plain, synth, dropped })
884}
885
886fn reassemble_dropped(dropped: &[&str]) -> Result<HashMap<String, BTreeMap<u64, VBlock>>, CheckFailure> {
888 let l2 = |detail: &str| CheckFailure::L2 { detail: detail.into() };
889 let mut by_msg: HashMap<String, BTreeMap<u64, VBlock>> = HashMap::new();
890 let mut cur: HashMap<String, Option<String>> = HashMap::new();
891 for l in dropped {
892 let v = parse(l).expect("is_fragment parsed it");
893 let key = v.get("parent_tool_use_id").and_then(Value::as_str).unwrap_or("").to_string();
894 let ev = v.get("event").cloned().unwrap_or(Value::Null);
895 let t = ev.get("type").and_then(Value::as_str).unwrap_or("");
896 if t == "message_start" {
897 cur.insert(key, field(&ev, &["message", "id"]).and_then(Value::as_str).map(str::to_string));
898 continue;
899 }
900 let Some(Some(id)) = cur.get(&key).cloned() else {
901 return Err(l2("a dropped fragment has no message start before it"));
902 };
903 let blocks = by_msg.entry(id).or_default();
904 let ix = ev.get("index").and_then(Value::as_u64).unwrap_or(u64::MAX);
905 let d = ev.get("delta").cloned().unwrap_or(Value::Null);
906 let ds = |k: &str| d.get(k).and_then(Value::as_str).unwrap_or("").to_string();
907 match t {
908 "content_block_start" => {
909 let b = ev.get("content_block").cloned().unwrap_or(Value::Null);
910 let kind = b.get("type").and_then(Value::as_str).unwrap_or("").to_string();
911 let tool = matches!(kind.as_str(), "tool_use" | "server_tool_use" | "mcp_tool_use");
912 let unknown = !tool && !matches!(kind.as_str(), "text" | "thinking");
913 let extra = if tool {
915 format!("{}\u{1}{}", b.get("id").and_then(Value::as_str).unwrap_or(""), b.get("name").and_then(Value::as_str).unwrap_or(""))
916 } else if unknown {
917 b.to_string()
918 } else {
919 String::new()
920 };
921 let seed = |k: &str| if kind == "text" && k == "text" || kind == "thinking" && k != "text" { b.get(k).and_then(Value::as_str).unwrap_or("").to_string() } else { String::new() };
923 let (body, sig) = (if kind == "text" { seed("text") } else { seed("thinking") }, seed("signature"));
924 blocks.insert(ix, (kind, body, sig, extra, unknown));
925 }
926 "content_block_delta" => {
927 let Some(b) = blocks.get_mut(&ix) else {
928 return Err(l2("a dropped delta has no block start"));
929 };
930 match (d.get("type").and_then(Value::as_str), b.0.as_str()) {
931 (Some("text_delta"), "text") => b.1.push_str(&ds("text")),
932 (Some("thinking_delta"), "thinking") => b.1.push_str(&ds("thinking")),
933 (Some("signature_delta"), "thinking") => b.2.push_str(&ds("signature")),
934 (Some("input_json_delta"), "tool_use" | "server_tool_use" | "mcp_tool_use") => b.1.push_str(&ds("partial_json")),
935 (Some("citations_delta"), "text") => add_citation(&mut b.3, d.get("citation")),
936 _ => return Err(l2("a dropped delta is of a kind the compact form does not reassemble")),
937 }
938 }
939 "content_block_stop" | "message_delta" | "message_stop" | "ping" => {}
940 "error" => return Err(l2("a dropped fragment is an error event, which no kept line holds")),
941 _ => {}
943 }
944 }
945 Ok(by_msg)
946}
947
948fn block_is(c: &Value, b: &VBlock) -> bool {
950 let (kind, body, sig, extra, unknown) = b;
951 if c.get("type").and_then(Value::as_str) != Some(kind.as_str()) {
952 return false;
953 }
954 if *unknown {
955 return serde_json::from_str::<Value>(extra).is_ok_and(|start| &start == c);
956 }
957 let s = |k: &str| c.get(k).and_then(Value::as_str);
958 match kind.as_str() {
959 "text" => s("text") == Some(body.as_str()) && (extra.is_empty() || serde_json::from_str::<Vec<Value>>(extra).is_ok_and(|all| c.get("citations").and_then(Value::as_array) == Some(&all))),
960 "thinking" => s("thinking") == Some(body.as_str()) && (sig.is_empty() || s("signature") == Some(sig.as_str())),
961 _ => {
962 let (tid, name) = extra.split_once('\u{1}').unwrap_or(("", ""));
963 let input = if body.is_empty() { Some(Value::Object(Map::new())) } else { serde_json::from_str::<Value>(body).ok() };
964 s("id") == Some(tid) && s("name") == Some(name) && input.map_or_else(|| c.get("partial_input_json").and_then(Value::as_str) == Some(body.as_str()), |i| c.get("input") == Some(&i))
965 }
966 }
967}
968
969fn check_l2(split: &Split<'_>, by_msg: &HashMap<String, BTreeMap<u64, VBlock>>) -> Result<(), CheckFailure> {
971 let mut kept_blocks: HashMap<String, Vec<Value>> = HashMap::new();
973 let mut synth_blocks: HashMap<String, Vec<Value>> = HashMap::new();
974 for (is_synth, l) in split.plain.iter().map(|l| (false, *l)).chain(split.synth.iter().map(|l| (true, *l))) {
975 let Some(v) = parse(l) else { continue };
976 if line_type(&v) != "assistant" || v.get("partial").and_then(Value::as_bool) == Some(true) {
977 continue;
978 }
979 let Some(id) = field(&v, &["message", "id"]).and_then(Value::as_str) else { continue };
980 let Some(Value::Array(bs)) = field(&v, &["message", "content"]) else { continue };
981 let into = if is_synth { &mut synth_blocks } else { &mut kept_blocks };
982 into.entry(id.to_string()).or_default().extend(bs.iter().cloned());
983 }
984 for (id, blocks) in by_msg {
985 let mut have: Vec<(Value, bool)> = kept_blocks.get(id).into_iter().flatten().map(|b| (b.clone(), false)).collect();
986 let kept = have.len();
987 have.extend(synth_blocks.get(id).into_iter().flatten().map(|b| (b.clone(), false)));
988 for b in blocks.values() {
989 let reach = if b.0 == "text" && !b.3.is_empty() { kept } else { have.len() };
991 match have.iter_mut().take(reach).find(|(c, used)| !*used && block_is(c, b)) {
992 Some((_, used)) => *used = true,
993 None => return Err(CheckFailure::L2 { detail: format!("a dropped {} block of a message is in no kept line", b.0) }),
994 }
995 }
996 }
997 for (id, bs) in &synth_blocks {
998 if bs.len() > by_msg.get(id).map_or(0, BTreeMap::len) {
999 return Err(CheckFailure::L2 { detail: "an interrupted line has more blocks than its fragments".into() });
1000 }
1001 }
1002 Ok(())
1003}
1004
1005fn check_l3<S: AsRef<str>, T: AsRef<str>>(old: &[S], new: &[T], split: &Split<'_>) -> Result<(), CheckFailure> {
1007 let count = |ls: &mut dyn Iterator<Item = &str>| {
1008 let mut m: BTreeMap<String, i64> = BTreeMap::new();
1009 for l in ls {
1010 let k = parse(l).map_or_else(|| "unparsed".to_string(), |v| line_type(&v).to_string());
1011 *m.entry(k).or_insert(0) += 1;
1012 }
1013 m
1014 };
1015 let mut old_counts = count(&mut old.iter().map(AsRef::as_ref));
1016 *old_counts.entry("stream_event".into()).or_insert(0) -= split.dropped.len() as i64;
1017 *old_counts.entry("assistant".into()).or_insert(0) += split.synth.len() as i64;
1018 old_counts.retain(|_, n| *n != 0);
1019 let mut new_counts = count(&mut new.iter().map(AsRef::as_ref));
1020 new_counts.retain(|_, n| *n != 0);
1021 if old_counts != new_counts {
1022 return Err(CheckFailure::L3 { detail: format!("line counts by kind differ: expected {old_counts:?}, found {new_counts:?}") });
1023 }
1024 let (mut old_ids, mut new_ids) = (HashSet::new(), HashSet::new());
1025 for l in old {
1026 if let Some(v) = parse(l.as_ref()) {
1027 ids_of(&v, &mut old_ids);
1028 }
1029 }
1030 for l in new {
1031 if let Some(v) = parse(l.as_ref()) {
1032 ids_of(&v, &mut new_ids);
1033 }
1034 }
1035 let lost = old_ids.difference(&new_ids).count();
1036 if lost > 0 {
1037 return Err(CheckFailure::L3 { detail: format!("{lost} session or tool ids of the old lines are in no kept line") });
1038 }
1039 Ok(())
1040}
1041
1042pub fn verify<S: AsRef<str>, T: AsRef<str>>(old: &[S], new: &[T]) -> Result<(), CheckFailure> {
1045 let split = check_l1(old, new)?;
1046 let by_msg = reassemble_dropped(&split.dropped)?;
1047 check_l2(&split, &by_msg)?;
1048 check_l3(old, new, &split)
1049}
1050
1051pub fn no_fragments<S: AsRef<str>>(lines: &[S]) -> Result<(), usize> {
1054 let n = lines.iter().filter(|l| l.as_ref().starts_with('{') && is_fragment(l.as_ref())).count();
1055 if n == 0 {
1056 Ok(())
1057 } else {
1058 Err(n)
1059 }
1060}
1061
1062#[cfg(test)]
1063#[path = "compact_tests.rs"]
1064mod tests;