|
| 1 | +# Working notes — 2026-09-16: the Haiku caching investigation |
| 2 | + |
| 3 | +Continues the "consistent 50-60% token savings" campaign from |
| 4 | +`docs/plans/repeat-detection-and-eval-harness-followups.md`. That plan's |
| 5 | +first four steps (bash/grep near-duplicate detection, evidence-ledger |
| 6 | +reconciliation, `zeroHotEvidence` resolution, SWE-bench grading) landed and |
| 7 | +pushed to `origin/main` as commits `38a3cdd`, `4f8a773`, `b8f8501`, |
| 8 | +`b39b8f8`. This note picks up mid-step-5, the multi-model repeat campaign, |
| 9 | +where a major, previously-undocumented finding derailed the campaign into |
| 10 | +its own investigation. |
| 11 | + |
| 12 | +## What the campaign found before the derailment |
| 13 | + |
| 14 | +**mycoder, ten-turn-mixed, n=3**: clean and tight — 3/3 correct both |
| 15 | +variants, zero assertion failures, range **-24.7% to -17.2%** (median |
| 16 | +-19.6%) on provider-input tokens. Real, consistent, but well below the old |
| 17 | +(already-flagged-stale) -60% headline number. |
| 18 | + |
| 19 | +**mycoder, SWE-bench sympy-18211, n=3 rerun** (after fixing stale |
| 20 | +`resume: true` expectations — see below): high variance persists, |
| 21 | +-20%..+21.6% across two n=3 batches, driven by one repeat where the model |
| 22 | +made 54 genuinely-distinct verification calls (traced with `npm run |
| 23 | +doctor`, confirmed not a near-duplicate pattern my bash/grep fix should |
| 24 | +have caught). Still bounded below baseline's own historical worst case |
| 25 | +(3.87M tokens, from the prior session's investigation). |
| 26 | + |
| 27 | +**A real, unrelated bug surfaced and fixed along the way**: both |
| 28 | +`evaluation/benchmarks/swebench-verified-sympy-*.json` configs, plus |
| 29 | +`pi-plan-phase-experiment.json` and `pi-ten-turn-plan-framing.json`, had |
| 30 | +stale `resume: true` expectations on non-first turns — the same |
| 31 | +already-diagnosed-elsewhere bug class as `pi-ten-turn-mixed.json`'s earlier |
| 32 | +fix (`resume` checks for a `"load"` task-state-audit op, which structurally |
| 33 | +never fires under `sessionMode: "continue"`, confirmed by reading |
| 34 | +`continuityAssertions` in `run.mjs` directly). Fixed and committed |
| 35 | +(`b39b8f8`). |
| 36 | + |
| 37 | +## The big one: Haiku 4.5 SWE-bench, tied tokens, 5-19x cost |
| 38 | + |
| 39 | +`anthropic/claude-haiku-4-5` on sympy-18211, n=3: card's raw provider-input |
| 40 | +tokens came out roughly **tied** with baseline (median -0.3%, range -54.4% |
| 41 | +to +482%), but card's **real dollar cost was 5-19x higher** |
| 42 | +($2.6-2.7/run vs $0.14-0.53/run). Traced with a narrow DuckDB query against |
| 43 | +the raw session log: card's cache-read tokens were ~0 across all three |
| 44 | +repeats (0, 0, 36K) against baseline's substantial cache-read (1.9M, 315K, |
| 45 | +3.2M). Checked whether this is universal by comparing mycoder's own card |
| 46 | +runs in the same rerun — it isn't: mycoder's card gets real cache-read hits |
| 47 | +(1.7M, 135K, 348K). This is specific to genuine Anthropic prompt caching |
| 48 | +(strict byte-exact prefix matching, confirmed in |
| 49 | +`node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js:954-975`), |
| 50 | +not universal to the extension's design. |
| 51 | + |
| 52 | +**Original hypothesis**: `projectContext` (`src/core/projection.ts`) |
| 53 | +recomputes retirement on every single provider request, not once per turn — |
| 54 | +confirmed via the same DuckDB query, `retiredMessages` climbed almost every |
| 55 | +request within one turn (0→2→4→…→242 across ~132 requests). Since |
| 56 | +retirement removes messages from the middle of the transcript, and |
| 57 | +Anthropic's cache requires the sequence up to a breakpoint to be |
| 58 | +byte-identical to a prior request, this should defeat the cache on nearly |
| 59 | +every call. |
| 60 | + |
| 61 | +## Fix #1: pin retirement decisions to turn boundaries — confirmed correct, did not help |
| 62 | + |
| 63 | +Built and shipped (then reverted, see below): a caching layer in the |
| 64 | +`context` handler (`src/pi/index.ts`) that computes the full |
| 65 | +`projectContext` result once at the start of a turn (using the existing |
| 66 | +`currentTurn` counter, confirmed via code trace to stay constant across |
| 67 | +every `context` call within a turn and increment exactly once between |
| 68 | +turns) and, for subsequent calls in the same turn, reuses that pinned |
| 69 | +result plus appends the new raw tail — instead of recomputing retirement |
| 70 | +fresh every call. `card`/`lastStatus`/the audit entry still used the fresh |
| 71 | +`projection` unchanged, so nothing about what the extension _reports_ |
| 72 | +(including `hotEvidence`/`zeroHotEvidence` assertions) was affected — only |
| 73 | +what actually got sent to the provider. |
| 74 | + |
| 75 | +Three new integration tests (`tests/pi-adapter.test.ts`, using the existing |
| 76 | +`harness()`/`project()` helpers, confirmed via grep that no existing test |
| 77 | +called `project()` twice within a simulated turn expecting full mid-turn |
| 78 | +recomputation) proved the invariant: a second request within a turn keeps |
| 79 | +everything the first request sent, even where fresh retirement would have |
| 80 | +collapsed it; the deferred collapse still applies once the turn ends; a |
| 81 | +`turnEnd` between two requests resets the pin. Full suite green |
| 82 | +(165/165), `tsc`/`eslint`/`prettier`/build all clean. |
| 83 | + |
| 84 | +**Reran the exact Haiku SWE-bench fixture. Cache-read stayed ~0 (0, 38K, 0) — no meaningful change.** |
| 85 | + |
| 86 | +## Diagnosing why: real request-level instrumentation, not more guessing |
| 87 | + |
| 88 | +Rather than keep theorizing, added temporary instrumentation directly in |
| 89 | +the installed SDK (`node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js`, |
| 90 | +gitignored, reverted after) to dump every real request's `params` (the |
| 91 | +exact payload sent to Anthropic) to a local NDJSON file, then ran a |
| 92 | +minimal, cheap, card-only diagnostic (`--variant card`, no baseline, no |
| 93 | +repeats — cheapest run that still reproduces the pattern). |
| 94 | + |
| 95 | +**Verified directly, byte-for-byte, across 48 real requests**: with the |
| 96 | +turn-pinning fix in place, the message array genuinely is prefix-stable |
| 97 | +within a turn (every within-turn consecutive pair matched exactly, modulo |
| 98 | +the deliberately-volatile trailing `statusMessage` and the moving |
| 99 | +`cache_control` marker, both expected). `system` and `tools` were also |
| 100 | +stable. Only the two genuine turn boundaries showed a (correct, expected) |
| 101 | +shrink. **The fix works exactly as designed at the request-payload level.** |
| 102 | + |
| 103 | +Despite that, real per-message usage data from the raw session log showed |
| 104 | +`cacheWrite` climbing every single request (4325→4453→4654→…) while |
| 105 | +`cacheRead` stayed **exactly 0** the entire run, and `input` (fresh, |
| 106 | +uncached tokens) dropped to near-nothing after the first few calls. That's |
| 107 | +a specific, real signature: the cache is being _written_ successfully every |
| 108 | +time but never _found_ on the next lookup, despite content being |
| 109 | +demonstrably stable. Ruled out a client-side reporting bug too — the code |
| 110 | +that parses `cache_read_input_tokens` from the Anthropic response and |
| 111 | +assigns it to `usage.cacheRead` is straightforward and correct |
| 112 | +(`anthropic-messages.js:381-382`, `:537-541`). |
| 113 | + |
| 114 | +## Hypotheses checked and ruled out |
| 115 | + |
| 116 | +1. **Missing OAuth `x-session-affinity` header** — these Haiku calls |
| 117 | + authenticate via OAuth (Claude subscription; confirmed by the OAuth-only |
| 118 | + system message `"You are Claude Code, Anthropic's official CLI for |
| 119 | +Claude."` appearing in the captured payload). Code-confirmed |
| 120 | + (`anthropic-messages.js:661-677` vs `:678-684`): the OAuth client branch |
| 121 | + never sets `x-session-affinity`, unlike the API-key branch. **Ruled |
| 122 | + out** as a _sufficient_ explanation: baseline uses the identical |
| 123 | + auth/model and gets real cache hits, so a missing header on the shared |
| 124 | + client construction path can't be what differentiates card from |
| 125 | + baseline. |
| 126 | +2. **Missing caching-related beta flag** — checked; prompt caching is GA, |
| 127 | + no beta header exists anywhere in this SDK version for it. Not the |
| 128 | + cause. |
| 129 | +3. **Cache retention resolving to "none"** — checked `resolveCacheRetention`/ |
| 130 | + `getCacheControl`; defaults to `"short"` (standard 5-minute ephemeral), |
| 131 | + and `cache_control: {type: "ephemeral"}` was directly observed present |
| 132 | + in captured requests. Not the cause. |
| 133 | +4. **Two consecutive `role: "user"` messages** (custom→user conversion |
| 134 | + happens in `@earendil-works/pi-coding-agent`'s `convertToLlm`, meaning |
| 135 | + `cardMessage` immediately followed by the real turn-starting user |
| 136 | + message produces two adjacent user-role objects — a shape baseline |
| 137 | + never has). Built and tested a second fix: `mergeCardIntoFirst` folded |
| 138 | + the card's text into the first wire-history message as an extra content |
| 139 | + block instead of sending it as its own message (only 1 of 16 |
| 140 | + `messages[0]`-touching tests needed a structural update; the other 15 |
| 141 | + were content-substring checks that kept passing). Full suite green |
| 142 | + (165/165). **Reran the same minimal Haiku diagnostic. Cache-read stayed |
| 143 | + at 0.** Ruled out. |
| 144 | + |
| 145 | +## Current status |
| 146 | + |
| 147 | +**Both caching fixes reverted** — cleanly, since neither was ever |
| 148 | +committed (`git checkout -- src/pi/index.ts tests/pi-adapter.test.ts` |
| 149 | +restored the exact state after commit `b39b8f8`). Confirmed: working tree |
| 150 | +clean, 162/162 tests pass, `tsc` clean. The turn-pinning fix was correct |
| 151 | +and independently defensible (confers no proven benefit right now, but is |
| 152 | +harmless in isolation and would be the right foundation if the underlying |
| 153 | +cache-lookup problem is ever resolved) — reverted anyway per explicit |
| 154 | +instruction, to avoid carrying unproven complexity. |
| 155 | + |
| 156 | +**Genuinely unresolved**: why Anthropic's cache lookup misses for card's |
| 157 | +Haiku requests specifically, despite a demonstrably stable, correctly |
| 158 | +cache_control-marked, non-consecutive-user-role payload, while the |
| 159 | +identical model/auth under baseline's simpler (no injected messages, |
| 160 | +natural role alternation) request shape gets substantial cache hits. Every |
| 161 | +theory checkable from this client's code has been checked and ruled out. |
| 162 | +What's left is either something in the _exact_ token-level serialization |
| 163 | +that differs in a way not visible at the message-object level (not yet |
| 164 | +found), or an account/platform-side quirk not diagnosable without |
| 165 | +Anthropic-side visibility. |
| 166 | + |
| 167 | +**Practical implication for the "consistent 50-60% savings" goal**: on |
| 168 | +Haiku (and plausibly any Claude model authenticated the same way), card's |
| 169 | +real dollar-cost advantage cannot currently be assumed even when raw token |
| 170 | +counts look favorable or neutral — this needs to be checked explicitly, |
| 171 | +per-provider, going forward, not inferred from token counts alone. mycoder |
| 172 | +(and presumably any router without strict Anthropic-style prefix caching) |
| 173 | +remains unaffected by this specific problem. |
| 174 | + |
| 175 | +## What's next, if anyone picks this back up |
| 176 | + |
| 177 | +- Don't re-attempt either of the two ruled-out fixes without new evidence. |
| 178 | +- If pursued further, the highest-value next step is probably getting |
| 179 | + Anthropic-side account/support visibility into why cache lookups aren't |
| 180 | + matching for these specific requests, rather than more client-side |
| 181 | + guessing — every angle checkable from this codebase has been checked. |
| 182 | +- The original step-5 campaign (mycoder + Haiku, both fixtures, n≥3) is |
| 183 | + still incomplete: the Haiku `pi-ten-turn-mixed.json` leg was never run |
| 184 | + (this investigation superseded it). If resumed, budget for it |
| 185 | + separately — it would likely reproduce the same cost/token disconnect on |
| 186 | + Haiku, now a known, documented risk rather than a surprise. |
0 commit comments