Skip to main content

kvleak · cut Claude Code token cost at the source

Your Claude Code cache hit rate is 95%+. A quarter of your input spend still goes to cache rebuilds. kvleak shows where, and fixes most of it with one command. · 中文

CI PyPI Python Dependencies License

kvleak audit card: 95.2% hit rate, $638 leaked to misses, 66% of it idle gaps that outlived the cache TTL

The maintainer's last 30 days, from kvleak --card. Yours will differ; that is the point. Post yours in #1, as the card or the four redacted lines of kvleak --share.

▶ Two-minute video: why the hit rate lies, the leak, the fix, before/after, the benchmark.

uvx kvleak            # or: pipx run kvleak  ·  pip install kvleak

Also a Claude Code skill, so Claude runs the audit when you ask why the bill is high: npx skills add shangliy/kvleak or /plugin marketplace add shangliy/kvleak then /plugin install kvleak@kvleak.

No API key, no config, no network calls, no dependencies. It reads the session files Claude Code, Codex CLI, Gemini CLI and OpenCode already keep on disk, and the claude -p --output-format json results of a batch harness, and is done in seconds. On a subscription the dollars are list-price equivalents; the percentages are your rate-limit headroom.

 kvleak · prompt-cache leak report
 100 sessions + 311 subagents + 25,421 one-shot runs (Claude Code 83, Codex CLI 17) · 56,195 model calls · 10.0k min miss size

  Cache hit rate    94.6%  ██████████████████████▋
  Input spend        $2,641   caching already saved you $21,594
  Output spend      $641.66   replies + thinking at the output price · whole bill $3,283: 48.4% cache writes, 30.9% cache reads, 19.5% output
  Leaked to misses  $632.74   24.0% of input spend went to cache rebuilds and cold starts · 19.3% of the whole bill
  Recoverable       $121.10   with keep-alive pings (idle ≤ 2h, capped at break-even; `kvleak keepalive` sizes the budget from when you come back)
  Dead writes       $262.91   write premium on tokens never read back (mostly one-shot `claude -p` runs)

 Where the leak comes from
  cause                            misses  uncached  per miss     leak  share
  Idle gap outlived the cache TTL     215     45.9M      135k  $419.73  66.3%  ██████████▌
  New session cold start            1,981     51.0M     14.2k  $123.44  19.5%  ███
  Subagent cold start                 160      4.5M     28.5k   $31.58   5.0%  ▊

The same audit as text. Not convinced by one person's history? On kenseii1's public 945-run benchmark, priced by the costUSD in its own logs, /compact cut raw tokens 40–72% and raised the bill 14–37%; a subagent cut tokens 3% and raised it 30%.

Turn it on

The audit changes nothing. These four do, each with an undo, and each takes effect in Claude Code sessions started afterwards:

pip install kvleak
kvleak tune --apply          # settings.json: compaction window, cache TTLs, idle compaction, Bash cap   (--reset)
kvleak hooks --install       # long shell output stays out of the context; compaction keeps an archive  (--uninstall)
kvleak refine --apply        # context-hygiene rules, with their dollar figures, in ~/.claude/CLAUDE.md (--remove)
kvleak statusline --install  # cache countdown in the status bar, ticking while you read              (--uninstall)

How to tell it worked: /hooks in Claude Code lists four kvleak entries, the status bar reads ● cache 59:47 · 86k ctx · rebuild $1.73 after the first reply, and a long seq 1 20000 comes back as head + tail + a path instead of 20,000 lines. A week later, kvleak probe puts a number on it.

Why the hit rate lies

A cache hit costs 0.1× the input price (0.025× on Fable 5.1). A rebuild costs 1.25–2×. One miss on a 200k context is worth 80 hits, so 2% of calls can carry half of all uncached input and the hit rate never moves. kvleak prices only the avoidable part of each miss: context the cache already held, at write price minus read price.

Why "60–90% fewer tokens" did not shrink your bill

Tool-output compressors shrink what the context carries, and carrying is paid at the cache-read price, the cheapest line on the bill. On 2,848 billed Claude Code runs, a 38% cut in tool output raised cost by 6.8% (arXiv 2607.12161). kvleak whatif replays each tool's promise on your own bill, as an upper bound:

$ kvleak whatif

  What if · 58,199 model calls · $3,053 over the last 30d
  Bill = $80.38 uncached input + $1,337 cache writes + $1,183 cache reads + $452.12 output

  if you…                who promises it                                     bill saving  share of bill
  kvleak tune --apply    compaction window, TTLs, idle compaction, Bash cap  −$786.56             25.8%
  Shell output −60%      rtk's low end ("60–90%")                            −$222.00              7.3%
  All tool results −40%  AgentDiet, arXiv 2509.23586                         −$183.98              6.0%
  Thinking −25%          effort high → medium                                −$59.22               1.9%
  Startup context −50%   claude-token-optimizer                              −$43.19               1.4%
  Replies half as long   caveman                                             −$32.74               1.1%

Compaction changes how much is carried at all. That is why the settings levers are three times the best compressor, on a history where 44% of the bill is cache writes.

Three commands

kvleak audit, whatif and tune on the maintainer's history

1. See the leak. kvleak (above). --since 7d, --html report.html for a shareable report, kvleak session <id> for one session call by call.

2. Fix the settings. Claude Code can compact for you, pick the cache TTL and compact idle sessions, but its defaults are tuned for nobody. kvleak tune replays your last 30 days under every value of each setting and --apply writes the winners to settings.json (backed up; --reset undoes it):

