{"slug": "why-a-97-4-prompt-cache-hit-rate-still-hid-12-06-of-waste-in-one-232-turn", "title": "Why a 97.4% Prompt-Cache Hit Rate Still Hid $12.06 of Waste in One 232-Turn Session", "summary": "A developer built an offline token-forensics tool, agent-token-forensics (Python stdlib CLI) and token-audit-engine.js (browser), that parses coding-agent JSONL transcripts from four provider log formats into a common token 4-tuple and separates productive cache reads from wasted re-reads. On a real 232-turn session with a 97.4% headline prompt-cache hit rate, the tool attributed $12.06 (75.3%) of $16.01 in spend to waste, including two cache-bust cliffs, six Bash retry loops, and a 16k-token command output re-read 219 times, dropping the effective cache hit rate to 10.9%.", "body_md": "Last week I pulled a real 232-turn local transcript from our Windows/Linux ISP ops repo because weekly coding-agent quota kept draining even though the headline prompt-cache hit rate looked healthy at `97.4%`.\n\nParsing the raw JSONL turn-by-turn showed why aggregate cache hit percentages mislead you on long sessions:\n\n`232`\n`40.08M` tokens`352.7k` tokens (crossed `80k` on turn `11` and rode `221` turns without compacting)`97.4%`\n`10.9%`\n`$16.01`\n`$12.06` (`75.3%`)` 2` cache-bust cliffs (`99% -> 0%` on a `210k` window), `6` consecutive Bash retry loops, `16k`-token command output on turn `13` re-read `219` times)\nA `97.4%` hit rate sounds great until you notice that `90%` of those cached reads are re-reading stale history and giant command dumps across 200+ turns.\n\nThe offline parser in `token-audit-engine.js` (browser) and `agent-token-forensics` (Python stdlib CLI) normalizes four provider log shapes into the same 4-tuple `(input_tokens, output_tokens, cache_read_tokens, cache_write_tokens)`:\n\n`usage`):` input_tokens`, `output_tokens`\n`cache_read_input_tokens` (fallback: `cache_read_tokens`)` cache_creation_input_tokens` (fallback: `cache_creation_tokens`)` event_msg` `token_count` -> `last_token_usage` or diff of cumulative `total_token_usage`):` cached_input_tokens`\n`max(0, input_tokens - cached_input_tokens)`.` prompt_tokens`, `completion_tokens`, `prompt_tokens_details.cached_tokens`\n`usageMetadata`):` promptTokenCount`, `candidatesTokenCount`, `cachedContentTokenCount`\nPer turn, total context and apparent cache hit are:\n\n```\ntotal_context = input_tokens + cache_read_tokens + cache_write_tokens\ncache_hit_ratio = total_context > 0 ? cache_read_tokens / total_context : 0\n```\n\nTo separate productive cached prefix reads from wasted re-reads, the engine tracks `perTurnWastedCr[k]` on every turn `k` across three waste buckets:\n\n`80,000` tokens`compactThreshold = 80_000`, `postCompactTarget = 20_000`):\n`excess = max(0, total_context - 20_000)`.` k`: `round(cache_read_tokens * (excess / total_context))`.` turn_cost * (excess / total_context) * 0.85`.` loopThreshold = 3` turns):\n`>= 3` consecutive turns, every repeated turn after the first counts its full `bloatCharThreshold = 24_000` chars or `bloatDeltaThreshold = 15_000` context jump on a non-cache-bust turn):\n`2,000` (`excessBlob = max(0, blobTokens - 2_000)`) are billed once at ingest (` cache_write` or `input` rate) and then carried at `cache_read` rate on every subsequent turn `k > pos`, contributing `min(cache_read_tokens, excessBlob)` to `perTurnWastedCr[k]`.\nWe take the per-turn maximum across those buckets so overlapping waste is never double-counted, clamp to `cache_read_tokens`, sum `totalWastedCacheReadTokens`, and compute:\n\n```\neffective_cache_hit =\n  total_context_sum > 0\n    ? Math.max(0, total_cache_read - total_wasted_cache_read) / total_context_sum\n    : 0\n```\n\nSeparately, the **cache-bust cliff detector** fires whenever the previous turn was warm (`total_context >= 10_000` and `cache_hit_ratio >= 0.7`) and the current turn has `total_context >= 10_000` with `cache_hit_ratio < 0.3`. Extra dollar cost is `(input_tokens * (inRate - cacheReadRate) + cache_write_tokens * (cacheWriteRate - cacheReadRate)) / 1_000_000`.\n\nPer-turn dollar waste is deduplicated and capped at `95%` of the turn's cost:\n\n```\ncombinedTurnWaste = Math.min(\n  turnCost * 0.95,\n  Math.max(\n    loopWaste,\n    bustWaste + Math.max(tailWaste, bloatWaste)\n  )\n)\n```\n\nIn our 232-turn trace, `total_cache_read / total_context_sum` was `97.4%`, while `(total_cache_read - total_wasted_cache_read) / total_context_sum` dropped to `10.9%`.\n\nPrivate repo transcripts should never leave your machine, so both interfaces run offline:\n\n`v0.1.1`, 0 runtime deps, 39 tests on Win/Linux/macOS CI):\n\n```\npipx install agent-token-forensics\n\n# Preview on built-in synthetic trace\nagent-token-forensics analyze --demo\n\n# Auto-scan local Claude Code / Codex / Antigravity JSONL logs\nagent-token-forensics analyze\n\n# Expose strictly read-only stdio MCP tools (analyze_transcripts, forensics_about)\nagent-token-forensics mcp-serve\n```\n\nScope note: this is strictly read-only offline forensics. Dollar figures are deterministic estimates from logged token counts and public list rates, not provider invoices, and the tool does not intercept or auto-compact live sessions.\n\nWhat worked best on our own repo after reading these traces: compacting hard around `80k-120k`, piping noisy shell commands through `head`/` tail`/` rg` or writing to a scratch file, and stopping identical retry loops after 2 failures.", "url": "https://wpnews.pro/news/why-a-97-4-prompt-cache-hit-rate-still-hid-12-06-of-waste-in-one-232-turn", "canonical_source": "https://dev.to/blackbadhope/why-a-974-prompt-cache-hit-rate-still-hid-1206-of-waste-in-one-232-turn-session-c1l", "published_at": "2026-12-02 10:06:59+00:00", "updated_at": "2026-12-02 10:14:30.334163+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools"], "entities": ["agent-token-forensics", "token-audit-engine.js", "Claude Code", "Codex", "Antigravity"], "also_reported_by": [], "takeaway": "Aggregate prompt-cache hit rates hide waste on long sessions: in a 232-turn trace a 97.4% hit rate fell to a 10.9% effective rate once stale-history re-reads, retry loops and oversized command outputs were subtracted, accounting for $12.06 of $16.01 spent.", "recommendation": {"advice": "Audit long agent sessions turn-by-turn for cache-bust cliffs, retry loops and oversized command outputs rather than trusting aggregate cache hit rates, since a 97.4% headline rate masked 75.3% of spend as waste.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/why-a-97-4-prompt-cache-hit-rate-still-hid-12-06-of-waste-in-one-232-turn", "markdown": "https://wpnews.pro/news/why-a-97-4-prompt-cache-hit-rate-still-hid-12-06-of-waste-in-one-232-turn.md", "text": "https://wpnews.pro/news/why-a-97-4-prompt-cache-hit-rate-still-hid-12-06-of-waste-in-one-232-turn.txt", "jsonld": "https://wpnews.pro/news/why-a-97-4-prompt-cache-hit-rate-still-hid-12-06-of-waste-in-one-232-turn.jsonld"}}