inferdiff 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
inferdiff/differ.py ADDED
@@ -0,0 +1,649 @@
1
+ """Anti-chunk-jitter two-layer semantic alignment and exact physical frame back-mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, List, Optional, Tuple
7
+
8
+ from .detectors import Finding, audit_trace, detect_d5
9
+ from .schema import (
10
+ EXIT_OK,
11
+ EXIT_SEMANTIC_REGRESSION,
12
+ EXIT_SILENT_PROTOCOL_BREACH,
13
+ TraceDocument,
14
+ TraceFrame,
15
+ is_strict_int,
16
+ strict_json_loads,
17
+ )
18
+
19
+
20
+ @dataclass
21
+ class DivergencePoint:
22
+ category: str # "CONTENT" | "REASONING" | "TOOL_CALL" | "TERMINAL" | "EOF" | "USAGE"
23
+ detail: str
24
+ before_seq: Optional[int]
25
+ before_t_rel_ms: Optional[float]
26
+ before_raw_wire: Optional[str]
27
+ after_seq: Optional[int]
28
+ after_t_rel_ms: Optional[float]
29
+ after_raw_wire: Optional[str]
30
+
31
+ def to_dict(self, *, include_wire: bool = True) -> Dict[str, Any]:
32
+ return {
33
+ "category": self.category,
34
+ "detail": self.detail,
35
+ "before_seq": self.before_seq,
36
+ "before_t_rel_ms": self.before_t_rel_ms,
37
+ "before_raw_wire": self.before_raw_wire if include_wire else None,
38
+ "after_seq": self.after_seq,
39
+ "after_t_rel_ms": self.after_t_rel_ms,
40
+ "after_raw_wire": self.after_raw_wire if include_wire else None,
41
+ }
42
+
43
+
44
+ @dataclass
45
+ class DiffReport:
46
+ before_label: str
47
+ after_label: str
48
+ before_dialect: str
49
+ after_dialect: str
50
+ before_findings: List[Finding]
51
+ after_findings: List[Finding]
52
+ pair_findings: List[Finding]
53
+ new_findings: List[Finding]
54
+ semantic_equal: bool
55
+ terminal_drifted: bool
56
+ ttft_regressed: bool
57
+ ttft_delta_pct: Optional[float]
58
+ first_divergence: Optional[DivergencePoint]
59
+ exit_code: int
60
+ summary_table: Dict[str, Any] = field(default_factory=dict)
61
+
62
+ def to_dict(self, *, include_wire: bool = True) -> Dict[str, Any]:
63
+ return {
64
+ "before_label": self.before_label,
65
+ "after_label": self.after_label,
66
+ "before_dialect": self.before_dialect,
67
+ "after_dialect": self.after_dialect,
68
+ "semantic_equal": self.semantic_equal,
69
+ "terminal_drifted": self.terminal_drifted,
70
+ "ttft_regressed": self.ttft_regressed,
71
+ "ttft_delta_pct": self.ttft_delta_pct,
72
+ "first_divergence": self.first_divergence.to_dict(include_wire=include_wire) if self.first_divergence else None,
73
+ "before_findings": [f.to_dict() for f in self.before_findings],
74
+ "after_findings": [f.to_dict() for f in self.after_findings],
75
+ "pair_findings": [f.to_dict() for f in self.pair_findings],
76
+ "new_findings": [f.to_dict() for f in self.new_findings],
77
+ "summary_table": self.summary_table,
78
+ "exit_code": self.exit_code,
79
+ }
80
+
81
+
82
+ def _extract_semantic_text_streams(
83
+ doc: TraceDocument,
84
+ ) -> Tuple[str, List[Tuple[int, int, int]], str, List[Tuple[int, int, int]]]:
85
+ """Extract normalized (visible_text, visible_spans, reasoning_text, reasoning_spans).
86
+
87
+ Chronologically interleaves dedicated reasoning_delta and inline <think>...</think> spans
88
+ frame-by-frame (handling tags split across frame boundaries) so mixed inline + dedicated
89
+ reasoning produces identical normalized streams.
90
+ """
91
+ vis_chars: List[str] = []
92
+ vis_seqs: List[int] = []
93
+ reas_chars: List[str] = []
94
+ reas_seqs: List[int] = []
95
+
96
+ depth = 0
97
+ # Pending character buffer for potential "<think>" (7) or "</think>" (8) split across frames
98
+ pending_chars: List[str] = []
99
+ pending_seqs: List[int] = []
100
+
101
+ def _emit_char(ch: str, seq: int) -> None:
102
+ if depth > 0:
103
+ reas_chars.append(ch)
104
+ reas_seqs.append(seq)
105
+ else:
106
+ vis_chars.append(ch)
107
+ vis_seqs.append(seq)
108
+
109
+ def _drain_pending(*, flush_all: bool) -> None:
110
+ nonlocal depth, pending_chars, pending_seqs
111
+ while pending_chars:
112
+ s = "".join(pending_chars)
113
+ if s.startswith("<think>"):
114
+ depth += 1
115
+ del pending_chars[:7]
116
+ del pending_seqs[:7]
117
+ continue
118
+ if s.startswith("</think>"):
119
+ if depth > 0:
120
+ depth -= 1
121
+ else:
122
+ for ch, sq in zip(pending_chars[:8], pending_seqs[:8]):
123
+ vis_chars.append(ch)
124
+ vis_seqs.append(sq)
125
+ del pending_chars[:8]
126
+ del pending_seqs[:8]
127
+ continue
128
+ if not flush_all and ("<think>".startswith(s) or "</think>".startswith(s)):
129
+ break
130
+ _emit_char(pending_chars.pop(0), pending_seqs.pop(0))
131
+
132
+ for f in doc.frames:
133
+ norm = f.norm or {}
134
+ rd = norm.get("reasoning_delta") or ""
135
+ if rd:
136
+ for ch in rd:
137
+ reas_chars.append(ch)
138
+ reas_seqs.append(f.seq)
139
+ td = norm.get("text_delta") or ""
140
+ if td:
141
+ for ch in td:
142
+ pending_chars.append(ch)
143
+ pending_seqs.append(f.seq)
144
+ _drain_pending(flush_all=False)
145
+
146
+ _drain_pending(flush_all=True)
147
+
148
+ def _compress_spans(seqs: List[int]) -> List[Tuple[int, int, int]]:
149
+ if not seqs:
150
+ return []
151
+ spans: List[Tuple[int, int, int]] = []
152
+ start = 0
153
+ cur_seq = seqs[0]
154
+ for idx in range(1, len(seqs)):
155
+ if seqs[idx] != cur_seq:
156
+ spans.append((start, idx, cur_seq))
157
+ start = idx
158
+ cur_seq = seqs[idx]
159
+ spans.append((start, len(seqs), cur_seq))
160
+ return spans
161
+
162
+ return (
163
+ "".join(vis_chars),
164
+ _compress_spans(vis_seqs),
165
+ "".join(reas_chars),
166
+ _compress_spans(reas_seqs),
167
+ )
168
+
169
+
170
+ def _build_tool_arg_offset_map(doc: TraceDocument, tc: Dict[str, Any], k: int) -> Tuple[str, List[Tuple[int, int, int]]]:
171
+ """Build argument char-offset -> physical frame map for logical tool call `tc`."""
172
+ tool_idx = tc.get("index", k)
173
+ tool_id = tc.get("id")
174
+ tool_item_id = tc.get("item_id")
175
+
176
+ def _matches(td: Dict[str, Any]) -> bool:
177
+ if tool_item_id and td.get("item_id") == tool_item_id:
178
+ return True
179
+ if tool_id and td.get("id") == tool_id:
180
+ return True
181
+ if td.get("index") == tool_idx:
182
+ return True
183
+ if td.get("index") is None and tool_idx == 0 and not td.get("item_id") and not td.get("id"):
184
+ return True
185
+ return False
186
+
187
+ parts: List[str] = []
188
+ spans: List[Tuple[int, int, int]] = []
189
+ cursor = 0
190
+ for f in doc.frames:
191
+ for td in (f.norm or {}).get("tool_deltas") or []:
192
+ if not isinstance(td, dict):
193
+ continue
194
+ if _matches(td):
195
+ ad = td.get("arguments_delta") or td.get("args_delta") or ""
196
+ if ad:
197
+ end = cursor + len(ad)
198
+ parts.append(ad)
199
+ spans.append((cursor, end, f.seq))
200
+ cursor = end
201
+ if parts:
202
+ return "".join(parts), spans
203
+
204
+ # Fallback to recorded snapshot_seq / raw_arguments
205
+ raw_args = tc.get("raw_arguments") or ""
206
+ snap_seq = tc.get("done_seq") if is_strict_int(tc.get("done_seq")) else tc.get("snapshot_seq")
207
+ if snap_seq is None:
208
+ snap_seq = tc.get("first_seq")
209
+ if raw_args and is_strict_int(snap_seq):
210
+ return raw_args, [(0, len(raw_args), snap_seq)]
211
+ return raw_args, []
212
+
213
+
214
+ def _lookup_frame_for_offset(spans: List[Tuple[int, int, int]], offset: int, fallback_seq: Optional[int]) -> Optional[int]:
215
+ for start, end, seq in spans:
216
+ if start <= offset < end:
217
+ return seq
218
+ if spans:
219
+ return spans[-1][2]
220
+ return fallback_seq
221
+
222
+
223
+ def _terminal_frame(doc: TraceDocument) -> Optional[TraceFrame]:
224
+ for f in reversed(doc.frames):
225
+ norm = f.norm or {}
226
+ if norm.get("finish_reason") or norm.get("terminal_status"):
227
+ return f
228
+ for f in reversed(doc.frames):
229
+ norm = f.norm or {}
230
+ if norm.get("phase") == "TERMINAL":
231
+ return f
232
+ return doc.frames[-1] if doc.frames else None
233
+
234
+
235
+ def _usage_frame_seq(doc: TraceDocument, fallback: Optional[int]) -> Optional[int]:
236
+ for f in reversed(doc.frames):
237
+ u = (f.norm or {}).get("usage")
238
+ if isinstance(u, dict) and is_strict_int(u.get("completion_tokens")):
239
+ return f.seq
240
+ return fallback
241
+
242
+
243
+ def _eof_violation_seq(doc: TraceDocument, fallback: Optional[int]) -> Optional[int]:
244
+ for f in doc.frames:
245
+ if f.parse_error or (f.norm or {}).get("protocol_error"):
246
+ return f.seq
247
+ if doc.frames:
248
+ return doc.frames[-1].seq
249
+ return fallback
250
+
251
+
252
+ def _frame_by_seq(doc: TraceDocument, seq: Optional[int]) -> Optional[TraceFrame]:
253
+ if seq is None or seq < 0 or seq >= len(doc.frames):
254
+ return None
255
+ return doc.frames[seq]
256
+
257
+
258
+ def _make_div(
259
+ category: str,
260
+ detail: str,
261
+ before: TraceDocument,
262
+ b_seq: Optional[int],
263
+ after: TraceDocument,
264
+ a_seq: Optional[int],
265
+ ) -> DivergencePoint:
266
+ bf = _frame_by_seq(before, b_seq)
267
+ af = _frame_by_seq(after, a_seq)
268
+ return DivergencePoint(
269
+ category=category,
270
+ detail=detail,
271
+ before_seq=bf.seq if bf else None,
272
+ before_t_rel_ms=bf.t_rel_ms if bf else None,
273
+ before_raw_wire=bf.raw_wire if bf else None,
274
+ after_seq=af.seq if af else None,
275
+ after_t_rel_ms=af.t_rel_ms if af else None,
276
+ after_raw_wire=af.raw_wire if af else None,
277
+ )
278
+
279
+
280
+ def _first_char_diff(a: str, b: str) -> Optional[int]:
281
+ lim = min(len(a), len(b))
282
+ for i in range(lim):
283
+ if a[i] != b[i]:
284
+ return i
285
+ if len(a) != len(b):
286
+ return lim
287
+ return None
288
+
289
+
290
+ def _tool_is_closed(tc: Dict[str, Any], dialect: str) -> bool:
291
+ if tc.get("json_valid") is not True:
292
+ return False
293
+ if tc.get("args_mismatch") or tc.get("identity_conflict"):
294
+ return False
295
+ saw_delta = tc.get("saw_args_delta")
296
+ if saw_delta is None:
297
+ saw_delta = tc.get("saw_args_done_event") is False
298
+ if dialect == "openai-responses" and bool(saw_delta) and tc.get("saw_args_done_event") is False:
299
+ return False
300
+ return True
301
+
302
+
303
+ def _json_strict_equal(a: Any, b: Any) -> bool:
304
+ """Strict JSON value equality (prevents Python bool True == 1 / False == 0 collapse)."""
305
+ if isinstance(a, bool) or isinstance(b, bool):
306
+ return isinstance(a, bool) and isinstance(b, bool) and a is b
307
+ if isinstance(a, dict) and isinstance(b, dict):
308
+ if len(a) != len(b) or set(a.keys()) != set(b.keys()):
309
+ return False
310
+ return all(_json_strict_equal(a[k], b[k]) for k in a)
311
+ if isinstance(a, list) and isinstance(b, list):
312
+ if len(a) != len(b):
313
+ return False
314
+ return all(_json_strict_equal(x, y) for x, y in zip(a, b))
315
+ return type(a) is type(b) and a == b if not isinstance(a, (int, float)) else (isinstance(b, (int, float)) and not isinstance(b, bool) and a == b)
316
+
317
+
318
+ def _compare_tool_args_structurally(bt: Dict[str, Any], at: Dict[str, Any]) -> bool:
319
+ """Return True if both tool calls have strict-valid JSON representing equal values (key-order invariant, strict types)."""
320
+ if bt.get("json_valid") is not True or at.get("json_valid") is not True:
321
+ return False
322
+ try:
323
+ return _json_strict_equal(
324
+ strict_json_loads(bt.get("raw_arguments") or ""),
325
+ strict_json_loads(at.get("raw_arguments") or ""),
326
+ )
327
+ except Exception:
328
+ return False
329
+
330
+
331
+ def _terminal_drifted(before: TraceDocument, after: TraceDocument) -> bool:
332
+ b_asm = before.summary.assembled
333
+ a_asm = after.summary.assembled
334
+ b_sig = (b_asm.get("finish_reason", "unknown"), b_asm.get("terminal_status", "unknown"))
335
+ a_sig = (a_asm.get("finish_reason", "unknown"), a_asm.get("terminal_status", "unknown"))
336
+
337
+ # Within the same dialect, preserve distinct terminal reasons (e.g. stop -> tool_calls)
338
+ if before.header.dialect == after.header.dialect:
339
+ return b_sig != a_sig
340
+
341
+ # Cross-dialect equivalence (e.g. chat finish_reason="stop"/"tool_calls" ~ responses status="completed")
342
+ def _canon_term(sig: Tuple[str, str], has_tools: bool) -> str:
343
+ fr, st = sig
344
+ if st == "failed" or fr == "error":
345
+ return "failed"
346
+ if fr in ("length", "max_output_tokens") or st == "incomplete":
347
+ return "incomplete"
348
+ if fr == "tool_calls" or (st == "completed" and has_tools):
349
+ return "completed_tools"
350
+ if fr == "stop" or (st == "completed" and not has_tools):
351
+ return "completed"
352
+ return f"{fr}/{st}"
353
+
354
+ b_has_tools = bool(b_asm.get("tool_calls"))
355
+ a_has_tools = bool(a_asm.get("tool_calls"))
356
+ return _canon_term(b_sig, b_has_tools) != _canon_term(a_sig, a_has_tools)
357
+
358
+
359
+ def _find_first_divergence(before: TraceDocument, after: TraceDocument) -> Tuple[Optional[DivergencePoint], bool]:
360
+ """Perform jitter-proof semantic alignment across content, reasoning, tools, EOF, terminal, and usage.
361
+
362
+ Collects candidate divergences with their exact causal physical frame sequences and selects
363
+ the earliest chronological divergence.
364
+ """
365
+ b_asm = before.summary.assembled
366
+ a_asm = after.summary.assembled
367
+
368
+ b_term = _terminal_frame(before)
369
+ a_term = _terminal_frame(after)
370
+ b_term_seq = b_term.seq if b_term else None
371
+ a_term_seq = a_term.seq if a_term else None
372
+
373
+ term_drifted = _terminal_drifted(before, after)
374
+ candidates: List[Tuple[Tuple[int, int, int], DivergencePoint]] = []
375
+
376
+ def _add_candidate(priority: int, div: DivergencePoint) -> None:
377
+ a_ord = div.after_seq if div.after_seq is not None else 10**9
378
+ b_ord = div.before_seq if div.before_seq is not None else 10**9
379
+ # Order chronologically by earliest causal frame, then category priority
380
+ key = (min(a_ord, b_ord), a_ord, priority)
381
+ candidates.append((key, div))
382
+
383
+ # 1. Normalized visible content & reasoning streams (inline <think> == dedicated reasoning_delta!)
384
+ b_vis, b_vspans, b_reas, b_rspans = _extract_semantic_text_streams(before)
385
+ a_vis, a_vspans, a_reas, a_rspans = _extract_semantic_text_streams(after)
386
+
387
+ r_idx = _first_char_diff(b_reas, a_reas)
388
+ if r_idx is not None:
389
+ b_seq = _lookup_frame_for_offset(b_rspans, r_idx, b_term_seq)
390
+ a_seq = _lookup_frame_for_offset(a_rspans, r_idx, a_term_seq)
391
+ _add_candidate(
392
+ 1,
393
+ _make_div(
394
+ "REASONING",
395
+ f"Reasoning stream diverged at char offset {r_idx} (before={len(b_reas)} chars, after={len(a_reas)} chars)",
396
+ before,
397
+ b_seq,
398
+ after,
399
+ a_seq,
400
+ ),
401
+ )
402
+
403
+ t_idx = _first_char_diff(b_vis, a_vis)
404
+ if t_idx is not None:
405
+ b_seq = _lookup_frame_for_offset(b_vspans, t_idx, b_term_seq)
406
+ a_seq = _lookup_frame_for_offset(a_vspans, t_idx, a_term_seq)
407
+ _add_candidate(
408
+ 2,
409
+ _make_div(
410
+ "CONTENT",
411
+ f"Content stream diverged at char offset {t_idx} (before={len(b_vis)} chars, after={len(a_vis)} chars)",
412
+ before,
413
+ b_seq,
414
+ after,
415
+ a_seq,
416
+ ),
417
+ )
418
+
419
+ # 2. Tool calls (count, name, structural JSON args, dialect-aware closure)
420
+ b_tools = b_asm.get("tool_calls") or []
421
+ a_tools = a_asm.get("tool_calls") or []
422
+ max_tc = max(len(b_tools), len(a_tools))
423
+ for k in range(max_tc):
424
+ if k >= len(b_tools) or k >= len(a_tools):
425
+ b_cite = b_tools[k].get("first_seq") if k < len(b_tools) else b_term_seq
426
+ a_cite = a_tools[k].get("first_seq") if k < len(a_tools) else a_term_seq
427
+ _add_candidate(
428
+ 3,
429
+ _make_div(
430
+ "TOOL_CALL",
431
+ f"Tool call count diverged (before={len(b_tools)}, after={len(a_tools)})",
432
+ before,
433
+ b_cite if is_strict_int(b_cite) else b_term_seq,
434
+ after,
435
+ a_cite if is_strict_int(a_cite) else a_term_seq,
436
+ ),
437
+ )
438
+ break
439
+
440
+ bt, at = b_tools[k], a_tools[k]
441
+ if bt.get("name") != at.get("name"):
442
+ b_nseq = bt.get("name_seq") if is_strict_int(bt.get("name_seq")) else bt.get("first_seq")
443
+ a_nseq = at.get("name_seq") if is_strict_int(at.get("name_seq")) else at.get("first_seq")
444
+ _add_candidate(
445
+ 3,
446
+ _make_div(
447
+ "TOOL_CALL",
448
+ f"Tool #{k} name changed ({bt.get('name')!r} -> {at.get('name')!r})",
449
+ before,
450
+ b_nseq if is_strict_int(b_nseq) else b_term_seq,
451
+ after,
452
+ a_nseq if is_strict_int(a_nseq) else a_term_seq,
453
+ ),
454
+ )
455
+ break
456
+
457
+ b_closed = _tool_is_closed(bt, before.header.dialect)
458
+ a_closed = _tool_is_closed(at, after.header.dialect)
459
+
460
+ if not _compare_tool_args_structurally(bt, at):
461
+ b_args, b_aspans = _build_tool_arg_offset_map(before, bt, k)
462
+ a_args, a_aspans = _build_tool_arg_offset_map(after, at, k)
463
+ a_idx = _first_char_diff(b_args, a_args)
464
+ if a_idx is not None:
465
+ b_seq = _lookup_frame_for_offset(b_aspans, a_idx, bt.get("last_seq") or b_term_seq)
466
+ a_seq = _lookup_frame_for_offset(a_aspans, a_idx, at.get("last_seq") or a_term_seq)
467
+ _add_candidate(
468
+ 3,
469
+ _make_div(
470
+ "TOOL_CALL",
471
+ f"Tool #{k} ({at.get('name')}) arguments diverged at char offset {a_idx} "
472
+ f"(before json_valid={bt.get('json_valid')}, after json_valid={at.get('json_valid')})",
473
+ before,
474
+ b_seq,
475
+ after,
476
+ a_seq,
477
+ ),
478
+ )
479
+ break
480
+
481
+ if b_closed != a_closed:
482
+ b_cseq = bt.get("done_seq") if is_strict_int(bt.get("done_seq")) else b_term_seq
483
+ a_cseq = at.get("done_seq") if is_strict_int(at.get("done_seq")) else a_term_seq
484
+ _add_candidate(
485
+ 4,
486
+ _make_div(
487
+ "TOOL_CALL",
488
+ f"Tool #{k} ({at.get('name')}) closure diverged "
489
+ f"(before closed={b_closed}, after closed={a_closed}, "
490
+ f"after json_valid={at.get('json_valid')}, args_done={at.get('saw_args_done_event')})",
491
+ before,
492
+ b_cseq,
493
+ after,
494
+ a_cseq,
495
+ ),
496
+ )
497
+ break
498
+
499
+ # 3. EOF cleanliness & protocol-order violations
500
+ b_viol = b_asm.get("protocol_violations") or []
501
+ a_viol = a_asm.get("protocol_violations") or []
502
+ if before.summary.eof_clean != after.summary.eof_clean or b_viol != a_viol:
503
+ _add_candidate(
504
+ 5,
505
+ _make_div(
506
+ "EOF",
507
+ f"Stream EOF/protocol cleanliness changed (eof_clean {before.summary.eof_clean} -> {after.summary.eof_clean})",
508
+ before,
509
+ _eof_violation_seq(before, b_term_seq),
510
+ after,
511
+ _eof_violation_seq(after, a_term_seq),
512
+ ),
513
+ )
514
+
515
+ # 4. Terminal status drift
516
+ if term_drifted:
517
+ b_sig = (b_asm.get("finish_reason", "unknown"), b_asm.get("terminal_status", "unknown"))
518
+ a_sig = (a_asm.get("finish_reason", "unknown"), a_asm.get("terminal_status", "unknown"))
519
+ _add_candidate(
520
+ 6,
521
+ _make_div(
522
+ "TERMINAL",
523
+ f"Terminal signal drifted ({b_sig[0]}/{b_sig[1]} -> {a_sig[0]}/{a_sig[1]})",
524
+ before,
525
+ b_term_seq,
526
+ after,
527
+ a_term_seq,
528
+ ),
529
+ )
530
+
531
+ # 5. Completion token mismatch when both are reported integers
532
+ b_comp = (b_asm.get("reported_usage") or {}).get("completion_tokens")
533
+ a_comp = (a_asm.get("reported_usage") or {}).get("completion_tokens")
534
+ if is_strict_int(b_comp) and is_strict_int(a_comp) and b_comp != a_comp:
535
+ _add_candidate(
536
+ 7,
537
+ _make_div(
538
+ "USAGE",
539
+ f"Reported completion_tokens changed ({b_comp} -> {a_comp})",
540
+ before,
541
+ _usage_frame_seq(before, b_term_seq),
542
+ after,
543
+ _usage_frame_seq(after, a_term_seq),
544
+ ),
545
+ )
546
+
547
+ if not candidates:
548
+ return None, term_drifted
549
+ candidates.sort(key=lambda item: item[0])
550
+ return candidates[0][1], term_drifted
551
+
552
+
553
+ def diff_traces(
554
+ before: TraceDocument,
555
+ after: TraceDocument,
556
+ *,
557
+ ignore_timing: bool = False,
558
+ ttft_regress_pct: float = 50.0,
559
+ min_ttft_delta_ms: float = 0.0,
560
+ fail_on: str = "p0",
561
+ ) -> DiffReport:
562
+ """Compare two TraceDocuments with chunk-jitter-proof semantic alignment and D1..D5."""
563
+ before_findings = audit_trace(before)
564
+ after_findings = audit_trace(after)
565
+ pair_findings = detect_d5(
566
+ before,
567
+ after,
568
+ ignore_timing=ignore_timing,
569
+ min_delta_ms=min_ttft_delta_ms,
570
+ )
571
+
572
+ before_keys = {(f.detector_id, f.code) for f in before_findings}
573
+ new_after = [f for f in after_findings if (f.detector_id, f.code) not in before_keys]
574
+ new_findings = new_after + pair_findings
575
+
576
+ first_div, terminal_drifted = _find_first_divergence(before, after)
577
+
578
+ b_ttft = before.summary.timing.get("ttft_effective_ms")
579
+ a_ttft = after.summary.timing.get("ttft_effective_ms")
580
+ ttft_delta_pct: Optional[float] = None
581
+ ttft_regressed = False
582
+ if (
583
+ not ignore_timing
584
+ and isinstance(b_ttft, (int, float))
585
+ and isinstance(a_ttft, (int, float))
586
+ and b_ttft > 0
587
+ ):
588
+ ttft_delta_pct = round(((a_ttft - b_ttft) / b_ttft) * 100.0, 2)
589
+ if ttft_delta_pct >= ttft_regress_pct and (a_ttft - b_ttft) >= min_ttft_delta_ms:
590
+ ttft_regressed = True
591
+
592
+ semantic_equal = (first_div is None) and not terminal_drifted
593
+
594
+ # Exit code per Spec §2.1 & §2.2 (--fail-on gates CI return code cleanly):
595
+ # - P0 finding always exits 2 (EXIT_SILENT_PROTOCOL_BREACH)
596
+ # - Under --fail-on p0: only P0 fails (exits 0 otherwise)
597
+ # - Under --fail-on p1: P1 findings, terminal drift, or TTFT regression exit 3
598
+ # - Under --fail-on any-diff: any P1 or semantic divergence (incl. content/reasoning/tool/usage) exits 3
599
+ all_target_findings = after_findings + pair_findings
600
+ has_p0 = any(f.severity == "P0" for f in all_target_findings)
601
+ has_p1 = any(f.severity == "P1" for f in all_target_findings) or terminal_drifted or ttft_regressed
602
+
603
+ if has_p0:
604
+ exit_code = EXIT_SILENT_PROTOCOL_BREACH
605
+ elif fail_on == "p0":
606
+ exit_code = EXIT_OK
607
+ elif fail_on == "p1":
608
+ exit_code = EXIT_SEMANTIC_REGRESSION if has_p1 else EXIT_OK
609
+ else: # any-diff
610
+ exit_code = EXIT_SEMANTIC_REGRESSION if (has_p1 or not semantic_equal) else EXIT_OK
611
+
612
+ summary_table = {
613
+ "before_status": before.header.response_meta.get("status_code"),
614
+ "after_status": after.header.response_meta.get("status_code"),
615
+ "before_eof_clean": before.summary.eof_clean,
616
+ "after_eof_clean": after.summary.eof_clean,
617
+ "before_frames": before.summary.total_frames,
618
+ "after_frames": after.summary.total_frames,
619
+ "before_ttff_ms": before.summary.timing.get("ttff_ms"),
620
+ "after_ttff_ms": after.summary.timing.get("ttff_ms"),
621
+ "before_ttft_effective_ms": b_ttft,
622
+ "after_ttft_effective_ms": a_ttft,
623
+ "before_total_ms": before.summary.timing.get("total_ms"),
624
+ "after_total_ms": after.summary.timing.get("total_ms"),
625
+ "before_completion_tokens": (before.summary.assembled.get("reported_usage") or {}).get("completion_tokens"),
626
+ "after_completion_tokens": (after.summary.assembled.get("reported_usage") or {}).get("completion_tokens"),
627
+ "before_finish_reason": before.summary.assembled.get("finish_reason"),
628
+ "after_finish_reason": after.summary.assembled.get("finish_reason"),
629
+ "before_terminal_status": before.summary.assembled.get("terminal_status"),
630
+ "after_terminal_status": after.summary.assembled.get("terminal_status"),
631
+ }
632
+
633
+ return DiffReport(
634
+ before_label=before.header.label or before.header.dialect,
635
+ after_label=after.header.label or after.header.dialect,
636
+ before_dialect=before.header.dialect,
637
+ after_dialect=after.header.dialect,
638
+ before_findings=before_findings,
639
+ after_findings=after_findings,
640
+ pair_findings=pair_findings,
641
+ new_findings=new_findings,
642
+ semantic_equal=semantic_equal,
643
+ terminal_drifted=terminal_drifted,
644
+ ttft_regressed=ttft_regressed,
645
+ ttft_delta_pct=ttft_delta_pct,
646
+ first_divergence=first_div,
647
+ exit_code=exit_code,
648
+ summary_table=summary_table,
649
+ )