$ kvleak tune

  setting                                         now           best   saving / 30d  why
  autoCompactWindow                               auto (~967k)  200k        $720.52  98 compactions instead of 32 · −57.7% of input spend
  `claude -p` runs: CLAUDE_CODE_PROMPT_CACHE_TTL  1h            5m          $169.11  42% of their cache writes were never read back
  CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS             200k          100k         $19.72  153 idle gaps ≥54 min
  bashOutputMaxChars                              30,000        8,000        $32.54  Bash results are 29% of what entered the context

  Total if applied: $909 per 30d (−45% of input spend)
  Write these to ~/.claude/settings.json: kvleak tune --apply

A week later, kvleak probe shows what actually changed: input spend per call, leak share, context per call, compactions and shell output on your own interactive sessions before vs after the day you applied, and what the difference is worth per 30 days. Measured on what was billed, not replayed.

3. Watch the cache live. kvleak statusline --install puts a TTL countdown in Claude Code and tells you when carrying the context costs more than shrinking it:

◕ cache 3:41 · 182k ctx · rebuild $0.89
● cache 59:47 · 249k ctx · rebuild $1.99 · ⚠ /compact saves ~$9.42
◔ cache 1:19 · 250k ctx · rebuild $2.00 · ⚑ ≤2 pings pay

What else is in the box

Each of these is measured on your own history before it suggests anything. Numbers are the maintainer's 30 days; method and reproduction in docs/benchmarks.md.

kvleak probe Did it help? Splits your sessions at the day tune --apply / hooks --install / refine --apply ran and contrasts input spend per call, leak share, context per call, compactions and shell output before vs after, with a projected 30-day figure your own before/after, no replay
kvleak advise Should you /compact or hand off to a fresh session now, and after how many calls it pays off −58% input spend in backtest
kvleak diet What filled the context: shell output 29%, scripts sent to the shell 21%, thinking 14%, file reads 4%; the costliest single items named 114 long tool loops cost $351 to re-read; in subagents −$319
kvleak hooks --install Claude Code hooks that keep long shell output out of the context (head + tail + error lines + a path) and archive everything a compaction drops, so kvleak recall can find it accuracy 1.00 in 72 benchmark runs, −16% on long-output tasks
kvleak refine --apply Evidence-gated context-hygiene rules for CLAUDE.md, dollar figure written into each; --probe later shows which rules changed behaviour 5 rules covering ≈$640 / 30 d
kvleak skills Every skill's description rides in the cached prefix of every call; its body is carried until the next compaction once invoked. Prices the listing, names the skills never invoked (and how to turn each off), prices each loaded body and repeat injections 12 of 19 skills never invoked: $153 / 30 d of listing
kvleak keepalive How many keep-alive pings your own pauses justify before giving up, overall and by time of day; feeds cache-refresher 5 pings worth $337; lunch pauses return 25%, 6–8 am ones 86%
kvleak pointer, --fail-over, --path Multi-agent hand-off pointers, a CI gate on leak share, any JSONL with usage counters (Anthropic, OpenAI, Gemini keys) playbook for swarms

audit, advise, keepalive and whatif read Claude Code, Codex CLI (~/.codex/sessions), Gemini CLI (~/.gemini/tmp/*/chats) and OpenCode (opencode.db) automatically. The context-level commands (diet, tune, hooks, refine) need the tool results themselves and read Claude Code only.

Full tour with outputs: docs/guide.md. How every number is computed: docs/how-it-works.md. ccusage tells you how much you spent; kvleak tells you why and what to change. How it relates to rtk, caveman, claude-token-optimizer and cache-refresher: docs/compare.md.

FAQ

Is my data sent anywhere? No. Local files only, no network calls.

I'm on a subscription. Misses eat the same rate-limit headroom they would cost in dollars on the API. Read the figures as relative weights.

Does trimming context hurt the model? In the A/B benchmark (bench/, 72 runs on Opus 5.5) every arm scored 1.0 on every task. The settings tune writes only compact above 200k context; --min-window raises that.

Credits

The countdown idea comes from olddonkey/cache-refresher; hooks, recall and refine borrow from Prime Agent and Harness². MIT licensed.

Metadata

Release files for kvleak 0.12.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kvleak 0.12.0
File Size Uploaded Provenance Actions
kvleak-0.12.0.tar.gz 285.8 kB Without provenance Details for kvleak-0.12.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kvleak 0.12.0
File Interpreter ABI Platform Actions
kvleak-0.12.0-py3-none-any.whl Python 3 none any Details for kvleak-0.12.0-py3-none-any.whl

Total release size: 385.9 kB

Release files / kvleak-0.12.0.tar.gz

Download URL kvleak-0.12.0.tar.gz
Size 285.8 kB
Tags Source
SHA-256 checksum
How to use checksums
c36a381b1d7980c9a8582139fc258f46e18be9287fbf0bab27e2c485c38617a5
BLAKE2b-256 checksum
How to use checksums
eaf37dd2e09aee92094383226103b95957d1a454d4bc6184d9e09062afe73c6f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.7

Release files / kvleak-0.12.0-py3-none-any.whl

Download URL kvleak-0.12.0-py3-none-any.whl
Size 100.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e40ec83d79f4bff58c8088a7f0a2f7089ec686080aa99317d5afb08e4a005a6c
BLAKE2b-256 checksum
How to use checksums
9f530c96469a98557933462a8030cfdc4dd61ba90eb85275f663fed11e6d07e8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.7

Security for kvleak 0.12.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page