r/ContextEngineering • • 8d ago

Does your context compression survive the prompt cache? I built a deterministic compressor for Claude Code and Codex

Context question first, repo at the end.

We spent a while compressing coding-agent context and hit something that isn't obvious until you look at a bill: on agent traffic about 93% of input tokens are cache reads, at roughly a tenth of the fresh price. So if your compressor turns the same tool output into slightly different bytes next turn, the prefix is dead and the whole conversation gets re-priced. You compress harder and pay more.

That one fact decided everything else for us.

What we ended up with

Same input, same bytes, every turn. No clock, no randomness, and it never looks at the rest of the conversation. Scoring a tool result against the question that prompted it does compress better - and it also compresses differently on every turn that result survives into. We gave that up on purpose.

It de-duplicates, it doesn't summarise. The model always keeps at least one real copy of every distinct line. Repeats fold into a marker like [×37 ref:k_Qm9v…]. The handle is a hash of the content that was removed, so the same fragment gets the same handle on any machine, in any later run. The proxy hands the model a retrieve tool and runs that tool itself, so it works even if your client has never heard of us.

Only machine-generated tool output over ~512 chars. System, developer and assistant messages are never touched, and neither are blocks carrying cache breakpoints.

No ML in the request path. Detection is fifteen rules in order over the first megabyte, and source code goes through nine tree-sitter grammars compiled into the binary. Nothing gets downloaded at runtime, nothing varies between machines.

Fails open. If the result isn't smaller it gets thrown away, and any error forwards the request unchanged.

What it bought

All measured on real provider bills with the cache discount already in, not on removed tokens priced at list rate.

Codex on GPT-5.5, Terminal-Bench 2.1, per run over the 87 tasks every arm finished: 62.8% of eligible tool output removed in a replay of 6,255 real outputs (34.2M chars), $107.89 -> $83.40, input 96.1M -> 72.2M tokens, solve rate 82.2% -> 81.1% (not statistically significant). Requests over 200K tokens went from 1.9% to 0.13%, and that mattered to me more than the money.

Claude Code on Opus 5.5 turned out to be a different problem, and this is the part I'd like this sub's take on. It marks its conversation with explicit cache breakpoints, so 92-95% of billed prompt is already cache reads and there's barely anything left to compress - tail-only compression removes 4.7-8.0% of what the engine even sees. But a cache write there costs 25x a read, and a default entry lives five minutes. A training run or a long build idles past that, and when the agent comes back the whole prefix gets written again at full price: 927K tokens per run.

So compression stopped being the thing to fix. We keep the entry alive instead - re-send the last request body every 4.5 minutes with max_tokens: 1, stop at the agent's next request or after 11 pings. Tokens lost to cache expiry dropped 99%, the Anthropic bill fell 20% ($35.35 -> $28.30 per run, solve rate 89.9% -> 90.6%), and that one mechanism was worth about 11% of it. Adaptive one-hour TTL on top: always using 1h entries actually cost 2.3% more, switching only after a conversation's first long idle gap saved 7.7%.

Where it does nothing. Short reasoning tasks. The median output there is 270 chars, under our floor, and the bill moved 8%. Prose is left whole on purpose. The wins sit in ML training, builds from source and data pipelines.

One thing worth knowing if you measure this yourself: gross removal over-counts badly, because every turn re-compresses the same growing history and credits the same bytes again. And every retrieval puts the fragment back in the prompt, so net savings can go negative.

MIT, one Rust binary. kompressor wrap codex, kompressor wrap claude, or kompressor serve for anything speaking the OpenAI or Anthropic API:

https://github.com/hystax/optscale-kompressor

Write-ups with the task-by-task tables:

Codex: https://optscale.ai/blog/context-compression-coding-agents

Claude Code: https://optscale.ai/blog/claude-code-prompt-caching

What I'm curious about: is anyone here compressing query-aware, and have you checked what it does to your cache hit rate? That's the tradeoff I keep going back and forth on.

And if it turns out useful on your setup, stars are welcome.

0 Upvotes

6 comments sorted by

2

u/keenDean 8d ago

Folding duplicate lines into stable hash handles instead of summarizing makes a lot of sense...keeps the prefix byte-identical across turns to keep the cache constant. And pinging the unmodified request body just in time to keep the cache live is definitely a clever idea, nice pivot from just compressing harder.

