Reversible Compression (CCR)
Compress-Cache-Retrieve architecture that makes compression lossless — the LLM can always get the original data back.
Headroom's CCR (Compress-Cache-Retrieve) architecture makes compression reversible. When content is compressed, the original data is cached locally. If the LLM needs the full data, it retrieves it instantly.
Nothing is ever thrown away
Unlike traditional lossy compression, CCR guarantees that every piece of original data remains accessible in the compression store, even when the compressed content the LLM sees is much smaller. Actual token savings depend heavily on how redundant the source data is -- see How Compression Works for measured ranges per content type.
The problem with traditional compression
Traditional compression forces a difficult tradeoff:
- Aggressive compression risks losing data the LLM needs
- Conservative compression misses out on token savings
CCR eliminates this tradeoff entirely. Compress aggressively, retrieve on demand.
Architecture
CCR flows through four phases:
TOOL OUTPUT (1000 items)
-> SmartCrusher compresses to 20 items
-> Original cached with hash=abc123
-> Retrieval tool injected into context
LLM PROCESSING
Option A: LLM solves task with 20 items -> Done (90% savings)
Option B: LLM calls headroom_retrieve(hash=abc123)
-> Response Handler returns full data automaticallyPhase 1: Compression Store
When SmartCrusher compresses tool output:
- The original content is stored, keyed by hash, with LRU-style eviction once the store hits capacity. In the proxy, this store defaults to a SQLite file (
ccr_store.dbin the workspace directory) rather than a pure in-process dict -- so it survives a proxy restart and is shared across worker processes. SetHEADROOM_CCR_BACKEND=memoryto opt back into an in-process-only store. Other backend names are resolved via theheadroom.ccr_backendsetuptools entry-point group (e.g. aredisbackend, if one is installed and registered) -- none besidessqlite/memoryship in this repo. Seeheadroom/cache/compression_store.py:1000-1017. - A hash key is generated for retrieval
- A marker is added to the compressed output:
[1000 items compressed to 20. Retrieve more: hash=abc123]Phase 2: Tool Injection
Headroom injects a headroom_retrieve tool into the LLM's available tools:
{
"name": "headroom_retrieve",
"description": "Retrieve original uncompressed data from Headroom cache",
"parameters": {
"hash": "The hash key from the compression marker"
}
}The LLM sees this tool alongside your application's tools and can call it whenever the compressed data is insufficient.
Phase 3: Response Handler
When the LLM calls headroom_retrieve:
- The Response Handler intercepts the tool call
- Data is retrieved from the local cache (around 1ms)
- The result is added to the conversation
- The API call continues automatically
The client never sees CCR tool calls on the Anthropic and OpenAI proxy paths; Headroom resolves them transparently there.
Gemini CCR boundary
Buffered native Gemini requests resolve headroom_retrieve server-side and
return the model's final response. Streaming native Gemini requests keep the
existing forwarding behavior. When a response contains headroom_retrieve
alongside a client-owned function call, Headroom preserves both calls for the
client instead of resolving the mixed response. Google's OpenAI-compatible Gemini endpoint can
also return finish_reason=MALFORMED_FUNCTION_CALL on large function-response
continuations after CCR retrieval; that separate limitation remains tracked in
issue #2041.
Phase 4: Context Tracker
Across multiple turns, the Context Tracker maintains awareness of all compressed content:
- Remembers what was compressed in earlier turns
- Analyzes new queries for relevance to compressed content
- Proactively expands relevant data before the LLM asks
Turn 1: User searches for files
-> 500 files compressed to 15, cached (hash=abc123)
-> LLM answers with 15 files
Turn 5: User asks "What about the auth middleware?"
-> Context Tracker detects "auth" may match cached content
-> Proactively expands compressed data
-> LLM finds auth_middleware.py in the full listRetrieving originals
CCR works automatically on the Anthropic and OpenAI proxy paths, but you can also retrieve cached data programmatically:
import { } from "headroom-ai";
import type { } from "headroom-ai";
// CCR is enabled by default when compressing through the proxy.
const = await (messages, {
: "gpt-4o",
});
// Access compressed messages — CCR markers are embedded automatically
.(.messages);
// CCR configuration options
const : = {
: true,
: true, // Inject headroom_retrieve tool
: true, // Add retrieval markers to compressed output
: true, // Learn from retrieval patterns
: 1000, // Max cached items
: 3600, // Cache TTL
};The full CCR loop -- markers injected, headroom_retrieve tool added to the
request, and the model's retrieval call resolved automatically -- only runs
through headroom proxy (headroom/proxy/handlers/*.py wire tool injection
and the response handler; the direct SDK client does not). Point an OpenAI
client at the proxy to get it:
from openai import OpenAI
# Start `headroom proxy` first (defaults to port 8787); use --no-optimize
# for a passthrough baseline or --no-ccr to disable CCR specifically.
client = OpenAI(base_url="http://127.0.0.1:8787/v1", api_key="local")
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
)HeadroomClient (the direct SDK integration, no proxy) still routes JSON
tool outputs through SmartCrusher and embeds <<ccr:HASH>> markers when a
compression ratio warrants one, and the original is stored and retrievable
via headroom.cache.compression_store. It does not, however, inject the
headroom_retrieve tool or intercept the model's retrieval call for you --
that wiring lives only in the proxy's request handlers. Resolve markers
yourself with headroom.ccr.marker_resolution.resolve_markers_in_text if
you're integrating CCR outside the proxy.
Retention
Proxy CCR originals are kept for 1800 seconds (30 minutes) by default. For longer autonomous
agent runs, set HEADROOM_CCR_TTL_SECONDS before starting the proxy:
HEADROOM_CCR_TTL_SECONDS=7200 headroom proxyCheck the effective setting at /v1/retrieve/stats under
store.default_ttl_seconds.
Message-level CCR
Retired: The "Message-level CCR via IntelligentContext" feature (where
IntelligentContextwould store dropped messages in CCR with a retrieval marker) was part of theIntelligentContextConfigAPI that has since been removed. Context management is now handled automatically by the pipeline without a separate configurable IntelligentContext stage. Tool-output CCR via SmartCrusher and ContentRouter remains fully supported.
CCR-enabled components
| Component | What it compresses | CCR integration |
|---|---|---|
| SmartCrusher | JSON arrays (tool outputs) | Stores original array, marker includes hash |
| ContentRouter | Code, logs, search results, text | Stores original content by strategy |
Why CCR matters
| Approach | Risk | Savings |
|---|---|---|
| No compression | None | 0% |
| Traditional compression | Data loss | Depends on content and target ratio |
| CCR compression | None (reversible) | Same range as traditional compression -- CCR changes the risk, not the ratio |
CCR gives you the savings of aggressive compression with zero risk: SmartCrusher, LogCompressor, SearchCompressor, and Kompress can all compress as aggressively as their configuration allows, because the original is always one retrieval away. See How Compression Works for measured savings ranges per compressor.