prefixwise 0.3.0__tar.gz → 0.3.1__tar.gz

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.
Files changed (63) hide show
  1. prefixwise-0.3.1/CHANGELOG.md +51 -0
  2. {prefixwise-0.3.0 → prefixwise-0.3.1}/PKG-INFO +21 -7
  3. {prefixwise-0.3.0 → prefixwise-0.3.1}/README.md +20 -6
  4. prefixwise-0.3.1/benchmarks/README.md +35 -0
  5. {prefixwise-0.3.0 → prefixwise-0.3.1}/docs/USE_CASES.md +2 -2
  6. prefixwise-0.3.1/experiments/dogfood/2026-11-07-opencode-2.md +26 -0
  7. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_hosted/e1_hosted.py +16 -8
  8. prefixwise-0.3.1/experiments/e1_hosted/runs/2026-11-07-anthropic-lanes.md +23 -0
  9. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_open/e1_open.py +30 -18
  10. prefixwise-0.3.1/experiments/e1_open/runs/2026-11-07-lanes.md +25 -0
  11. {prefixwise-0.3.0 → prefixwise-0.3.1}/pyproject.toml +1 -1
  12. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/__init__.py +1 -1
  13. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/classifier.py +7 -0
  14. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/cli.py +42 -3
  15. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/explain.py +5 -1
  16. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/fingerprint.py +25 -3
  17. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/ledger.py +22 -4
  18. prefixwise-0.3.1/src/prefixwise/prices.json +92 -0
  19. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/pricing.py +19 -10
  20. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/proxy.py +129 -9
  21. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_classifier.py +16 -0
  22. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_cli.py +17 -0
  23. prefixwise-0.3.1/tests/test_lanes.py +67 -0
  24. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_pricing.py +28 -4
  25. prefixwise-0.3.1/tests/test_production.py +220 -0
  26. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_proxy.py +3 -2
  27. prefixwise-0.3.0/CHANGELOG.md +0 -31
  28. prefixwise-0.3.0/src/prefixwise/prices.json +0 -61
  29. {prefixwise-0.3.0 → prefixwise-0.3.1}/.gitignore +0 -0
  30. {prefixwise-0.3.0 → prefixwise-0.3.1}/LICENSE +0 -0
  31. {prefixwise-0.3.0 → prefixwise-0.3.1}/SECURITY.md +0 -0
  32. {prefixwise-0.3.0 → prefixwise-0.3.1}/examples/openai_agent.py +0 -0
  33. {prefixwise-0.3.0 → prefixwise-0.3.1}/examples/session.jsonl +0 -0
  34. {prefixwise-0.3.0 → prefixwise-0.3.1}/examples/turn1.json +0 -0
  35. {prefixwise-0.3.0 → prefixwise-0.3.1}/examples/turn2.json +0 -0
  36. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/dogfood/2026-11-06-opencode.md +0 -0
  37. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_hosted/README.md +0 -0
  38. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_hosted/runs/2026-11-06-anthropic-claude-haiku-5-5.md +0 -0
  39. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_hosted/runs/2026-11-06-openai-probes-round3.md +0 -0
  40. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_hosted/runs/2026-11-06-probes.md +0 -0
  41. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_hosted/runs/2026-11-06-round4.md +0 -0
  42. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_open/README.md +0 -0
  43. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_open/colab_e1_open.ipynb +0 -0
  44. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_open/runs/2026-11-06-colab-l4-qwen3-4b.json +0 -0
  45. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_open/runs/2026-11-06-colab-l4-qwen3-4b.md +0 -0
  46. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e1_open/vllm_server.sh +0 -0
  47. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e4/README.md +0 -0
  48. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e4/e4.py +0 -0
  49. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e4/runs/2026-11-06-live.md +0 -0
  50. {prefixwise-0.3.0 → prefixwise-0.3.1}/experiments/e4/sessions/tool-order-drift.jsonl +0 -0
  51. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/__main__.py +0 -0
  52. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/diagnostics.py +0 -0
  53. {prefixwise-0.3.0 → prefixwise-0.3.1}/src/prefixwise/fixes.py +0 -0
  54. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_diagnostics.py +0 -0
  55. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_e1_hosted.py +0 -0
  56. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_e1_open.py +0 -0
  57. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_e4.py +0 -0
  58. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_examples.py +0 -0
  59. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_fingerprint.py +0 -0
  60. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_fixes.py +0 -0
  61. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_ledger.py +0 -0
  62. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_routing.py +0 -0
  63. {prefixwise-0.3.0 → prefixwise-0.3.1}/tests/test_security.py +0 -0