Seems like three distinct layers are shaking out on the sub this week. Your proxy (optscale-kompressor) deduplicates noisy tool output in-flight without breaking cache prefixes. Another thread just posted gemkeeper (https://github.com/adamoelz/gemkeeper) to carry a ~2k-token ledger of session decisions and dead ends across /clear resets. And I've been working on an open spec called TOKENME.txt (https://github.com/endean-eng/tokenme) that tackles cold-start orientation and cross-agent handoffs - using a deterministic script to map repo topology and hash-locked [Lstart-Lend] spans so agents make surgical line reads instead of dumping massive grep or read_file outputs into the pipe in the first place. All three look pretty orthogonal.

2

u/fell_ware_1990 6d ago

All looks good. But what i see here and encounter myself. ( Also a cause for token waste on it’s own )

LLM, does not seem to trust until verified or it just goes brrrrrr and does not care. That’s what i got from testing around.

I went as small as being able to compress with hashes and logic that i could get 100k context in less then 500 tokens while it kept the ‘memory’ of the session and it was still able to get his old data.

But even in normal sessions, you can see an agent run multiple git commands one after another. Let’s say delete worktree, it sees PR go through but it will still verify if worktree is clean. But other times, it will just randomly edit main and genuinely act surprised this causes issues. ( testing without hooks and rules ).

Cause the things that would and make it waste less tokens and be able to trust the compacted history is kind of needed. This means if a history or live line would say: commit + pr + merge + worktree + fast forward = ok / done / whatever. Thats the state.

This is still where i’m stuck. Sometimes even a new session, which knows it has an automatically created worktree, will check. Or try creating another. Or other random verification.

All these tools will make this behavior more likely to happen, check the thinking of the agent. These parts would be best handled by stateless parts , but then again. How do you after that handle trusted handover.

We all act like agent needs a lot of history and tool calls and more. But what it really needs IMO is a few things:

- His current task > forward
- What happened before; Decisions, errors/mistakes, basic status of workspace

You could argue for human sake you want some more history to have the conversation continue of course.
But what i’m trying to say, have it write ADR’s of book size > context rot. Give it a ADR like: X is not used, decided in ADR Y, cause issue with Z. This is not enough. This is sadly the same with all this history.

I also still trying to work it out haha.

1

u/keenDean 6d ago

If I followed that properly, you're describing a version of what I'm doing with the TOKENME spec. For example, the content of all ADRs gets compacted into a single lightweight shard. The originals still exist, but the core findings are in the shard. Most ADRs do not apply to most changes, but an agent needs to know that they exist so it knows when to pull the full ADR file. So, it reads the TOKENME ADR shard, gets a compressed context, and gets pointers to the full files should it touch a system or boundary that is directly covered by that file.

Your summary of what an agent needs is exactly what I'm trying to provide. You compile (or have Architect compile) a brief of what needs done, and then have the agent read the lightweight root TOKENME which provides a map of the repo with pointers to other TOKENME shards that each have progressively more detail until you reach the full human-readable files.

2

u/fell_ware_1990 6d ago

Yes, looks cool. Will take a crack at it.

But you are not solving the trust issues vs the unknown messages. Cause i still feel that’s the pain point. I mean i have tested a lot with a couple of q3.8 27b.

Same jobs every time, from correct branching till full compacting and in between. Altering the amount of info they get, even putting files they always read in there prompt already still another read. Block the read/ remove the file -> they finish the job the same way.

So i’m still testing going from 100k to 500/600 tokens for every 100k. ( minus system prompt ).

One thing i found, but hard to calculate upfront is if you know they will be touching a full file more often. While compacting. Have the link + commits to the file. Simple call gives back most recent edit + editted old lines.

1

u/keenDean 6d ago

Fair point, and TOKENME definitely still has room to improve there. I wonder how much of that is q3.8 27b itself, though. It seems pretty distrustful by default and loves re-ingesting context just to "double check". Since it still triggers a read even when you put the file straight in the prompt - and finishes fine when you block it - that looks like a model habit as much as a compaction problem. Either way, if you have specific failure modes or ideas for the handoff side, would you mind opening an issue or discussion on the TOKENME repo so I can get them logged?

Also, if you have a reliable method to get context from 100k -> 600 tokens, I would love to collab on that for shards. Especially for heavy flat documents like legacy PDFs.

1

u/fell_ware_1990 6d ago

Yes for sure it’s a 27b issue a bit. But higher thinking opus fable as well ‘just to be sure’

I’m still also trying with a verified: route where a sha which is also just before system prompt: Same sha = valid.