Metadata-Version: 2.4
Name: inferdiff
Version: 0.1.0
Summary: Wireshark for streaming LLMs: catch HTTP 200 silent truncations, broken tool JSON, fake SSE relays & usage drops.
Author: ApacheWang
License-Expression: MIT
Project-URL: Homepage, https://github.com/ApacheWang/inferdiff
Project-URL: Repository, https://github.com/ApacheWang/inferdiff
Project-URL: Issues, https://github.com/ApacheWang/inferdiff/issues
Keywords: llm,inference,sse,streaming,vllm,llama-cpp,sglang,ollama,litellm,testing
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: httpx
Requires-Dist: httpx>=0.27; extra == "httpx"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Dynamic: license-file

# inferdiff

[![CI](https://github.com/ApacheWang/inferdiff/actions/workflows/ci.yml/badge.svg)](https://github.com/ApacheWang/inferdiff/actions/workflows/ci.yml)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-3776AB?logo=python&logoColor=white)](https://github.com/ApacheWang/inferdiff)
[![Zero Dependencies](https://raw.githubusercontent.com/ApacheWang/inferdiff/main/assets/badge-zero-deps.svg)](https://github.com/ApacheWang/inferdiff/blob/main/pyproject.toml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ApacheWang/inferdiff/blob/main/LICENSE)

**Wireshark & protocol bill-checker for streaming LLM APIs.**

Catch silent `HTTP 200 OK` failures — truncated tool JSON, ghost thinking starvation, buffered nonconformant SSE relays, and illusory benchmark speedups — with **zero third-party runtime dependencies** (Python 3.11+ standard library only).

[中文文档 (README.zh-CN.md)](https://github.com/ApacheWang/inferdiff/blob/main/README.zh-CN.md)

![inferdiff live relay doctor and GitHub Issue export demo](https://raw.githubusercontent.com/ApacheWang/inferdiff/main/assets/hero-demo.gif)

## Why `inferdiff`? (`HTTP 200 OK` != Your Stream Worked)

Standard uptime monitors and latency benchmarks only check HTTP status codes and wall-clock speed. In production, streaming LLM upgrades and third-party OpenAI-compatible relays routinely return `200 OK` while silently corrupting wire contracts:

| Who Gets Burned | What Breaks Silently Under `HTTP 200 OK` | Real-World Bug Anchors | How `inferdiff` Catches It |
| :--- | :--- | :--- | :--- |
| **Agent & App Engineers** | Tool-call JSON arguments are cut off mid-string by token budgets yet reported as `completed` / `stop`, reasoning tokens starve `content` to empty, or chunk splits emit `U+FFFD` replacement chars — sending agents into retry loops. | [`llama.cpp #30773`](https://github.com/ggml-org/llama.cpp/issues/30773), [`Ollama #17274`](https://github.com/ollama/ollama/issues/17274), [`vLLM #68324`](https://github.com/vllm-project/vllm/issues/68324) | Rules `D1`, `D2` & Canary `C1`, `C2`, `C6` validate strict JSON syntax trees, UTF-8 multibyte boundaries, and terminal state honesty. |
| **API Relay & Gateway Users** | Proxies buffer upstream non-streaming responses and dump them as a fake SSE burst, strip trailing `include_usage` chunks, undercount tool-schema tokens, strip initial `delta.role`, or route across mixed-quantization pools. | [`LiteLLM #5803`](https://github.com/BerriAI/litellm/issues/5803), [`LiteLLM #16112`](https://github.com/BerriAI/litellm/issues/16112), [`LiteLLM #24221`](https://github.com/BerriAI/litellm/issues/24221), [vLLM Streaming Usage](https://docs.vllm.ai/en/latest/serving/online_serving/derenderer/) | `inferdiff doctor --profile relay` runs low-budget canary probes (`C1–C8`) and grades wire health from `A+` to `F`. |
| **AI Infra & Perf Engineers** | Engine upgrades report massive throughput/TTFT jumps because fixed-length `ignore_eos` runs stopped at `8 / 8000` tokens, prefix caches leaked across runs, or empty handshake frames gamed first-frame timers. | [`SGLang #53119`](https://github.com/sgl-project/sglang/pull/53119), [`SGLang #50443`](https://github.com/sgl-project/sglang/issues/50443), [vLLM Benchmarking CLI](https://docs.vllm.ai/en/stable/benchmarking/cli/) | Separates empty handshake `ttff_ms` from real `ttft_effective_ms` and flags short-generation & cache-pollution illusions (`D3`, `D5`). |
| **OSS Contributors & Release CI** | SSE chunk boundaries shift between runs, making raw `curl` logs impossible to diff by eye — while noisy log dumps get closed upstream. | [rusefi LLM Policy](https://github.com/rusefi/rusefi/wiki/LLM-policy) | Normalizes chunk jitter, pins the **exact first divergent wire frame**, and exports an airgapped `<80 KiB` HTML waterfall or a `<=25`-line redacted `curl` reproducer. |

## Quickstart

Zero-install via [`uvx`](https://docs.astral.sh/uv/guides/tools/) directly from GitHub, or install locally with `pip` (Python 3.11+, zero runtime dependencies):

```bash
# 1. Zero-install live health check on a local engine (llama-server, vLLM, SGLang, Ollama)
uvx --from git+https://github.com/ApacheWang/inferdiff inferdiff \
  doctor http://127.0.0.1:8080/v1 --html doctor.html

# 2. Audit an OpenAI-compatible relay API + generate shareable single-file HTML scorecard
OPENAI_API_KEY=sk-... uvx --from git+https://github.com/ApacheWang/inferdiff inferdiff \
  doctor https://api.your-relay.example/v1 \
  --model qwen3-32b --profile relay --html relay-report.html

# 3. Or install once locally (or clone this repo to try bundled golden examples offline)
pip install git+https://github.com/ApacheWang/inferdiff

# Offline demo on bundled Case 1 (llama.cpp #30773, no GPU or server required)
inferdiff diff \
  examples/case1_responses_truncated_tool/baseline.trace.jsonl \
  examples/case1_responses_truncated_tool/target.trace.jsonl \
  --html case1-waterfall.html

inferdiff export \
  examples/case1_responses_truncated_tool/baseline.trace.jsonl \
  examples/case1_responses_truncated_tool/target.trace.jsonl \
  --format github-issue
```

> **Auth note**: If neither `--api-key` nor `-H "Authorization: ..."` is passed, `inferdiff doctor` falls back to `OPENAI_API_KEY` from the environment and sends it to the target URL (use `https://` for production keys). Reflected secrets are scrubbed from terminal output, saved traces, JSON, and HTML exports.

## Single-File Offline HTML Frame Waterfall

Every `diff --html`, `audit --html`, `doctor --html`, and `export --format html` command produces a self-contained, airgap-safe HTML5 + inline SVG report strictly under `80 KiB` with zero external CDN requests:

![inferdiff single-file HTML frame waterfall for llama.cpp #30773](https://raw.githubusercontent.com/ApacheWang/inferdiff/main/assets/case1-waterfall.png)

> GitHub Markdown strips interactive SVG scripts; download [`case1-waterfall.html` from the `v0.1.0` Release](https://github.com/ApacheWang/inferdiff/releases/tag/v0.1.0) to hover frame timings, toggle Absolute ms / Normalized %, and click any lane segment offline.

## Canary Probe Matrix (`inferdiff doctor`)

| Probe | Target Failure Mode | Profiles | Upstream Anchor |
| :--- | :--- | :--- | :--- |
| `C1` (P0) | Truncated tool-call JSON claiming `stop`/`completed` (plus `/v1/responses` cross-check in `full`) | `quick`, `full`, `relay` | [`llama.cpp #30773`](https://github.com/ggml-org/llama.cpp/issues/30773) |
| `C2` (P0) | Reasoning swallows budget -> empty visible output claiming `stop` | `full`, `relay` | [`Ollama #17274`](https://github.com/ollama/ollama/issues/17274) |
| `C3` (P1) | `ignore_eos=true` fixed-length budget mismatch (auto-`SKIP` on HTTP 400/422) | `full` | [`SGLang #53119`](https://github.com/sgl-project/sglang/pull/53119) |
| `C4` (P1) | Stripped trailing empty-`choices` `include_usage` chunk or omitted tool-schema tokens | `quick`, `full`, `relay` | [`LiteLLM #16112`](https://github.com/BerriAI/litellm/issues/16112), [`#28553`](https://github.com/BerriAI/litellm/issues/28553) |
| `C5` (P1/P0) | Missing initial `delta.role`, omitted/invalid raw indices, or parallel tool index collision | `quick`, `full`, `relay` | [`LiteLLM #24221`](https://github.com/BerriAI/litellm/issues/24221) |
| `C6` (P0) | Multi-byte UTF-8 / 4-byte emoji `U+FFFD` corruption or swallowed stream tail | `quick`, `full`, `relay` | [`vLLM #68324`](https://github.com/vllm-project/vllm/issues/68324), [`#47161`](https://github.com/vllm-project/vllm/issues/47161) |
| `C7` (P1) | Buffered non-streaming response dumped as a fake SSE burst | `quick`, `full`, `relay` | [`LiteLLM #5803`](https://github.com/BerriAI/litellm/issues/5803) |
| `C8` (P2) | Randomized-prefix same-seed heterogeneous backend pool drift (advisory) | `full`, `relay` | [vLLM Benchmarking CLI](https://docs.vllm.ai/en/stable/benchmarking/cli/) |

## Recording, Side-by-Side Comparison & Bundled Examples

```bash
# Record one request or a multi-line .jsonl suite (strict RFC 9112 framing + per-frame flush)
inferdiff record --url http://127.0.0.1:8080/v1/responses -d request.json -o target.trace.jsonl

# Compare two live endpoints sequentially with per-target scoped credentials
inferdiff compare \
  --before-url http://127.0.0.1:8080/v1/chat/completions \
  --after-url  http://127.0.0.1:8081/v1/chat/completions \
  --before-header "Authorization: Bearer $KEY_A" \
  --after-header  "Authorization: Bearer $KEY_B" \
  -d request.json --save-dir ./traces --html compare.html --fail-on p1

# Additional bundled golden examples
inferdiff diff examples/case2_ollama_ghost_thinking_tokens/baseline.trace.jsonl \
               examples/case2_ollama_ghost_thinking_tokens/target.trace.jsonl
inferdiff diff examples/case3_sglang_8_of_8000_short_gen/baseline.trace.jsonl \
               examples/case3_sglang_8_of_8000_short_gen/target.trace.jsonl --fail-on p1
```

## Wire Health Grades & Deterministic CI Exit Codes

- **Doctor grades**: `A+` (all executed probes pass with zero skips/warnings), `A` (zero P0/P1 issues, advisory P2 warning or inconclusive/skipped probe), `B` (1 P1 warning), `C` (2+ P1 warnings), `F` (any P0 silent protocol breach or transport/HTTP error).

| Exit Code | Constant | Meaning |
| :--- | :--- | :--- |
| `0` | `EXIT_OK` | Gate passed (`doctor` grades `A+` / `A` / `B` / `C` without `--strict`) |
| `1` | `EXIT_USAGE_OR_IO_ERROR` | CLI usage error, malformed trace schema, unreachable endpoint, or non-200 HTTP failure |
| `2` | `EXIT_SILENT_PROTOCOL_BREACH` | Confirmed P0 silent protocol breach (`D1`, `D2`, `D4`, or `doctor` P0 `FAIL`) |
| `3` | `EXIT_SEMANTIC_REGRESSION` | P1 regression (`D3`, `D5`, terminal drift, TTFT regression, `--fail-on any-diff`, or `doctor --strict` P1 warn) |

## Airgap-Safe HTML Waterfall & Privacy Defaults

- Single-file HTML5 + inline SVG reports use a hash-locked CSP (`default-src 'none'; style-src 'unsafe-inline'; script-src 'sha256-...'; img-src data:;`) with zero external scripts, fonts, or stylesheets, and adaptive folding to stay strictly under `80 KiB`.
- Shareable exports (`export --format github-issue|json|html`, `diff --html`, `audit --html`, `doctor --html`) omit arbitrary request bodies and raw wire payloads by default; pass `--include-body` or `--include-wire` to `export` only after reviewing your trace.

## Positioning: How `inferdiff` Complements Existing Tools

`inferdiff` is intentionally scoped as a **wire-level surgical knife** (`git diff` + protocol bill-checker for streaming frames), not an all-in-one evaluation or load-testing platform. Use it alongside — not instead of — established ecosystem tools:

| Tool Category | Great Open-Source Options | Use Them When You Need To... | Use `inferdiff` When You Need To... |
| :--- | :--- | :--- | :--- |
| **Semantic & Agent Evals** | [promptfoo](https://github.com/promptfoo/promptfoo) | Grade prompt accuracy, RAG faithfulness, or red-team safety across models after responses are assembled. | Catch **wire-level silent corruption** under `HTTP 200 OK` (truncated tool JSON, missing `arguments.done`, `U+FFFD` chunk-split leaks) before SDKs even finish assembling text. |
| **Load & Throughput Benchmarks** | [GuideLLM](https://github.com/vllm-project/guidellm), [LLMPerf](https://github.com/ray-project/llmperf) | Measure multi-concurrency QPS, latency percentiles, and capacity curves under sustained load. | Verify your benchmark isn't **measuring an illusion** (e.g., `8 / 8000` short generation on `ignore_eos`, empty handshake frames gaming TTFT, or unisolated prefix caches). |
| **Broad Engine & Relay Suites** | [ddalcu/llmprobe](https://github.com/ddalcu/llmprobe), [lmspeed-audit](https://github.com/nexmoe/lmspeed-audit) | Run comprehensive Node.js capability scorecards (GPQA/AIME evals, surface coverage, or provider fingerprinting) using built-in test banks. | Run a **zero-dep Python CLI** inside GPU containers to **record & frame-diff your own failing production payloads** across `openai-chat`, `openai-responses`, `sglang-native`, and `ollama-ndjson`, and export a `<=25`-line upstream GitHub Issue. |
| **Interactive Local Proxies** | [StreamLens](https://github.com/alexandrmotologa/streamlens), [ForkMind](https://github.com/Medhovarsh/forkmind) | Route local app traffic through a persistent reverse proxy and inspect conversations interactively in a Web UI. | Run **stateless CLI / CI regression gates** (`Exit 0/1/2/3`) and generate `<80 KiB` airgap-safe single-file HTML frame waterfalls without deploying a proxy. |

### Explicit Non-Goals

- **No LLM-as-a-Judge or capability leaderboards**: `inferdiff` never grades prose quality, math/coding intelligence, or jailbreak resistance. Every verdict is a deterministic function of raw wire bytes, JSON syntax trees, and monotonic frame timestamps.
- **No heavy runtime stack**: Core CLI and HTML/SVG waterfall rendering stay 100% Python 3.11+ standard library (`0` mandatory `pip` packages, `0` Node.js runtime, `0` external CDN requests).

## Roadmap (v0.2: Non-Intrusive KV & Storage Probes)

`inferdiff.trace.v1` and `inferdiff.probes.base.BackendProbe` already expose the three-point snapshot lifecycle (`T_pre -> T_ttft -> T_eof`) for optional v0.2 plugins (`LmcacheMpProbe`, `MooncakeStoreProbe`, `LinuxProcIoProbe`) and storage x inference rules `D6`–`D8`.

## License

MIT