@@ -0,0 +1,51 @@
1
+ # Changelog
2
+
3
+ ## 0.3.1: 2026-11-07
4
+
5
+ Production hardening, found by a new benchmark; per-model lanes; OpenAI prices.
6
+ **Upgrading:** existing ledgers are migrated in place on first start. Rows written before
7
+ 0.3.1 have no timestamp, so `prefixwise prune` keeps them unless you add `--include-undated`.
8
+
9
+ - **Production benchmark** (`benchmarks/bench.py`): added latency, throughput, memory, a soak and 13 failure cases, against the real `prefixwise serve` and a fake upstream. Results in `benchmarks/runs/`; README "Running in production" summarises them. CI runs the failure cases on every push.
10
+ - **3-4x lower overhead on long prompts:** masked block hashes are cached, since an agent resends the same prefix every turn. A 120k-token request went from +50 ms to +13 ms (p50).
11
+ - **Fails open:** a ledger write or classifier failure no longer turns a paid upstream response into a 500 (or, mid-stream, appends an error to the stream). The response passes through with `X-Prefixwise-Error: not recorded`.
12
+ - **Upstream headers relayed:** `retry-after`, `retry-after-ms`, `x-should-retry`, rate-limit headers and the provider's request id now reach the client, on success, errors and streams. They were dropped, so SDKs could not honour the provider's backoff.
13
+ - **Idle connections are closed** after `PREFIXWISE_CLIENT_TIMEOUT` (120 s). Before, 300 idle sockets held 300 threads forever.
14
+ - **Graceful shutdown:** SIGTERM drains in-flight requests and streams (up to `PREFIXWISE_DRAIN_SECONDS`, 8 s) and exits 0. In Docker the proxy is PID 1, where an unhandled SIGTERM was ignored and `docker stop` killed it mid-stream after 10 s.
15
+ - **Ledger retention:** entries record when they were written; `prefixwise prune --older-than 30d` deletes old ones.
16
+ - **Per-model lanes within a session.** Each request is compared with the last request to the same model, so small-model side calls no longer mask causes on the main thread. Found by dogfooding opencode, which interleaves Haiku calls with Sonnet. A first call to a new model is still `model_switch`; switching back to a model whose prefix is still cached is a hit. Provider diagnostics chain to the same model's last response.
17
+ - **Replacing a one-shot request is not a history edit:** a single-message request followed by a different one (side calls) is judged on its shared-prefix cache reuse.
18
+ - **E1-open harness fix:** Session B turns 8–10 now keep the compacted history. They had reverted to the pre-compaction history, hidden by the model switch until lanes exposed it.
19
+ - **CLI:** `prefixwise report | head` exits quietly.
20
+ - **OpenAI prices:** GPT-5.6 Luna, Terra and Sol are priced from OpenAI's own pricing page (read 2026-11-07; standard speed, short context). The cache-write column is OpenAI's 30-minute write; the 12-hour rate is recorded but not applied. Sol's price is promotional and expires after 2026-11-30, after which it shows `-` until updated. Plain `gpt-5.6` has no published row and stays unpriced.
21
+ - **Price matching is stricter:** a table id matches only itself plus a dated snapshot or cloud version suffix, so `gpt-5.6-sol-pro` no longer borrows Sol's price.
22
+
23
+ ## 0.3.0: 2026-11-07
24
+
25
+ - **Fixes the proxy can apply:** `prefixwise serve --fix canonical_tools` sorts tools so a drifting tool list stops breaking the cache. It is opt-in and reversible, and the ledger records which requests it rewrote.
26
+ - **`prefixwise fixes`:** ranks fixes by the tokens your own ledger says they would save.
27
+ - **Found by dogfooding (opencode):** `/messages`-style paths without `/v1` are accepted. Query strings are forwarded. Endpoints Prefixwise does not analyse (`/v1/models`, `count_tokens`, ...) pass through unrecorded. `HEAD` is answered. Sonnet 4.6 is priced.
28
+ - **Dollar costs:** every request is priced from a dated price table. Built in: Claude Haiku, Sonnet and Opus 5.5 and Fable 5.1, verified from Anthropic's pricing page on 2026-11-06, including Haiku's over-100k tier and 1-hour cache writes. Add your own with `PREFIXWISE_PRICES`. `report` shows cost, avoidable cost and cost per successful task; `fixes` shows savings in dollars; `prefixwise prices` shows the table. Unknown rates stay empty, never estimated.
29
+ - **E4 harness** (`experiments/e4`): replays recorded sessions with a fix off and on, and measures predicted vs. realised savings and task success. **`canonical_tools` is proven:** 99.9% (Anthropic) and 97.5% (vLLM) of predicted savings realised, with task success flat. `prefixwise fixes` shows the evidence.
30
+ - **E1-hosted:** on Anthropic, Prefixwise agreed with Anthropic's own miss diagnosis on 37 of 37 misses. OpenAI's diagnostics returned `unavailable` (recorded as an open question).
31
+ - **Fixed:** the moving Anthropic `cache_control` breakpoint, and string vs. text-block content, were both misread as `history_edit`.
32
+ - **Fixed:** Anthropic's real diagnostics shape (`diagnostics.cache_miss_reason`) is now read.
33
+ - **Fixed:** a request with no usage is now `unknown`, not `below_min_prefix`.
34
+ - **Security:**
35
+ - `PREFIXWISE_AUTH_TOKEN`, and the proxy refuses to expose an API key without one
36
+ - input validation and body limits
37
+ - the ledger file is owner-only
38
+ - `SECURITY.md`
39
+
40
+ ## 0.2.0: 2026-11-06
41
+
42
+ - **CLI:** `prefixwise serve | report | task | request | explain`.
43
+ - **Proxy:** a drop-in pass-through for OpenAI chat completions, the Responses API and Anthropic messages, streaming included. Verdicts come back in `X-Prefixwise-*` headers.
44
+ - **Tokens per successful task:** measured per task, not per request, with a `/tasks` endpoint.
45
+ - **Causes:** tool-result, TTL and fork causes now fire, and the timing rules no longer guess.
46
+ - **E1-open** passed live on vLLM: 120 turns, 100%.
47
+ - Docker image and CI on Python 3.11 to 3.13.
48
+
49
+ ## 0.1.0: 2026-11-05
50
+
51
+ - First version: fingerprinting, the 19-cause classifier, the ledger and the proxy.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: prefixwise
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: Name why your LLM prompt cache missed, price the miss, and measure tokens per successful task. A local proxy and CLI for OpenAI, Anthropic and vLLM.
5
5
  Project-URL: Homepage, https://github.com/tejachavali/prefixwise
6
6
  Project-URL: Issues, https://github.com/tejachavali/prefixwise/issues
@@ -53,7 +53,7 @@ none 790 5,925,000 84.0% 0 0
53
53
  ## Quickstart
54
54
 
55
55
  ```bash
56
- pip install "git+https://github.com/tejachavali/prefixwise"
56
+ pip install prefixwise
57
57
  prefixwise serve --mock # no API key, synthetic responses; try it first
58
58
  ```
59
59
 
@@ -89,7 +89,7 @@ docker build -t prefixwise . && docker run -p 127.0.0.1:8080:8080 -v pw:/data pr
89
89
 
90
90
  ## What it tells you
91
91
 
92
- One cause per request: the first thing, in prefix order, that broke reuse. Waste is avoidable; legitimate changes cost tokens but are not waste.
92
+ One cause per request: the first thing, in prefix order, that broke reuse. Each request is compared with the previous request **to the same model** in its session, so an agent's small-model side calls (titles, summaries) never mask what is happening on its main thread. Waste is avoidable; legitimate changes cost tokens but are not waste.
93
93
 
94
94
  | Cause | Meaning | Waste? | Typical fix |
95
95
  |---|---|---|---|
@@ -103,7 +103,7 @@ One cause per request: the first thing, in prefix order, that broke reuse. Waste
103
103
  | `tool_result_mutation` | An earlier tool result was re-rendered or removed | **yes** | Freeze tool output once sent |
104
104
  | `compaction_rewrite` | Context was compacted (send `X-Prefixwise-Compaction-Event: 1`) | no | Compact at task boundaries, not per turn |
105
105
  | `param_rendered` | Blocks equal, but tool_choice / thinking / reasoning / format changed | depends | Keep those params stable within a session |
106
- | `model_switch` | Different model than the previous turn | no | - |
106
+ | `model_switch` | First call to a different model in the session | no | - |
107
107
  | `retry_replay` | Identical request within 60 s with nothing cached | **yes** | Check retry logic |
108
108
  | `breakpoint_misplaced` | Anthropic: no `cache_control` breakpoint | **yes** | Add `cache_control` after the stable prefix |
109
109
  | `below_min_prefix` | Prompt below the provider's minimum cacheable length | depends | - |
@@ -123,6 +123,7 @@ Avoidable tokens for a waste turn = the part of the previous turn's prompt that
123
123
  |---|---|
124
124
  | `prefixwise serve [--upstream URL] [--mock] [--fix canonical_tools] [--host H] [--port P] [--ledger FILE]` | Run the proxy. Ledger defaults to `./prefixwise.db`. `--fix` applies an opt-in, reversible rewrite to every request (see below). |
125
125
  | `prefixwise prices [--json]` | The dated price table behind dollar costs, and where each rate came from. |
126
+ | `prefixwise prune --older-than 30d` | Delete ledger entries older than that (retention). Add `--include-undated` to also drop rows written before 0.3.1. |
126
127
  | `prefixwise fixes [--json]` | The fixes that would save the most, ranked by the avoidable tokens your own ledger attributes to each cause. |
127
128
  | `prefixwise report [--by cause\|session_id\|agent_id\|model\|provider\|task_id] [--json]` | Totals and a breakdown, most avoidable first. |
