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/schema.py ADDED
@@ -0,0 +1,955 @@
1
+ """inferdiff.trace.v1 dataclasses, strict JSON/schema validation, effective_params, and JSONL I/O."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List, Optional, Tuple, Union
11
+
12
+ SCHEMA_VERSION = "inferdiff.trace.v1"
13
+
14
+ EXIT_OK = 0
15
+ EXIT_USAGE_OR_IO_ERROR = 1
16
+ EXIT_SILENT_PROTOCOL_BREACH = 2
17
+ EXIT_SEMANTIC_REGRESSION = 3
18
+
19
+ VALID_DIALECTS = (
20
+ "openai-chat",
21
+ "openai-responses",
22
+ "sglang-native",
23
+ "ollama-ndjson",
24
+ )
25
+
26
+ UsageValue = Union[int, str]
27
+
28
+
29
+ class TraceSchemaError(ValueError):
30
+ """Raised when a .trace.jsonl file violates inferdiff.trace.v1."""
31
+
32
+
33
+ def is_strict_int(val: Any) -> bool:
34
+ return isinstance(val, int) and not isinstance(val, bool)
35
+
36
+
37
+ def is_finite_number(val: Any) -> bool:
38
+ if not isinstance(val, (int, float)) or isinstance(val, bool):
39
+ return False
40
+ try:
41
+ return math.isfinite(float(val))
42
+ except (OverflowError, ValueError):
43
+ return False
44
+
45
+
46
+ def _reject_json_constant(token: str) -> Any:
47
+ raise ValueError(f"Non-standard JSON constant not allowed: {token!r}")
48
+
49
+
50
+ def strict_json_loads(text: str) -> Any:
51
+ """Parse RFC 8259 JSON, rejecting NaN, Infinity, -Infinity, and oversized integers."""
52
+ return json.loads(text, parse_constant=_reject_json_constant)
53
+
54
+
55
+ def has_lone_surrogate(obj: Any) -> bool:
56
+ """Return True if any string inside a parsed JSON object contains UTF-16 surrogates."""
57
+ if isinstance(obj, str):
58
+ for ch in obj:
59
+ code = ord(ch)
60
+ if 0xD800 <= code <= 0xDFFF:
61
+ return True
62
+ return False
63
+ if isinstance(obj, list):
64
+ return any(has_lone_surrogate(item) for item in obj)
65
+ if isinstance(obj, dict):
66
+ return any(has_lone_surrogate(k) or has_lone_surrogate(v) for k, v in obj.items())
67
+ return False
68
+
69
+
70
+ def safe_utf8_len(text: str) -> int:
71
+ """Compute UTF-8 byte length safely without crashing on escaped lone surrogates."""
72
+ return len(text.encode("utf-8", errors="surrogatepass"))
73
+
74
+
75
+ def canonical_json_bytes(obj: Any) -> bytes:
76
+ return json.dumps(obj, ensure_ascii=True, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")
77
+
78
+
79
+ def canonical_json_line(obj: Any) -> str:
80
+ return json.dumps(obj, ensure_ascii=True, separators=(",", ":"), allow_nan=False)
81
+
82
+
83
+ def body_sha256(body: Dict[str, Any]) -> str:
84
+ return hashlib.sha256(canonical_json_bytes(body)).hexdigest()
85
+
86
+
87
+ def empty_usage() -> Dict[str, UsageValue]:
88
+ return {
89
+ "prompt_tokens": "unknown",
90
+ "completion_tokens": "unknown",
91
+ "reasoning_tokens": "unknown",
92
+ "cached_tokens": "unknown",
93
+ }
94
+
95
+
96
+ def frame_has_effective_payload(norm: Dict[str, Any]) -> bool:
97
+ """True iff frame carries actual content, reasoning, or tool arguments payload (not initial snapshot)."""
98
+ if norm.get("text_delta") or norm.get("reasoning_delta"):
99
+ return True
100
+ for td in norm.get("tool_deltas") or []:
101
+ if not isinstance(td, dict):
102
+ continue
103
+ if td.get("arguments_delta") or td.get("args_delta"):
104
+ return True
105
+ if td.get("arguments_snapshot") and td.get("is_args_done"):
106
+ return True
107
+ return False
108
+
109
+
110
+ def _pick_first_present(
111
+ containers: List[Dict[str, Any]],
112
+ keys: Tuple[str, ...],
113
+ *,
114
+ allow_null_override: bool = False,
115
+ ) -> Tuple[bool, Any]:
116
+ """Return (found, value) for the highest-precedence container that explicitly defines a key."""
117
+ for container in containers:
118
+ for key in keys:
119
+ if key in container:
120
+ if allow_null_override or container[key] is not None:
121
+ return True, container[key]
122
+ return False, None
123
+
124
+
125
+ def _normalize_str_stop_value(val: Any) -> List[str]:
126
+ out: List[str] = []
127
+ if isinstance(val, str):
128
+ if val != "":
129
+ out.append(val)
130
+ elif isinstance(val, list):
131
+ for item in val:
132
+ if isinstance(item, str) and item != "" and item not in out:
133
+ out.append(item)
134
+ return out
135
+
136
+
137
+ def _normalize_int_stop_value(val: Any) -> List[int]:
138
+ out: List[int] = []
139
+ if is_strict_int(val):
140
+ out.append(val)
141
+ elif isinstance(val, list):
142
+ for item in val:
143
+ if is_strict_int(item) and item not in out:
144
+ out.append(item)
145
+ return out
146
+
147
+
148
+ def extract_effective_params(body: Dict[str, Any], dialect: str) -> Dict[str, Any]:
149
+ """Extract effective budget, ignore_eos, stop conditions, and tool flags with dialect precedence."""
150
+ sp = body.get("sampling_params") if isinstance(body.get("sampling_params"), dict) else {}
151
+ extra = body.get("extra_request_body") if isinstance(body.get("extra_request_body"), dict) else {}
152
+ opts = body.get("options") if isinstance(body.get("options"), dict) else {}
153
+
154
+ if dialect == "sglang-native":
155
+ containers = [sp, extra, body]
156
+ budget_keys = ("max_new_tokens", "max_tokens", "max_completion_tokens", "max_output_tokens")
157
+ elif dialect == "ollama-ndjson":
158
+ containers = [opts, body]
159
+ budget_keys = ("num_predict", "max_tokens")
160
+ elif dialect == "openai-responses":
161
+ # Nested engine override containers take precedence over top-level body when present
162
+ containers = [extra, sp, body]
163
+ budget_keys = ("max_output_tokens", "max_completion_tokens", "max_tokens", "max_new_tokens")
164
+ else: # openai-chat
165
+ containers = [extra, sp, body]
166
+ budget_keys = ("max_completion_tokens", "max_output_tokens", "max_tokens", "max_new_tokens")
167
+
168
+ _, raw_budget = _pick_first_present(containers, budget_keys)
169
+ _, raw_ignore = _pick_first_present(containers, ("ignore_eos",))
170
+ _, raw_temp = _pick_first_present(containers, ("temperature",))
171
+ _, raw_seed = _pick_first_present(containers, ("seed",))
172
+
173
+ # Validate the winning value only (never fall back past an explicit override like 0 or -1)
174
+ max_budget = raw_budget if (is_strict_int(raw_budget) and raw_budget > 0) else None
175
+ ignore_eos = raw_ignore if isinstance(raw_ignore, bool) else False
176
+ temperature = float(raw_temp) if is_finite_number(raw_temp) else None
177
+ seed = raw_seed if is_strict_int(raw_seed) else None
178
+
179
+ # Resolve each stop type independently using container precedence so explicit empty or null overrides win
180
+ found_stop, raw_stop = _pick_first_present(containers, ("stop",), allow_null_override=True)
181
+ stop_sequences = _normalize_str_stop_value(raw_stop) if (found_stop and raw_stop is not None) else []
182
+
183
+ found_stop_ids, raw_stop_ids = _pick_first_present(containers, ("stop_token_ids",), allow_null_override=True)
184
+ stop_token_ids = _normalize_int_stop_value(raw_stop_ids) if (found_stop_ids and raw_stop_ids is not None) else []
185
+
186
+ found_stop_re, raw_stop_re = _pick_first_present(containers, ("stop_regex",), allow_null_override=True)
187
+ stop_regex = _normalize_str_stop_value(raw_stop_re) if (found_stop_re and raw_stop_re is not None) else []
188
+
189
+ # Flattened list of effective (non-empty) stop conditions for v0.1 schema compatibility
190
+ stops: List[Any] = []
191
+ for item in (*stop_sequences, *stop_token_ids, *stop_regex):
192
+ if item not in stops:
193
+ stops.append(item)
194
+
195
+ tools = body.get("tools")
196
+ has_tools = isinstance(tools, list) and len(tools) > 0
197
+
198
+ model = body.get("model") if isinstance(body.get("model"), str) else None
199
+ stream = body.get("stream") if isinstance(body.get("stream"), bool) else True
200
+
201
+ return {
202
+ "model": model,
203
+ "stream": stream,
204
+ "max_budget_tokens": max_budget,
205
+ "ignore_eos": ignore_eos,
206
+ "temperature": temperature,
207
+ "seed": seed,
208
+ "has_tools": has_tools,
209
+ "stop_sequences": stop_sequences,
210
+ "stop_token_ids": stop_token_ids,
211
+ "stop_regex": stop_regex,
212
+ "stop_conditions": stops,
213
+ }
214
+
215
+
216
+ @dataclass
217
+ class NormalizedDelta:
218
+ phase: str = "CONTENT" # HANDSHAKE | REASONING | CONTENT | TOOL | TERMINAL | USAGE | ERROR | UNKNOWN
219
+ text_delta: str = ""
220
+ reasoning_delta: str = ""
221
+ tool_deltas: List[Dict[str, Any]] = field(default_factory=list)
222
+ closed_events: List[str] = field(default_factory=list)
223
+ finish_reason: Optional[str] = None
224
+ terminal_status: Optional[str] = None
225
+ matched_stop: Optional[Any] = None
226
+ usage: Dict[str, UsageValue] = field(default_factory=empty_usage)
227
+ is_done_sentinel: bool = False
228
+ is_cumulative_text: bool = False
229
+ inband_error: Optional[str] = None
230
+ protocol_error: Optional[str] = None
231
+
232
+
233
+ @dataclass
234
+ class TraceHeader:
235
+ trace_id: str
236
+ label: str
237
+ recorded_at_utc: str
238
+ dialect: str
239
+ request: Dict[str, Any]
240
+ response_meta: Dict[str, Any]
241
+ backend_probe: Optional[Dict[str, Any]] = None
242
+ schema_version: str = SCHEMA_VERSION
243
+ type: str = "header"
244
+
245
+ def to_dict(self) -> Dict[str, Any]:
246
+ return {
247
+ "type": "header",
248
+ "schema_version": self.schema_version,
249
+ "trace_id": self.trace_id,
250
+ "label": self.label,
251
+ "recorded_at_utc": self.recorded_at_utc,
252
+ "dialect": self.dialect,
253
+ "request": self.request,
254
+ "response_meta": self.response_meta,
255
+ "backend_probe": self.backend_probe,
256
+ }
257
+
258
+
259
+ @dataclass
260
+ class TraceFrame:
261
+ seq: int
262
+ t_rel_ms: float
263
+ dt_ms: float
264
+ sse_event: Optional[str]
265
+ raw_wire: str
266
+ is_done_sentinel: bool
267
+ parse_error: Optional[str]
268
+ norm: Dict[str, Any]
269
+ type: str = "frame"
270
+
271
+ def to_dict(self) -> Dict[str, Any]:
272
+ return {
273
+ "type": "frame",
274
+ "seq": self.seq,
275
+ "t_rel_ms": self.t_rel_ms,
276
+ "dt_ms": self.dt_ms,
277
+ "sse_event": self.sse_event,
278
+ "raw_wire": self.raw_wire,
279
+ "is_done_sentinel": self.is_done_sentinel,
280
+ "parse_error": self.parse_error,
281
+ "norm": self.norm,
282
+ }
283
+
284
+
285
+ @dataclass
286
+ class TraceSummary:
287
+ eof_clean: bool
288
+ total_frames: int
289
+ timing: Dict[str, Optional[float]]
290
+ assembled: Dict[str, Any]
291
+ backend_probe: Optional[Dict[str, Any]] = None
292
+ type: str = "summary"
293
+
294
+ def to_dict(self) -> Dict[str, Any]:
295
+ out: Dict[str, Any] = {
296
+ "type": "summary",
297
+ "eof_clean": self.eof_clean,
298
+ "total_frames": self.total_frames,
299
+ "timing": self.timing,
300
+ "assembled": self.assembled,
301
+ }
302
+ if self.backend_probe is not None:
303
+ out["backend_probe"] = self.backend_probe
304
+ return out
305
+
306
+
307
+ @dataclass
308
+ class TraceDocument:
309
+ header: TraceHeader
310
+ frames: List[TraceFrame]
311
+ summary: TraceSummary
312
+
313
+
314
+ def scan_think_tags(text: str) -> Tuple[str, str, bool]:
315
+ """Strip <think>...</think> spans into reasoning; return (visible, reasoning, has_unclosed_think)."""
316
+ depth = 0
317
+ vis: List[str] = []
318
+ reas: List[str] = []
319
+ i = 0
320
+ n = len(text)
321
+ while i < n:
322
+ if text.startswith("<think>", i):
323
+ depth += 1
324
+ i += 7
325
+ continue
326
+ if text.startswith("</think>", i):
327
+ if depth > 0:
328
+ depth -= 1
329
+ i += 8
330
+ continue
331
+ vis.append("</think>")
332
+ i += 8
333
+ continue
334
+ ch = text[i]
335
+ if depth > 0:
336
+ reas.append(ch)
337
+ else:
338
+ vis.append(ch)
339
+ i += 1
340
+ return "".join(vis), "".join(reas), depth > 0
341
+
342
+
343
+ def _merge_tool_records(primary: Dict[str, Any], secondary: Dict[str, Any]) -> None:
344
+ """Merge secondary provisional tool record into primary while preserving chronological order."""
345
+ if not primary["id"] and secondary["id"]:
346
+ primary["id"] = secondary["id"]
347
+ if not primary["item_id"] and secondary["item_id"]:
348
+ primary["item_id"] = secondary["item_id"]
349
+ if primary["explicit_index"] is None and secondary["explicit_index"] is not None:
350
+ primary["explicit_index"] = secondary["explicit_index"]
351
+ primary["index"] = secondary["explicit_index"]
352
+ if not primary["name"] and secondary["name"]:
353
+ primary["name"] = secondary["name"]
354
+ primary["name_seq"] = secondary["name_seq"]
355
+
356
+ primary["delta_entries"].extend(secondary["delta_entries"])
357
+ primary["delta_entries"].sort(key=lambda pair: (pair[0], pair[1]))
358
+
359
+ if secondary["done_snapshot"] is not None:
360
+ primary["done_snapshot"] = secondary["done_snapshot"]
361
+ primary["done_seq"] = secondary["done_seq"]
362
+ if secondary["item_snapshot"] is not None:
363
+ primary["item_snapshot"] = secondary["item_snapshot"]
364
+ primary["snapshot_seq"] = secondary["snapshot_seq"]
365
+ primary["saw_args_delta"] = primary["saw_args_delta"] or secondary["saw_args_delta"]
366
+ primary["saw_args_done_event"] = primary["saw_args_done_event"] or secondary["saw_args_done_event"]
367
+ primary["identity_conflict"] = primary["identity_conflict"] or secondary["identity_conflict"]
368
+ primary["first_seq"] = min(primary["first_seq"], secondary["first_seq"])
369
+ primary["last_seq"] = max(primary["last_seq"], secondary["last_seq"])
370
+
371
+
372
+ def assemble_summary(
373
+ header: TraceHeader,
374
+ frames: List[TraceFrame],
375
+ *,
376
+ total_ms: float,
377
+ socket_eof_clean: bool = True,
378
+ backend_probe_summary: Optional[Dict[str, Any]] = None,
379
+ ) -> TraceSummary:
380
+ """Build deterministic TraceSummary from recorded frames with strict protocol ordering."""
381
+ dialect = header.dialect
382
+ t_headers_ms = header.response_meta.get("t_headers_ms")
383
+ ttff_ms: Optional[float] = None
384
+ ttft_effective_ms: Optional[float] = None
385
+
386
+ raw_text_parts: List[str] = []
387
+ reasoning_parts: List[str] = []
388
+ observed_delta_frames = 0
389
+ finish_reason: str = "unknown"
390
+ terminal_status: str = "unknown"
391
+ matched_stop: Optional[Any] = None
392
+ usage = empty_usage()
393
+
394
+ saw_done_sentinel = False
395
+ saw_typed_responses_terminal = False
396
+ saw_raw_sse_done = False
397
+ saw_finish_reason = False
398
+ saw_textless_usage_frame = False
399
+ protocol_violations: List[str] = []
400
+
401
+ # Tool accumulation with alias reconciliation & identity conflict detection
402
+ tools_by_key: Dict[str, Dict[str, Any]] = {}
403
+ tool_order: List[str] = []
404
+ alias_item_to_key: Dict[str, str] = {}
405
+ alias_call_to_key: Dict[str, str] = {}
406
+ alias_idx_to_key: Dict[int, str] = {}
407
+ event_counter = 0
408
+
409
+ def _repoint_aliases(old_key: str, new_key: str) -> None:
410
+ for mp in (alias_item_to_key, alias_call_to_key):
411
+ for ak, kv in list(mp.items()):
412
+ if kv == old_key:
413
+ mp[ak] = new_key
414
+ for ik, kv in list(alias_idx_to_key.items()):
415
+ if kv == old_key:
416
+ alias_idx_to_key[ik] = new_key
417
+
418
+ def _new_tool_record(
419
+ key: str,
420
+ *,
421
+ idx: Optional[int],
422
+ call_id: Optional[str],
423
+ item_id: Optional[str],
424
+ name: str,
425
+ seq: int,
426
+ conflict: bool = False,
427
+ ) -> Dict[str, Any]:
428
+ rec = {
429
+ "index": idx if is_strict_int(idx) else len(tool_order),
430
+ "explicit_index": idx if is_strict_int(idx) else None,
431
+ "id": call_id,
432
+ "item_id": item_id,
433
+ "name": name,
434
+ "name_seq": seq if name else None,
435
+ "first_seq": seq,
436
+ "last_seq": seq,
437
+ "done_seq": None,
438
+ "snapshot_seq": None,
439
+ "delta_entries": [], # List[Tuple[seq, order, str]]
440
+ "done_snapshot": None,
441
+ "item_snapshot": None,
442
+ "saw_args_delta": False,
443
+ "saw_args_done_event": False,
444
+ "identity_conflict": conflict,
445
+ }
446
+ tools_by_key[key] = rec
447
+ tool_order.append(key)
448
+ return rec
449
+
450
+ def _compatible(rec: Dict[str, Any], item_id: Optional[str], call_id: Optional[str]) -> bool:
451
+ if item_id and rec["item_id"] and rec["item_id"] != item_id:
452
+ return False
453
+ if call_id and rec["id"] and rec["id"] != call_id:
454
+ return False
455
+ return True
456
+
457
+ def _resolve_tool(td: Dict[str, Any], seq: int) -> Dict[str, Any]:
458
+ item_id = td.get("item_id") if isinstance(td.get("item_id"), str) and td.get("item_id") else None
459
+ call_id = td.get("id") if isinstance(td.get("id"), str) and td.get("id") else None
460
+ idx = td.get("index") if is_strict_int(td.get("index")) else None
461
+ name = td.get("name") if isinstance(td.get("name"), str) else ""
462
+
463
+ # Ollama streaming emits complete tool calls per chunk with frame-local positions.
464
+ if td.get("tool_accumulate_mode") == "append":
465
+ key = f"append:{len(tool_order)}"
466
+ return _new_tool_record(
467
+ key,
468
+ idx=len(tool_order),
469
+ call_id=call_id,
470
+ item_id=item_id,
471
+ name=name,
472
+ seq=seq,
473
+ )
474
+
475
+ cand_keys: List[str] = []
476
+ if item_id and item_id in alias_item_to_key:
477
+ cand_keys.append(alias_item_to_key[item_id])
478
+ if call_id and call_id in alias_call_to_key:
479
+ k = alias_call_to_key[call_id]
480
+ if k not in cand_keys:
481
+ cand_keys.append(k)
482
+ if idx is not None and idx in alias_idx_to_key:
483
+ k = alias_idx_to_key[idx]
484
+ if k not in cand_keys:
485
+ cand_keys.append(k)
486
+
487
+ # Partition candidates into compatible vs conflicting
488
+ compat = [k for k in cand_keys if _compatible(tools_by_key[k], item_id, call_id)]
489
+ conflicts = [k for k in cand_keys if k not in compat]
490
+
491
+ if not compat:
492
+ had_conflict = bool(conflicts)
493
+ if had_conflict:
494
+ for ck in conflicts:
495
+ tools_by_key[ck]["identity_conflict"] = True
496
+ key = f"conflict:{len(tool_order)}" if had_conflict else (
497
+ f"item:{item_id}" if item_id else (f"call:{call_id}" if call_id else (f"idx:{idx}" if idx is not None else f"ord:{len(tool_order)}"))
498
+ )
499
+ if key in tools_by_key:
500
+ key = f"{key}#{len(tool_order)}"
501
+ rec = _new_tool_record(
502
+ key,
503
+ idx=idx,
504
+ call_id=call_id,
505
+ item_id=item_id,
506
+ name=name,
507
+ seq=seq,
508
+ conflict=had_conflict,
509
+ )
510
+ if item_id:
511
+ alias_item_to_key[item_id] = key
512
+ if call_id:
513
+ alias_call_to_key[call_id] = key
514
+ if idx is not None and not had_conflict:
515
+ alias_idx_to_key[idx] = key
516
+ return rec
517
+
518
+ # Reconcile multiple compatible provisional records (pick earliest in tool_order)
519
+ compat.sort(key=lambda k: tool_order.index(k))
520
+ primary_key = compat[0]
521
+ rec = tools_by_key[primary_key]
522
+ if conflicts:
523
+ # Known item reused an index already owned by a different call -> flag conflict on both!
524
+ rec["identity_conflict"] = True
525
+ for ck in conflicts:
526
+ tools_by_key[ck]["identity_conflict"] = True
527
+ for other_key in compat[1:]:
528
+ other_rec = tools_by_key[other_key]
529
+ # Verify pairwise compatibility between primary and secondary
530
+ if _compatible(rec, other_rec["item_id"], other_rec["id"]):
531
+ _merge_tool_records(rec, other_rec)
532
+ _repoint_aliases(other_key, primary_key)
533
+ del tools_by_key[other_key]
534
+ tool_order.remove(other_key)
535
+ else:
536
+ rec["identity_conflict"] = True
537
+ other_rec["identity_conflict"] = True
538
+
539
+ if item_id:
540
+ rec["item_id"] = item_id
541
+ alias_item_to_key[item_id] = primary_key
542
+ if call_id:
543
+ rec["id"] = call_id
544
+ alias_call_to_key[call_id] = primary_key
545
+ if idx is not None and not conflicts:
546
+ if rec["explicit_index"] is None:
547
+ rec["explicit_index"] = idx
548
+ rec["index"] = idx
549
+ alias_idx_to_key[idx] = primary_key
550
+ if name and not rec["name"]:
551
+ rec["name"] = name
552
+ rec["name_seq"] = seq
553
+ rec["last_seq"] = max(rec["last_seq"], seq)
554
+ return rec
555
+
556
+ for frame in frames:
557
+ if ttff_ms is None and frame.parse_error != "incomplete_event":
558
+ ttff_ms = frame.t_rel_ms
559
+
560
+ norm = frame.norm or {}
561
+ closed_events = norm.get("closed_events") or []
562
+ is_sse_done = "[DONE]" in closed_events or (frame.is_done_sentinel and frame.raw_wire.strip().endswith("[DONE]"))
563
+ is_typed_resp_term = any(
564
+ ev in ("response.completed", "response.incomplete", "response.failed") for ev in closed_events
565
+ ) and not norm.get("protocol_error")
566
+ is_ollama_done = "ollama.done" in closed_events or "done:true" in closed_events
567
+
568
+ # Detect protocol violations from dialect normalizers
569
+ if norm.get("protocol_error"):
570
+ protocol_violations.append(f"frame#{frame.seq}: {norm['protocol_error']}")
571
+
572
+ # Detect payload arriving AFTER an EOF sentinel (e.g., [DONE] placed before content/finish!)
573
+ if saw_raw_sse_done:
574
+ protocol_violations.append(f"frame#{frame.seq}: frame_after_done_sentinel")
575
+ elif dialect == "openai-responses" and saw_typed_responses_terminal and not is_sse_done:
576
+ protocol_violations.append(f"frame#{frame.seq}: payload_after_responses_terminal")
577
+ elif dialect == "ollama-ndjson" and saw_done_sentinel:
578
+ protocol_violations.append(f"frame#{frame.seq}: frame_after_ollama_done")
579
+
580
+ if is_sse_done:
581
+ saw_raw_sse_done = True
582
+ if dialect != "openai-responses":
583
+ saw_done_sentinel = True
584
+ if is_typed_resp_term:
585
+ saw_typed_responses_terminal = True
586
+ saw_done_sentinel = True
587
+ if is_ollama_done:
588
+ saw_done_sentinel = True
589
+
590
+ text_delta = norm.get("text_delta") or ""
591
+ reas_delta = norm.get("reasoning_delta") or ""
592
+ tool_deltas = norm.get("tool_deltas") or []
593
+
594
+ # Detect payload arriving after finish_reason on Chat / SGLang streams (allows trailing usage & [DONE])
595
+ if (
596
+ dialect in ("openai-chat", "sglang-native")
597
+ and saw_finish_reason
598
+ and not is_sse_done
599
+ and (text_delta or reas_delta or tool_deltas)
600
+ ):
601
+ protocol_violations.append(f"frame#{frame.seq}: payload_after_finish_reason")
602
+
603
+ if frame_has_effective_payload(norm):
604
+ observed_delta_frames += 1
605
+ if ttft_effective_ms is None:
606
+ ttft_effective_ms = frame.t_rel_ms
607
+
608
+ if text_delta:
609
+ raw_text_parts.append(text_delta)
610
+ if reas_delta:
611
+ reasoning_parts.append(reas_delta)
612
+
613
+ for td in tool_deltas:
614
+ if not isinstance(td, dict):
615
+ continue
616
+ rec = _resolve_tool(td, frame.seq)
617
+ arg_d = td.get("arguments_delta") if td.get("arguments_delta") is not None else td.get("args_delta")
618
+ if td.get("is_args_delta_event") or (isinstance(arg_d, str) and arg_d != ""):
619
+ rec["saw_args_delta"] = True
620
+ if isinstance(arg_d, str) and arg_d != "":
621
+ event_counter += 1
622
+ rec["delta_entries"].append((frame.seq, event_counter, arg_d))
623
+ arg_s = td.get("arguments_snapshot")
624
+ if td.get("is_args_done"):
625
+ rec["saw_args_done_event"] = True
626
+ rec["done_seq"] = frame.seq
627
+ if isinstance(arg_s, str):
628
+ rec["done_snapshot"] = arg_s
629
+ elif isinstance(arg_s, str) and td.get("is_item_done_snapshot") is not False:
630
+ rec["item_snapshot"] = arg_s
631
+ rec["snapshot_seq"] = frame.seq
632
+
633
+ fr = norm.get("finish_reason")
634
+ if isinstance(fr, str) and fr and fr != "unknown":
635
+ finish_reason = fr
636
+ saw_finish_reason = True
637
+
638
+ ts = norm.get("terminal_status")
639
+ if isinstance(ts, str) and ts and ts != "unknown":
640
+ terminal_status = ts
641
+
642
+ if norm.get("matched_stop") is not None:
643
+ matched_stop = norm["matched_stop"]
644
+
645
+ f_usage = norm.get("usage")
646
+ if isinstance(f_usage, dict):
647
+ updated_usage = False
648
+ for k in ("prompt_tokens", "completion_tokens", "reasoning_tokens", "cached_tokens"):
649
+ v = f_usage.get(k)
650
+ if is_strict_int(v) and v >= 0:
651
+ usage[k] = v
652
+ updated_usage = True
653
+ if updated_usage and not text_delta and not tool_deltas:
654
+ saw_textless_usage_frame = True
655
+
656
+ joined_raw_text = "".join(raw_text_parts)
657
+ visible_text, think_text, has_unclosed_think = scan_think_tags(joined_raw_text)
658
+ full_reasoning = "".join(reasoning_parts) + think_text
659
+
660
+ assembled_tools: List[Dict[str, Any]] = []
661
+ for key in tool_order:
662
+ rec = tools_by_key[key]
663
+ streamed_args = "".join(chunk for _, _, chunk in rec["delta_entries"])
664
+ done_snap = rec["done_snapshot"]
665
+ item_snap = rec["item_snapshot"]
666
+
667
+ args_mismatch = False
668
+ args_mismatch_detail: Optional[str] = None
669
+ if rec["delta_entries"] and done_snap is not None and streamed_args != done_snap:
670
+ args_mismatch = True
671
+ args_mismatch_detail = "streamed arguments.delta differs from arguments.done snapshot"
672
+ elif rec["delta_entries"] and item_snap is not None and streamed_args != item_snap:
673
+ args_mismatch = True
674
+ args_mismatch_detail = "streamed arguments.delta differs from final item snapshot"
675
+ elif done_snap is not None and item_snap is not None and done_snap != item_snap:
676
+ args_mismatch = True
677
+ args_mismatch_detail = "arguments.done snapshot differs from final item snapshot"
678
+
679
+ # Empty Responses delta without arguments.done must NOT be hidden by final item snapshot
680
+ if rec["delta_entries"]:
681
+ raw_args = streamed_args
682
+ elif dialect == "openai-responses" and rec["saw_args_delta"] and not rec["saw_args_done_event"]:
683
+ raw_args = ""
684
+ elif done_snap is not None:
685
+ raw_args = done_snap
686
+ else:
687
+ raw_args = item_snap or ""
688
+
689
+ json_valid = False
690
+ json_error: Optional[str] = None
691
+ if not raw_args or not raw_args.strip():
692
+ json_valid = False
693
+ json_error = "Empty arguments string"
694
+ else:
695
+ try:
696
+ parsed_args = strict_json_loads(raw_args)
697
+ if has_lone_surrogate(parsed_args):
698
+ json_valid = False
699
+ json_error = "Arguments contain invalid lone UTF-16 surrogate"
700
+ else:
701
+ json_valid = True
702
+ except (json.JSONDecodeError, ValueError, RecursionError) as exc:
703
+ json_valid = False
704
+ json_error = str(exc)
705
+
706
+ assembled_tools.append(
707
+ {
708
+ "index": rec["index"],
709
+ "id": rec["id"] or rec["item_id"] or f"call_{rec['index']}",
710
+ "item_id": rec["item_id"],
711
+ "name": rec["name"],
712
+ "raw_arguments": raw_args,
713
+ "json_valid": json_valid,
714
+ "json_error": json_error,
715
+ "saw_args_delta": rec["saw_args_delta"],
716
+ "saw_args_done_event": rec["saw_args_done_event"],
717
+ "args_mismatch": args_mismatch,
718
+ "args_mismatch_detail": args_mismatch_detail,
719
+ "identity_conflict": rec["identity_conflict"],
720
+ "first_seq": rec["first_seq"],
721
+ "name_seq": rec["name_seq"],
722
+ "last_seq": rec["last_seq"],
723
+ "done_seq": rec["done_seq"],
724
+ "snapshot_seq": rec["snapshot_seq"],
725
+ }
726
+ )
727
+
728
+ # Strict dialect-specific clean EOF
729
+ if not socket_eof_clean or protocol_violations:
730
+ eof_clean = False
731
+ elif dialect in ("openai-chat", "sglang-native"):
732
+ eof_clean = saw_done_sentinel
733
+ elif dialect == "openai-responses":
734
+ eof_clean = saw_typed_responses_terminal
735
+ elif dialect == "ollama-ndjson":
736
+ eof_clean = saw_done_sentinel
737
+ else:
738
+ eof_clean = saw_done_sentinel
739
+
740
+ assembled = {
741
+ "content_text": visible_text,
742
+ "content_utf8_bytes": safe_utf8_len(visible_text),
743
+ "reasoning_text": full_reasoning,
744
+ "has_unclosed_think": has_unclosed_think,
745
+ "tool_calls": assembled_tools,
746
+ "finish_reason": finish_reason,
747
+ "terminal_status": terminal_status,
748
+ "matched_stop": matched_stop,
749
+ "protocol_violations": protocol_violations,
750
+ "observed_delta_frames": observed_delta_frames,
751
+ "saw_textless_usage_frame": saw_textless_usage_frame,
752
+ "reported_usage": usage,
753
+ }
754
+ timing = {
755
+ "t_headers_ms": round(float(t_headers_ms), 3) if is_finite_number(t_headers_ms) else None,
756
+ "ttff_ms": round(ttff_ms, 3) if ttff_ms is not None else None,
757
+ "ttft_effective_ms": round(ttft_effective_ms, 3) if ttft_effective_ms is not None else None,
758
+ "total_ms": round(total_ms, 3),
759
+ }
760
+ return TraceSummary(
761
+ eof_clean=eof_clean,
762
+ total_frames=len(frames),
763
+ timing=timing,
764
+ assembled=assembled,
765
+ backend_probe=backend_probe_summary,
766
+ )
767
+
768
+
769
+ def write_trace(path: Union[str, Path], doc: TraceDocument) -> None:
770
+ """Write a complete TraceDocument atomically as UTF-8 LF JSONL."""
771
+ target = Path(path)
772
+ target.parent.mkdir(parents=True, exist_ok=True)
773
+ tmp = target.with_name(f".{target.name}.tmp")
774
+ try:
775
+ with tmp.open("w", encoding="utf-8", newline="\n") as fh:
776
+ fh.write(canonical_json_line(doc.header.to_dict()) + "\n")
777
+ for frame in doc.frames:
778
+ fh.write(canonical_json_line(frame.to_dict()) + "\n")
779
+ fh.write(canonical_json_line(doc.summary.to_dict()) + "\n")
780
+ fh.flush()
781
+ tmp.replace(target)
782
+ except Exception:
783
+ if tmp.exists():
784
+ tmp.unlink(missing_ok=True)
785
+ raise
786
+
787
+
788
+ def _require_type(obj: Dict[str, Any], key: str, expected_type: Any, ctx: str) -> Any:
789
+ if key not in obj:
790
+ raise TraceSchemaError(f"{ctx}: missing required field {key!r}")
791
+ val = obj[key]
792
+ if expected_type is bool:
793
+ if not isinstance(val, bool):
794
+ raise TraceSchemaError(f"{ctx}: field {key!r} must be boolean, got {type(val).__name__}")
795
+ elif expected_type is int:
796
+ if not is_strict_int(val):
797
+ raise TraceSchemaError(f"{ctx}: field {key!r} must be integer, got {type(val).__name__}")
798
+ elif expected_type is float:
799
+ if not is_finite_number(val):
800
+ raise TraceSchemaError(f"{ctx}: field {key!r} must be finite number, got {type(val).__name__}")
801
+ elif not isinstance(val, expected_type):
802
+ raise TraceSchemaError(f"{ctx}: field {key!r} must be {expected_type.__name__}, got {type(val).__name__}")
803
+ return val
804
+
805
+
806
+ def load_trace(path: Union[str, Path]) -> TraceDocument:
807
+ """Load and strictly validate an inferdiff.trace.v1 JSONL file."""
808
+ src = Path(path)
809
+ if not src.exists():
810
+ raise TraceSchemaError(f"Trace file not found: {src}")
811
+ try:
812
+ lines = src.read_text(encoding="utf-8").splitlines()
813
+ except (OSError, UnicodeDecodeError) as exc:
814
+ raise TraceSchemaError(f"{src}: failed to read UTF-8 trace: {exc}") from exc
815
+ if len(lines) < 2:
816
+ raise TraceSchemaError(f"Trace file too short (expected header + summary): {src}")
817
+
818
+ records: List[Dict[str, Any]] = []
819
+ for lineno, line in enumerate(lines, start=1):
820
+ if not line.strip():
821
+ continue
822
+ try:
823
+ obj = strict_json_loads(line)
824
+ except (json.JSONDecodeError, ValueError, RecursionError) as exc:
825
+ raise TraceSchemaError(f"{src}:{lineno}: invalid JSON: {exc}") from exc
826
+ if not isinstance(obj, dict):
827
+ raise TraceSchemaError(f"{src}:{lineno}: JSON record must be an object")
828
+ records.append(obj)
829
+
830
+ if len(records) < 2:
831
+ raise TraceSchemaError(f"{src}: missing header or summary record")
832
+
833
+ hdr_obj = records[0]
834
+ if hdr_obj.get("type") != "header":
835
+ raise TraceSchemaError(f"{src}: first record must have type='header'")
836
+ if hdr_obj.get("schema_version") != SCHEMA_VERSION:
837
+ raise TraceSchemaError(f"{src}: unsupported schema_version={hdr_obj.get('schema_version')!r}")
838
+ dialect = _require_type(hdr_obj, "dialect", str, f"{src}:header")
839
+ if dialect not in VALID_DIALECTS:
840
+ raise TraceSchemaError(f"{src}: unsupported dialect={dialect!r}")
841
+ trace_id = _require_type(hdr_obj, "trace_id", str, f"{src}:header")
842
+ recorded_at = _require_type(hdr_obj, "recorded_at_utc", str, f"{src}:header")
843
+ label = hdr_obj.get("label", "")
844
+ if not isinstance(label, str):
845
+ raise TraceSchemaError(f"{src}:header: field 'label' must be str")
846
+ req_obj = _require_type(hdr_obj, "request", dict, f"{src}:header")
847
+ resp_meta = _require_type(hdr_obj, "response_meta", dict, f"{src}:header")
848
+ _require_type(resp_meta, "status_code", int, f"{src}:header.response_meta")
849
+
850
+ req_copy = dict(req_obj)
851
+ if "url" in req_copy and not isinstance(req_copy["url"], str):
852
+ raise TraceSchemaError(f"{src}:header.request: field 'url' must be str")
853
+ if "body" in req_copy and req_copy["body"] is not None and not isinstance(req_copy["body"], dict):
854
+ raise TraceSchemaError(f"{src}:header.request: field 'body' must be dict or null")
855
+ if "effective_params" in req_copy and req_copy["effective_params"] is not None and not isinstance(req_copy["effective_params"], dict):
856
+ raise TraceSchemaError(f"{src}:header.request: field 'effective_params' must be dict or null")
857
+ # Recover effective_params using the same dialect precedence rules if absent
858
+ if not req_copy.get("effective_params") and isinstance(req_copy.get("body"), dict):
859
+ req_copy["effective_params"] = extract_effective_params(req_copy["body"], dialect)
860
+
861
+ bp_hdr = hdr_obj.get("backend_probe")
862
+ if bp_hdr is not None and not isinstance(bp_hdr, dict):
863
+ raise TraceSchemaError(f"{src}:header: field 'backend_probe' must be dict or null")
864
+
865
+ sum_obj = records[-1]
866
+ if sum_obj.get("type") != "summary":
867
+ raise TraceSchemaError(f"{src}: last record must have type='summary'")
868
+ eof_clean = _require_type(sum_obj, "eof_clean", bool, f"{src}:summary")
869
+ total_frames = _require_type(sum_obj, "total_frames", int, f"{src}:summary")
870
+ timing = _require_type(sum_obj, "timing", dict, f"{src}:summary")
871
+ for tk, tv in timing.items():
872
+ if tv is not None and not is_finite_number(tv):
873
+ raise TraceSchemaError(f"{src}:summary.timing: field {tk!r} must be finite number or null")
874
+ assembled = _require_type(sum_obj, "assembled", dict, f"{src}:summary")
875
+ for s_key in ("content_text", "reasoning_text", "finish_reason", "terminal_status"):
876
+ if s_key in assembled and assembled[s_key] is not None and not isinstance(assembled[s_key], str):
877
+ raise TraceSchemaError(f"{src}:summary.assembled: field {s_key!r} must be str")
878
+ if "tool_calls" in assembled and assembled["tool_calls"] is not None:
879
+ if not isinstance(assembled["tool_calls"], list):
880
+ raise TraceSchemaError(f"{src}:summary.assembled: field 'tool_calls' must be list")
881
+ for ti, tc in enumerate(assembled["tool_calls"]):
882
+ if not isinstance(tc, dict):
883
+ raise TraceSchemaError(f"{src}:summary.assembled.tool_calls[{ti}] must be object")
884
+ if "raw_arguments" in tc and tc["raw_arguments"] is not None and not isinstance(tc["raw_arguments"], str):
885
+ raise TraceSchemaError(f"{src}:summary.assembled.tool_calls[{ti}].raw_arguments must be str")
886
+ if "name" in tc and tc["name"] is not None and not isinstance(tc["name"], str):
887
+ raise TraceSchemaError(f"{src}:summary.assembled.tool_calls[{ti}].name must be str")
888
+ if "json_valid" in tc and tc["json_valid"] is not None and not isinstance(tc["json_valid"], bool):
889
+ raise TraceSchemaError(f"{src}:summary.assembled.tool_calls[{ti}].json_valid must be bool")
890
+ if "reported_usage" in assembled and assembled["reported_usage"] is not None and not isinstance(assembled["reported_usage"], dict):
891
+ raise TraceSchemaError(f"{src}:summary.assembled: field 'reported_usage' must be object")
892
+ bp_sum = sum_obj.get("backend_probe")
893
+ if bp_sum is not None and not isinstance(bp_sum, dict):
894
+ raise TraceSchemaError(f"{src}:summary: field 'backend_probe' must be dict or null")
895
+
896
+ frames: List[TraceFrame] = []
897
+ for idx, rec in enumerate(records[1:-1]):
898
+ ctx = f"{src}:frame[{idx}]"
899
+ if rec.get("type") != "frame":
900
+ raise TraceSchemaError(f"{ctx}: record must have type='frame'")
901
+ seq = _require_type(rec, "seq", int, ctx)
902
+ if seq != idx:
903
+ raise TraceSchemaError(f"{ctx}: non-contiguous frame seq={seq} expected {idx}")
904
+ t_rel = float(_require_type(rec, "t_rel_ms", float, ctx))
905
+ dt = float(_require_type(rec, "dt_ms", float, ctx))
906
+ raw_wire = _require_type(rec, "raw_wire", str, ctx)
907
+ is_done = _require_type(rec, "is_done_sentinel", bool, ctx)
908
+ sse_ev = rec.get("sse_event")
909
+ if sse_ev is not None and not isinstance(sse_ev, str):
910
+ raise TraceSchemaError(f"{ctx}: field 'sse_event' must be str or null")
911
+ parse_err = rec.get("parse_error")
912
+ if parse_err is not None and not isinstance(parse_err, str):
913
+ raise TraceSchemaError(f"{ctx}: field 'parse_error' must be str or null")
914
+ norm = _require_type(rec, "norm", dict, ctx)
915
+ if "tool_deltas" in norm and norm["tool_deltas"] is not None:
916
+ if not isinstance(norm["tool_deltas"], list) or not all(isinstance(td, dict) for td in norm["tool_deltas"]):
917
+ raise TraceSchemaError(f"{ctx}: field 'norm.tool_deltas' must be list of objects")
918
+ if "usage" in norm and norm["usage"] is not None and not isinstance(norm["usage"], dict):
919
+ raise TraceSchemaError(f"{ctx}: field 'norm.usage' must be object or null")
920
+ frames.append(
921
+ TraceFrame(
922
+ seq=seq,
923
+ t_rel_ms=t_rel,
924
+ dt_ms=dt,
925
+ sse_event=sse_ev,
926
+ raw_wire=raw_wire,
927
+ is_done_sentinel=is_done,
928
+ parse_error=parse_err,
929
+ norm=norm,
930
+ )
931
+ )
932
+
933
+ if total_frames != len(frames):
934
+ raise TraceSchemaError(
935
+ f"{src}: summary.total_frames={total_frames} != actual frames={len(frames)}"
936
+ )
937
+
938
+ header = TraceHeader(
939
+ trace_id=trace_id,
940
+ label=label,
941
+ recorded_at_utc=recorded_at,
942
+ dialect=dialect,
943
+ request=req_copy,
944
+ response_meta=dict(resp_meta),
945
+ backend_probe=bp_hdr,
946
+ schema_version=SCHEMA_VERSION,
947
+ )
948
+ summary = TraceSummary(
949
+ eof_clean=eof_clean,
950
+ total_frames=total_frames,
951
+ timing=dict(timing),
952
+ assembled=dict(assembled),
953
+ backend_probe=bp_sum,
954
+ )
955
+ return TraceDocument(header=header, frames=frames, summary=summary)