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/cli.py ADDED
@@ -0,0 +1,490 @@
1
+ """Argparse CLI entrypoint for inferdiff (doctor, record, audit, diff, compare, export)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional, Sequence
10
+
11
+ from . import __version__
12
+ from .canary import render_doctor_terminal, run_doctor
13
+ from .detectors import VALID_AUDIT_DETECTORS, audit_trace
14
+ from .differ import diff_traces
15
+ from .exporter import (
16
+ render_audit_terminal,
17
+ render_ci_summary,
18
+ render_diff_terminal,
19
+ render_github_issue,
20
+ sanitize_trace_for_json_export,
21
+ )
22
+ from .recorder import RecorderError, record_stream, validate_and_merge_headers
23
+ from .schema import (
24
+ EXIT_OK,
25
+ EXIT_SEMANTIC_REGRESSION,
26
+ EXIT_SILENT_PROTOCOL_BREACH,
27
+ EXIT_USAGE_OR_IO_ERROR,
28
+ TraceSchemaError,
29
+ VALID_DIALECTS,
30
+ load_trace,
31
+ strict_json_loads,
32
+ )
33
+ from .waterfall import render_audit_html, render_diff_html, render_doctor_html
34
+
35
+
36
+ def _configure_stdio() -> None:
37
+ for stream in (sys.stdout, sys.stderr):
38
+ if hasattr(stream, "reconfigure"):
39
+ try:
40
+ stream.reconfigure(encoding="utf-8", errors="backslashreplace", newline="\n")
41
+ except Exception:
42
+ pass
43
+
44
+
45
+ def _norm_path_key(path: str | Path) -> str:
46
+ resolved = str(Path(path).resolve())
47
+ return resolved.lower() if sys.platform == "win32" else resolved
48
+
49
+
50
+ def _assert_distinct_output_path(out_path: str, protected_paths: Sequence[str | Path]) -> None:
51
+ """Reject writing HTML/export output over an input trace, captured trace, or doctor_summary.json."""
52
+ if not out_path:
53
+ return
54
+ out_key = _norm_path_key(out_path)
55
+ for prot in protected_paths:
56
+ if prot and _norm_path_key(prot) == out_key:
57
+ raise ValueError(f"Output path {out_path!r} would overwrite trace/evidence file {str(prot)!r}.")
58
+
59
+
60
+ def _write_text_file(path: str, content: str) -> None:
61
+ p = Path(path)
62
+ p.parent.mkdir(parents=True, exist_ok=True)
63
+ p.write_text(content, encoding="utf-8", newline="\n")
64
+
65
+
66
+ def _parse_headers(raw_headers: Optional[Sequence[str]]) -> Dict[str, str]:
67
+ parsed: Dict[str, str] = {}
68
+ if not raw_headers:
69
+ return parsed
70
+ for item in raw_headers:
71
+ if ":" not in item:
72
+ raise ValueError("Invalid --header format (expected 'Name: value').")
73
+ name, val = item.split(":", 1)
74
+ parsed[name.strip()] = val.strip()
75
+ return validate_and_merge_headers({}, parsed)
76
+
77
+
78
+ def _load_request_bodies(source: str, *, allow_jsonl: bool = False) -> List[Dict[str, Any]]:
79
+ """Load a single JSON request object (or multi-line JSONL request suite when allow_jsonl=True)."""
80
+ if source in ("-", "@-"):
81
+ text = sys.stdin.read()
82
+ else:
83
+ p = Path(source)
84
+ if not p.exists():
85
+ raise ValueError(f"Request file not found: {source}")
86
+ text = p.read_text(encoding="utf-8")
87
+
88
+ stripped = text.strip()
89
+ if not stripped:
90
+ raise ValueError("Request input is empty.")
91
+
92
+ try:
93
+ obj = strict_json_loads(stripped)
94
+ except json.JSONDecodeError:
95
+ if not allow_jsonl:
96
+ raise
97
+ bodies: List[Dict[str, Any]] = []
98
+ for lineno, line in enumerate(text.splitlines(), start=1):
99
+ if not line.strip():
100
+ continue
101
+ item = strict_json_loads(line)
102
+ if not isinstance(item, dict):
103
+ raise ValueError(f"Request JSONL line {lineno} must be a JSON object.")
104
+ bodies.append(item)
105
+ if not bodies:
106
+ raise ValueError("Request JSONL input contains no objects.")
107
+ return bodies
108
+
109
+ if not isinstance(obj, dict):
110
+ raise ValueError("Request JSON must be an object.")
111
+ return [obj]
112
+
113
+
114
+ def _derive_suite_out_path(base_out: str, idx: int) -> Path:
115
+ p = Path(base_out)
116
+ if base_out.endswith(("/", "\\")) or p.is_dir():
117
+ return p / f"req_{idx:03d}.trace.jsonl"
118
+ name = p.name
119
+ if name.endswith(".trace.jsonl"):
120
+ stem = name[: -len(".trace.jsonl")]
121
+ return p.with_name(f"{stem}_{idx:03d}.trace.jsonl")
122
+ return p.with_name(f"{p.stem}_{idx:03d}{p.suffix or '.trace.jsonl'}")
123
+
124
+
125
+ def _audit_exit_code(findings: List[Any], *, strict: bool) -> int:
126
+ if any(f.severity == "P0" for f in findings):
127
+ return EXIT_SILENT_PROTOCOL_BREACH
128
+ if strict and any(f.severity == "P1" for f in findings):
129
+ return EXIT_SEMANTIC_REGRESSION
130
+ return EXIT_OK
131
+
132
+
133
+ def _aggregate_exit_code(current: int, new_rc: int) -> int:
134
+ if current == EXIT_SILENT_PROTOCOL_BREACH or new_rc == EXIT_SILENT_PROTOCOL_BREACH:
135
+ return EXIT_SILENT_PROTOCOL_BREACH
136
+ if current == EXIT_SEMANTIC_REGRESSION or new_rc == EXIT_SEMANTIC_REGRESSION:
137
+ return EXIT_SEMANTIC_REGRESSION
138
+ return EXIT_OK
139
+
140
+
141
+ def _cmd_doctor(args: argparse.Namespace) -> int:
142
+ headers = _parse_headers(args.header)
143
+ if args.html and args.save_dir:
144
+ _assert_distinct_output_path(args.html, [Path(args.save_dir) / "doctor_summary.json"])
145
+ report = run_doctor(
146
+ base_url=args.base_url,
147
+ model=args.model or None,
148
+ api_key=args.api_key,
149
+ headers=headers,
150
+ profile=args.profile,
151
+ timeout=args.timeout,
152
+ save_dir=args.save_dir,
153
+ strict=args.strict,
154
+ )
155
+ if args.html:
156
+ protected: List[str | Path] = []
157
+ if report.save_dir:
158
+ protected.append(Path(report.save_dir) / "doctor_summary.json")
159
+ for r in report.results:
160
+ protected.extend(r.trace_paths)
161
+ _assert_distinct_output_path(args.html, protected)
162
+ _write_text_file(args.html, render_doctor_html(report))
163
+ if args.json:
164
+ sys.stdout.write(json.dumps(report.to_dict(), ensure_ascii=True, separators=(",", ":")) + "\n")
165
+ else:
166
+ sys.stdout.write(render_doctor_terminal(report, no_color=args.no_color))
167
+ if args.html:
168
+ sys.stdout.write(f"Saved HTML waterfall report: {args.html}\n")
169
+ return report.exit_code
170
+
171
+
172
+ def _cmd_record(args: argparse.Namespace) -> int:
173
+ headers = _parse_headers(args.header)
174
+ bodies = _load_request_bodies(args.request, allow_jsonl=True)
175
+ agg_rc = EXIT_OK
176
+
177
+ for idx, body in enumerate(bodies, start=1):
178
+ out_target = Path(args.out) if len(bodies) == 1 else _derive_suite_out_path(args.out, idx)
179
+ lbl = args.label or ""
180
+ if len(bodies) > 1:
181
+ lbl = f"{lbl}#{idx}" if lbl else f"req#{idx}"
182
+ doc = record_stream(
183
+ url=args.url,
184
+ request_body=body,
185
+ out_path=out_target,
186
+ headers=headers,
187
+ dialect=args.dialect,
188
+ label=lbl,
189
+ timeout=args.timeout,
190
+ )
191
+ findings = audit_trace(doc)
192
+ sys.stdout.write(render_audit_terminal(doc, findings, no_color=args.no_color))
193
+ sys.stdout.write(f"Saved trace: {out_target}\n")
194
+ agg_rc = _aggregate_exit_code(agg_rc, _audit_exit_code(findings, strict=True))
195
+ return agg_rc
196
+
197
+
198
+ def _parse_only_detectors(raw_only: Optional[str]) -> Optional[set[str]]:
199
+ if raw_only is None:
200
+ return None
201
+ tokens = [tok.strip().upper() for tok in raw_only.split(",") if tok.strip()]
202
+ if not tokens:
203
+ raise ValueError("Invalid --only value: must specify one or more of D1, D2, D3, D4.")
204
+ unknown = sorted(set(tokens) - VALID_AUDIT_DETECTORS)
205
+ if unknown:
206
+ raise ValueError(
207
+ f"Unknown detector(s) in --only: {', '.join(unknown)} (valid for audit: D1, D2, D3, D4)."
208
+ )
209
+ return set(tokens)
210
+
211
+
212
+ def _cmd_audit(args: argparse.Namespace) -> int:
213
+ only = _parse_only_detectors(args.only)
214
+ if args.html:
215
+ _assert_distinct_output_path(args.html, [args.trace_path])
216
+ doc = load_trace(args.trace_path)
217
+ findings = audit_trace(doc, only=only)
218
+ rc = _audit_exit_code(findings, strict=args.strict)
219
+ if args.html:
220
+ _write_text_file(args.html, render_audit_html(doc, findings))
221
+ if args.json:
222
+ safe = sanitize_trace_for_json_export(doc, include_body=False, include_wire=False)
223
+ payload = {
224
+ **safe,
225
+ "findings": [f.to_dict() for f in findings],
226
+ "exit_code": rc,
227
+ }
228
+ sys.stdout.write(json.dumps(payload, ensure_ascii=True, separators=(",", ":")) + "\n")
229
+ else:
230
+ sys.stdout.write(render_audit_terminal(doc, findings, no_color=args.no_color))
231
+ if args.html:
232
+ sys.stdout.write(f"Saved HTML waterfall report: {args.html}\n")
233
+ return rc
234
+
235
+
236
+ def _cmd_diff(args: argparse.Namespace) -> int:
237
+ if args.html:
238
+ _assert_distinct_output_path(args.html, [args.before_trace, args.after_trace])
239
+ before = load_trace(args.before_trace)
240
+ after = load_trace(args.after_trace)
241
+ report = diff_traces(
242
+ before,
243
+ after,
244
+ ignore_timing=args.ignore_timing,
245
+ ttft_regress_pct=args.ttft_regress_pct,
246
+ fail_on=args.fail_on,
247
+ )
248
+ if args.html:
249
+ _write_text_file(args.html, render_diff_html(before, after, report))
250
+ if args.json:
251
+ sys.stdout.write(json.dumps(report.to_dict(include_wire=False), ensure_ascii=True, separators=(",", ":")) + "\n")
252
+ else:
253
+ sys.stdout.write(render_diff_terminal(report, no_color=args.no_color))
254
+ if args.html:
255
+ sys.stdout.write(f"Saved HTML waterfall report: {args.html}\n")
256
+ return report.exit_code
257
+
258
+
259
+ def _cmd_compare(args: argparse.Namespace) -> int:
260
+ shared_headers = _parse_headers(args.header)
261
+ before_headers = validate_and_merge_headers(shared_headers, _parse_headers(args.before_header))
262
+ after_headers = validate_and_merge_headers(shared_headers, _parse_headers(args.after_header))
263
+
264
+ bodies = _load_request_bodies(args.request, allow_jsonl=False)
265
+ body = bodies[0]
266
+ save_dir = Path(args.save_dir) if args.save_dir else None
267
+ b_out = (save_dir / "before.trace.jsonl") if save_dir else None
268
+ a_out = (save_dir / "after.trace.jsonl") if save_dir else None
269
+ if args.html:
270
+ protected = [p for p in (b_out, a_out) if p is not None]
271
+ if args.request not in ("-", "@-"):
272
+ protected.append(args.request)
273
+ _assert_distinct_output_path(args.html, protected)
274
+
275
+ before = record_stream(
276
+ url=args.before_url,
277
+ request_body=body,
278
+ out_path=b_out,
279
+ headers=before_headers,
280
+ dialect=args.dialect,
281
+ label=args.before_label or "before",
282
+ timeout=args.timeout,
283
+ )
284
+ after = record_stream(
285
+ url=args.after_url,
286
+ request_body=body,
287
+ out_path=a_out,
288
+ headers=after_headers,
289
+ dialect=args.dialect,
290
+ label=args.after_label or "after",
291
+ timeout=args.timeout,
292
+ )
293
+ report = diff_traces(
294
+ before,
295
+ after,
296
+ ignore_timing=args.ignore_timing,
297
+ ttft_regress_pct=args.ttft_regress_pct,
298
+ fail_on=args.fail_on,
299
+ )
300
+ if args.html:
301
+ _write_text_file(args.html, render_diff_html(before, after, report))
302
+ if args.json:
303
+ sys.stdout.write(json.dumps(report.to_dict(include_wire=False), ensure_ascii=True, separators=(",", ":")) + "\n")
304
+ else:
305
+ sys.stdout.write(render_diff_terminal(report, no_color=args.no_color))
306
+ if args.html:
307
+ sys.stdout.write(f"Saved HTML waterfall report: {args.html}\n")
308
+ return report.exit_code
309
+
310
+
311
+ def _cmd_export(args: argparse.Namespace) -> int:
312
+ if args.out:
313
+ _assert_distinct_output_path(args.out, [p for p in (args.before, args.after) if p])
314
+ before = load_trace(args.before)
315
+ after = load_trace(args.after) if args.after else None
316
+
317
+ if after is not None:
318
+ report = diff_traces(before, after, fail_on="p1")
319
+ rc = report.exit_code
320
+ if args.format == "github-issue":
321
+ rendered = render_github_issue(
322
+ before,
323
+ after,
324
+ diff_report=report,
325
+ before_path=Path(args.before).name,
326
+ after_path=Path(args.after).name,
327
+ include_body=args.include_body,
328
+ include_wire=args.include_wire,
329
+ )
330
+ elif args.format == "ci-summary":
331
+ rendered = render_ci_summary(before, after, diff_report=report)
332
+ elif args.format == "html":
333
+ rendered = render_diff_html(before, after, report, include_body=args.include_body, include_wire=args.include_wire)
334
+ else:
335
+ rendered = json.dumps(report.to_dict(include_wire=args.include_wire), ensure_ascii=True, indent=2) + "\n"
336
+ else:
337
+ findings = audit_trace(before)
338
+ rc = _audit_exit_code(findings, strict=True)
339
+ if args.format == "github-issue":
340
+ rendered = render_github_issue(
341
+ before,
342
+ None,
343
+ audit_findings=findings,
344
+ before_path=Path(args.before).name,
345
+ include_body=args.include_body,
346
+ include_wire=args.include_wire,
347
+ )
348
+ elif args.format == "ci-summary":
349
+ rendered = render_ci_summary(before, None, audit_findings=findings)
350
+ elif args.format == "html":
351
+ rendered = render_audit_html(before, findings, include_body=args.include_body, include_wire=args.include_wire)
352
+ else:
353
+ safe = sanitize_trace_for_json_export(
354
+ before,
355
+ include_body=args.include_body,
356
+ include_wire=args.include_wire,
357
+ )
358
+ rendered = (
359
+ json.dumps(
360
+ {
361
+ **safe,
362
+ "findings": [f.to_dict() for f in findings],
363
+ "exit_code": rc,
364
+ },
365
+ ensure_ascii=True,
366
+ indent=2,
367
+ )
368
+ + "\n"
369
+ )
370
+
371
+ if args.out:
372
+ _write_text_file(args.out, rendered)
373
+ else:
374
+ sys.stdout.write(rendered)
375
+ return rc
376
+
377
+
378
+ def build_parser() -> argparse.ArgumentParser:
379
+ parser = argparse.ArgumentParser(
380
+ prog="inferdiff",
381
+ description="Wire-level canary doctor, regression diff, and silent-failure forensics for LLM serving & API relays.",
382
+ )
383
+ parser.add_argument("--version", action="version", version=f"inferdiff {__version__}")
384
+ sub = parser.add_subparsers(dest="command", required=True)
385
+
386
+ # doctor (primary zero-setup entry point per Spec §2.1)
387
+ p_doc = sub.add_parser("doctor", help="Zero-setup C1..C8 canary health check for local engines or API relays")
388
+ p_doc.add_argument("base_url", help="Target base URL (e.g. http://127.0.0.1:8080/v1 or https://api.example.com/v1)")
389
+ p_doc.add_argument("--model", "-m", default="", help="Model ID (auto-discovers /models or /api/tags if omitted)")
390
+ p_doc.add_argument("--api-key", default=None, help="API key or $ENV_VAR (defaults to OPENAI_API_KEY, always redacted)")
391
+ p_doc.add_argument("--header", "-H", action="append", default=[], help="Extra HTTP header 'Name: value' (repeatable)")
392
+ p_doc.add_argument("--profile", choices=("quick", "full", "relay"), default="quick", help="Canary profile (quick/full/relay)")
393
+ p_doc.add_argument("--timeout", type=float, default=60.0, help="Per-probe socket timeout in seconds")
394
+ p_doc.add_argument("--save-dir", default="", help="Directory to save canary .trace.jsonl files (default ./.inferdiff-doctor/<ts>/)")
395
+ p_doc.add_argument("--html", default="", help="Write single-file airgap-safe HTML scorecard & SVG waterfall")
396
+ p_doc.add_argument("--strict", action="store_true", help="Exit 3 on P1 warnings (P0 breaches always exit 2)")
397
+ p_doc.add_argument("--json", action="store_true", help="Emit JSON canary matrix report")
398
+ p_doc.add_argument("--no-color", action="store_true")
399
+ p_doc.set_defaults(func=_cmd_doctor)
400
+
401
+ # record
402
+ p_rec = sub.add_parser("record", help="Record live streaming LLM request (or JSONL suite) to .trace.jsonl")
403
+ p_rec.add_argument("--url", required=True, help="Target endpoint URL")
404
+ p_rec.add_argument("--request", "-d", required=True, help="JSON request file, multi-line .jsonl suite, or '-' / '@-' for stdin")
405
+ p_rec.add_argument("--header", "-H", action="append", default=[], help="Extra HTTP header 'Name: value' (repeatable)")
406
+ p_rec.add_argument("--dialect", choices=("auto", *VALID_DIALECTS), default="auto")
407
+ p_rec.add_argument("--label", default="", help="Version label (e.g. llama-server-v1.1.0)")
408
+ p_rec.add_argument("--timeout", type=float, default=120.0, help="Socket timeout in seconds")
409
+ p_rec.add_argument("--out", "-o", required=True, help="Output .trace.jsonl path (or prefix/dir for JSONL suites)")
410
+ p_rec.add_argument("--no-color", action="store_true")
411
+ p_rec.set_defaults(func=_cmd_record)
412
+
413
+ # audit
414
+ p_aud = sub.add_parser("audit", help="Audit a single .trace.jsonl for D1..D4 silent failures")
415
+ p_aud.add_argument("trace_path", help="Path to .trace.jsonl")
416
+ p_aud.add_argument("--only", default=None, help="Comma-separated detector subset from D1,D2,D3,D4")
417
+ p_aud.add_argument("--html", default="", help="Write single-file airgap-safe HTML frame waterfall")
418
+ p_aud.add_argument("--json", action="store_true", help="Emit sanitized JSON audit report")
419
+ p_aud.add_argument("--strict", action="store_true", help="Treat P1 warnings as non-zero exit code 3")
420
+ p_aud.add_argument("--no-color", action="store_true")
421
+ p_aud.set_defaults(func=_cmd_audit)
422
+
423
+ # diff
424
+ p_diff = sub.add_parser("diff", help="Diff baseline and target .trace.jsonl with chunk-jitter-proof alignment")
425
+ p_diff.add_argument("before_trace", help="Baseline .trace.jsonl")
426
+ p_diff.add_argument("after_trace", help="Target .trace.jsonl")
427
+ p_diff.add_argument(
428
+ "--ignore-timing",
429
+ action="store_true",
430
+ help="Ignore TTFT latency regression and D5 timing/benchmark-illusion alerts",
431
+ )
432
+ p_diff.add_argument("--ttft-regress-pct", type=float, default=50.0)
433
+ p_diff.add_argument("--fail-on", choices=("p0", "p1", "any-diff"), default="p0")
434
+ p_diff.add_argument("--html", default="", help="Write dual-lane single-file HTML frame waterfall")
435
+ p_diff.add_argument("--json", action="store_true")
436
+ p_diff.add_argument("--no-color", action="store_true")
437
+ p_diff.set_defaults(func=_cmd_diff)
438
+
439
+ # compare
440
+ p_cmp = sub.add_parser("compare", help="Record two live endpoints sequentially and diff immediately")
441
+ p_cmp.add_argument("--before-url", required=True)
442
+ p_cmp.add_argument("--after-url", required=True)
443
+ p_cmp.add_argument("--request", "-d", required=True)
444
+ p_cmp.add_argument("--header", "-H", action="append", default=[], help="Shared HTTP header for both targets")
445
+ p_cmp.add_argument("--before-header", action="append", default=[], help="HTTP header scoped only to --before-url")
446
+ p_cmp.add_argument("--after-header", action="append", default=[], help="HTTP header scoped only to --after-url")
447
+ p_cmp.add_argument("--dialect", choices=("auto", *VALID_DIALECTS), default="auto")
448
+ p_cmp.add_argument("--before-label", default="before")
449
+ p_cmp.add_argument("--after-label", default="after")
450
+ p_cmp.add_argument("--timeout", type=float, default=120.0)
451
+ p_cmp.add_argument("--save-dir", default="", help="Optional directory to save before/after traces")
452
+ p_cmp.add_argument(
453
+ "--ignore-timing",
454
+ action="store_true",
455
+ help="Ignore TTFT latency regression and D5 timing/benchmark-illusion alerts",
456
+ )
457
+ p_cmp.add_argument("--ttft-regress-pct", type=float, default=50.0)
458
+ p_cmp.add_argument("--fail-on", choices=("p0", "p1", "any-diff"), default="p0")
459
+ p_cmp.add_argument("--html", default="", help="Write dual-lane single-file HTML frame waterfall")
460
+ p_cmp.add_argument("--json", action="store_true")
461
+ p_cmp.add_argument("--no-color", action="store_true")
462
+ p_cmp.set_defaults(func=_cmd_compare)
463
+
464
+ # export
465
+ p_exp = sub.add_parser("export", help="Export compact <=25-line sanitized GitHub Issue, HTML waterfall, or CI summary")
466
+ p_exp.add_argument("before", help="Single trace (audit) or baseline trace (diff)")
467
+ p_exp.add_argument("after", nargs="?", default=None, help="Optional target trace for diff export")
468
+ p_exp.add_argument("--format", choices=("github-issue", "ci-summary", "html", "json"), default="github-issue")
469
+ p_exp.add_argument("--include-body", action="store_true", help="Include sanitized request body in export")
470
+ p_exp.add_argument("--include-wire", action="store_true", help="Include sanitized raw wire frame excerpts in export")
471
+ p_exp.add_argument("--out", "-o", default="", help="Output file path (defaults to stdout)")
472
+ p_exp.set_defaults(func=_cmd_export)
473
+
474
+ return parser
475
+
476
+
477
+ def main(argv: Optional[Sequence[str]] = None) -> int:
478
+ _configure_stdio()
479
+ parser = build_parser()
480
+ try:
481
+ args = parser.parse_args(argv)
482
+ except SystemExit as exc:
483
+ code = exc.code if isinstance(exc.code, int) else EXIT_USAGE_OR_IO_ERROR
484
+ return EXIT_OK if code == 0 else EXIT_USAGE_OR_IO_ERROR
485
+
486
+ try:
487
+ return int(args.func(args))
488
+ except (RecorderError, TraceSchemaError, ValueError, OSError, json.JSONDecodeError) as exc:
489
+ sys.stderr.write(f"inferdiff error: {exc}\n")
490
+ return EXIT_USAGE_OR_IO_ERROR