128
129
  | `prefixwise task ID --success\|--failure` | Record a task outcome (safe while the proxy runs). |
@@ -144,9 +145,9 @@ Avoidable tokens for a waste turn = the part of the previous turn's prompt that
144
145
 
145
146
  **Response headers:** `X-Prefixwise-Request-Id` always; `X-Prefixwise-Cause`, `X-Prefixwise-Legit`, `X-Prefixwise-Avoidable-Tokens` on non-streaming responses; `X-Prefixwise-Fixes` when a fix rewrote the request. Streamed requests are classified when the stream ends: read them from `GET /requests/<id>`.
146
147
 
147
- **Environment:** `PREFIXWISE_UPSTREAM_URL`, `PREFIXWISE_API_KEY` (overrides client auth; `x-api-key` for Anthropic), `PREFIXWISE_LEDGER_PATH`, `PREFIXWISE_HMAC_KEY` (HMAC short blocks so their hashes cannot be dictionary-guessed), `PREFIXWISE_MAX_SESSIONS` (default 10,000), `PREFIXWISE_FIXES` (e.g. `canonical_tools`), `PREFIXWISE_AUTH_TOKEN` (require `X-Prefixwise-Token`), `PREFIXWISE_MAX_BODY_BYTES`, `PREFIXWISE_PRICES` (your own rates file), `PORT`.
148
+ **Environment:** `PREFIXWISE_UPSTREAM_URL`, `PREFIXWISE_API_KEY` (overrides client auth; `x-api-key` for Anthropic), `PREFIXWISE_LEDGER_PATH`, `PREFIXWISE_HMAC_KEY` (HMAC short blocks so their hashes cannot be dictionary-guessed), `PREFIXWISE_MAX_SESSIONS` (default 10,000), `PREFIXWISE_FIXES` (e.g. `canonical_tools`), `PREFIXWISE_AUTH_TOKEN` (require `X-Prefixwise-Token`), `PREFIXWISE_MAX_BODY_BYTES`, `PREFIXWISE_PRICES` (your own rates file), `PREFIXWISE_CLIENT_TIMEOUT` (default 120 s), `PREFIXWISE_DRAIN_SECONDS` (default 8), `PORT`.
148
149
 
149
- **Dollar costs.** Each request is priced from the provider's own usage breakdown (uncached input, cache reads, cache writes by TTL, output), using a dated price table: `prefixwise prices` shows it. *Avoidable cost* is the avoidable tokens times (input price − cache-read price): what they would have cost as cache hits. A model with no rates shows `-`, never an estimate. To add OpenAI models or your negotiated rates, write a JSON file in the same format (`prefixwise prices --json` prints one) and set `PREFIXWISE_PRICES=/path/prices.json`. Your entries override the built-in ones. `prefixwise report` and `prefixwise fixes` then show dollars, and say how many requests were priced.
150
+ **Dollar costs.** Each request is priced from the provider's own usage breakdown (uncached input, cache reads, cache writes by TTL, output), using a dated price table: `prefixwise prices` shows it. *Avoidable cost* is the avoidable tokens times (input price − cache-read price): what they would have cost as cache hits. A model with no rates shows `-`, never an estimate. To add other models or your negotiated rates, write a JSON file in the same format (`prefixwise prices --json` prints one) and set `PREFIXWISE_PRICES=/path/prices.json`. Your entries override the built-in ones. `prefixwise report` and `prefixwise fixes` then show dollars, and say how many requests were priced.
150
151
 
151
152
  **Fixes the proxy can apply.** `canonical_tools` sorts tools by name and sorts each tool's keys before forwarding, so a tool list that drifts between turns (plugin reload, dict rebuild) stops breaking the cache. It is off by default; with it off, requests pass through unchanged. Prefixwise classifies the request the provider actually received. Fixes that would change what the model reads, like moving a timestamp out of the system prompt, are advice only: `prefixwise fixes` lists them. `canonical_tools` is **proven**: in [E4](experiments/e4/runs/2026-11-06-live.md), turning it on realised 99.9% (Anthropic Haiku 5.5) and 97.5% (vLLM Qwen3-4B) of the savings Prefixwise predicted, with task success flat.
152
153
 
@@ -159,6 +160,19 @@ Avoidable tokens for a waste turn = the part of the previous turn's prompt that
159
160
 
160
161
  Found a vulnerability? See [SECURITY.md](SECURITY.md).
161
162
 
163
+ ## Running in production
164
+
165
+ Measured by [`benchmarks/bench.py`](benchmarks/README.md) (results in [`benchmarks/runs/`](benchmarks/runs/)); rerun it on your own hardware.
166
+
167
+ - **Added latency:** about 3 ms per request at a 2k-token prompt, 6 ms at 30k, 13 ms at 120k (p50; p95 under 22 ms). Streaming adds the same to time to first byte. A model call takes seconds, so this is well under 1%.
168
+ - **Capacity:** one proxy process handles about 185 requests/s of agent-sized traffic before CPU-bound, with no errors up to 128 concurrent clients. An agent sends roughly one request every few seconds, so one process serves hundreds of agents at once. Session state lives in the process: to run several, route each session to the same instance (e.g. hash `X-Prefixwise-Session-Id`).
169
+ - **Memory:** about 11 KB per tracked session, capped by `PREFIXWISE_MAX_SESSIONS` (default 10,000: roughly 100-150 MB), plus a bounded cache of block hashes (about 8 MB). In a 15-minute soak (148,000 requests, 0 errors) RSS went 60 to 74 MB; Python-level memory is flat once the caches fill (tracemalloc: 16.2 MB at both 2,400 and 4,800 sessions), so the remainder is the allocator keeping freed request buffers.
170
+ - **It fails open.** If the ledger cannot be written (disk full, locked) or classification fails, the client still gets the upstream response, with `X-Prefixwise-Error: not recorded`; the proxy logs why to stderr. Upstream errors (429, 500, ...) reach the client unchanged, with `retry-after`, `x-should-retry`, rate-limit headers and the provider's request id, so SDK retries behave as without the proxy. An unreachable or broken upstream is a 502.
171
+ - **Timeouts:** a client connection idle for `PREFIXWISE_CLIENT_TIMEOUT` seconds (default 120) is closed, so idle or half-sent connections cannot pin threads. Upstream calls time out after 600 s (long generations stream for minutes).
172
+ - **Shutdown:** on SIGTERM (`docker stop`, systemd, Kubernetes) the proxy stops accepting connections, lets in-flight requests and streams finish for up to `PREFIXWISE_DRAIN_SECONDS` (default 8), then exits 0.
173
+ - **Ledger growth and retention:** about 450 bytes per request (a million requests is about 450 MB); `prefixwise report` takes about 2 s at a million rows. Delete old rows with `prefixwise prune --older-than 30d`, e.g. from a daily cron. Back it up while the proxy runs with `sqlite3 prefixwise.db ".backup backup.db"`.
174
+ - **Not built yet:** shared session state across processes, a metrics endpoint, and request logging (the proxy logs only errors).
175
+
162
176
  ## Limits
163
177
 
164
178
  - **What has been verified live (2026-11-06):**
