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/__init__.py +64 -0
- inferdiff/__main__.py +10 -0
- inferdiff/canary.py +1431 -0
- inferdiff/cli.py +490 -0
- inferdiff/detectors.py +423 -0
- inferdiff/dialects/__init__.py +41 -0
- inferdiff/dialects/ollama_ndjson.py +94 -0
- inferdiff/dialects/openai_chat.py +113 -0
- inferdiff/dialects/openai_responses.py +180 -0
- inferdiff/dialects/sglang_native.py +68 -0
- inferdiff/differ.py +649 -0
- inferdiff/exporter.py +482 -0
- inferdiff/probes/__init__.py +5 -0
- inferdiff/probes/base.py +52 -0
- inferdiff/recorder.py +918 -0
- inferdiff/redact.py +355 -0
- inferdiff/schema.py +955 -0
- inferdiff/waterfall.py +771 -0
- inferdiff-0.1.0.dist-info/METADATA +165 -0
- inferdiff-0.1.0.dist-info/RECORD +24 -0
- inferdiff-0.1.0.dist-info/WHEEL +5 -0
- inferdiff-0.1.0.dist-info/entry_points.txt +2 -0
- inferdiff-0.1.0.dist-info/licenses/LICENSE +21 -0
- inferdiff-0.1.0.dist-info/top_level.txt +1 -0
inferdiff/exporter.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""Terminal ANSI renderer and strict <=25-line sanitized GitHub Issue Markdown exporter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import shlex
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Any, Dict, List, Optional
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .detectors import Finding
|
|
12
|
+
from .differ import DiffReport
|
|
13
|
+
from .redact import (
|
|
14
|
+
extract_safe_repro_body,
|
|
15
|
+
redact_headers,
|
|
16
|
+
redact_secret_text,
|
|
17
|
+
sanitize_body_for_export,
|
|
18
|
+
sanitize_url_for_export,
|
|
19
|
+
)
|
|
20
|
+
from .schema import TraceDocument
|
|
21
|
+
|
|
22
|
+
MAX_ISSUE_LINES = 25
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _supports_color(no_color: bool) -> bool:
|
|
26
|
+
if no_color:
|
|
27
|
+
return False
|
|
28
|
+
try:
|
|
29
|
+
return sys.stdout.isatty()
|
|
30
|
+
except Exception:
|
|
31
|
+
return False
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _c(text: str, code: str, use_color: bool) -> str:
|
|
35
|
+
return f"\033[{code}m{text}\033[0m" if use_color else text
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _strip_controls_and_newlines(text: Any) -> str:
|
|
39
|
+
"""Flatten control characters and Unicode line separators so no field can inject extra lines."""
|
|
40
|
+
s = str(text)
|
|
41
|
+
out: List[str] = []
|
|
42
|
+
for ch in s:
|
|
43
|
+
code = ord(ch)
|
|
44
|
+
if ch in ("\r", "\n", "\u0085", "\u2028", "\u2029"):
|
|
45
|
+
out.append(" ")
|
|
46
|
+
elif code < 32 or code == 127:
|
|
47
|
+
out.append(f"\\x{code:02x}")
|
|
48
|
+
else:
|
|
49
|
+
out.append(ch)
|
|
50
|
+
return "".join(out)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _esc_md(text: Any, max_chars: int = 160) -> str:
|
|
54
|
+
flat = _strip_controls_and_newlines(text).replace("|", "\\|").replace("`", "'").strip()
|
|
55
|
+
if len(flat) > max_chars:
|
|
56
|
+
return flat[: max_chars - 3] + "..."
|
|
57
|
+
return flat
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _one_line_wire(raw_wire: Optional[str], max_chars: int = 125) -> str:
|
|
61
|
+
if raw_wire is None:
|
|
62
|
+
return "null"
|
|
63
|
+
scrubbed = redact_secret_text(raw_wire)
|
|
64
|
+
compact = scrubbed.replace("\r\n", " | ").replace("\n", " | ").replace("\r", " | ")
|
|
65
|
+
compact = _strip_controls_and_newlines(compact).strip(" |")
|
|
66
|
+
if len(compact) > max_chars:
|
|
67
|
+
return compact[: max_chars - 3] + "..."
|
|
68
|
+
return compact
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _safe_shell_url(doc: TraceDocument) -> str:
|
|
72
|
+
raw_url = str(doc.header.request.get("url") or "http://127.0.0.1:8080/v1/chat/completions")
|
|
73
|
+
try:
|
|
74
|
+
clean = sanitize_url_for_export(raw_url)
|
|
75
|
+
except ValueError:
|
|
76
|
+
clean = "http://invalid-url.redacted/"
|
|
77
|
+
return shlex.quote(clean)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _sanitized_curl_lines(doc: TraceDocument, *, include_body: bool = False) -> List[str]:
|
|
81
|
+
"""Build a POSIX-safe curl reproducer with --globoff --url and strict credential separation."""
|
|
82
|
+
quoted_url = _safe_shell_url(doc)
|
|
83
|
+
body = doc.header.request.get("body")
|
|
84
|
+
body_hash8 = str(doc.header.request.get("body_sha256") or "unknown")[:8]
|
|
85
|
+
|
|
86
|
+
if not isinstance(body, dict):
|
|
87
|
+
return [
|
|
88
|
+
f"# Attach sanitized request.json (body_sha256={body_hash8})",
|
|
89
|
+
f"curl -sS -N --globoff --url {quoted_url} -H 'Content-Type: application/json' --data-binary @request.json",
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
if include_body:
|
|
93
|
+
payload = sanitize_body_for_export(body)
|
|
94
|
+
compact_body = _strip_controls_and_newlines(json.dumps(payload, ensure_ascii=True, separators=(",", ":")))
|
|
95
|
+
if len(compact_body) <= 420:
|
|
96
|
+
return [
|
|
97
|
+
f"curl -sS -N --globoff --url {quoted_url} -H 'Content-Type: application/json' -d {shlex.quote(compact_body)}"
|
|
98
|
+
]
|
|
99
|
+
return [
|
|
100
|
+
f"# Body >420 chars: save sanitized request payload (sha256:{body_hash8}) to request.json",
|
|
101
|
+
f"curl -sS -N --globoff --url {quoted_url} -H 'Content-Type: application/json' --data-binary @request.json",
|
|
102
|
+
]
|
|
103
|
+
|
|
104
|
+
# Default shareable mode: never echo arbitrary user prompts or custom body fields
|
|
105
|
+
safe_proto, omitted_arbitrary = extract_safe_repro_body(body)
|
|
106
|
+
if not omitted_arbitrary:
|
|
107
|
+
compact_body = _strip_controls_and_newlines(json.dumps(safe_proto, ensure_ascii=True, separators=(",", ":")))
|
|
108
|
+
if len(compact_body) <= 420:
|
|
109
|
+
return [
|
|
110
|
+
f"curl -sS -N --globoff --url {quoted_url} -H 'Content-Type: application/json' -d {shlex.quote(compact_body)}"
|
|
111
|
+
]
|
|
112
|
+
|
|
113
|
+
proto_hint = _strip_controls_and_newlines(
|
|
114
|
+
json.dumps(
|
|
115
|
+
{k: safe_proto[k] for k in ("model", "stream", "temperature", "seed") if k in safe_proto},
|
|
116
|
+
ensure_ascii=True,
|
|
117
|
+
separators=(",", ":"),
|
|
118
|
+
)
|
|
119
|
+
)
|
|
120
|
+
return [
|
|
121
|
+
f"# Arbitrary prompt/body omitted by default (sha256:{body_hash8}, params={proto_hint}); save to request.json or re-export with --include-body",
|
|
122
|
+
f"curl -sS -N --globoff --url {quoted_url} -H 'Content-Type: application/json' --data-binary @request.json",
|
|
123
|
+
]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _md_code_span(text: str) -> str:
|
|
127
|
+
"""Wrap exact command text in a Markdown code span without mangling or truncating characters."""
|
|
128
|
+
# Choose a backtick fence longer than any consecutive backtick run inside text
|
|
129
|
+
max_run = 0
|
|
130
|
+
cur = 0
|
|
131
|
+
for ch in text:
|
|
132
|
+
if ch == "`":
|
|
133
|
+
cur += 1
|
|
134
|
+
if cur > max_run:
|
|
135
|
+
max_run = cur
|
|
136
|
+
else:
|
|
137
|
+
cur = 0
|
|
138
|
+
fence = "`" * (max_run + 1)
|
|
139
|
+
pad = " " if (text.startswith("`") or text.endswith("`")) else ""
|
|
140
|
+
return f"{fence}{pad}{text}{pad}{fence}"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def sanitize_trace_for_json_export(
|
|
144
|
+
doc: TraceDocument,
|
|
145
|
+
*,
|
|
146
|
+
include_body: bool = False,
|
|
147
|
+
include_wire: bool = False,
|
|
148
|
+
) -> Dict[str, Any]:
|
|
149
|
+
"""Build a strictly allowlisted, credential-safe trace header + summary dict for JSON export."""
|
|
150
|
+
raw_req = doc.header.request if isinstance(doc.header.request, dict) else {}
|
|
151
|
+
raw_url = raw_req.get("url")
|
|
152
|
+
if isinstance(raw_url, str):
|
|
153
|
+
try:
|
|
154
|
+
safe_url = sanitize_url_for_export(raw_url)
|
|
155
|
+
except ValueError:
|
|
156
|
+
safe_url = "http://invalid-url.redacted/"
|
|
157
|
+
else:
|
|
158
|
+
safe_url = "http://invalid-url.redacted/"
|
|
159
|
+
|
|
160
|
+
# Re-redact imported headers so a tampered or third-party trace cannot smuggle raw secrets
|
|
161
|
+
raw_hdrs = raw_req.get("headers_redacted")
|
|
162
|
+
safe_hdrs = redact_headers(
|
|
163
|
+
{str(k): str(v) for k, v in raw_hdrs.items()} if isinstance(raw_hdrs, dict) else {}
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
eff = raw_req.get("effective_params") if isinstance(raw_req.get("effective_params"), dict) else {}
|
|
167
|
+
safe_eff = {
|
|
168
|
+
"model": redact_secret_text(str(eff["model"])) if isinstance(eff.get("model"), str) else None,
|
|
169
|
+
"stream": eff.get("stream") if isinstance(eff.get("stream"), bool) else True,
|
|
170
|
+
"max_budget_tokens": eff.get("max_budget_tokens"),
|
|
171
|
+
"ignore_eos": eff.get("ignore_eos") if isinstance(eff.get("ignore_eos"), bool) else False,
|
|
172
|
+
"temperature": eff.get("temperature"),
|
|
173
|
+
"seed": eff.get("seed"),
|
|
174
|
+
"has_tools": eff.get("has_tools") if isinstance(eff.get("has_tools"), bool) else False,
|
|
175
|
+
"stop_conditions_count": len(eff.get("stop_conditions") or []),
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
safe_req: Dict[str, Any] = {
|
|
179
|
+
"method": str(raw_req.get("method") or "POST"),
|
|
180
|
+
"url": safe_url,
|
|
181
|
+
"headers_redacted": safe_hdrs,
|
|
182
|
+
"body_sha256": str(raw_req.get("body_sha256") or ""),
|
|
183
|
+
"effective_params": safe_eff,
|
|
184
|
+
}
|
|
185
|
+
if include_body and isinstance(raw_req.get("body"), dict):
|
|
186
|
+
safe_req["body"] = sanitize_body_for_export(raw_req["body"])
|
|
187
|
+
|
|
188
|
+
rm = doc.header.response_meta if isinstance(doc.header.response_meta, dict) else {}
|
|
189
|
+
safe_rm = {
|
|
190
|
+
"status_code": rm.get("status_code"),
|
|
191
|
+
"content_type": redact_secret_text(str(rm.get("content_type") or "")),
|
|
192
|
+
"t_headers_ms": rm.get("t_headers_ms"),
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
hdr = {
|
|
196
|
+
"type": "header",
|
|
197
|
+
"schema_version": doc.header.schema_version,
|
|
198
|
+
"trace_id": doc.header.trace_id,
|
|
199
|
+
"label": redact_secret_text(doc.header.label),
|
|
200
|
+
"recorded_at_utc": doc.header.recorded_at_utc,
|
|
201
|
+
"dialect": doc.header.dialect,
|
|
202
|
+
"request": safe_req,
|
|
203
|
+
"response_meta": safe_rm,
|
|
204
|
+
"backend_probe": sanitize_body_for_export(doc.header.backend_probe) if doc.header.backend_probe is not None else None,
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
raw_asm = doc.summary.assembled if isinstance(doc.summary.assembled, dict) else {}
|
|
208
|
+
safe_tools: List[Dict[str, Any]] = []
|
|
209
|
+
for tc in raw_asm.get("tool_calls") or []:
|
|
210
|
+
if not isinstance(tc, dict):
|
|
211
|
+
continue
|
|
212
|
+
item: Dict[str, Any] = {
|
|
213
|
+
"index": tc.get("index"),
|
|
214
|
+
"id": tc.get("id"),
|
|
215
|
+
"name": tc.get("name"),
|
|
216
|
+
"json_valid": tc.get("json_valid"),
|
|
217
|
+
"json_error": tc.get("json_error"),
|
|
218
|
+
"saw_args_delta": tc.get("saw_args_delta"),
|
|
219
|
+
"saw_args_done_event": tc.get("saw_args_done_event"),
|
|
220
|
+
"args_mismatch": tc.get("args_mismatch"),
|
|
221
|
+
"identity_conflict": tc.get("identity_conflict"),
|
|
222
|
+
}
|
|
223
|
+
if include_wire and isinstance(tc.get("raw_arguments"), str):
|
|
224
|
+
item["raw_arguments"] = redact_secret_text(tc["raw_arguments"])
|
|
225
|
+
safe_tools.append(item)
|
|
226
|
+
|
|
227
|
+
safe_asm: Dict[str, Any] = {
|
|
228
|
+
"content_utf8_bytes": raw_asm.get("content_utf8_bytes"),
|
|
229
|
+
"has_unclosed_think": raw_asm.get("has_unclosed_think"),
|
|
230
|
+
"tool_calls": safe_tools,
|
|
231
|
+
"finish_reason": raw_asm.get("finish_reason"),
|
|
232
|
+
"terminal_status": raw_asm.get("terminal_status"),
|
|
233
|
+
"protocol_violations": raw_asm.get("protocol_violations") or [],
|
|
234
|
+
"observed_delta_frames": raw_asm.get("observed_delta_frames"),
|
|
235
|
+
"saw_textless_usage_frame": raw_asm.get("saw_textless_usage_frame"),
|
|
236
|
+
"reported_usage": raw_asm.get("reported_usage") if isinstance(raw_asm.get("reported_usage"), dict) else {},
|
|
237
|
+
}
|
|
238
|
+
if include_wire:
|
|
239
|
+
safe_asm["content_text"] = redact_secret_text(str(raw_asm.get("content_text") or ""))
|
|
240
|
+
safe_asm["reasoning_text"] = redact_secret_text(str(raw_asm.get("reasoning_text") or ""))
|
|
241
|
+
|
|
242
|
+
summary: Dict[str, Any] = {
|
|
243
|
+
"type": "summary",
|
|
244
|
+
"eof_clean": doc.summary.eof_clean,
|
|
245
|
+
"total_frames": doc.summary.total_frames,
|
|
246
|
+
"timing": dict(doc.summary.timing),
|
|
247
|
+
"assembled": safe_asm,
|
|
248
|
+
}
|
|
249
|
+
if doc.summary.backend_probe is not None:
|
|
250
|
+
summary["backend_probe"] = sanitize_body_for_export(doc.summary.backend_probe)
|
|
251
|
+
return {"header": hdr, "summary": summary}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _safe_frame_summary(doc: TraceDocument, seq: Optional[int]) -> str:
|
|
255
|
+
if seq is None or seq < 0 or seq >= len(doc.frames):
|
|
256
|
+
return "none"
|
|
257
|
+
f = doc.frames[seq]
|
|
258
|
+
norm = f.norm or {}
|
|
259
|
+
parts = [f"phase={_esc_md(norm.get('phase', 'UNKNOWN'), 24)}"]
|
|
260
|
+
if f.sse_event:
|
|
261
|
+
parts.append(f"event={_esc_md(f.sse_event, 40)}")
|
|
262
|
+
if norm.get("finish_reason"):
|
|
263
|
+
parts.append(f"finish_reason={_esc_md(norm['finish_reason'], 24)}")
|
|
264
|
+
if norm.get("terminal_status"):
|
|
265
|
+
parts.append(f"status={_esc_md(norm['terminal_status'], 24)}")
|
|
266
|
+
if norm.get("text_delta"):
|
|
267
|
+
parts.append(f"text_delta_chars={len(norm['text_delta'])}")
|
|
268
|
+
if norm.get("reasoning_delta"):
|
|
269
|
+
parts.append(f"reasoning_delta_chars={len(norm['reasoning_delta'])}")
|
|
270
|
+
if norm.get("tool_deltas"):
|
|
271
|
+
parts.append(f"tool_deltas={len(norm['tool_deltas'])}")
|
|
272
|
+
if f.parse_error:
|
|
273
|
+
parts.append(f"parse_error={_esc_md(f.parse_error, 48)}")
|
|
274
|
+
return ", ".join(parts)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def render_audit_terminal(doc: TraceDocument, findings: List[Finding], *, no_color: bool = False) -> str:
|
|
278
|
+
use_color = _supports_color(no_color)
|
|
279
|
+
label = _strip_controls_and_newlines(doc.header.label or doc.header.dialect)
|
|
280
|
+
asm = doc.summary.assembled
|
|
281
|
+
t = doc.summary.timing
|
|
282
|
+
usage = asm.get("reported_usage") or {}
|
|
283
|
+
|
|
284
|
+
lines = [
|
|
285
|
+
_c(f"inferdiff v{__version__} audit :: {label} ({doc.header.dialect})", "1", use_color),
|
|
286
|
+
f" HTTP {doc.header.response_meta.get('status_code')} | eof_clean={doc.summary.eof_clean} | frames={doc.summary.total_frames}",
|
|
287
|
+
f" timing: ttff={t.get('ttff_ms')} ms | ttft_effective={t.get('ttft_effective_ms')} ms | total={t.get('total_ms')} ms",
|
|
288
|
+
f" output: content={asm.get('content_utf8_bytes')} B | tools={len(asm.get('tool_calls') or [])} | finish={asm.get('finish_reason')}/{asm.get('terminal_status')} | completion_tokens={usage.get('completion_tokens')}",
|
|
289
|
+
]
|
|
290
|
+
if not findings:
|
|
291
|
+
lines.append(_c(" PASS: 0 silent failures detected (D1-D4)", "32", use_color))
|
|
292
|
+
else:
|
|
293
|
+
for f in findings:
|
|
294
|
+
col = "31" if f.severity == "P0" else "33"
|
|
295
|
+
seq_s = f" @frame#{f.frame_seq}" if f.frame_seq is not None else ""
|
|
296
|
+
lines.append(_c(f" [{f.severity}] {f.detector_id} {f.code}{seq_s}: {_strip_controls_and_newlines(f.message)}", col, use_color))
|
|
297
|
+
return "\n".join(lines) + "\n"
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def render_diff_terminal(report: DiffReport, *, no_color: bool = False) -> str:
|
|
301
|
+
use_color = _supports_color(no_color)
|
|
302
|
+
st = report.summary_table
|
|
303
|
+
lines = [
|
|
304
|
+
_c(
|
|
305
|
+
f"inferdiff v{__version__} diff :: {_strip_controls_and_newlines(report.before_label)} -> {_strip_controls_and_newlines(report.after_label)}",
|
|
306
|
+
"1",
|
|
307
|
+
use_color,
|
|
308
|
+
),
|
|
309
|
+
f" HTTP/EOF : {st['before_status']} (clean={st['before_eof_clean']}, {st['before_frames']}f) -> {st['after_status']} (clean={st['after_eof_clean']}, {st['after_frames']}f)",
|
|
310
|
+
f" Terminal : {_strip_controls_and_newlines(st['before_finish_reason'])}/{_strip_controls_and_newlines(st['before_terminal_status'])} -> {_strip_controls_and_newlines(st['after_finish_reason'])}/{_strip_controls_and_newlines(st['after_terminal_status'])}",
|
|
311
|
+
f" Timing : ttft_eff {st['before_ttft_effective_ms']} -> {st['after_ttft_effective_ms']} ms | total {st['before_total_ms']} -> {st['after_total_ms']} ms",
|
|
312
|
+
f" Tokens : completion {st['before_completion_tokens']} -> {st['after_completion_tokens']} | semantic_equal={report.semantic_equal}",
|
|
313
|
+
]
|
|
314
|
+
if report.first_divergence:
|
|
315
|
+
d = report.first_divergence
|
|
316
|
+
lines.append(_c(f" First Divergence [{d.category}]: {_strip_controls_and_newlines(d.detail)}", "33", use_color))
|
|
317
|
+
lines.append(_c(f" - before #{d.before_seq} (+{d.before_t_rel_ms} ms): {_one_line_wire(d.before_raw_wire)}", "36", use_color))
|
|
318
|
+
lines.append(_c(f" + after #{d.after_seq} (+{d.after_t_rel_ms} ms): {_one_line_wire(d.after_raw_wire)}", "31", use_color))
|
|
319
|
+
|
|
320
|
+
all_findings = report.after_findings + report.pair_findings
|
|
321
|
+
for f in all_findings:
|
|
322
|
+
col = "31" if f.severity == "P0" else "33"
|
|
323
|
+
lines.append(_c(f" [{f.severity}] {f.detector_id} {f.code}: {_strip_controls_and_newlines(f.message)}", col, use_color))
|
|
324
|
+
if report.ttft_regressed:
|
|
325
|
+
lines.append(_c(f" [P1] TTFT_REGRESSION: ttft_effective increased by +{report.ttft_delta_pct}%", "33", use_color))
|
|
326
|
+
|
|
327
|
+
# Gate banner strictly reflects report.exit_code (never prints PASS while returning non-zero)
|
|
328
|
+
if report.exit_code == 0:
|
|
329
|
+
if not report.semantic_equal or all_findings or report.ttft_regressed:
|
|
330
|
+
lines.append(_c(" PASS (exit 0; gate passed, non-blocking diff/warning shown above)", "32", use_color))
|
|
331
|
+
else:
|
|
332
|
+
lines.append(_c(" PASS (exit 0): no silent protocol breach or semantic regression", "32", use_color))
|
|
333
|
+
elif report.exit_code == 2:
|
|
334
|
+
lines.append(_c(" FAIL (exit 2): P0 silent protocol breach detected", "31", use_color))
|
|
335
|
+
else:
|
|
336
|
+
lines.append(_c(f" FAIL (exit {report.exit_code}): semantic or benchmark regression exceeded gate", "33", use_color))
|
|
337
|
+
|
|
338
|
+
return "\n".join(lines) + "\n"
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _enforce_line_budget(lines: List[str], max_lines: int = MAX_ISSUE_LINES) -> str:
|
|
342
|
+
"""Guarantee rendered output has strictly <= max_lines physical lines and balanced code fences."""
|
|
343
|
+
# Flatten every entry through splitlines() so embedded newlines can never bypass the budget
|
|
344
|
+
physical: List[str] = []
|
|
345
|
+
for entry in lines:
|
|
346
|
+
parts = entry.splitlines() if entry != "" else [""]
|
|
347
|
+
physical.extend(parts)
|
|
348
|
+
|
|
349
|
+
if len(physical) <= max_lines:
|
|
350
|
+
return "\n".join(physical) + "\n"
|
|
351
|
+
|
|
352
|
+
footer = physical[-1]
|
|
353
|
+
body = physical[: max_lines - 1]
|
|
354
|
+
# Ensure any open triple-backtick fence in body is closed cleanly within the budget
|
|
355
|
+
fence_count = sum(1 for ln in body if ln.lstrip().startswith("```"))
|
|
356
|
+
if fence_count % 2 == 1:
|
|
357
|
+
body = body[: max_lines - 2] + ["```"]
|
|
358
|
+
final = body + [footer]
|
|
359
|
+
assert len(final) <= max_lines
|
|
360
|
+
return "\n".join(final) + "\n"
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def render_github_issue(
|
|
364
|
+
before: TraceDocument,
|
|
365
|
+
after: Optional[TraceDocument] = None,
|
|
366
|
+
*,
|
|
367
|
+
diff_report: Optional[DiffReport] = None,
|
|
368
|
+
audit_findings: Optional[List[Finding]] = None,
|
|
369
|
+
before_path: str = "before.trace.jsonl",
|
|
370
|
+
after_path: str = "after.trace.jsonl",
|
|
371
|
+
include_body: bool = False,
|
|
372
|
+
include_wire: bool = False,
|
|
373
|
+
) -> str:
|
|
374
|
+
"""Render a strictly <=25-line sanitized, zero-fluff GitHub Issue Markdown report."""
|
|
375
|
+
lines: List[str] = []
|
|
376
|
+
# Preserve exact POSIX shell-quoted filenames (never truncate or rewrite after shlex.quote!)
|
|
377
|
+
q_before = shlex.quote(_strip_controls_and_newlines(before_path))
|
|
378
|
+
q_after = shlex.quote(_strip_controls_and_newlines(after_path))
|
|
379
|
+
|
|
380
|
+
if after is not None and diff_report is not None:
|
|
381
|
+
all_f = diff_report.after_findings + diff_report.pair_findings
|
|
382
|
+
primary = f"{all_f[0].detector_id}: {all_f[0].code}" if all_f else ("SEMANTIC_DRIFT" if not diff_report.semantic_equal else "NO_REGRESSION")
|
|
383
|
+
st = diff_report.summary_table
|
|
384
|
+
b_lbl = _esc_md(diff_report.before_label, 48)
|
|
385
|
+
a_lbl = _esc_md(diff_report.after_label, 48)
|
|
386
|
+
lines.append(f"### Wire-Level Regression Report (`inferdiff v{__version__}` - `{_esc_md(primary, 60)}`)")
|
|
387
|
+
lines.append(f"| Metric | Baseline (`{b_lbl}`) | Target (`{a_lbl}`) |")
|
|
388
|
+
lines.append("| :--- | :--- | :--- |")
|
|
389
|
+
lines.append(
|
|
390
|
+
f"| HTTP / Clean EOF | `{_esc_md(st['before_status'], 16)}` / `{str(st['before_eof_clean']).lower()}` (`{st['before_frames']}` frames) "
|
|
391
|
+
f"| `{_esc_md(st['after_status'], 16)}` / `{str(st['after_eof_clean']).lower()}` (`{st['after_frames']}` frames) |"
|
|
392
|
+
)
|
|
393
|
+
lines.append(
|
|
394
|
+
f"| Terminal Signal | `{_esc_md(st['before_finish_reason'], 24)}` / `{_esc_md(st['before_terminal_status'], 24)}` "
|
|
395
|
+
f"| `{_esc_md(st['after_finish_reason'], 24)}` / `{_esc_md(st['after_terminal_status'], 24)}` |"
|
|
396
|
+
)
|
|
397
|
+
lines.append(
|
|
398
|
+
f"| Timing (`ttft_eff` / `total`) | `{st['before_ttft_effective_ms']}` / `{st['before_total_ms']} ms` "
|
|
399
|
+
f"| `{st['after_ttft_effective_ms']}` / `{st['after_total_ms']} ms` |"
|
|
400
|
+
)
|
|
401
|
+
lines.append(
|
|
402
|
+
f"| Completion Tokens | `{_esc_md(st['before_completion_tokens'], 16)}` | `{_esc_md(st['after_completion_tokens'], 16)}` |"
|
|
403
|
+
)
|
|
404
|
+
if diff_report.first_divergence:
|
|
405
|
+
d = diff_report.first_divergence
|
|
406
|
+
lines.append(f"| First Divergence | Frame `#{d.before_seq}` (`+{d.before_t_rel_ms} ms`) | Frame `#{d.after_seq}` (`+{d.after_t_rel_ms} ms`) |")
|
|
407
|
+
lines.append("")
|
|
408
|
+
lines.append("**Minimal Reproducer (auth & secrets redacted):**")
|
|
409
|
+
lines.append("```bash")
|
|
410
|
+
lines.extend(_sanitized_curl_lines(after, include_body=include_body))
|
|
411
|
+
lines.append("```")
|
|
412
|
+
if all_f:
|
|
413
|
+
f0 = all_f[0]
|
|
414
|
+
lines.append(f"**Finding (`[{f0.severity}] {f0.detector_id}:{f0.code}`):** {_esc_md(f0.message, 240)}")
|
|
415
|
+
if diff_report.first_divergence:
|
|
416
|
+
d = diff_report.first_divergence
|
|
417
|
+
lines.append(f"**First Divergent Frame (`Target #{d.after_seq}` vs `Baseline #{d.before_seq}`):**")
|
|
418
|
+
lines.append("```diff")
|
|
419
|
+
if include_wire:
|
|
420
|
+
lines.append(f"- Baseline #{d.before_seq}: {_one_line_wire(d.before_raw_wire)}")
|
|
421
|
+
lines.append(f"+ Target #{d.after_seq}: {_one_line_wire(d.after_raw_wire)}")
|
|
422
|
+
else:
|
|
423
|
+
lines.append(f"- Baseline #{d.before_seq}: {_safe_frame_summary(before, d.before_seq)}")
|
|
424
|
+
lines.append(f"+ Target #{d.after_seq}: {_safe_frame_summary(after, d.after_seq)}")
|
|
425
|
+
lines.append("```")
|
|
426
|
+
offline_cmd = _md_code_span(f"inferdiff diff {q_before} {q_after} --fail-on p1")
|
|
427
|
+
lines.append(f"Reproduce offline: {offline_cmd} (exits `{diff_report.exit_code}`).")
|
|
428
|
+
else:
|
|
429
|
+
findings = audit_findings or []
|
|
430
|
+
primary = f"{findings[0].detector_id}: {findings[0].code}" if findings else "CLEAN"
|
|
431
|
+
lbl = _esc_md(before.header.label or before.header.dialect, 48)
|
|
432
|
+
asm = before.summary.assembled
|
|
433
|
+
t = before.summary.timing
|
|
434
|
+
usage = asm.get("reported_usage") or {}
|
|
435
|
+
lines.append(f"### Wire-Level Audit Report (`inferdiff v{__version__}` - `{_esc_md(primary, 60)}`)")
|
|
436
|
+
lines.append(f"| Metric | Target (`{lbl}`) |")
|
|
437
|
+
lines.append("| :--- | :--- |")
|
|
438
|
+
lines.append(f"| HTTP / Clean EOF | `{_esc_md(before.header.response_meta.get('status_code'), 16)}` / `{str(before.summary.eof_clean).lower()}` (`{before.summary.total_frames}` frames) |")
|
|
439
|
+
lines.append(f"| Terminal Signal | `{_esc_md(asm.get('finish_reason'), 24)}` / `{_esc_md(asm.get('terminal_status'), 24)}` |")
|
|
440
|
+
lines.append(f"| Timing (`ttft_eff` / `total`) | `{t.get('ttft_effective_ms')}` / `{t.get('total_ms')} ms` |")
|
|
441
|
+
lines.append(f"| Output / Tokens | `{asm.get('content_utf8_bytes')} B`, `{len(asm.get('tool_calls') or [])}` tools / `{_esc_md(usage.get('completion_tokens'), 16)}` tokens |")
|
|
442
|
+
lines.append("")
|
|
443
|
+
lines.append("**Minimal Reproducer (auth & secrets redacted):**")
|
|
444
|
+
lines.append("```bash")
|
|
445
|
+
lines.extend(_sanitized_curl_lines(before, include_body=include_body))
|
|
446
|
+
lines.append("```")
|
|
447
|
+
if findings:
|
|
448
|
+
f0 = findings[0]
|
|
449
|
+
lines.append(f"**Triggering Finding (`[{f0.severity}] {f0.detector_id}:{f0.code}`):**")
|
|
450
|
+
lines.append("```text")
|
|
451
|
+
lines.append(_esc_md(f0.message, 240))
|
|
452
|
+
if f0.frame_seq is not None and 0 <= f0.frame_seq < len(before.frames):
|
|
453
|
+
if include_wire:
|
|
454
|
+
lines.append(f"Frame #{f0.frame_seq}: {_one_line_wire(before.frames[f0.frame_seq].raw_wire)}")
|
|
455
|
+
else:
|
|
456
|
+
lines.append(f"Frame #{f0.frame_seq}: {_safe_frame_summary(before, f0.frame_seq)}")
|
|
457
|
+
lines.append("```")
|
|
458
|
+
offline_cmd = _md_code_span(f"inferdiff audit {q_before} --strict")
|
|
459
|
+
lines.append(f"Reproduce offline: {offline_cmd}.")
|
|
460
|
+
|
|
461
|
+
return _enforce_line_budget(lines, MAX_ISSUE_LINES)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def render_ci_summary(
|
|
465
|
+
before: TraceDocument,
|
|
466
|
+
after: Optional[TraceDocument] = None,
|
|
467
|
+
*,
|
|
468
|
+
diff_report: Optional[DiffReport] = None,
|
|
469
|
+
audit_findings: Optional[List[Finding]] = None,
|
|
470
|
+
) -> str:
|
|
471
|
+
if after is not None and diff_report is not None:
|
|
472
|
+
all_f = diff_report.after_findings + diff_report.pair_findings
|
|
473
|
+
status = "PASS" if diff_report.exit_code == 0 else "FAIL"
|
|
474
|
+
codes = ",".join(f"{f.detector_id}:{f.code}" for f in all_f) or "none"
|
|
475
|
+
return (
|
|
476
|
+
f"inferdiff ci-summary: {status} | {_strip_controls_and_newlines(diff_report.before_label)} -> {_strip_controls_and_newlines(diff_report.after_label)} | "
|
|
477
|
+
f"semantic_equal={diff_report.semantic_equal} | findings={codes} | exit={diff_report.exit_code}\n"
|
|
478
|
+
)
|
|
479
|
+
findings = audit_findings or []
|
|
480
|
+
status = "PASS" if not findings else "FAIL"
|
|
481
|
+
codes = ",".join(f"{f.detector_id}:{f.code}" for f in findings) or "none"
|
|
482
|
+
return f"inferdiff ci-summary: {status} | {_strip_controls_and_newlines(before.header.label or before.header.dialect)} | findings={codes}\n"
|
inferdiff/probes/base.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""v0.2 extension protocol for optional non-intrusive backend KV/storage probes.
|
|
2
|
+
|
|
3
|
+
Implements the three-point snapshot contract (T_pre -> T_ttft -> T_eof):
|
|
4
|
+
- describe_topology() -> written to header.backend_probe
|
|
5
|
+
- sample_pre() -> baseline before request dispatch (HTTP /metrics + /proc/pid/io)
|
|
6
|
+
- sample_ttft() -> microsecond local snapshot at first effective payload frame
|
|
7
|
+
- sample_eof() -> post-EOF snapshot & delta payload for summary.backend_probe
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any, Dict, Optional, Protocol
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class BackendProbe(Protocol):
|
|
16
|
+
"""Interface for v0.2 backend telemetry probes (LMCache / Mooncake / Linux proc_io)."""
|
|
17
|
+
|
|
18
|
+
name: str
|
|
19
|
+
|
|
20
|
+
def describe_topology(self) -> Optional[Dict[str, Any]]:
|
|
21
|
+
"""Return static probe topology & version metadata for header.backend_probe."""
|
|
22
|
+
...
|
|
23
|
+
|
|
24
|
+
def sample_pre(self) -> None:
|
|
25
|
+
"""T_pre: capture baseline counters immediately before request dispatch."""
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
def sample_ttft(self) -> None:
|
|
29
|
+
"""T_ttft: capture microsecond local snapshot on first effective payload frame."""
|
|
30
|
+
...
|
|
31
|
+
|
|
32
|
+
def sample_eof(self) -> Optional[Dict[str, Any]]:
|
|
33
|
+
"""T_eof: capture post-stream counters and return delta dict for summary.backend_probe."""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class NullProbe:
|
|
38
|
+
"""Default v0.1 no-op probe (keeps header.backend_probe = null and zero runtime overhead)."""
|
|
39
|
+
|
|
40
|
+
name = "null"
|
|
41
|
+
|
|
42
|
+
def describe_topology(self) -> Optional[Dict[str, Any]]:
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
def sample_pre(self) -> None:
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
def sample_ttft(self) -> None:
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
def sample_eof(self) -> Optional[Dict[str, Any]]:
|
|
52
|
+
return None
|