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/waterfall.py ADDED
@@ -0,0 +1,771 @@
1
+ """Zero-external-dependency single-file HTML5 + inline SVG frame waterfall renderer (<80 KiB)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import html
8
+ import urllib.parse
9
+ from typing import Any, Callable, Dict, List, Optional, Tuple
10
+
11
+ from . import __version__
12
+ from .canary import DoctorReport
13
+ from .detectors import Finding
14
+ from .differ import DiffReport
15
+ from .exporter import _safe_frame_summary, _sanitized_curl_lines, _strip_controls_and_newlines
16
+ from .redact import redact_secret_text
17
+ from .schema import TraceDocument, TraceFrame, frame_has_effective_payload
18
+
19
+ MAX_HTML_BYTES = 81_920
20
+ STALL_GAP_MS = 250.0
21
+ FOLD_THRESHOLD_FRAMES = 500
22
+ MAX_FINDING_ROWS = 20
23
+
24
+ APPROVED_ANCHOR_HOSTS = frozenset(
25
+ {
26
+ "github.com",
27
+ "docs.vllm.ai",
28
+ "docs.ollama.com",
29
+ "docs.lmcache.ai",
30
+ "developers.openai.com",
31
+ }
32
+ )
33
+
34
+ # Colorblind-friendly semantic phase palette
35
+ COLOR_HANDSHAKE = "#64748b" # Slate gray
36
+ COLOR_REASONING = "#f59e0b" # Amber
37
+ COLOR_CONTENT = "#10b981" # Emerald
38
+ COLOR_TOOL = "#6366f1" # Indigo
39
+ COLOR_STALL = "#f97316" # Orange dashed bridge
40
+ COLOR_ALERT = "#ef4444" # Crimson crosshair & breach highlight
41
+ COLOR_TERMINAL = "#38bdf8" # Sky blue (healthy terminal)
42
+
43
+ _STATIC_JS = (
44
+ "(function(){"
45
+ "var a=document.getElementById('svg-abs'),n=document.getElementById('svg-norm'),"
46
+ "ba=document.getElementById('btn-abs'),bn=document.getElementById('btn-norm');"
47
+ "if(ba&&bn&&a&&n){"
48
+ "ba.onclick=function(){a.classList.remove('hid');n.classList.add('hid');ba.classList.add('on');bn.classList.remove('on');};"
49
+ "bn.onclick=function(){n.classList.remove('hid');a.classList.add('hid');bn.classList.add('on');ba.classList.remove('on');};"
50
+ "}"
51
+ "var box=document.getElementById('click-wire');"
52
+ "document.querySelectorAll('.wf-bar').forEach(function(el){"
53
+ "el.addEventListener('click',function(){"
54
+ "if(!box)return;"
55
+ "var w=el.getAttribute('data-wire')||'';"
56
+ "box.textContent='['+el.getAttribute('data-lane')+'] '+el.getAttribute('data-info')+(w?'\\n'+w:'');"
57
+ "});"
58
+ "});"
59
+ "var cp=document.getElementById('btn-copy'),cu=document.getElementById('curl-box');"
60
+ "if(cp&&cu&&navigator.clipboard){"
61
+ "cp.onclick=function(){navigator.clipboard.writeText(cu.textContent).then(function(){cp.textContent='Copied';});};"
62
+ "}"
63
+ "})();"
64
+ )
65
+ _SCRIPT_SHA256_B64 = base64.b64encode(hashlib.sha256(_STATIC_JS.encode("utf-8")).digest()).decode("ascii")
66
+
67
+
68
+ def _safe_utf8_str(val: Any) -> str:
69
+ """Replace any lone UTF-16 surrogates so UTF-8 encoding never raises UnicodeEncodeError."""
70
+ return str(val).encode("utf-8", errors="replace").decode("utf-8")
71
+
72
+
73
+ def _esc(val: Any, max_chars: Optional[int] = None) -> str:
74
+ s = _safe_utf8_str(val)
75
+ if max_chars is not None and len(s) > max_chars:
76
+ s = s[: max(0, max_chars - 3)] + "..."
77
+ return html.escape(s, quote=True)
78
+
79
+
80
+ def _safe_anchor(url: str, label: str = "anchor") -> str:
81
+ try:
82
+ p = urllib.parse.urlsplit(url)
83
+ if p.scheme == "https" and (p.hostname or "").lower() in APPROVED_ANCHOR_HOSTS:
84
+ return f'<a href="{_esc(url, 200)}" style="color:#93c5fd" rel="noreferrer noopener">{_esc(label)}</a>'
85
+ except ValueError:
86
+ pass
87
+ return _esc(label)
88
+
89
+
90
+ def _frame_category(f: TraceFrame) -> str:
91
+ norm = f.norm or {}
92
+ if f.parse_error or norm.get("phase") == "ERROR":
93
+ return "ERROR"
94
+ if norm.get("phase") == "TOOL" or norm.get("tool_deltas"):
95
+ return "TOOL"
96
+ if norm.get("phase") == "REASONING" or (norm.get("reasoning_delta") and not norm.get("text_delta")):
97
+ return "REASONING"
98
+ if norm.get("text_delta"):
99
+ return "CONTENT"
100
+ if norm.get("phase") in ("TERMINAL", "EOF") or f.is_done_sentinel or norm.get("finish_reason") or norm.get("terminal_status"):
101
+ return "TERMINAL"
102
+ return "HANDSHAKE"
103
+
104
+
105
+ def _frame_color(cat: str, is_alert: bool = False) -> str:
106
+ if is_alert or cat == "ERROR":
107
+ return COLOR_ALERT
108
+ return {
109
+ "HANDSHAKE": COLOR_HANDSHAKE,
110
+ "REASONING": COLOR_REASONING,
111
+ "CONTENT": COLOR_CONTENT,
112
+ "TOOL": COLOR_TOOL,
113
+ "TERMINAL": COLOR_TERMINAL,
114
+ }.get(cat, COLOR_HANDSHAKE)
115
+
116
+
117
+ def _bucket_segments(segments: List[Dict[str, Any]], max_segments: int) -> List[Dict[str, Any]]:
118
+ """Hard-cap segment count per lane (even on 1,200+ stall frames) while keeping critical markers."""
119
+ if max_segments <= 0 or len(segments) <= max_segments:
120
+ return segments
121
+ # Always retain first, last, and divergence segments; bucket interior uniformly
122
+ first = segments[0]
123
+ last = segments[-1]
124
+ div_indices = {i for i, s in enumerate(segments) if s.get("is_div")}
125
+ interior = segments[1:-1]
126
+ budget = max(1, max_segments - 2)
127
+ step = max(1, (len(interior) + budget - 1) // budget)
128
+
129
+ out: List[Dict[str, Any]] = [first]
130
+ i = 0
131
+ while i < len(interior):
132
+ orig_idx = i + 1
133
+ if orig_idx in div_indices:
134
+ out.append(interior[i])
135
+ i += 1
136
+ continue
137
+ chunk = interior[i : i + step]
138
+ # Split chunk if it contains a divergence marker
139
+ split_at = next((k for k in range(len(chunk)) if (orig_idx + k) in div_indices), None)
140
+ if split_at is not None and split_at > 0:
141
+ chunk = chunk[:split_at]
142
+ if len(chunk) == 1:
143
+ out.append(chunk[0])
144
+ else:
145
+ s0, s1 = chunk[0], chunk[-1]
146
+ cnt = sum(c.get("count", 1) for c in chunk)
147
+ out.append(
148
+ {
149
+ "folded": True,
150
+ "seq": s0["seq"],
151
+ "end_seq": s1["end_seq"],
152
+ "count": cnt,
153
+ "start_ms": s0["start_ms"],
154
+ "end_ms": s1["end_ms"],
155
+ "dt_ms": round(max(0.0, s1["end_ms"] - s0["start_ms"]), 2),
156
+ "cat": s0["cat"],
157
+ "has_fffd": any(c.get("has_fffd") for c in chunk),
158
+ "is_stall": any(c.get("is_stall") for c in chunk),
159
+ "is_div": False,
160
+ "detail": f"Collapsed {cnt} frames #{s0['seq']}..#{s1['end_seq']}",
161
+ }
162
+ )
163
+ i += len(chunk)
164
+ out.append(last)
165
+ return out
166
+
167
+
168
+ def _fold_frames_for_svg(
169
+ doc: TraceDocument,
170
+ *,
171
+ divergence_seq: Optional[int] = None,
172
+ threshold: int = FOLD_THRESHOLD_FRAMES,
173
+ max_segments: int = 240,
174
+ include_wire: bool = False,
175
+ ) -> List[Dict[str, Any]]:
176
+ """Build renderable SVG segment descriptors with adaptive folding and hard per-lane cap."""
177
+ frames = doc.frames
178
+ if not frames:
179
+ return []
180
+
181
+ first_eff_seq: Optional[int] = None
182
+ for f in frames:
183
+ if frame_has_effective_payload(f.norm or {}):
184
+ first_eff_seq = f.seq
185
+ break
186
+
187
+ keep_all = len(frames) <= threshold
188
+ must_keep: set[int] = set()
189
+ if not keep_all:
190
+ must_keep.add(0)
191
+ if first_eff_seq is not None:
192
+ must_keep.add(first_eff_seq)
193
+ for s in range(max(0, len(frames) - 3), len(frames)):
194
+ must_keep.add(s)
195
+ if divergence_seq is not None:
196
+ for s in range(max(0, divergence_seq - 10), min(len(frames), divergence_seq + 11)):
197
+ must_keep.add(s)
198
+ for f in frames:
199
+ cat = _frame_category(f)
200
+ if cat in ("TOOL", "ERROR", "TERMINAL") or f.dt_ms > STALL_GAP_MS or "\ufffd" in ((f.norm or {}).get("text_delta") or ""):
201
+ must_keep.add(f.seq)
202
+
203
+ segments: List[Dict[str, Any]] = []
204
+ i = 0
205
+ n = len(frames)
206
+ while i < n:
207
+ f = frames[i]
208
+ cat = _frame_category(f)
209
+ if keep_all or f.seq in must_keep or cat not in ("CONTENT", "REASONING"):
210
+ start_ms = max(0.0, f.t_rel_ms - f.dt_ms)
211
+ has_fffd = "\ufffd" in ((f.norm or {}).get("text_delta") or "")
212
+ detail = (
213
+ redact_secret_text(f.raw_wire)
214
+ if include_wire
215
+ else _safe_frame_summary(doc, f.seq)
216
+ )
217
+ segments.append(
218
+ {
219
+ "folded": False,
220
+ "seq": f.seq,
221
+ "end_seq": f.seq,
222
+ "count": 1,
223
+ "start_ms": start_ms,
224
+ "end_ms": f.t_rel_ms,
225
+ "dt_ms": f.dt_ms,
226
+ "cat": cat,
227
+ "has_fffd": has_fffd,
228
+ "is_stall": f.dt_ms > STALL_GAP_MS,
229
+ "is_div": (divergence_seq is not None and f.seq == divergence_seq),
230
+ "detail": detail,
231
+ }
232
+ )
233
+ i += 1
234
+ else:
235
+ j = i + 1
236
+ while j < n and frames[j].seq not in must_keep and _frame_category(frames[j]) == cat:
237
+ j += 1
238
+ f_start = frames[i]
239
+ f_end = frames[j - 1]
240
+ span_ms = round(max(0.0, f_end.t_rel_ms - max(0.0, f_start.t_rel_ms - f_start.dt_ms)), 2)
241
+ segments.append(
242
+ {
243
+ "folded": True,
244
+ "seq": f_start.seq,
245
+ "end_seq": f_end.seq,
246
+ "count": j - i,
247
+ "start_ms": max(0.0, f_start.t_rel_ms - f_start.dt_ms),
248
+ "end_ms": f_end.t_rel_ms,
249
+ "dt_ms": span_ms,
250
+ "cat": cat,
251
+ "has_fffd": False,
252
+ "is_stall": False,
253
+ "is_div": False,
254
+ "detail": f"Collapsed {j - i} healthy {cat} frames #{f_start.seq}..#{f_end.seq} (+{span_ms} ms)",
255
+ }
256
+ )
257
+ i = j
258
+
259
+ return _bucket_segments(segments, max_segments)
260
+
261
+
262
+ def _render_lane_svg_elements(
263
+ lane_id: str,
264
+ label: str,
265
+ doc: TraceDocument,
266
+ y_top: int,
267
+ *,
268
+ max_ms: float,
269
+ normalized: bool,
270
+ divergence_seq: Optional[int],
271
+ lane_alert: bool,
272
+ fold_threshold: int = FOLD_THRESHOLD_FRAMES,
273
+ max_segments: int = 240,
274
+ wire_cap: int = 160,
275
+ include_wire: bool = False,
276
+ svg_w: int = 1120,
277
+ left_pad: int = 190,
278
+ right_pad: int = 24,
279
+ bar_h: int = 24,
280
+ ) -> Tuple[str, Optional[float]]:
281
+ plot_w = svg_w - left_pad - right_pad
282
+ denom = (doc.summary.timing.get("total_ms") or max_ms) if normalized else max_ms
283
+ if denom <= 0:
284
+ denom = 1.0
285
+
286
+ segs = _fold_frames_for_svg(
287
+ doc,
288
+ divergence_seq=divergence_seq,
289
+ threshold=fold_threshold,
290
+ max_segments=max_segments,
291
+ include_wire=include_wire,
292
+ )
293
+ parts: List[str] = []
294
+ parts.append(
295
+ f'<text x="8" y="{y_top + 16}" fill="#cbd5e1" font-size="11" font-family="ui-monospace,Consolas,monospace">'
296
+ f'{_esc(_strip_controls_and_newlines(redact_secret_text(label)), 24)}</text>'
297
+ )
298
+ parts.append(
299
+ f'<rect x="{left_pad}" y="{y_top}" width="{plot_w}" height="{bar_h}" rx="4" fill="#1e293b" stroke="#334155" stroke-width="1"/>'
300
+ )
301
+
302
+ div_x: Optional[float] = None
303
+ for s in segs:
304
+ x0 = left_pad + (s["start_ms"] / denom) * plot_w
305
+ x1 = left_pad + (s["end_ms"] / denom) * plot_w
306
+ x0 = max(left_pad, min(left_pad + plot_w - 3, x0))
307
+ w = max(3.0, min(left_pad + plot_w - x0, x1 - x0))
308
+
309
+ if s["is_stall"] and w > 6:
310
+ mid_y = y_top + bar_h / 2
311
+ parts.append(
312
+ f'<line x1="{x0:.1f}" y1="{mid_y:.1f}" x2="{x0 + w - 3:.1f}" y2="{mid_y:.1f}" '
313
+ f'stroke="{COLOR_STALL}" stroke-width="2" stroke-dasharray="4,3"/>'
314
+ )
315
+
316
+ is_err_frame = s["is_div"] or (lane_alert and s["cat"] == "TERMINAL")
317
+ fill = _frame_color(s["cat"], is_alert=is_err_frame)
318
+ fill_attr = f'url(#fold-{s["cat"]})' if (s["folded"] and s["cat"] in ("CONTENT", "REASONING")) else fill
319
+ stroke = f' stroke="{COLOR_ALERT}" stroke-width="2"' if s["is_div"] else ""
320
+ title_txt = (
321
+ f'Collapsed {s["count"]} {s["cat"]} frames #{s["seq"]}..#{s["end_seq"]} ({s["start_ms"]:.1f}->{s["end_ms"]:.1f}ms)'
322
+ if s["folded"]
323
+ else f'#{s["seq"]} | {s["cat"]} | t={s["end_ms"]:.2f}ms | dt={s["dt_ms"]:.2f}ms'
324
+ )
325
+ detail_preview = _strip_controls_and_newlines(s["detail"])[:wire_cap] if wire_cap > 0 else ""
326
+ wire_attr = f' data-wire="{_esc(detail_preview)}"' if detail_preview else ""
327
+ parts.append(
328
+ f'<rect class="wf-bar" data-lane="{_esc(lane_id, 24)}" data-seq="{s["seq"]}" '
329
+ f'data-info="{_esc(title_txt, 120)}"{wire_attr} '
330
+ f'x="{x0:.1f}" y="{y_top + 2}" width="{w:.1f}" height="{bar_h - 4}" rx="2" fill="{fill_attr}"{stroke}>'
331
+ f'<title>{_esc(title_txt, 120)}</title></rect>'
332
+ )
333
+
334
+ if s["has_fffd"]:
335
+ cx = x0 + w / 2
336
+ cy = y_top + bar_h / 2
337
+ parts.append(
338
+ f'<polygon points="{cx:.1f},{cy - 5:.1f} {cx + 5:.1f},{cy:.1f} {cx:.1f},{cy + 5:.1f} {cx - 5:.1f},{cy:.1f}" '
339
+ f'fill="{COLOR_ALERT}" stroke="#fff" stroke-width="1"><title>U+FFFD UTF-8 corruption at #{s["seq"]}</title></polygon>'
340
+ )
341
+
342
+ if s["is_div"]:
343
+ div_x = x0 + w / 2
344
+
345
+ return "\n".join(parts), div_x
346
+
347
+
348
+ def _svg_defs() -> str:
349
+ return (
350
+ "<defs>"
351
+ f'<pattern id="fold-CONTENT" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">'
352
+ f'<rect width="6" height="6" fill="{COLOR_CONTENT}" fill-opacity="0.35"/>'
353
+ f'<line x1="0" y1="0" x2="0" y2="6" stroke="{COLOR_CONTENT}" stroke-width="2"/></pattern>'
354
+ f'<pattern id="fold-REASONING" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">'
355
+ f'<rect width="6" height="6" fill="{COLOR_REASONING}" fill-opacity="0.35"/>'
356
+ f'<line x1="0" y1="0" x2="0" y2="6" stroke="{COLOR_REASONING}" stroke-width="2"/></pattern>'
357
+ "</defs>"
358
+ )
359
+
360
+
361
+ def _highlight_diff_text(a: str, b: str) -> Tuple[str, str]:
362
+ sa = _strip_controls_and_newlines(redact_secret_text(a))[:280]
363
+ sb = _strip_controls_and_newlines(redact_secret_text(b))[:280]
364
+ lim = min(len(sa), len(sb))
365
+ k = 0
366
+ while k < lim and sa[k] == sb[k]:
367
+ k += 1
368
+ if k == len(sa) and k == len(sb):
369
+ return _esc(sa), _esc(sb)
370
+ ha = f"{_esc(sa[:k])}<mark>{_esc(sa[k:])}</mark>" if k < len(sa) else f"{_esc(sa)}<mark>[EOF]</mark>"
371
+ hb = f"{_esc(sb[:k])}<mark>{_esc(sb[k:])}</mark>" if k < len(sb) else f"{_esc(sb)}<mark>[EOF]</mark>"
372
+ return ha, hb
373
+
374
+
375
+ def _kpi_card(title: str, value: str, sub: str, accent: str = "") -> str:
376
+ cls = f"kpi {accent}".strip()
377
+ return (
378
+ f'<div class="{cls}"><div class="kpi-t">{_esc(title, 48)}</div>'
379
+ f'<div class="kpi-v">{_esc(value, 64)}</div>'
380
+ f'<div class="kpi-s">{_esc(sub, 80)}</div></div>'
381
+ )
382
+
383
+
384
+ def _backend_probe_kpi(doc: TraceDocument) -> str:
385
+ bp = doc.summary.backend_probe
386
+ if not isinstance(bp, dict):
387
+ return _kpi_card("Backend Probe (v0.2)", "idle", "slot ready (LMCache/Mooncake/io)")
388
+ pio = bp.get("proc_io") if isinstance(bp.get("proc_io"), dict) else {}
389
+ pref = pio.get("prefill_window") if isinstance(pio.get("prefill_window"), dict) else {}
390
+ rbytes = pref.get("delta_read_bytes", "n/a")
391
+ lmc = bp.get("lmcache_mp") if isinstance(bp.get("lmcache_mp"), dict) else {}
392
+ l2_keys = lmc.get("delta_hit_l2_keys", "n/a")
393
+ return _kpi_card("Backend Probe", f"Δread={rbytes} B", f"L2 keys={l2_keys}", "kpi-lit")
394
+
395
+
396
+ def _wrap_html_document(title: str, body_html: str) -> str:
397
+ """Wrap body in a 100% airgap-safe HTML5 shell with hash-locked CSP and zero external assets."""
398
+ css = (
399
+ ":root{--bg:#0b1120;--card:#111827;--bd:#1f2937;--fg:#e5e7eb;--mut:#94a3b8}"
400
+ "*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:13px/1.45 ui-sans-serif,system-ui,sans-serif;padding:14px}"
401
+ ".wrap{max-width:1200px;margin:0 auto}.hero{background:var(--card);border:1px solid var(--bd);border-radius:10px;padding:12px 16px;margin-bottom:10px}"
402
+ ".top{display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:10px}"
403
+ ".badge{padding:4px 10px;border-radius:6px;font:700 12px ui-monospace,Consolas,monospace;color:#fff}"
404
+ ".b-red{background:#dc2626}.b-amb{background:#d97706}.b-grn{background:#059669}"
405
+ ".pill{padding:2px 8px;border-radius:999px;background:#1e293b;color:#cbd5e1;font:11px ui-monospace,Consolas,monospace;border:1px solid #334155}"
406
+ ".kpis{display:grid;grid-template-columns:repeat(5,1fr);gap:8px}"
407
+ ".kpi{background:#0f172a;border:1px solid var(--bd);border-radius:8px;padding:8px 10px}"
408
+ ".kpi-lit{border-color:#6366f1}.kpi-t{font-size:11px;color:var(--mut)}.kpi-v{font:700 14px ui-monospace,Consolas,monospace;margin-top:2px}.kpi-s{font-size:11px;color:#94a3b8;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}"
409
+ ".sec{background:var(--card);border:1px solid var(--bd);border-radius:10px;padding:12px 14px;margin-bottom:10px}"
410
+ ".sec-h{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;gap:8px;flex-wrap:wrap}"
411
+ ".sec-h h2{margin:0;font-size:13px;letter-spacing:.02em;color:#f8fafc}"
412
+ ".legend{display:flex;gap:10px;flex-wrap:wrap;font-size:11px;color:var(--mut)}.dot{display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:4px;vertical-align:-1px}"
413
+ ".btn{background:#1e293b;color:#e2e8f0;border:1px solid #334155;border-radius:6px;padding:3px 9px;font:11px ui-monospace,Consolas,monospace;cursor:pointer}"
414
+ ".btn.on{background:#312e81;border-color:#6366f1}"
415
+ "svg{width:100%;height:auto;display:block}.wf-bar{cursor:pointer}.wf-bar:hover{opacity:.85}"
416
+ ".split{display:grid;grid-template-columns:1fr 1fr;gap:10px}.code{background:#020617;border:1px solid var(--bd);border-radius:6px;padding:8px 10px;font:11.5px/1.4 ui-monospace,Consolas,monospace;overflow-x:auto;white-space:pre-wrap;word-break:break-all;margin:4px 0 0}"
417
+ "mark{background:rgba(239,68,68,.35);color:#fecaca;border-radius:2px;padding:0 2px}"
418
+ "table{width:100%;border-collapse:collapse;font-size:12px}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--bd)}th{color:var(--mut);font-weight:600}"
419
+ "details summary{cursor:pointer;color:#93c5fd;font-size:12px}"
420
+ ".foot{display:flex;justify-content:space-between;align-items:center;color:#64748b;font:11px ui-monospace,Consolas,monospace;padding:4px 2px}"
421
+ ".hid{display:none}"
422
+ "@media print{body{background:#fff;color:#111}.hero,.sec,.kpi,.code{background:#fff;border-color:#cbd5e1;color:#111}}"
423
+ "@media(max-width:860px){.kpis{grid-template-columns:repeat(2,1fr)}.split{grid-template-columns:1fr}}"
424
+ )
425
+ csp = f"default-src 'none'; style-src 'unsafe-inline'; script-src 'sha256-{_SCRIPT_SHA256_B64}'; img-src data:;"
426
+ doc_html = (
427
+ "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">"
428
+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"
429
+ f"<meta http-equiv=\"Content-Security-Policy\" content=\"{csp}\">"
430
+ f"<title>{_esc(title, 90)}</title><style>{css}</style></head><body>"
431
+ f"<div class=\"wrap\">{_safe_utf8_str(body_html)}"
432
+ f"<div class=\"foot\"><span>100% offline self-contained report (zero external CDN/fonts)</span>"
433
+ f"<span>Generated by inferdiff v{__version__} &middot; Wire-Level LLM Regression &amp; Relay Forensics</span></div>"
434
+ f"</div><script>{_STATIC_JS}</script></body></html>\n"
435
+ )
436
+ return _safe_utf8_str(doc_html)
437
+
438
+
439
+ def _fit_within_budget(
440
+ title: str,
441
+ summary_line: str,
442
+ builder: Callable[[int, int, int], str],
443
+ ) -> str:
444
+ """Adaptively tighten folding and per-lane segment caps; fallback guarantees <80 KiB strictly."""
445
+ tiers = (
446
+ (FOLD_THRESHOLD_FRAMES, 200, 140),
447
+ (120, 80, 80),
448
+ (40, 32, 0),
449
+ (12, 16, 0),
450
+ (0, 8, 0),
451
+ )
452
+ for thresh, max_segs, wcap in tiers:
453
+ candidate = builder(thresh, max_segs, wcap)
454
+ if len(candidate.encode("utf-8")) <= MAX_HTML_BYTES:
455
+ return candidate
456
+ # Guaranteed compact fallback (< 6 KiB) for extreme pathological traces
457
+ fallback_body = (
458
+ f'<div class="hero"><div class="top"><span class="badge b-amb">{_esc(title, 80)}</span></div>'
459
+ f'<pre class="code">{_esc(summary_line, 600)}</pre></div>'
460
+ )
461
+ return _wrap_html_document(title, fallback_body)
462
+
463
+
464
+ def _legend_html() -> str:
465
+ items = [
466
+ (COLOR_HANDSHAKE, "Handshake/Empty"),
467
+ (COLOR_REASONING, "Reasoning"),
468
+ (COLOR_CONTENT, "Content"),
469
+ (COLOR_TOOL, "Tool Call"),
470
+ (COLOR_STALL, "Stall >250ms"),
471
+ (COLOR_ALERT, "Divergence/Breach"),
472
+ ]
473
+ return '<div class="legend">' + "".join(
474
+ f'<span><i class="dot" style="background:{c}"></i>{lbl}</span>' for c, lbl in items
475
+ ) + "</div>"
476
+
477
+
478
+ def _safe_model_label(doc: TraceDocument) -> str:
479
+ raw = (doc.header.request.get("effective_params") or {}).get("model")
480
+ if not isinstance(raw, str) or not raw.strip():
481
+ return "unknown"
482
+ return _strip_controls_and_newlines(redact_secret_text(raw))[:48]
483
+
484
+
485
+ def render_diff_html(
486
+ before: TraceDocument,
487
+ after: TraceDocument,
488
+ report: DiffReport,
489
+ *,
490
+ include_body: bool = False,
491
+ include_wire: bool = False,
492
+ ) -> str:
493
+ """Render a dual-lane single-file HTML5 + SVG frame waterfall report for `diff` / `compare`."""
494
+ all_f = report.after_findings + report.pair_findings
495
+ if report.exit_code == 2:
496
+ b_cls = "b-red"
497
+ verdict = f"EXIT 2 · {all_f[0].detector_id}: {all_f[0].code}" if all_f else "EXIT 2 · P0 PROTOCOL BREACH"
498
+ elif report.exit_code == 3:
499
+ b_cls = "b-amb"
500
+ verdict = f"EXIT 3 · {all_f[0].detector_id}: {all_f[0].code}" if all_f else "EXIT 3 · SEMANTIC REGRESSION"
501
+ else:
502
+ b_cls = "b-grn"
503
+ verdict = "EXIT 0 · PASS"
504
+
505
+ st = report.summary_table
506
+ model = _safe_model_label(after)
507
+ a_asm = after.summary.assembled
508
+ tools = a_asm.get("tool_calls") or []
509
+ json_ok = all(tc.get("json_valid") is True for tc in tools) if tools else True
510
+ has_fffd = "\ufffd" in (a_asm.get("content_text") or "")
511
+
512
+ kpis = "".join(
513
+ [
514
+ _kpi_card(
515
+ "TTFF / Effective TTFT",
516
+ f"{st['before_ttft_effective_ms']} -> {st['after_ttft_effective_ms']} ms",
517
+ f"handshake ttff: {st['before_ttff_ms']} -> {st['after_ttff_ms']} ms",
518
+ ),
519
+ _kpi_card(
520
+ "Total / Clean EOF",
521
+ f"{st['before_total_ms']} -> {st['after_total_ms']} ms",
522
+ f"eof_clean: {st['before_eof_clean']} -> {st['after_eof_clean']}",
523
+ ),
524
+ _kpi_card(
525
+ "Tokens vs Frames",
526
+ f"{st['before_completion_tokens']} -> {st['after_completion_tokens']} tok",
527
+ f"frames: {st['before_frames']} -> {st['after_frames']}",
528
+ ),
529
+ _kpi_card(
530
+ "JSON / UTF-8 Integrity",
531
+ "FAIL" if (not json_ok or has_fffd) else "OK",
532
+ f"tools={len(tools)} json_valid={json_ok} fffd={has_fffd}",
533
+ ),
534
+ _backend_probe_kpi(after),
535
+ ]
536
+ )
537
+
538
+ max_ms = max(before.summary.timing.get("total_ms") or 1.0, after.summary.timing.get("total_ms") or 1.0, 1.0)
539
+ b_div_seq = report.first_divergence.before_seq if report.first_divergence else None
540
+ a_div_seq = report.first_divergence.after_seq if report.first_divergence else None
541
+
542
+ if report.first_divergence:
543
+ d = report.first_divergence
544
+ if include_wire:
545
+ b_txt = d.before_raw_wire or "null"
546
+ a_txt = d.after_raw_wire or "null"
547
+ else:
548
+ b_txt = _safe_frame_summary(before, d.before_seq)
549
+ a_txt = _safe_frame_summary(after, d.after_seq)
550
+ hl_b, hl_a = _highlight_diff_text(b_txt, a_txt)
551
+ mode_note = "Raw wire (redacted)" if include_wire else "Structured frame summary (pass --include-wire for raw wire)"
552
+ insp = (
553
+ f'<div class="sec"><div class="sec-h"><h2>First-Divergence Inspector [{_esc(d.category, 24)}]</h2>'
554
+ f'<span class="pill">{_esc(_strip_controls_and_newlines(d.detail), 120)}</span></div>'
555
+ f'<div class="split">'
556
+ f'<div><div class="kpi-t">Baseline Frame #{d.before_seq} (+{d.before_t_rel_ms} ms) · {_esc(mode_note, 64)}</div><pre class="code">{hl_b}</pre></div>'
557
+ f'<div><div class="kpi-t">Target Frame #{d.after_seq} (+{d.after_t_rel_ms} ms) · {_esc(mode_note, 64)}</div><pre class="code">{hl_a}</pre></div>'
558
+ f"</div>"
559
+ f'<details style="margin-top:8px"><summary>Inspect clicked frame &amp; minimal sanitized curl reproducer</summary>'
560
+ f'<pre id="click-wire" class="code">Click any frame bar in the waterfall above to inspect its frame summary.</pre>'
561
+ f'<div style="display:flex;justify-content:space-between;align-items:center;margin-top:6px"><span class="kpi-t">Sanitized curl reproducer</span>'
562
+ f'<button id="btn-copy" class="btn" type="button">Copy curl</button></div>'
563
+ f'<pre id="curl-box" class="code">{_esc(chr(10).join(_sanitized_curl_lines(after, include_body=include_body)), 600)}</pre>'
564
+ f"</details></div>"
565
+ )
566
+ else:
567
+ insp = (
568
+ '<div class="sec"><div class="sec-h"><h2>Frame Inspector</h2></div>'
569
+ '<pre id="click-wire" class="code">No semantic divergence detected. Click any frame bar above to inspect its summary.</pre></div>'
570
+ )
571
+
572
+ title = f"inferdiff diff · {_strip_controls_and_newlines(report.before_label)[:32]} vs {_strip_controls_and_newlines(report.after_label)[:32]}"
573
+
574
+ def _assemble(thresh: int, max_segs: int, wcap: int) -> str:
575
+ def _dual_svg(svg_id: str, normalized: bool, hidden: bool, cap: int) -> str:
576
+ l1, x1 = _render_lane_svg_elements(
577
+ "Baseline", report.before_label, before, 14, max_ms=max_ms, normalized=normalized, divergence_seq=b_div_seq, lane_alert=False, fold_threshold=thresh, max_segments=max_segs, wire_cap=cap, include_wire=include_wire
578
+ )
579
+ l2, x2 = _render_lane_svg_elements(
580
+ "Target", report.after_label, after, 54, max_ms=max_ms, normalized=normalized, divergence_seq=a_div_seq, lane_alert=(report.exit_code == 2), fold_threshold=thresh, max_segments=max_segs, wire_cap=cap, include_wire=include_wire
581
+ )
582
+ cross = ""
583
+ if x1 is not None and x2 is not None:
584
+ cross = (
585
+ f'<line x1="{x1:.1f}" y1="10" x2="{x2:.1f}" y2="82" '
586
+ f'stroke="{COLOR_ALERT}" stroke-width="1.6" stroke-dasharray="4,3"/>'
587
+ )
588
+ cls = ' class="hid"' if hidden else ""
589
+ axis_lbl = "0% → 100% normalized progress" if normalized else f"0 ms → {max_ms:.1f} ms shared absolute clock"
590
+ return (
591
+ f'<svg id="{svg_id}"{cls} viewBox="0 0 1120 98" xmlns="http://www.w3.org/2000/svg">'
592
+ f"{_svg_defs()}{l1}{l2}{cross}"
593
+ f'<text x="190" y="94" fill="#64748b" font-size="10" font-family="ui-monospace,Consolas,monospace">{_esc(axis_lbl)}</text>'
594
+ "</svg>"
595
+ )
596
+
597
+ svg_abs = _dual_svg("svg-abs", False, False, wcap)
598
+ svg_norm = _dual_svg("svg-norm", True, True, 0)
599
+ body = (
600
+ f'<div class="hero"><div class="top"><div><span class="badge {b_cls}">{_esc(verdict, 80)}</span> '
601
+ f'<span class="pill">{_esc(report.before_dialect)} → {_esc(report.after_dialect)}</span> '
602
+ f'<span class="pill">model: {_esc(model, 48)}</span></div>'
603
+ f'<div class="pill">{_esc(report.before_label, 36)} vs {_esc(report.after_label, 36)}</div></div>'
604
+ f'<div class="kpis">{kpis}</div></div>'
605
+ f'<div class="sec"><div class="sec-h"><h2>Dual-Lane Frame Waterfall (Hover for timing, click to inspect)</h2>'
606
+ f'<div><button id="btn-abs" class="btn on" type="button">Absolute ms</button> '
607
+ f'<button id="btn-norm" class="btn" type="button">Normalized %</button></div></div>'
608
+ f"{_legend_html()}{svg_abs}{svg_norm}</div>"
609
+ f"{insp}"
610
+ )
611
+ return _wrap_html_document(title, body)
612
+
613
+ return _fit_within_budget(title, f"{verdict} | frames {st['before_frames']} -> {st['after_frames']}", _assemble)
614
+
615
+
616
+ def render_audit_html(
617
+ doc: TraceDocument,
618
+ findings: List[Finding],
619
+ *,
620
+ include_body: bool = False,
621
+ include_wire: bool = False,
622
+ ) -> str:
623
+ """Render a single-lane airgap-safe HTML5 + SVG waterfall report for `audit`."""
624
+ has_p0 = any(f.severity == "P0" for f in findings)
625
+ has_p1 = any(f.severity == "P1" for f in findings)
626
+ b_cls = "b-red" if has_p0 else ("b-amb" if has_p1 else "b-grn")
627
+ verdict = f"{findings[0].severity} · {findings[0].detector_id}: {findings[0].code}" if findings else "PASS · 0 SILENT FAILURES"
628
+
629
+ asm = doc.summary.assembled
630
+ t = doc.summary.timing
631
+ u = asm.get("reported_usage") or {}
632
+ model = _safe_model_label(doc)
633
+ tools = asm.get("tool_calls") or []
634
+ json_ok = all(tc.get("json_valid") is True for tc in tools) if tools else True
635
+ has_fffd = "\ufffd" in (asm.get("content_text") or "")
636
+
637
+ kpis = "".join(
638
+ [
639
+ _kpi_card("TTFF / Effective TTFT", f"{t.get('ttff_ms')} / {t.get('ttft_effective_ms')} ms", f"headers: {t.get('t_headers_ms')} ms"),
640
+ _kpi_card("Total / Clean EOF", f"{t.get('total_ms')} ms", f"eof_clean={doc.summary.eof_clean}"),
641
+ _kpi_card("Tokens vs Frames", f"{u.get('completion_tokens')} tok", f"{doc.summary.total_frames} frames ({asm.get('content_utf8_bytes')} B)"),
642
+ _kpi_card("JSON / UTF-8", "FAIL" if (not json_ok or has_fffd) else "OK", f"finish={_strip_controls_and_newlines(asm.get('finish_reason'))[:24]}/{_strip_controls_and_newlines(asm.get('terminal_status'))[:24]}"),
643
+ _backend_probe_kpi(doc),
644
+ ]
645
+ )
646
+
647
+ max_ms = max(t.get("total_ms") or 1.0, 1.0)
648
+ div_seq = findings[0].frame_seq if findings else None
649
+ capped_findings = findings[:MAX_FINDING_ROWS]
650
+ f_rows = "".join(
651
+ f"<tr><td><span class='badge {'b-red' if f.severity == 'P0' else 'b-amb'}'>{_esc(f.severity, 8)}</span></td>"
652
+ f"<td><code>{_esc(f.detector_id, 8)}</code></td><td>{_esc(f.code, 48)}</td><td>#{f.frame_seq}</td>"
653
+ f"<td>{_esc(_strip_controls_and_newlines(redact_secret_text(f.message)), 160)}</td></tr>"
654
+ for f in capped_findings
655
+ ) or "<tr><td colspan='5'>No silent protocol breaches detected (D1-D4).</td></tr>"
656
+ if len(findings) > MAX_FINDING_ROWS:
657
+ f_rows += f"<tr><td colspan='5'>... {len(findings) - MAX_FINDING_ROWS} additional finding(s) omitted for 80 KiB budget.</td></tr>"
658
+
659
+ title = f"inferdiff audit · {_strip_controls_and_newlines(doc.header.label or doc.header.dialect)[:48]}"
660
+
661
+ def _assemble(thresh: int, max_segs: int, wcap: int) -> str:
662
+ lane_svg, _ = _render_lane_svg_elements(
663
+ "Target", doc.header.label or doc.header.dialect, doc, 14, max_ms=max_ms, normalized=False, divergence_seq=div_seq, lane_alert=has_p0, fold_threshold=thresh, max_segments=max_segs, wire_cap=wcap, include_wire=include_wire
664
+ )
665
+ svg = (
666
+ f'<svg id="svg-abs" viewBox="0 0 1120 58" xmlns="http://www.w3.org/2000/svg">{_svg_defs()}{lane_svg}'
667
+ f'<text x="190" y="54" fill="#64748b" font-size="10" font-family="ui-monospace,Consolas,monospace">0 ms → {max_ms:.1f} ms</text></svg>'
668
+ )
669
+ body = (
670
+ f'<div class="hero"><div class="top"><div><span class="badge {b_cls}">{_esc(verdict, 80)}</span> '
671
+ f'<span class="pill">{_esc(doc.header.dialect)}</span> <span class="pill">model: {_esc(model, 48)}</span></div></div>'
672
+ f'<div class="kpis">{kpis}</div></div>'
673
+ f'<div class="sec"><div class="sec-h"><h2>Single-Track Frame Waterfall</h2></div>{_legend_html()}{svg}</div>'
674
+ f'<div class="sec"><div class="sec-h"><h2>Audit Findings &amp; Frame Inspector</h2></div>'
675
+ f"<table><thead><tr><th>Sev</th><th>ID</th><th>Rule</th><th>Frame</th><th>Evidence</th></tr></thead><tbody>{f_rows}</tbody></table>"
676
+ f'<pre id="click-wire" class="code" style="margin-top:8px">Click any frame bar above to inspect its summary.</pre>'
677
+ f'<details style="margin-top:8px"><summary>Minimal sanitized curl reproducer</summary>'
678
+ f'<pre id="curl-box" class="code">{_esc(chr(10).join(_sanitized_curl_lines(doc, include_body=include_body)), 600)}</pre></details></div>'
679
+ )
680
+ return _wrap_html_document(title, body)
681
+
682
+ return _fit_within_budget(title, f"{verdict} | {doc.summary.total_frames} frames", _assemble)
683
+
684
+
685
+ def render_doctor_html(report: DoctorReport, *, include_wire: bool = False) -> str:
686
+ """Render the C1..C8 Doctor Health Scorecard + multi-lane SVG frame waterfalls."""
687
+ b_cls = "b-red" if report.grade == "F" else ("b-amb" if report.warning_count > 0 else "b-grn")
688
+ verdict = f"DOCTOR GRADE: {report.grade} · EXIT {report.exit_code}"
689
+ tok_str = f"{report.total_tokens:,} tok" if report.total_tokens is not None else "unknown"
690
+ passed = sum(1 for r in report.results if r.status == "PASS")
691
+ tot_ms = sum(r.duration_ms for r in report.results)
692
+
693
+ kpis = "".join(
694
+ [
695
+ _kpi_card("Wire Health Grade", report.grade, f"{passed}/{len(report.results)} probes passed"),
696
+ _kpi_card("P0 Protocol Breaches", str(report.p0_count), f"{report.error_count} errors, {report.warning_count} warnings"),
697
+ _kpi_card("Total Canary Cost", tok_str, f"profile: {report.profile}"),
698
+ _kpi_card("Total Latency", f"{tot_ms:.0f} ms", f"dialect: {report.dialect}"),
699
+ _kpi_card("Target Endpoint", redact_secret_text(report.model)[:22], redact_secret_text(report.target_url)[:36]),
700
+ ]
701
+ )
702
+
703
+ traced_lanes: List[Tuple[str, TraceDocument, bool]] = []
704
+ for r in report.results:
705
+ if r.traces:
706
+ traced_lanes.append((f"{r.probe_id} {r.status}", r.traces[-1], r.status in ("FAIL", "ERROR")))
707
+
708
+ max_ms = max((doc.summary.timing.get("total_ms") or 1.0 for _, doc, _ in traced_lanes), default=1.0)
709
+ svg_h = max(60, len(traced_lanes) * 34 + 26)
710
+ st_badge = {"PASS": "b-grn", "WARN": "b-amb", "FAIL": "b-red", "ERROR": "b-red", "SKIP": "pill"}
711
+ rows: List[str] = []
712
+ for r in report.results:
713
+ cls = st_badge.get(r.status, "pill")
714
+ tok = str(r.tokens_used) if r.tokens_used is not None else "unknown"
715
+ ref_html = _safe_anchor(r.reference_url, "anchor")
716
+ wire_snippet = ""
717
+ if r.traces and r.traces[-1].frames:
718
+ doc_last = r.traces[-1]
719
+ snip = (
720
+ redact_secret_text(doc_last.frames[-1].raw_wire)[:180]
721
+ if include_wire
722
+ else _safe_frame_summary(doc_last, doc_last.frames[-1].seq)
723
+ )
724
+ wire_snippet = f'<details><summary>frame</summary><pre class="code">{_esc(_strip_controls_and_newlines(snip), 180)}</pre></details>'
725
+ rows.append(
726
+ f"<tr><td><span class='badge {cls}'>{_esc(r.status, 12)}</span></td>"
727
+ f"<td><code>{_esc(r.probe_id, 8)}</code> {_esc(r.code, 40)}</td>"
728
+ f"<td>{r.duration_ms:.0f} ms</td><td>{r.total_frames}</td><td>{_esc(tok, 16)}</td>"
729
+ f"<td>{_esc(_strip_controls_and_newlines(redact_secret_text(r.summary)), 150)} {wire_snippet}</td><td>{ref_html}</td></tr>"
730
+ )
731
+
732
+ title = f"inferdiff doctor · {redact_secret_text(report.model)[:36]} (Grade {report.grade})"
733
+
734
+ def _assemble(thresh: int, max_segs: int, wcap: int) -> str:
735
+ per_lane_cap = max(8, max_segs // max(1, len(traced_lanes)))
736
+ lanes_abs: List[str] = []
737
+ lanes_norm: List[str] = []
738
+ for idx, (lbl, doc, is_fail) in enumerate(traced_lanes):
739
+ y = 12 + idx * 34
740
+ s_a, _ = _render_lane_svg_elements(lbl, lbl, doc, y, max_ms=max_ms, normalized=False, divergence_seq=None, lane_alert=is_fail, fold_threshold=thresh, max_segments=per_lane_cap, wire_cap=wcap, include_wire=include_wire)
741
+ s_n, _ = _render_lane_svg_elements(lbl, lbl, doc, y, max_ms=max_ms, normalized=True, divergence_seq=None, lane_alert=is_fail, fold_threshold=thresh, max_segments=per_lane_cap, wire_cap=0, include_wire=include_wire)
742
+ lanes_abs.append(s_a)
743
+ lanes_norm.append(s_n)
744
+
745
+ svg_abs = (
746
+ f'<svg id="svg-abs" viewBox="0 0 1120 {svg_h}" xmlns="http://www.w3.org/2000/svg">'
747
+ f"{_svg_defs()}{''.join(lanes_abs)}"
748
+ f'<text x="190" y="{svg_h - 6}" fill="#64748b" font-size="10" font-family="ui-monospace,Consolas,monospace">0 ms → {max_ms:.1f} ms shared absolute clock</text></svg>'
749
+ )
750
+ svg_norm = (
751
+ f'<svg id="svg-norm" class="hid" viewBox="0 0 1120 {svg_h}" xmlns="http://www.w3.org/2000/svg">'
752
+ f"{_svg_defs()}{''.join(lanes_norm)}"
753
+ f'<text x="190" y="{svg_h - 6}" fill="#64748b" font-size="10" font-family="ui-monospace,Consolas,monospace">0% → 100% normalized per-probe progress</text></svg>'
754
+ )
755
+ body = (
756
+ f'<div class="hero"><div class="top"><div><span class="badge {b_cls}">{_esc(verdict, 80)}</span> '
757
+ f'<span class="pill">profile: {_esc(report.profile)}</span> <span class="pill">model: {_esc(redact_secret_text(report.model), 48)}</span></div>'
758
+ f'<div class="pill">{_esc(redact_secret_text(report.target_url), 72)}</div></div>'
759
+ f'<div class="kpis">{kpis}</div></div>'
760
+ f'<div class="sec"><div class="sec-h"><h2>Canary Multi-Lane Frame Waterfall (C1-C8)</h2>'
761
+ f'<div><button id="btn-abs" class="btn on" type="button">Absolute ms</button> '
762
+ f'<button id="btn-norm" class="btn" type="button">Normalized %</button></div></div>'
763
+ f"{_legend_html()}{svg_abs}{svg_norm}"
764
+ f'<pre id="click-wire" class="code" style="margin-top:8px">Click any frame bar above to inspect its summary.</pre></div>'
765
+ f'<div class="sec"><div class="sec-h"><h2>Endpoint &amp; Relay Canary Matrix (C1-C8)</h2></div>'
766
+ f"<table><thead><tr><th>Status</th><th>Probe</th><th>Time</th><th>Frames</th><th>Tokens</th><th>Verdict &amp; Evidence</th><th>Ref</th></tr></thead>"
767
+ f"<tbody>{''.join(rows)}</tbody></table></div>"
768
+ )
769
+ return _wrap_html_document(title, body)
770
+
771
+ return _fit_within_budget(title, f"{verdict} | profile={report.profile}", _assemble)