@@ -173,7 +187,7 @@ Found a vulnerability? See [SECURITY.md](SECURITY.md).
173
187
  - One proxy process keeps session state in memory: run one instance per agent fleet, or send all of a session's turns to the same instance.
174
188
  - `evicted` needs vLLM KV events, which the proxy does not consume yet.
175
189
  - OpenAI's default in-memory cache TTL is not a fixed number, so after a long gap a cold OpenAI cache is `unknown` unless you send `X-Prefixwise-Cache-Ttl`.
176
- - **Dollar costs:** only models in the dated price table are priced: Claude Haiku, Sonnet and Opus 5.5, Fable 5.1 and Sonnet 4.6, read from Anthropic's pricing page (2026-11-06/07). Everything else, OpenAI included, shows `-` until you add rates with `PREFIXWISE_PRICES`. Batch, fast-mode and data-residency multipliers are not modelled.
190
+ - **Dollar costs:** only models in the dated price table are priced: Claude Haiku, Sonnet and Opus 5.5, Fable 5.1 and Sonnet 4.6 (Anthropic's pricing page, 2026-11-06/07), and OpenAI GPT-5.6 Luna, Terra and Sol (OpenAI's pricing page, 2026-11-07; Sol's promotional price expires after 2026-11-30). Everything else shows `-` until you add rates with `PREFIXWISE_PRICES`. OpenAI cache writes are priced at the 30-minute rate. Batch, fast-mode and data-residency multipliers are not modelled.
177
191
 
178
192
  ## Working on Prefixwise
179
193
 
@@ -29,7 +29,7 @@ none 790 5,925,000 84.0% 0 0
29
29
  ## Quickstart
30
30
 
31
31
  ```bash
32
- pip install "git+https://github.com/tejachavali/prefixwise"
32
+ pip install prefixwise
33
33
  prefixwise serve --mock # no API key, synthetic responses; try it first
34
34
  ```
35
35
 
@@ -65,7 +65,7 @@ docker build -t prefixwise . && docker run -p 127.0.0.1:8080:8080 -v pw:/data pr
65
65
 
66
66
  ## What it tells you
67
67
 
68
- One cause per request: the first thing, in prefix order, that broke reuse. Waste is avoidable; legitimate changes cost tokens but are not waste.
68
+ One cause per request: the first thing, in prefix order, that broke reuse. Each request is compared with the previous request **to the same model** in its session, so an agent's small-model side calls (titles, summaries) never mask what is happening on its main thread. Waste is avoidable; legitimate changes cost tokens but are not waste.
69
69
 
70
70
  | Cause | Meaning | Waste? | Typical fix |
71
71
  |---|---|---|---|
@@ -79,7 +79,7 @@ One cause per request: the first thing, in prefix order, that broke reuse. Waste
79
79
  | `tool_result_mutation` | An earlier tool result was re-rendered or removed | **yes** | Freeze tool output once sent |
80
80
  | `compaction_rewrite` | Context was compacted (send `X-Prefixwise-Compaction-Event: 1`) | no | Compact at task boundaries, not per turn |
81
81
  | `param_rendered` | Blocks equal, but tool_choice / thinking / reasoning / format changed | depends | Keep those params stable within a session |
82
- | `model_switch` | Different model than the previous turn | no | - |
82
+ | `model_switch` | First call to a different model in the session | no | - |
83
83
  | `retry_replay` | Identical request within 60 s with nothing cached | **yes** | Check retry logic |
84
84
  | `breakpoint_misplaced` | Anthropic: no `cache_control` breakpoint | **yes** | Add `cache_control` after the stable prefix |
85
85
  | `below_min_prefix` | Prompt below the provider's minimum cacheable length | depends | - |
@@ -99,6 +99,7 @@ Avoidable tokens for a waste turn = the part of the previous turn's prompt that
99
99
  |---|---|
100
100
  | `prefixwise serve [--upstream URL] [--mock] [--fix canonical_tools] [--host H] [--port P] [--ledger FILE]` | Run the proxy. Ledger defaults to `./prefixwise.db`. `--fix` applies an opt-in, reversible rewrite to every request (see below). |
101
101
  | `prefixwise prices [--json]` | The dated price table behind dollar costs, and where each rate came from. |
102
+ | `prefixwise prune --older-than 30d` | Delete ledger entries older than that (retention). Add `--include-undated` to also drop rows written before 0.3.1. |
102
103
  | `prefixwise fixes [--json]` | The fixes that would save the most, ranked by the avoidable tokens your own ledger attributes to each cause. |
103
104
  | `prefixwise report [--by cause\|session_id\|agent_id\|model\|provider\|task_id] [--json]` | Totals and a breakdown, most avoidable first. |
104
105
  | `prefixwise task ID --success\|--failure` | Record a task outcome (safe while the proxy runs). |
@@ -120,9 +121,9 @@ Avoidable tokens for a waste turn = the part of the previous turn's prompt that
120
121
 
121
122
  **Response headers:** `X-Prefixwise-Request-Id` always; `X-Prefixwise-Cause`, `X-Prefixwise-Legit`, `X-Prefixwise-Avoidable-Tokens` on non-streaming responses; `X-Prefixwise-Fixes` when a fix rewrote the request. Streamed requests are classified when the stream ends: read them from `GET /requests/<id>`.
122
123
 
123
- **Environment:** `PREFIXWISE_UPSTREAM_URL`, `PREFIXWISE_API_KEY` (overrides client auth; `x-api-key` for Anthropic), `PREFIXWISE_LEDGER_PATH`, `PREFIXWISE_HMAC_KEY` (HMAC short blocks so their hashes cannot be dictionary-guessed), `PREFIXWISE_MAX_SESSIONS` (default 10,000), `PREFIXWISE_FIXES` (e.g. `canonical_tools`), `PREFIXWISE_AUTH_TOKEN` (require `X-Prefixwise-Token`), `PREFIXWISE_MAX_BODY_BYTES`, `PREFIXWISE_PRICES` (your own rates file), `PORT`.
124
+ **Environment:** `PREFIXWISE_UPSTREAM_URL`, `PREFIXWISE_API_KEY` (overrides client auth; `x-api-key` for Anthropic), `PREFIXWISE_LEDGER_PATH`, `PREFIXWISE_HMAC_KEY` (HMAC short blocks so their hashes cannot be dictionary-guessed), `PREFIXWISE_MAX_SESSIONS` (default 10,000), `PREFIXWISE_FIXES` (e.g. `canonical_tools`), `PREFIXWISE_AUTH_TOKEN` (require `X-Prefixwise-Token`), `PREFIXWISE_MAX_BODY_BYTES`, `PREFIXWISE_PRICES` (your own rates file), `PREFIXWISE_CLIENT_TIMEOUT` (default 120 s), `PREFIXWISE_DRAIN_SECONDS` (default 8), `PORT`.
124
125
 
125
- **Dollar costs.** Each request is priced from the provider's own usage breakdown (uncached input, cache reads, cache writes by TTL, output), using a dated price table: `prefixwise prices` shows it. *Avoidable cost* is the avoidable tokens times (input price − cache-read price): what they would have cost as cache hits. A model with no rates shows `-`, never an estimate. To add OpenAI models or your negotiated rates, write a JSON file in the same format (`prefixwise prices --json` prints one) and set `PREFIXWISE_PRICES=/path/prices.json`. Your entries override the built-in ones. `prefixwise report` and `prefixwise fixes` then show dollars, and say how many requests were priced.
126
+ **Dollar costs.** Each request is priced from the provider's own usage breakdown (uncached input, cache reads, cache writes by TTL, output), using a dated price table: `prefixwise prices` shows it. *Avoidable cost* is the avoidable tokens times (input price − cache-read price): what they would have cost as cache hits. A model with no rates shows `-`, never an estimate. To add other models or your negotiated rates, write a JSON file in the same format (`prefixwise prices --json` prints one) and set `PREFIXWISE_PRICES=/path/prices.json`. Your entries override the built-in ones. `prefixwise report` and `prefixwise fixes` then show dollars, and say how many requests were priced.
126
127
 
127
128
  **Fixes the proxy can apply.** `canonical_tools` sorts tools by name and sorts each tool's keys before forwarding, so a tool list that drifts between turns (plugin reload, dict rebuild) stops breaking the cache. It is off by default; with it off, requests pass through unchanged. Prefixwise classifies the request the provider actually received. Fixes that would change what the model reads, like moving a timestamp out of the system prompt, are advice only: `prefixwise fixes` lists them. `canonical_tools` is **proven**: in [E4](experiments/e4/runs/2026-11-06-live.md), turning it on realised 99.9% (Anthropic Haiku 5.5) and 97.5% (vLLM Qwen3-4B) of the savings Prefixwise predicted, with task success flat.
128
129
 
@@ -135,6 +136,19 @@ Avoidable tokens for a waste turn = the part of the previous turn's prompt that
135
136
 
136
137
  Found a vulnerability? See [SECURITY.md](SECURITY.md).
137
138
 
139
+ ## Running in production
140
+
141
+ Measured by [`benchmarks/bench.py`](benchmarks/README.md) (results in [`benchmarks/runs/`](benchmarks/runs/)); rerun it on your own hardware.
142
+
143
+ - **Added latency:** about 3 ms per request at a 2k-token prompt, 6 ms at 30k, 13 ms at 120k (p50; p95 under 22 ms). Streaming adds the same to time to first byte. A model call takes seconds, so this is well under 1%.
144
+ - **Capacity:** one proxy process handles about 185 requests/s of agent-sized traffic before CPU-bound, with no errors up to 128 concurrent clients. An agent sends roughly one request every few seconds, so one process serves hundreds of agents at once. Session state lives in the process: to run several, route each session to the same instance (e.g. hash `X-Prefixwise-Session-Id`).
145
+ - **Memory:** about 11 KB per tracked session, capped by `PREFIXWISE_MAX_SESSIONS` (default 10,000: roughly 100-150 MB), plus a bounded cache of block hashes (about 8 MB). In a 15-minute soak (148,000 requests, 0 errors) RSS went 60 to 74 MB; Python-level memory is flat once the caches fill (tracemalloc: 16.2 MB at both 2,400 and 4,800 sessions), so the remainder is the allocator keeping freed request buffers.
146
+ - **It fails open.** If the ledger cannot be written (disk full, locked) or classification fails, the client still gets the upstream response, with `X-Prefixwise-Error: not recorded`; the proxy logs why to stderr. Upstream errors (429, 500, ...) reach the client unchanged, with `retry-after`, `x-should-retry`, rate-limit headers and the provider's request id, so SDK retries behave as without the proxy. An unreachable or broken upstream is a 502.
147
+ - **Timeouts:** a client connection idle for `PREFIXWISE_CLIENT_TIMEOUT` seconds (default 120) is closed, so idle or half-sent connections cannot pin threads. Upstream calls time out after 600 s (long generations stream for minutes).
148
+ - **Shutdown:** on SIGTERM (`docker stop`, systemd, Kubernetes) the proxy stops accepting connections, lets in-flight requests and streams finish for up to `PREFIXWISE_DRAIN_SECONDS` (default 8), then exits 0.
149
+ - **Ledger growth and retention:** about 450 bytes per request (a million requests is about 450 MB); `prefixwise report` takes about 2 s at a million rows. Delete old rows with `prefixwise prune --older-than 30d`, e.g. from a daily cron. Back it up while the proxy runs with `sqlite3 prefixwise.db ".backup backup.db"`.
150
+ - **Not built yet:** shared session state across processes, a metrics endpoint, and request logging (the proxy logs only errors).
151
+
138
152
  ## Limits
139
153
 
140
154
  - **What has been verified live (2026-11-06):**
@@ -149,7 +163,7 @@ Found a vulnerability? See [SECURITY.md](SECURITY.md).
149
163
  - One proxy process keeps session state in memory: run one instance per agent fleet, or send all of a session's turns to the same instance.
150
164
  - `evicted` needs vLLM KV events, which the proxy does not consume yet.
151
165
  - OpenAI's default in-memory cache TTL is not a fixed number, so after a long gap a cold OpenAI cache is `unknown` unless you send `X-Prefixwise-Cache-Ttl`.
152
- - **Dollar costs:** only models in the dated price table are priced: Claude Haiku, Sonnet and Opus 5.5, Fable 5.1 and Sonnet 4.6, read from Anthropic's pricing page (2026-11-06/07). Everything else, OpenAI included, shows `-` until you add rates with `PREFIXWISE_PRICES`. Batch, fast-mode and data-residency multipliers are not modelled.
166
+ - **Dollar costs:** only models in the dated price table are priced: Claude Haiku, Sonnet and Opus 5.5, Fable 5.1 and Sonnet 4.6 (Anthropic's pricing page, 2026-11-06/07), and OpenAI GPT-5.6 Luna, Terra and Sol (OpenAI's pricing page, 2026-11-07; Sol's promotional price expires after 2026-11-30). Everything else shows `-` until you add rates with `PREFIXWISE_PRICES`. OpenAI cache writes are priced at the 30-minute rate. Batch, fast-mode and data-residency multipliers are not modelled.
153
167
 
154
168
  ## Working on Prefixwise
155
169
 
@@ -0,0 +1,35 @@
1
+ # Benchmarks
2
+
3
+ `bench.py` measures what Prefixwise costs you in production: added latency,
4
+ throughput, memory, behaviour over time, and what happens when things break.
5
+ No API keys and no network: the real `prefixwise serve` runs as its own process
6
+ in front of a fake model API (`upstream.py`, a third process), with an on-disk
7
+ ledger, and is driven with realistic agent sessions: a long system prompt and
8
+ eight tools, then one turn (user message, assistant reply) appended per request.
9
+
10
+ ```bash
11
+ python benchmarks/bench.py --quick # ~3 minutes
12
+ python benchmarks/bench.py # ~10 minutes
13
+ python benchmarks/bench.py --soak 1800 # with a 30-minute soak
14
+ python benchmarks/bench.py --only faults # one part
15
+ ```
16
+
17
+ It writes `benchmarks/runs/<date>-<host>.md` (tables) and `.json` (every
18
+ sample), and exits non-zero if any request errored or any fault case failed.
19
+ CI runs the fault suite on every push.
20
+
21
+ | part | what it measures | pass means |
22
+ |---|---|---|
23
+ | overhead | proxy latency minus direct latency to the same upstream, same request, at 2k, 30k and 120k-token prompts, streaming and not, OpenAI and Anthropic shapes; also time to first byte | small next to model latency |
24
+ | throughput | requests/s and p50/p99 at concurrency 1-128, with an instant upstream (the proxy's own ceiling) and a 300 ms one | 0 errors, every request in the ledger |
25
+ | memory | RSS over 6,000 sessions, with the default session cap and a cap of 1,000 | RSS plateaus at the cap |
26
+ | soak | mixed traffic for a fixed time: both providers, a third streamed, sessions of 5-25 turns, task outcomes posted; RSS, threads and fds sampled | 0 errors, RSS flat once warm, no thread or fd growth |
27
+ | faults | upstream 500 / 429 / dropped connection / HTML body / no usage / slow / drop mid-stream; client invalid JSON / non-object / oversize / disconnect mid-stream / 300 idle or half-sent sockets | the right status, and the proxy healthy after each |
28
+
29
+ What it does not measure: real provider latency (the overhead is additive, so
30
+ it carries over), or the classifier's accuracy. Accuracy is E1:
31
+ `experiments/e1_open` (vLLM, injected causes) and `experiments/e1_hosted`
32
+ (agreement with Anthropic's own diagnostics).
33
+
34
+ Results are machine-dependent; the fake upstream and the load generator share
35
+ the CPUs with the proxy, so throughput figures are a floor.
@@ -5,7 +5,7 @@ Eight situations where Prefixwise answers a question your provider dashboard can
5
5
  Setup for all of them:
6
6
 
7
7
  ```bash
8
- pip install "git+https://github.com/tejachavali/prefixwise"
8
+ pip install prefixwise
9
9
  ```
10
10
 
11
11
  ---
@@ -55,7 +55,7 @@ prefixwise explain examples/session.jsonl --fail-on-waste # exit code 2 on an
55
55
 
56
56
  ```yaml
57
57
  # .github/workflows/cache-gate.yml
58
- - run: pip install "git+https://github.com/tejachavali/prefixwise"
58
+ - run: pip install prefixwise
59
59
  - run: python scripts/record_golden_session.py > session.jsonl # your harness, offline or mocked
60
60
  - run: prefixwise explain session.jsonl --fail-on-waste
61
61
  ```
@@ -0,0 +1,26 @@
1
+ # Dogfood 2: opencode after the 0.3.0 fixes and per-model lanes
2
+
3
+ Run by Muse on 2026-11-07, code at a2c5c13. opencode 1.19.5 through the proxy on port 8081
4
+ (base URL without `/v1`), ledger `dogfood2.db`. Task: a small CSV-summary CLI; finished in
5
+ under 2 minutes, exit 0, 24 pytest tests passing. Transcribed by Claude from Muse's report.
6
+
7
+ **Fixes from dogfood 1 confirmed:** `POST /messages` (no `/v1`) answered; no 404s in the log.
8
+ Sonnet 4.6 is now priced.
9
+
10
+ `prefixwise report`: 21 requests, 251,328 prompt tokens, **92.2% cached**, 7,050 completion
11
+ tokens, **0 avoidable tokens**, cost **$0.2452**, avoidable cost $0.0000.
12
+
13
+ | cause | requests | prompt tokens | cached | cost |
14
+ |---|---:|---:|---:|---:|
15
+ | none | 18 | 242,417 | 95.6% | $0.2117 |
16
+ | model_switch | 1 | 7,986 | | $0.0334 |
17
+ | system_edit | 1 | 907 | | $0.0001 |
18
+ | first_write | 1 | 18 | | $0.0000 |
19
+
20
+ By model: claude-sonnet-4-6 19 requests, 92.5% cached, $0.2451; claude-haiku-5-5 2 requests
21
+ (a title call), $0.0001. `prefixwise fixes`: no avoidable waste with a known fix.
22
+
23
+ **Lanes:** the only `model_switch` is the first Sonnet turn; all 18 later Sonnet turns are
24
+ `none` (97-99% cached). **Limit:** opencode made its Haiku call before Sonnet started, so this
25
+ run did not interleave Haiku between Sonnet turns. Interleaving is covered by
26
+ `tests/test_lanes.py`, not yet by live traffic.
@@ -18,7 +18,11 @@ for the following turns, as a real harness would leave it):
18
18
  A: first_write, none, volatile_system, none, tool_reserialize, none,
19
19
  tool_catalog_change, none, system_edit, none
20
20
  B: first_write, none, param_rendered, none, compaction_rewrite, none,
21
- model_switch, model_switch (back), none, none
21
+ model_switch, switch_back, none, none
22
+
23
+ switch_back returns to the original model. Turns are compared with the
24
+ last turn to the same model (per-model lanes), so its prefix is still
25
+ cached: expected cause none, not a second model_switch.
22
26
 
23
27
  "none" turns append one exchange. RETRY_REPLAY and TTL_EXPIRED are not
24
28
  injected: a hosted cache cannot be made cold on demand, and a TTL test
@@ -79,7 +83,10 @@ SESSION_A = ["first_write", "none", "volatile_system", "none", "tool_reserialize
79
83
  # in the prefix (a full miss), the system prompt second (a partial miss).
80
84
  PROBE_SCRIPT = ["first_write", "none", "tool_reserialize", "system_edit", "none"]
81
85
  SESSION_B = ["first_write", "none", "param_rendered", "none", "compaction_rewrite", "none",
82
- "model_switch", "model_switch", "none", "none"]
86
+ "model_switch", "switch_back", "none", "none"]
87
+
88
+ # Injected labels whose expected cause differs from the label itself.
89
+ EXPECTED = {"switch_back": "none"}
83
90
 
84
91
  # ~4,700 tokens of stable instructions: above every provider's minimum
85
92
  # cacheable prefix (Anthropic is up to 4,096 on some models), so a miss
@@ -153,7 +160,7 @@ class SessionState:
153
160
  "for a failing test to be fixed; tests were run.]"},
154
161
  {"role": "assistant", "content": "Understood, continuing from the summary."}]
155
162
  headers["X-Prefixwise-Compaction-Event"] = "1"
156
- elif injected == "model_switch":
163
+ elif injected in ("model_switch", "switch_back"):
157
164
  self.model = alt_model if self.model == base_model else base_model
158
165
  return headers
159
166
 
@@ -196,7 +203,7 @@ def plan(provider: str, repeats: int, alt_model: str | None) -> list[tuple[int,
196
203
  scripts = []
197
204
  for r in range(repeats):
198
205
  scripts.append((2 * r, SESSION_A))
199
- b = SESSION_B if alt_model else [("none" if c == "model_switch" else c) for c in SESSION_B]
206
+ b = SESSION_B if alt_model else [("none" if c in ("model_switch", "switch_back") else c) for c in SESSION_B]
200
207
  scripts.append((2 * r + 1, b))
201
208
  return scripts
202
209
 
@@ -218,7 +225,7 @@ _MOCK_NATIVE = {
218
225
  def mock_forward_factory(provider: str, state: dict):
219
226
  def forward(prov, body, request_id, session_id, client_headers, api="chat"):
220
227
  injected, tokens = state["injected"], state["tokens"]
221
- hit = injected == "none"
228
+ hit = injected in ("none", "switch_back")
222
229
  cached = int(tokens * 0.9) if hit else 0
223
230
  reason = None if hit or injected == "first_write" else _MOCK_NATIVE[provider][injected]
224
231
  diag = None if injected == "first_write" else {"type": "cache_hit" if hit else "cache_miss",
@@ -305,7 +312,8 @@ def run_provider(provider: str, *, model: str, alt_model: str | None, repeats: i
305
312
  else prompt),
306
313
  "native_mapped": (map_native_reason(provider, native).value
307
314
  if map_native_reason(provider, native) else None),
308
- "agree_injected": result["cause"] == injected, "agree_native": agree_native,
315
+ "agree_injected": result["cause"] == EXPECTED.get(injected, injected),
316
+ "agree_native": agree_native,
309
317
  "prompt_tokens": prompt, "cached_tokens": cached,
310
318
  "raw_usage": payload.get("usage"),
311
319
  "raw_diagnostics": {k: payload.get(k) for k in ("diagnostics", "prompt_cache_diagnostics")
@@ -347,7 +355,7 @@ def probe_verdict(rows: list[dict]) -> tuple[bool, list[str]]:
347
355
  if "error" in r:
348
356
  return False, [f"turn {r['turn']}: HTTP {r['status']}"]
349
357
  label = f"turn {r['turn']} ({r['injected']}, {r['cached_tokens']}/{r['prompt_tokens']} cached)"
350
- if r["injected"] in ("first_write", "none"):
358
+ if r["injected"] in ("first_write", "none", "switch_back"):
351
359
  if r["native_reason"]:
352
360
  notes.append(f"{label}: unexpected miss reason {r['native_reason']!r} on a non-miss turn")
353
361
  continue
@@ -371,7 +379,7 @@ def probe_verdict(rows: list[dict]) -> tuple[bool, list[str]]:
371
379
 
372
380
  def score(results: list[dict], scorer: AgreementScorer) -> dict:
373
381
  ok = [r for r in results if "error" not in r]
374
- misses = [r for r in ok if r["injected"] not in ("none", "first_write")]
382
+ misses = [r for r in ok if EXPECTED.get(r["injected"], r["injected"]) not in ("none", "first_write")]
375
383
  per: dict[str, dict] = {}
376
384
  for r in ok:
377
385
  c = per.setdefault(r["injected"], {"n": 0, "agree_injected": 0, "with_native": 0, "agree_native": 0})
@@ -0,0 +1,23 @@
1
+ # E1-hosted, Anthropic: live re-check after per-model lanes (PR #21)
2
+
3
+ Run by Muse on 2026-11-07, `--providers anthropic --repeats 1`, code at a2c5c13
4
+ (pytest 139 passed). No code changed. Transcribed by Claude from Muse's report.
5
+
6
+ Turns 20, errors 0. Native agreement 100.0% (6 turns with a native reason).
7
+ Injected agreement 100.0%. UNKNOWN 0.0%. **Pass: YES.**
8
+ Input tokens 174,472, cached 121,684.
9
+
10
+ | injected | correct |
11
+ |---|---:|
12
+ | compaction_rewrite | 1/1 |
13
+ | first_write | 2/2 |
14
+ | model_switch | 1/1 |
15
+ | none | 10/10 |
16
+ | param_rendered | 1/1 |
17
+ | switch_back | 1/1 |
18
+ | system_edit | 1/1 |
19
+ | tool_catalog_change | 1/1 |
20
+ | tool_reserialize | 1/1 |
21
+ | volatile_system | 1/1 |
22
+
23
+ No disagreements. `switch_back` had no native reason (a hit); its expected cause is `none`.
@@ -18,7 +18,12 @@ Session A (x5, coding questions):
18
18
  Session B (x5, coding questions):
19
19
  1 FIRST_WRITE, 2 NONE, 3 COMPACTION_REWRITE, 4 COMPACTION_REWRITE,
20
20
  5 NONE, 6 RETRY_REPLAY, 7 RETRY_REPLAY, 8 MODEL_SWITCH,
21
- 9 MODEL_SWITCH, 10 NONE
21
+ 9 SWITCH_BACK (expected NONE), 10 NONE
22
+
23
+ SWITCH_BACK returns to the original model. Prefixwise compares each
24
+ turn with the last turn to the SAME model (per-model lanes), so going
25
+ back to a model whose prefix is still cached is a hit, not a second
26
+ MODEL_SWITCH. Its expected cause is NONE.
22
27
 
23
28
  Session C (x2, append-only growth, the shape of real agent traffic):
24
29
  1 FIRST_WRITE, 2-10 NONE. Each turn appends the previous assistant
@@ -27,9 +32,9 @@ Session C (x2, append-only growth, the shape of real agent traffic):
27
32
  and B repeat identical requests for NONE, which cannot catch a
28
33
  classifier that mistakes growth for HISTORY_EDIT; Session C does.
29
34
 
30
- That is 120 turns: FIRST_WRITE 12, NONE 38, VOLATILE_SYSTEM 10,
31
- TOOL_RESERIALIZE 10, TOOL_CATALOG_CHANGE 10, SYSTEM_EDIT 10,
32
- COMPACTION_REWRITE 10, RETRY_REPLAY 10, MODEL_SWITCH 10.
35
+ That is 120 turns: FIRST_WRITE 12, NONE 38 (+5 SWITCH_BACK expected
36
+ NONE), VOLATILE_SYSTEM 10, TOOL_RESERIALIZE 10, TOOL_CATALOG_CHANGE 10,
37
+ SYSTEM_EDIT 10, COMPACTION_REWRITE 10, RETRY_REPLAY 10, MODEL_SWITCH 5.
33
38
 
34
39
  How each injection is made (all other blocks identical to the
35
40
  previous turn, so the first divergence is the injected one):
@@ -132,7 +137,7 @@ SESSION_A = ["first_write", "none", "volatile_system", "volatile_system",
132
137
  "tool_catalog_change", "system_edit", "system_edit"]
133
138
  SESSION_B = ["first_write", "none", "compaction_rewrite", "compaction_rewrite",
134
139
  "none", "retry_replay", "retry_replay", "model_switch",
135
- "model_switch", "none"]
140
+ "switch_back", "none"]
136
141
  # Append-only growth: every turn adds an exchange; nothing earlier changes.
137
142
  SESSION_C = ["first_write"] + ["none"] * 9
138
143
  SESSIONS = [SESSION_A] * 5 + [SESSION_B] * 5 + [SESSION_C] * 2
@@ -157,6 +162,7 @@ def simulate_cached_tokens(injected: str, prompt_tokens: int = PROMPT_TOKENS_MOC
157
162
  "tool_catalog_change": 0.0,
158
163
  "compaction_rewrite": 0.1,
159
164
  "model_switch": 0.0,
165
+ "switch_back": 0.9, # the original model's prefix is still cached
160
166
  "retry_replay": 0.0,
161
167
  "system_edit": 0.2,
162
168
  }
@@ -219,12 +225,12 @@ def build_body(*, session_id: str, model: str, injected: str, turn: int,
219
225
  "max_tokens": 16,
220
226
  "temperature": 0,
221
227
  }
222
- if not grow and injected in ("none", "retry_replay") and turn in (5, 6, 7):
223
- # Session B, turns 5-7: these follow a compaction, so the
224
- # identical request to repeat is the compacted history from
225
- # turn 4, not the pre-compaction baseline. Without this the
226
- # "identical" turn would differ in messages and be classified
227
- # HISTORY_EDIT instead of NONE / RETRY_REPLAY.
228
+ if not grow and injected in ("none", "retry_replay", "model_switch", "switch_back") and 5 <= turn <= 10:
229
+ # Session B, turns 5-10: everything after the compaction carries the
230
+ # compacted history from turn 4, as a real harness would. (Until
231
+ # 2026-11-07 turns 8-10 reverted to the pre-compaction history; the
232
+ # model switch at turn 8 hid that. Per-model lanes compare turn 9
233
+ # with the same model's turn 7, which exposed it as HISTORY_EDIT.)
228
234
  messages = [
229
235
  {"role": "system", "content": system},
230
236
  {"role": "user", "content": "[Summary of prior turns, compaction 4] Prefix caching was discussed; the user asked about vLLM eviction."},
@@ -238,17 +244,25 @@ def build_body(*, session_id: str, model: str, injected: str, turn: int,
238
244
  return body
239
245
 
240
246
 
247
+ # Injected labels whose expected cause differs from the label itself.
248
+ EXPECTED = {"switch_back": "none"}
249
+
250
+
251
+ def expected_cause(injected: str) -> str:
252
+ return EXPECTED.get(injected, injected)
253
+
254
+
241
255
  def score_results(results: list[dict]) -> dict:
242
256
  """Score a list of turn results against their injected causes."""
243
257
  total = len(results)
244
- agreed = sum(1 for r in results if r["predicted"] == r["injected"])
245
- misses = [r for r in results if r["injected"] not in ("none", "first_write")]
258
+ agreed = sum(1 for r in results if r["predicted"] == expected_cause(r["injected"]))
259
+ misses = [r for r in results if expected_cause(r["injected"]) not in ("none", "first_write")]
246
260
  unknown = sum(1 for r in misses if r["predicted"] == "unknown")
247
261
  per_cause: dict[str, dict] = {}
248
262
  for r in results:
249
263
  c = per_cause.setdefault(r["injected"], {"n": 0, "correct": 0})
250
264
  c["n"] += 1
251
- if r["predicted"] == r["injected"]:
265
+ if r["predicted"] == expected_cause(r["injected"]):
252
266
  c["correct"] += 1
253
267
  for c in per_cause.values():
254
268
  c["precision"] = c["correct"] / c["n"] if c["n"] else None
@@ -348,9 +362,7 @@ def run(*, vllm_url: str, model: str, model_alias: str, mock: bool,
348
362
  if max_turns is not None and turn_no > max_turns:
349
363
  break
350
364
  model_for_turn = model_alias if injected == "model_switch" and turn_idx in (8,) else model
351
- # Turn 9 in session B switches back to the original model.
352
- if injected == "model_switch" and turn_idx == 9:
353
- model_for_turn = model
365
+ # Turn 9 in session B (switch_back) is on the original model again.
354
366
  state["injected"] = injected
355
367
  body = build_body(session_id=session_id, model=model_for_turn,
356
368
  injected=injected, turn=turn_idx, base_date=base_date,
@@ -379,7 +391,7 @@ def run(*, vllm_url: str, model: str, model_alias: str, mock: bool,
379
391
  "turn": turn_no, "session_id": session_id, "injected": injected,
380
392
  "predicted": predicted, "cached_tokens": cached,
381
393
  "prompt_tokens": prompt_tokens,
382
- "agreement": predicted == injected,
394
+ "agreement": predicted == expected_cause(injected),
383
395
  "unknown": predicted == "unknown",
384
396
  "upstream_error": upstream_error,
385
397
  "upstream_session_id": retry_upstream_session_id,
@@ -0,0 +1,25 @@
1
+ # E1-open report: live re-check after per-model lanes (PR #21)
2
+
3
+ Run by Muse on 2026-11-07: Colab L4, vLLM 0.33.0, Qwen3-4B (alias Qwen3-4B-alias), 70.8 s.
4
+ Code at e89f0ac (pytest 142 passed). No code changed for the run. Transcribed by Claude
5
+ from Muse's report; the original file stayed on Colab.
6
+
7
+ Turns: 120 | Agreement: 100.0% | UNKNOWN rate (misses): 0.0% | Pass: YES
8
+
9
+ | injected cause | correct | precision |
10
+ |---|---:|---:|
11
+ | compaction_rewrite | 10/10 | 100.0% |
12
+ | first_write | 12/12 | 100.0% |
13
+ | model_switch | 5/5 | 100.0% |
14
+ | none | 38/38 | 100.0% |
15
+ | retry_replay | 10/10 | 100.0% |
16
+ | switch_back | 5/5 | 100.0% |
17
+ | system_edit | 10/10 | 100.0% |
18
+ | tool_catalog_change | 10/10 | 100.0% |
19
+ | tool_reserialize | 10/10 | 100.0% |
20
+ | volatile_system | 10/10 | 100.0% |
21
+
22
+ The report's "misses" list (predicted != injected label) holds only the five `switch_back`
23
+ turns (59, 69, 79, 89, 99), each predicted `none` with 1776 of ~1786 tokens cached. That is
24
+ the expected lanes outcome: switching back to a model whose prefix is still cached is a hit,
25
+ so `switch_back` expects `none` and scores 5/5.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "prefixwise"
7
- version = "0.3.0"
7
+ version = "0.3.1"
8
8
  description = "Name why your LLM prompt cache missed, price the miss, and measure tokens per successful task. A local proxy and CLI for OpenAI, Anthropic and vLLM."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  """Prefixwise: model-agnostic ledger of avoidable agent token spend."""
2
2
 
3
- __version__ = "0.3.0"
3
+ __version__ = "0.3.1"
4
4
 
5
5
  from .classifier import MissCause, classify
6
6
  from .diagnostics import AgreementScorer
@@ -166,6 +166,13 @@ def classify(prev: RequestSnapshot | None, curr: RequestSnapshot,
166
166
  return Classification(MissCause.TOOL_CATALOG_CHANGE, True,
167
167
  "tool multiset differs", secondary, native_reason)
168
168
  if role == "messages":
169
+ if not curr.compaction_event and len(p) == 1 and c and p[0].raw != c[0].raw:
170
+ # The previous request was a one-shot (a single message, e.g. an
171
+ # agent's "title this" side call) and this one replaces it: a new
172
+ # conversation on the same tools and system prompt, not an edit of
173
+ # history. Judge it by whether the cache served the shared prefix.
174
+ secondary.append(MissCause.HISTORY_EDIT)
175
+ continue
169
176
  cause = MissCause.COMPACTION_REWRITE if curr.compaction_event else MissCause.HISTORY_EDIT
170
177
  legit = True if curr.compaction_event else False
171
178
  ev = "previous message blocks rewritten (not a prefix of this turn) with a compaction event" \