Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
feat(ccr): Redis backend, one CCR store for every replica (#4368)
Tejas Chopra185454be49d6
diff --git a/headroom/cache/backends/base.py b/headroom/cache/backends/base.pyindex ad3c3cec6..9f7538d7f 100644--- a/headroom/cache/backends/base.py+++ b/headroom/cache/backends/base.py@@ -49,13 +49,18 @@ class CompressionStoreBackend(Protocol):"""...- def set(self, hash_key: str, entry: CompressionEntry) -> None:+ def set(self, hash_key: str, entry: CompressionEntry) -> bool | None:"""Store an entry with the given hash key.Args:hash_key: The unique hash identifying the entry.entry: The CompressionEntry to store.+ Returns:+ ``False`` when a backend that absorbs its errors did not store it+ (``CompressionStore.store`` then raises ``StorageError``);+ ``None`` (or ``True``) otherwise.+Note:Overwrites any existing entry with the same key."""diff --git a/headroom/cache/backends/redis.py b/headroom/cache/backends/redis.pynew file mode 100644index 000000000..e6cc93307--- /dev/null+++ b/headroom/cache/backends/redis.py@@ -0,0 +1,117 @@+"""Redis storage backend for CompressionStore: one CCR store for every replica.++A ``<<ccr:hash>>`` marker points at an original kept by whichever replica+compressed it; behind a gateway that spreads requests across replicas, the+retrieval can land anywhere. With ``HEADROOM_CCR_BACKEND=redis`` and+``HEADROOM_REDIS_URL``, every replica reads and writes one store.++Each entry is one key, ``<prefix>:ccr:<hash>``, holding the entry as JSON and+expiring when the entry does (``created_at + ttl``). A Redis error is a miss+(see :mod:`headroom.cache.redis_client`): a retrieval then fails as it would for+an expired entry, and compression never waits on Redis.+"""++from __future__ import annotations++import json+import time+from dataclasses import asdict, fields+from typing import TYPE_CHECKING, Any++from ..redis_client import Guard, connect, key_prefix++if TYPE_CHECKING:+ from ..compression_store import CompressionEntry+++class RedisBackend:+ """CCR entries in Redis, shared by every replica that points at it."""++ #: Redis expires each entry with its TTL: CompressionStore neither caps nor+ #: sweeps this store (a per-replica cap would evict other replicas' entries).+ expires_entries = True++ def __init__(self, url: str, client: Any = None) -> None:+ self._client = client if client is not None else connect(url, setting="HEADROOM_REDIS_URL")+ self._prefix = f"{key_prefix()}:ccr:"+ self._guard = Guard("CCR store")++ def _key(self, hash_key: str) -> str:+ return self._prefix + hash_key++ def get(self, hash_key: str) -> CompressionEntry | None:+ raw = self._guard.call("read", lambda: self._client.get(self._key(hash_key)), None)+ return None if raw is None else _decode(raw)++ def set(self, hash_key: str, entry: CompressionEntry) -> bool:+ """Whether Redis took the entry (an error is logged, not raised)."""+ remaining_ms = int((entry.created_at + entry.ttl - time.time()) * 1000)+ if remaining_ms <= 0:+ return False+ blob = json.dumps(asdict(entry))+ return bool(+ self._guard.call(+ "write", lambda: self._client.set(self._key(hash_key), blob, px=remaining_ms), None+ )+ )++ def delete(self, hash_key: str) -> bool:+ return bool(self._guard.call("delete", lambda: self._client.delete(self._key(hash_key)), 0))++ def exists(self, hash_key: str) -> bool:+ return bool(self._guard.call("read", lambda: self._client.exists(self._key(hash_key)), 0))++ def clear(self) -> None:+ keys = self._scan()+ if keys:+ self._guard.call("delete", lambda: self._client.delete(*keys), 0)++ def count(self) -> int:+ return len(self._scan())++ def keys(self) -> list[str]:+ return [k[len(self._prefix) :] for k in self._scan()]++ def items(self) -> list[tuple[str, CompressionEntry]]:+ out = []+ for hash_key in self.keys():+ entry = self.get(hash_key)+ if entry is not None:+ out.append((hash_key, entry))+ return out++ def purge_expired(self, now: float | None = None) -> int:+ """Redis has already dropped them."""+ return 0++ def get_stats(self) -> dict[str, Any]:+ return {"backend_type": "redis", "entry_count": self.count()}++ def _scan(self) -> list[str]:+ def scan() -> list[str]:+ return [+ k.decode() if isinstance(k, bytes) else k+ for k in self._client.scan_iter(match=_glob_escape(self._prefix) + "*", count=500)+ ]++ return self._guard.call("scan", scan, [])+++def _decode(raw: Any) -> CompressionEntry | None:+ """An entry from its JSON, or ``None`` when it is not one (a miss)."""+ from ..compression_store import CompressionEntry++ try:+ data = json.loads(raw)+ known = {f.name for f in fields(CompressionEntry)}+ entry = CompressionEntry(**{k: v for k, v in data.items() if k in known})+ except (ValueError, TypeError, AttributeError):+ return None+ texts_ok = isinstance(entry.original_content, str) and isinstance(entry.compressed_content, str)+ times_ok = isinstance(entry.created_at, (int, float)) and isinstance(entry.ttl, int)+ return entry if texts_ok and times_ok else None+++def _glob_escape(text: str) -> str:+ """``text`` matched literally in a SCAN pattern."""+ return "".join("\\" + c if c in "*?[]\\" else c for c in text)diff --git a/headroom/cache/compression_store.py b/headroom/cache/compression_store.pyindex 8809a2b3b..62fba17f3 100644--- a/headroom/cache/compression_store.py+++ b/headroom/cache/compression_store.py@@ -43,6 +43,7 @@ from contextvars import ContextVarfrom dataclasses import asdict, dataclass, field, replacefrom typing import TYPE_CHECKING, Any+from ..exceptions import StorageErrorfrom ..log_safety import describe_exception, safe_idif TYPE_CHECKING:@@ -279,6 +280,14 @@ class CompressionStore:self._heap_rebuild_threshold = 0.5external_revision = getattr(self._backend, "external_revision", None)self._backend_revision_reader = external_revision if callable(external_revision) else None+ # A backend that expires entries itself and is shared by replicas+ # (Redis) is bounded by TTL, not by this process's max_entries: counting+ # it on every store would scan the shared keyspace, and evicting would+ # remove other replicas' live entries.+ self._backend_expires_entries = bool(getattr(self._backend, "expires_entries", False))+ # A shared store's totals, as this process contributed them since it+ # started: [original tokens stored, compressed tokens stored, retrievals].+ self._own_totals = [0, 0, 0]self._backend_revision = self._read_backend_revision()@property@@ -329,6 +338,11 @@ class CompressionStore:Returns:Hash key for retrieving this content.++ Raises:+ StorageError: The backend did not keep the entry (a shared store+ refused the write or was unreachable). No hash is issued for+ it: the caller must keep the original rather than emit a marker."""# Generate hash from original content. Default: SHA-256[:24] of the# original. When the caller provides `explicit_hash`, use it@@ -424,7 +438,8 @@ class CompressionStore:# turn a marker is re-encountered, so duplicate stores are common.existing = self._backend.get(hash_key)if existing is None:- self._evict_if_needed()+ if not self._backend_expires_entries:+ self._evict_if_needed()else:# Hash already present. Different content means a true (extremely# rare with SHA256[:24]) collision; same content is a duplicate@@ -445,7 +460,18 @@ class CompressionStore:# Mark old heap entry as stale since we're replacing it.self._mark_heap_entries_stale()- self._backend.set(hash_key, entry)+ if self._backend.set(hash_key, entry) is False:+ # Only a backend that absorbs its errors (Redis) returns False;+ # it has logged why. A hash here would be a marker that never+ # resolves, and producers drop the original once they hold one.+ raise StorageError(+ f"CCR store did not keep hash={hash_key}; keep the original content"+ )+ if self._backend_expires_entries:+ if existing is None:+ self._own_totals[0] += entry.original_tokens+ self._own_totals[1] += entry.compressed_tokens+ return hash_key # no local index: Redis expires it# MEDIUM FIX #16: Add to eviction heap for O(log n) evictionheapq.heappush(self._eviction_heap, (entry.created_at, hash_key))heapq.heappush(@@ -485,8 +511,13 @@ class CompressionStore:# Track access for feedbackentry.record_access(query)- # Update the backend with the modified entry- self._backend.set(hash_key, entry)+ # Update the backend with the modified entry. Not a shared store:+ # writing the whole entry back per read races other replicas and+ # resends the original; retrieval events below stay per process.+ if self._backend_expires_entries:+ self._own_totals[2] += 1+ else:+ self._backend.set(hash_key, entry)# Log retrieval eventif self._enable_feedback:@@ -654,6 +685,25 @@ class CompressionStore:def get_stats(self) -> dict[str, Any]:"""Get store statistics for monitoring."""+ if self._backend_expires_entries:+ # Totals over the store would read every replica's entries (a GET+ # each) under the lock retrievals take: a shared store reports the+ # entry count across replicas, and the totals this replica added+ # since it started ("totals_scope").+ backend_stats = self._backend.get_stats()+ with self._lock:+ original, compressed, retrievals = self._own_totals+ return {+ "entry_count": backend_stats["entry_count"],+ "max_entries": self._max_entries,+ "default_ttl_seconds": self._default_ttl,+ "total_original_tokens": original,+ "total_compressed_tokens": compressed,+ "total_retrievals": retrievals,+ "totals_scope": "this_replica",+ "event_count": len(self._retrieval_events),+ "backend": backend_stats,+ }with self._lock:# Clean expired entriesself._clean_expired()@@ -704,10 +754,15 @@ class CompressionStore:return ComponentStats(name="compression_store",- entry_count=self._backend.count(),+ entry_count=backend_stats.get("entry_count", 0)+ if self._backend_expires_entries+ else self._backend.count(),size_bytes=bytes_used,budget_bytes=None, # No budget set yet- hits=sum(1 for _, e in self._backend.items() if e.retrieval_count > 0),+ # A shared store would be read whole to count these.+ hits=0+ if self._backend_expires_entries+ else sum(1 for _, e in self._backend.items() if e.retrieval_count > 0),misses=0, # CompressionStore doesn't track misses directlyevictions=0, # Would need to track this separately)@@ -868,6 +923,8 @@ class CompressionStore:def _mark_heap_entries_stale(self) -> None:"""Record lazy tuples invalidated by deleting or replacing an entry."""+ if self._backend_expires_entries:+ return # no index kept for a self-expiring backendself._stale_heap_entries += 1self._stale_expiration_heap_entries += 1@@ -892,6 +949,8 @@ class CompressionStore:def _rebuild_heap_if_needed(self) -> None:"""Rebuild both indexes when either stale ratio reaches the threshold."""+ if self._backend_expires_entries:+ return # rebuilding would scan the shared storeheap_size = len(self._eviction_heap)expiration_heap_size = len(self._expiration_heap)stale_ratio = self._stale_heap_entries / heap_size if heap_size else 0@@ -1155,8 +1214,10 @@ def _create_default_ccr_backend() -> CompressionStoreBackend | None:Default (env unset or "sqlite"): SQLiteBackend at workspace_dir()/ccr_store.db— restart-safe and shared across worker processes, which thesession-scale 30-minute TTL assumes.- "memory" opts back into the in-process dict. Other values load- adapters via setuptools entry point 'headroom.ccr_backend'.+ "memory" opts back into the in-process dict. "redis" shares one store+ across replicas (HEADROOM_REDIS_URL; headroom.cache.backends.redis) unless a+ plugin registers that name. Other values load adapters via setuptools entry+ point 'headroom.ccr_backend'.Returns None to use InMemoryBackend.Stateless mode (``--stateless`` / ``HEADROOM_STATELESS``) never opens the@@ -1193,6 +1254,19 @@ def _create_default_ccr_backend() -> CompressionStoreBackend | None:all_eps = entry_points(group="headroom.ccr_backend")ep = next((e for e in all_eps if e.name == backend_type), None)+ if ep is None and backend_type == "redis":+ # Built in: one store for every replica behind a gateway. A plugin+ # registered as "redis" still wins, above.+ from .backends.redis import RedisBackend++ url = os.environ.get("HEADROOM_REDIS_URL", "").strip()+ if not url:+ logger.error(+ "HEADROOM_CCR_BACKEND=redis needs HEADROOM_REDIS_URL; using the "+ "in-process store, so a marker resolves only on the replica that made it"+ )+ return None+ return RedisBackend(url)if ep is None:logger.warning("HEADROOM_CCR_BACKEND=%s but no entry point headroom.ccr_backend[%s]",diff --git a/headroom/cache/redis_client.py b/headroom/cache/redis_client.pynew file mode 100644index 000000000..6753640b3--- /dev/null+++ b/headroom/cache/redis_client.py@@ -0,0 +1,121 @@+"""Redis connections for state that several Headroom replicas share.++The CCR store (``HEADROOM_CCR_BACKEND=redis``) and shared ``/v1/compress``+sessions keep their keys under ``HEADROOM_REDIS_KEY_PREFIX`` (default+``headroom``), so two deployments can share one Redis without sharing state.++Redis holds tool output and transcripts verbatim: it must be private to the+deployment, with authentication and TLS (``rediss://``). Plain ``redis://`` to a+host other than this machine is accepted with a warning.++Shared state is an optimisation of a request, never a condition for it: a Redis+error is a miss, logged when it starts and when Redis is back, and Redis is not+asked again for :data:`BACKOFF_SECONDS` after a connection failure, so an outage+costs requests nothing but the sharing.+"""++from __future__ import annotations++import logging+import os+import re+import threading+import time+from collections.abc import Callable+from typing import Any, TypeVar+from urllib.parse import urlsplit++from headroom.exceptions import ConfigurationError++logger = logging.getLogger(__name__)++PREFIX_ENV = "HEADROOM_REDIS_KEY_PREFIX"+#: Seconds Redis is skipped after a connection error.+BACKOFF_SECONDS = 5.0+#: Seconds a command may take. Commands carry small values (an entry, a few+#: messages), so a slow one is an outage, not a large transfer.+TIMEOUT_SECONDS = 1.0++T = TypeVar("T")+++def key_prefix() -> str:+ return os.environ.get(PREFIX_ENV, "").strip() or "headroom"+++def connect(url: str, *, setting: str) -> Any:+ """A client for ``url``. Raises :class:`ConfigurationError`, naming+ ``setting``, when the URL is not Redis or the client is not installed.+ Does not connect: an unreachable Redis does not stop startup."""+ scheme = urlsplit(url).scheme+ if scheme not in ("redis", "rediss", "unix"):+ raise ConfigurationError(f"{setting} must be a redis://, rediss:// or unix:// URL")+ try:+ import redis+ except ImportError as exc:+ raise ConfigurationError(+ f"{setting} names Redis but the client is not installed: "+ "pip install 'headroom-ai[redis]'"+ ) from exc+ from headroom.proxy.loopback_guard import is_loopback_host++ host = urlsplit(url).hostname+ if scheme == "redis" and not is_loopback_host(host):+ logger.warning(+ "%s: plain redis:// to %s; Redis will hold tool output and transcripts, "+ "so use rediss:// with authentication on a private network",+ setting,+ host,+ )+ return redis.Redis.from_url(+ url, socket_timeout=TIMEOUT_SECONDS, socket_connect_timeout=TIMEOUT_SECONDS+ )+++class Guard:+ """Runs Redis calls for one feature: an error is a miss, logged when that+ kind of call (``what``: read, write, ...) starts failing and when it works+ again; after a connection error Redis is skipped for :data:`BACKOFF_SECONDS`.+ Tracking each kind apart keeps a Redis that serves reads but refuses writes+ (``maxmemory`` with ``noeviction``) from logging on every request."""++ def __init__(self, feature: str) -> None:+ import redis++ self._feature = feature+ self._errors: tuple[type[BaseException], ...] = (redis.RedisError,)+ self._connection_errors = (redis.ConnectionError, redis.TimeoutError)+ self._lock = threading.Lock()+ self._skip_until = 0.0+ self._failing: set[str] = set()++ def call(self, what: str, fn: Callable[[], T], default: T) -> T:+ if time.monotonic() < self._skip_until:+ return default+ try:+ result = fn()+ except self._errors as exc:+ with self._lock:+ if isinstance(exc, self._connection_errors):+ self._skip_until = time.monotonic() + BACKOFF_SECONDS+ if what not in self._failing:+ self._failing.add(what)+ logger.warning(+ "%s: Redis %s failed (%s: %s); carrying on without shared state",+ self._feature,+ what,+ type(exc).__name__,+ _redact(str(exc)),+ )+ return default+ if what in self._failing:+ with self._lock:+ if what in self._failing:+ self._failing.discard(what)+ logger.info("%s: Redis %s works again", self._feature, what)+ return result+++def _redact(message: str) -> str:+ """``message`` with any URL credentials (``//user:password@``) masked."""+ return re.sub(r"//[^/@\s]*@", "//***@", message)diff --git a/headroom/ccr/mcp_server.py b/headroom/ccr/mcp_server.pyindex 74750eb9e..b4fa84f3c 100644--- a/headroom/ccr/mcp_server.py+++ b/headroom/ccr/mcp_server.py@@ -36,6 +36,7 @@ from typing import TYPE_CHECKING, Anyfrom headroom import paths as _pathsfrom headroom import savings_ledgerfrom headroom.cache.compression_store import format_retrieval_miss_detail+from headroom.exceptions import StorageErrorfrom headroom.log_safety import describe_exception, redact_url, safe_idfrom headroom.telemetry import session as telemetry_session@@ -460,16 +461,31 @@ class HeadroomMCPServer:# Store original in local store for later retrievalstore = self._get_local_store()- hash_key = store.store(- original=content,- compressed=compressed_content- if isinstance(compressed_content, str)- else json.dumps(compressed_content),- original_tokens=input_tokens,- compressed_tokens=output_tokens,- compression_strategy="mcp_compress",- ttl=MCP_SESSION_TTL,- )+ try:+ hash_key = store.store(+ original=content,+ compressed=compressed_content+ if isinstance(compressed_content, str)+ else json.dumps(compressed_content),+ original_tokens=input_tokens,+ compressed_tokens=output_tokens,+ compression_strategy="mcp_compress",+ ttl=MCP_SESSION_TTL,+ )+ except StorageError as e:+ # No stored original: hand back the content itself, which also+ # keeps out any marker the pipeline put in the compressed text.+ logger.warning("headroom_compress: returning the original, CCR store refused it: %s", e)+ return {+ "compressed": content,+ "hash": None,+ "original_tokens": input_tokens,+ "compressed_tokens": input_tokens,+ "tokens_saved": 0,+ "savings_percent": 0,+ "transforms": [],+ "note": "Not compressed: the CCR store could not keep the original.",+ }# Track statsstrategy = (@@ -1085,16 +1101,21 @@ class HeadroomMCPServer:# Fresh read: store in CCR and cache the hashstore = self._get_local_store()token_estimate = self._estimate_tokens(content)- ccr_hash = store.store(- original=content,- compressed=f"[File: {path.name}, {line_count} lines]",- original_tokens=token_estimate,- compressed_tokens=5,- tool_name="headroom_read",- ttl=MCP_SESSION_TTL,- )-- self._file_cache[str_path] = (content_hash, ccr_hash, line_count, token_estimate)+ try:+ ccr_hash = store.store(+ original=content,+ compressed=f"[File: {path.name}, {line_count} lines]",+ original_tokens=token_estimate,+ compressed_tokens=5,+ tool_name="headroom_read",+ ttl=MCP_SESSION_TTL,+ )+ except StorageError as e:+ # The full content is returned below either way; without a stored+ # original, a re-read must not answer with a hash.+ logger.warning("headroom_read: not cached, the CCR store refused it: %s", e)+ else:+ self._file_cache[str_path] = (content_hash, ccr_hash, line_count, token_estimate)# Return full content with line numbers (like Claude Code's Read tool)numbered_lines = []diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex b1b0f8a06..36701bda0 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -5378,6 +5378,9 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:"original_tokens_cached": compression_stats.get("total_original_tokens", 0),"compressed_tokens_cached": compression_stats.get("total_compressed_tokens", 0),"ccr_retrievals": compression_stats.get("total_retrievals", 0),+ # "this_replica" with a shared store: the token and retrieval+ # counts are this process's since it started, not the store's.+ "totals_scope": compression_stats.get("totals_scope", "store"),},"compression_cache": compression_cache_stats,# Per-language AST compression pauses. Empty on a healthy install;diff --git a/headroom/transforms/base.py b/headroom/transforms/base.pyindex d541d1c7d..07298a821 100644--- a/headroom/transforms/base.py+++ b/headroom/transforms/base.py@@ -13,14 +13,15 @@ from ..tokenizer import Tokenizerlogger = logging.getLogger(__name__)-def persist_rust_ccr_entry(original: str, compressed: str, cache_key: str, *, source: str) -> None:+def persist_rust_ccr_entry(original: str, compressed: str, cache_key: str, *, source: str) -> bool:"""Store a Rust-emitted CCR entry in the production ``CompressionStore``.The Rust search/diff/log compressors emit a retrieval marker but keep theoriginal only in their in-memory test store. This writes it through to thelong-lived Python store so the marker resolves. Failures are logged atwarning level with ``source`` (the compressor name): a store hiccup must not- break the response, just degrade retrieval.+ break the response. Returns whether the store kept it; when it did not, the+ caller returns the input unchanged rather than a marker that points nowhere."""try:from ..cache.compression_store import get_compression_store@@ -32,13 +33,14 @@ def persist_rust_ccr_entry(original: str, compressed: str, cache_key: str, *, sosafe_id(e),)logger.debug("CCR store import failure detail: %s", describe_exception(e))- return+ return Falsetry:store: Any = get_compression_store()# The Rust-emitted marker embeds MD5(original)[:24], but store() has# defaulted to SHA-256(original)[:24] since PR #395. Pass the marker's# key explicitly so retrieving the marker hash finds the entry (#816).store.store(original, compressed, explicit_hash=cache_key)+ return Trueexcept Exception as e:# Store backends can echo the payload in errors. The WARNING names only# the exception type; the DEBUG record has types and code locations, or@@ -50,6 +52,7 @@ def persist_rust_ccr_entry(original: str, compressed: str, cache_key: str, *, socache_key,)logger.debug("CCR store write failure detail: %s", describe_exception(e))+ return Falseclass Transform(ABC):diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.pyindex 9d56c87f6..30552ca09 100644--- a/headroom/transforms/content_router.py+++ b/headroom/transforms/content_router.py@@ -3691,8 +3691,15 @@ class ContentRouter(Transform):# Count with the router's OWN estimator, not the compressor's self-report.compressed_tokens = _estimate_tokens(compressed)# Persist the hash -> original recovery map the SAME way SmartCrusher- # mirrors its markers, so a later /v1/retrieve resolves each hash.- self._persist_external_recoverable(out.recoverable, name, context)+ # mirrors its markers, so a later /v1/retrieve resolves each hash. A+ # hash the store did not take points nowhere: fall back instead.+ if not self._persist_external_recoverable(out.recoverable, name, context):+ logger.warning(+ "external compressor %r: CCR store did not keep its originals; "+ "falling back to built-in",+ name,+ )+ return Noneif out.warnings:logger.debug("external compressor %r warnings: %s", name, "; ".join(map(str, out.warnings))@@ -3705,29 +3712,33 @@ class ContentRouter(Transform):def _persist_external_recoverable(self, recoverable: dict[str, str], name: str, context: str- ) -> None:+ ) -> bool:"""Mirror an external compressor's hash -> original map into the CCR store.Mirrors SmartCrusher's ``_mirror_single_hash_to_python_store``: eachentry is stored under its own hash via ``explicit_hash`` so a- ``/v1/retrieve/{hash}`` lookup returns the original. Best-effort — a- store failure or a non-hex hash is logged and never breaks the request- (the compressed block is still returned; only that entry is unretrievable).+ ``/v1/retrieve/{hash}`` lookup returns the original. Returns whether+ every entry was stored (True without a store module, as SmartCrusher):+ on False the caller discards the compressed block, whose markers would+ point nowhere. Failures are logged and never break the request."""if not recoverable:- return+ return Truetry:from ..cache.compression_store import get_compression_store-+ except ImportError as exc: # stripped builds ship no CCR store+ logger.debug("external compressor %r: CCR store unavailable (%s)", name, exc)+ return True+ try:store = get_compression_store()- except Exception as exc: # noqa: BLE001 - CCR store optional/stripped builds+ except Exception as exc: # noqa: BLE001 - never break the requestlogger.debug("external compressor %r: CCR store unavailable (%s)", name, exc)- return+ return Falsestrategy_label = f"external:{name}"for ccr_hash, original in recoverable.items():if not isinstance(ccr_hash, str) or not isinstance(original, str):- logger.debug("external compressor %r: skipping non-str recoverable entry", name)- continue+ logger.debug("external compressor %r: non-str recoverable entry", name)+ return Falsetry:store.store(original=original,@@ -3747,8 +3758,11 @@ class ContentRouter(Transform):name,ccr_hash,)+ return Falseexcept Exception as exc: # noqa: BLE001 - defensive; never break the requestlogger.debug("external compressor %r: store.store raised (%s)", name, exc)+ return False+ return Truedef _registry_compress(self,diff --git a/headroom/transforms/diff_compressor.py b/headroom/transforms/diff_compressor.pyindex 9bfacc9b8..2305c9572 100644--- a/headroom/transforms/diff_compressor.py+++ b/headroom/transforms/diff_compressor.py@@ -113,7 +113,17 @@ class DiffCompressor:# call. Without this, every diff CCR marker emitted in# production is dangling — the regression fixed in the# audit-cleanup PR.- persist_rust_ccr_entry(content, r.compressed, cache_key, source="diff")+ if not persist_rust_ccr_entry(content, r.compressed, cache_key, source="diff"):+ return DiffCompressionResult( # unstored original: no marker+ compressed=content,+ original_line_count=r.original_line_count,+ compressed_line_count=r.original_line_count,+ files_affected=r.files_affected,+ additions=r.additions,+ deletions=r.deletions,+ hunks_kept=r.hunks_kept + r.hunks_removed,+ hunks_removed=0,+ )return DiffCompressionResult(compressed=r.compressed,original_line_count=r.original_line_count,diff --git a/headroom/transforms/log_compressor.py b/headroom/transforms/log_compressor.pyindex c5cb05250..f5be42c0e 100644--- a/headroom/transforms/log_compressor.py+++ b/headroom/transforms/log_compressor.py@@ -199,8 +199,17 @@ class LogCompressor:del contextrust_result = self._rust.compress(content, bias)cache_key: str | None = rust_result.cache_key- if cache_key is not None:- persist_rust_ccr_entry(content, rust_result.compressed, cache_key, source="log")+ if cache_key is not None and not persist_rust_ccr_entry(+ content, rust_result.compressed, cache_key, source="log"+ ):+ return LogCompressionResult( # unstored original: no marker+ compressed=content,+ original=content,+ original_line_count=rust_result.original_line_count,+ compressed_line_count=rust_result.original_line_count,+ format_detected=_format_from_str(rust_result.format_detected),+ compression_ratio=1.0,+ )stats_dict = {k: int(v) for k, v in cast("dict[str, int]", rust_result.stats).items()}return LogCompressionResult(diff --git a/headroom/transforms/read_lifecycle.py b/headroom/transforms/read_lifecycle.pyindex 43a6ceea9..66e8672e4 100644--- a/headroom/transforms/read_lifecycle.py+++ b/headroom/transforms/read_lifecycle.py@@ -475,7 +475,8 @@ class ReadLifecycleManager:return False, content, None# Best-effort CCR persistence (mirrors read_maturation.py): a store- # failure must not break compress().+ # failure must not break compress(), and keeps the Read verbatim — a+ # marker would point at an original nobody stored.ccr_hash = hashlib.sha256(content.encode()).hexdigest()[:24]if self.store is not None:try:@@ -493,6 +494,7 @@ class ReadLifecycleManager:classification.tool_call_id,e,)+ return False, content, Nonefile_display = classification.file_path or "unknown"diff --git a/headroom/transforms/read_maturation.py b/headroom/transforms/read_maturation.pyindex 2f5f833da..cd40c4d14 100644--- a/headroom/transforms/read_maturation.py+++ b/headroom/transforms/read_maturation.py@@ -412,7 +412,10 @@ class ReadMaturationManager:compression_strategy="read_maturation",)except Exception as e: # noqa: BLE001 - storage failure must not break the request+ # Keep it verbatim (a marker would point at nothing); a later+ # request matures it once the store takes it.logger.warning("read_maturation: CCR store failed for %s: %s", tc_id, e)+ return None, Falsefile_display = file_path or "unknown"# NOTE: "Retrieve original: hash=" is load-bearing (marker-diff --git a/headroom/transforms/search_compressor.py b/headroom/transforms/search_compressor.pyindex cc98022d5..b2c1c91c1 100644--- a/headroom/transforms/search_compressor.py+++ b/headroom/transforms/search_compressor.py@@ -171,12 +171,21 @@ class SearchCompressor:) -> SearchCompressionResult:rust_result = self._rust.compress(content, context, bias)cache_key: str | None = rust_result.cache_key- if cache_key is not None:- # Mirror the original Python: persist to the production CCR- # store. The Rust crate already wrote to its in-memory test- # store; promote that to the long-lived Python store so the- # marker remains retrievable beyond the request lifecycle.- persist_rust_ccr_entry(content, rust_result.compressed, cache_key, source="search")+ # Mirror the original Python: persist to the production CCR+ # store. The Rust crate already wrote to its in-memory test+ # store; promote that to the long-lived Python store so the+ # marker remains retrievable beyond the request lifecycle.+ if cache_key is not None and not persist_rust_ccr_entry(+ content, rust_result.compressed, cache_key, source="search"+ ):+ return SearchCompressionResult( # unstored original: no marker+ compressed=content,+ original=content,+ original_match_count=rust_result.original_match_count,+ compressed_match_count=rust_result.original_match_count,+ files_affected=rust_result.files_affected,+ compression_ratio=1.0,+ )summaries = dict(cast("dict[str, str]", rust_result.summaries))return SearchCompressionResult(diff --git a/headroom/transforms/smart_crusher.py b/headroom/transforms/smart_crusher.pyindex 7713c6e5e..12033aada 100644--- a/headroom/transforms/smart_crusher.py+++ b/headroom/transforms/smart_crusher.py@@ -515,6 +515,7 @@ class SmartCrusher(Transform):# (``{...} {...} {...}``) rather than a real array. The Rust crusher# only compresses JSON arrays, so normalize that shape first —# otherwise it passes through at 0% compression (#1741).+ given = contentnormalized = normalize_concatenated_json(content)if normalized is not None:content = normalized@@ -524,6 +525,17 @@ class SmartCrusher(Transform):else self._build_rust(bool(lossless_only)))r = rust.crush(content, query, bias)+ # Bridge any CCR markers emitted by the Rust crusher into the+ # Python compression_store so /v1/retrieve resolves them; a marker+ # the store did not take points nowhere, so keep the input instead.+ # See `_mirror_ccr_to_python_store` for full rationale.+ if not self._mirror_ccr_to_python_store(+ rendered=r.compressed,+ strategy=r.strategy,+ query_context=query,+ tool_name=None,+ ):+ return CrushResult(compressed=given, original=given, was_modified=False)# Re-attach the TOIN learning loop. The retired Python class# recorded compressions into TOIN inline; the Rust port doesn't# know about TOIN, and `ContentRouter._record_to_toin` skips@@ -544,15 +556,6 @@ class SmartCrusher(Transform):query_context=query,tool_name=None,)- # Bridge any CCR markers emitted by the Rust crusher into the- # Python compression_store so /v1/retrieve resolves them.- # See `_mirror_ccr_to_python_store` for full rationale.- self._mirror_ccr_to_python_store(- rendered=r.compressed,- strategy=r.strategy,- query_context=query,- tool_name=None,- )return CrushResult(compressed=r.compressed,original=r.original,@@ -794,9 +797,10 @@ class SmartCrusher(Transform):# already stashed the canonical in its own store. Mirror that# entry into the Python compression_store keyed by the same# 12-char SHA-256 hash so /v1/retrieve resolves it.+ mirrored = Trueccr_hash = result.get("ccr_hash")if ccr_hash:- self._mirror_single_hash_to_python_store(+ mirrored = self._mirror_single_hash_to_python_store(ccr_hash,strategy=str(result.get("strategy_info") or "smart_crusher_row_drop"),query_context=query,@@ -804,22 +808,20 @@ class SmartCrusher(Transform):)# Opaque-blob substitutions inside the kept items also produce# markers. Walk the rendered shape to bridge those too.- kept_json = result.get("items")- if isinstance(kept_json, str) and "<<ccr:" in kept_json:- self._mirror_ccr_markers_in_text(- kept_json,- strategy=str(result.get("strategy_info") or "smart_crusher"),- query_context=query,- tool_name=None,- )- compacted = result.get("compacted")- if isinstance(compacted, str) and "<<ccr:" in compacted:- self._mirror_ccr_markers_in_text(- compacted,- strategy=str(result.get("strategy_info") or "smart_crusher"),- query_context=query,- tool_name=None,- )+ strategy = str(result.get("strategy_info") or "smart_crusher")+ for rendered in (result.get("items"), result.get("compacted")):+ if mirrored and isinstance(rendered, str):+ mirrored = self._mirror_ccr_to_python_store(rendered, strategy, query, None)+ if not mirrored:+ # A marker the store did not take points nowhere: keep the input.+ return {+ "items": items_json,+ "ccr_hash": None,+ "dropped_summary": "",+ "strategy_info": "passthrough",+ "compacted": None,+ "compaction_kind": None,+ }return resultdef compact_document_json(self, doc_json: str) -> str:@@ -836,13 +838,8 @@ class SmartCrusher(Transform):result: str = self._rust.compact_document_json(doc_json)# Mirror any opaque-blob markers the walker emitted into the# Python store so /v1/retrieve resolves them.- if "<<ccr:" in result:- self._mirror_ccr_markers_in_text(- result,- strategy="smart_crusher_compact_document",- query_context="",- tool_name=None,- )+ if not self._mirror_ccr_to_python_store(result, "smart_crusher_compact_document", "", None):+ return doc_json # a marker the store did not take points nowherereturn resultdef ccr_get(self, hash_key: str) -> str | None:@@ -890,6 +887,17 @@ class SmartCrusher(Transform):crushed, was_modified, info = self._apply_audit_safe_protection_to_content(protected, content, crushed, was_modified, info)+ # Bridge any CCR markers (row-drop sentinels or opaque-blob+ # substitutions) emitted by the Rust crusher into the Python+ # compression_store so /v1/retrieve resolves them; a marker the+ # store did not take points nowhere, so keep the input instead.+ if not self._mirror_ccr_to_python_store(+ rendered=crushed,+ strategy=info or "smart_crusher",+ query_context=query_context,+ tool_name=tool_name,+ ):+ return content, False, "passthrough"# Same passthrough filter as `crush()` — re-canonicalization of# JSON whitespace can flip `was_modified=True` even when the# `info` field reports `passthrough` and no compression happened.@@ -901,15 +909,6 @@ class SmartCrusher(Transform):query_context=query_context,tool_name=tool_name,)- # Bridge any CCR markers (row-drop sentinels or opaque-blob- # substitutions) emitted by the Rust crusher into the Python- # compression_store so /v1/retrieve resolves them.- self._mirror_ccr_to_python_store(- rendered=crushed,- strategy=info or "smart_crusher",- query_context=query_context,- tool_name=tool_name,- )return crushed, was_modified, infodef _record_to_toin(@@ -1026,10 +1025,11 @@ class SmartCrusher(Transform):# `compression_store.store(..., explicit_hash=hash)` so the Python# store is keyed by the exact hash that's in the prompt marker.#- # Best-effort by design: a missing compression_store import (e.g.- # in a stripped CLI build) or a transient store error must NOT- # break compression itself. Compression has already succeeded; the- # bridge just makes /v1/retrieve work. Errors log at debug.+ # A missing compression_store import (a stripped CLI build) or a+ # marker whose hash the Rust store does not hold is not a failure. A+ # store error is: the mirror returns False and the caller keeps the+ # input uncompressed, since a marker nobody stored never resolves on+ # another replica. Store errors log at warning; nothing raises.def _mirror_ccr_to_python_store(self,@@ -1037,9 +1037,10 @@ class SmartCrusher(Transform):strategy: str,query_context: str,tool_name: str | None,- ) -> None:+ ) -> bool:"""Walk `rendered` for any `<<ccr:HASH ...>>` markers and mirror- each into the Python `compression_store`.+ each into the Python `compression_store`. Returns whether every+ marker's original was stored (True when there is none).`rendered` may be a JSON string (the standard SmartCrusheroutput format) or arbitrary text. We try the structured walk@@ -1047,8 +1048,8 @@ class SmartCrusher(Transform):"""# Cheap pre-filter — most outputs have no marker at all.if "<<ccr:" not in rendered:- return- self._mirror_ccr_markers_in_text(+ return True+ return self._mirror_ccr_markers_in_text(rendered,strategy=strategy,query_context=query_context,@@ -1061,9 +1062,9 @@ class SmartCrusher(Transform):strategy: str,query_context: str,tool_name: str | None,- ) -> None:+ ) -> bool:"""Find every distinct `<<ccr:HASH...>>` hash in `rendered` and- mirror Rust→Python store for each.+ mirror Rust→Python store for each; whether all were stored.Tries JSON-tree walk first (structured, handles nested shapes);falls back to a token scan if `rendered` isn't valid JSON.@@ -1080,15 +1081,15 @@ class SmartCrusher(Transform):# always re-serializes via `python_safe_json_dumps`). Fall# through to a string-token scan so we still bridge.self._collect_ccr_hashes_from_string(rendered, hashes)- if not hashes:- return- for h in hashes:+ return all(self._mirror_single_hash_to_python_store(h,strategy=strategy,query_context=query_context,tool_name=tool_name,)+ for h in hashes+ )@staticmethoddef _collect_ccr_hashes(value: Any, sink: set[str]) -> None:@@ -1147,9 +1148,10 @@ class SmartCrusher(Transform):strategy: str,query_context: str,tool_name: str | None,- ) -> None:+ ) -> bool:"""Mirror a single Rust-stored CCR entry into the Python- compression_store, keyed by `ccr_hash`. Best-effort.+ compression_store, keyed by `ccr_hash`. False when the store did+ not take it; True when stored or there is nothing to mirror."""canonical = self._rust.ccr_get(ccr_hash)if canonical is None:@@ -1161,19 +1163,19 @@ class SmartCrusher(Transform):"CCR mirror: hash %s not in Rust store (skipped)",ccr_hash,)- return+ return Truetry:from ..cache.compression_store import get_compression_storeexcept ImportError:# Stripped build without the compression_store module.# Mirror is a no-op; Rust side still serves the data.logger.debug("CCR mirror: compression_store module unavailable")- return+ return Truetry:store = get_compression_store()except Exception as e: # pragma: no cover - defensive- logger.debug("CCR mirror: cannot get compression_store (%s)", e)- return+ logger.warning("CCR mirror: cannot get compression_store (%s)", safe_id(e))+ return False# The TTL on the Python store defaults to 30 minutes — same as# the Rust store's `DEFAULT_TTL` (see crates/headroom-core/src/# ccr/mod.rs). No need to override.@@ -1191,6 +1193,7 @@ class SmartCrusher(Transform):compression_strategy=strategy,explicit_hash=ccr_hash,)+ return Trueexcept ValueError:# explicit_hash validation failed — the marker had a# malformed hash (shouldn't happen in practice).@@ -1198,12 +1201,14 @@ class SmartCrusher(Transform):"CCR mirror: invalid hash %r from rendered marker",ccr_hash,)+ return Falseexcept Exception as e:# Store backends can echo the payload in errors, so no level logs it;# describe_exception keeps only types and code locations.logger.warning("CCR mirror: store write failed (%s) for hash %s", safe_id(e), ccr_hash)if logger.isEnabledFor(logging.DEBUG):logger.debug("CCR mirror store failure detail: %s", describe_exception(e))+ return Falsedef _extract_context_from_messages(self, messages: list[dict[str, Any]]) -> str:"""Build a query string from the last 5 user messages + recentdiff --git a/pyproject.toml b/pyproject.tomlindex dea9b8fd8..9b0cfbf4a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -300,6 +300,10 @@ bedrock = ["boto3>=1.41.0","botocore[crt]>=1.41.0",]+# State shared across replicas: CCR store (HEADROOM_CCR_BACKEND=redis).+redis = [+ "redis>=5.0.0",+]# HTML content extractionhtml = ["trafilatura>=1.6.0",@@ -332,6 +336,7 @@ dev = ["sentence-transformers>=2.2.0,<7.0","numpy>=1.24.0","openpyxl>=3.1.0", # exercises spreadsheet_ingest (.xlsx) in the test suite+ "fakeredis>=2.20.0", # Redis-backed shared state, without a Redis server"xlrd>=2.0.1", # exercises spreadsheet_ingest (.xls) in the test suite"xlwt>=1.3.0", # writes the legacy .xls fixtures for spreadsheet_ingest tests# test_upstream_guard builds a self-signed cert to prove the pinned connectiondiff --git a/tests/test_ccr_redis_backend.py b/tests/test_ccr_redis_backend.pynew file mode 100644index 000000000..f54c12d43--- /dev/null+++ b/tests/test_ccr_redis_backend.py@@ -0,0 +1,472 @@+"""One CCR store for every replica: HEADROOM_CCR_BACKEND=redis.++Behind a gateway that spreads requests across replicas, the retrieval of a+<<ccr:hash>> marker can land on a replica other than the one that compressed.+"""++from __future__ import annotations++import json++import pytest++fakeredis = pytest.importorskip("fakeredis")++from headroom.cache.backends.redis import RedisBackend # noqa: E402+from headroom.cache.compression_store import ( # noqa: E402+ CompressionStore,+ _create_default_ccr_backend,+)+from headroom.exceptions import StorageError # noqa: E402+++def server():+ return fakeredis.FakeServer()+++def _replica(server) -> CompressionStore:+ backend = RedisBackend("redis://localhost", client=fakeredis.FakeRedis(server=server))+ return CompressionStore(backend=backend)+++def test_a_marker_made_on_one_replica_is_retrieved_on_another(server):+ hash_key = _replica(server).store("the full original output " * 50, "short")+ entry = _replica(server).retrieve(hash_key)+ assert entry is not None and entry.original_content.startswith("the full original output")+++def test_an_entry_expires_in_redis_when_it_expires(server):+ store = _replica(server)+ hash_key = store.store("original " * 40, "short", ttl=60)+ ttl_ms = fakeredis.FakeRedis(server=server).pttl(f"headroom:ccr:{hash_key}")+ assert 0 < ttl_ms <= 60_000+++def test_deployments_with_different_prefixes_do_not_share(server, monkeypatch):+ hash_key = _replica(server).store("original " * 40, "short")+ monkeypatch.setenv("HEADROOM_REDIS_KEY_PREFIX", "staging")+ assert _replica(server).retrieve(hash_key) is None+++def test_redis_down_is_a_miss_and_issues_no_hash(monkeypatch):+ import redis++ class Down(fakeredis.FakeRedis):+ def execute_command(self, *args, **kwargs):+ raise redis.ConnectionError("connection refused")++ store = CompressionStore(backend=RedisBackend("redis://localhost", client=Down()))+ with pytest.raises(StorageError):+ store.store("original " * 40, "short")+ assert store.retrieve("abc123def456") is None+++def test_a_corrupt_entry_is_a_miss(server):+ store = _replica(server)+ fakeredis.FakeRedis(server=server).set("headroom:ccr:abc123def456", "not json")+ assert store.retrieve("abc123def456") is None+++def test_the_env_selects_the_redis_backend(monkeypatch):+ monkeypatch.setenv("HEADROOM_CCR_BACKEND", "redis")+ monkeypatch.setenv("HEADROOM_REDIS_URL", "redis://127.0.0.1:6399/0")+ assert isinstance(_create_default_ccr_backend(), RedisBackend)+++def test_a_url_that_is_not_redis_falls_back_to_the_local_store(monkeypatch):+ monkeypatch.setenv("HEADROOM_CCR_BACKEND", "redis")+ monkeypatch.setenv("HEADROOM_REDIS_URL", "memcached://cache:11211")+ assert _create_default_ccr_backend() is None+++def test_redis_is_skipped_for_a_while_after_a_connection_error():+ import redis++ calls = []++ class Down(fakeredis.FakeRedis):+ def execute_command(self, *args, **kwargs):+ calls.append(args[0])+ raise redis.ConnectionError("connection refused")++ backend = RedisBackend("redis://localhost", client=Down())+ for _ in range(5):+ backend.get("abc123def456")+ assert len(calls) == 1 # one failure, then back-off+++def test_storing_never_scans_the_shared_keyspace(server, monkeypatch):+ # A per-replica cap would count (SCAN) the whole store on every write and+ # evict other replicas' live entries; Redis expires entries by TTL.+ store = _replica(server)+ store._max_entries = 2+ monkeypatch.setattr(RedisBackend, "_scan", lambda self: pytest.fail("scanned"))+ hashes = [store.store(f"original {i} " * 40, f"short {i}") for i in range(5)]+ # Re-stores (a marker met again every turn) and retrievals neither.+ for _ in range(300):+ store.store("original 0 " * 40, "short 0")+ assert all(store.retrieve(h) is not None for h in hashes)+ assert not store._eviction_heap and not store._expiration_heap # nothing grows+++def test_a_redis_that_reads_but_refuses_writes_logs_once(caplog):+ import redis++ class Full(fakeredis.FakeRedis):+ def set(self, *args, **kwargs):+ raise redis.ResponseError("OOM command not allowed")++ store = CompressionStore(backend=RedisBackend("redis://localhost", client=Full()))+ with caplog.at_level("INFO", logger="headroom.cache.redis_client"):+ for i in range(5):+ with pytest.raises(StorageError):+ store.store(f"original {i} " * 40, "short")+ store.retrieve("abc123def456")+ messages = [r.getMessage() for r in caplog.records]+ assert sum("failed" in m for m in messages) == 1+ assert not any("works again" in m for m in messages)+++def test_a_prefix_with_glob_characters_matches_only_itself(server, monkeypatch):+ _replica(server).store("ours " * 40, "short")+ monkeypatch.setenv("HEADROOM_REDIS_KEY_PREFIX", "head*")+ assert RedisBackend("redis://localhost", client=fakeredis.FakeRedis(server=server)).count() == 0+++def test_stats_and_retrieval_never_read_or_rewrite_whole_entries(server, monkeypatch):+ store = _replica(server)+ hashes = [+ store.store(f"original {i} " * 40, f"short {i}", original_tokens=80, compressed_tokens=2)+ for i in range(5)+ ]+ reads, writes = [], []+ monkeypatch.setattr(fakeredis.FakeRedis, "get", lambda self, k: reads.append(k))+ stats = store.get_stats()+ assert stats["entry_count"] == 5 and not reads+ # Numeric totals (/stats contract): what this replica stored and retrieved.+ assert (stats["total_original_tokens"], stats["total_retrievals"]) == (400, 0)+ monkeypatch.undo()+ monkeypatch.setattr(fakeredis.FakeRedis, "set", lambda self, *a, **kw: writes.append(a))+ assert store.retrieve(hashes[0]) is not None+ assert not writes+ assert store.get_stats()["total_retrievals"] == 1+++def test_credentials_in_a_redis_error_are_not_logged(caplog):+ import redis++ class Refusing(fakeredis.FakeRedis):+ def get(self, *args, **kwargs):+ raise redis.ConnectionError("cannot reach redis://app:s3cret@cache:6379/0")++ backend = RedisBackend("redis://localhost", client=Refusing())+ with caplog.at_level("WARNING", logger="headroom.cache.redis_client"):+ assert backend.get("abc") is None+ assert "s3cret" not in caplog.text and "//***@cache" in caplog.text+++def test_a_write_redis_refuses_adds_no_tokens(caplog):+ import redis++ class Full(fakeredis.FakeRedis):+ def set(self, *args, **kwargs):+ raise redis.ResponseError("OOM command not allowed")++ store = CompressionStore(backend=RedisBackend("redis://localhost", client=Full()))+ with pytest.raises(StorageError):+ store.store("original " * 40, "short", original_tokens=80, compressed_tokens=2)+ stats = store.get_stats()+ assert (stats["total_original_tokens"], stats["totals_scope"]) == (0, "this_replica")+++# --- A producer never advertises an original Redis did not take -------------++_CONFIG = "[server]\n" + "".join(+ f"# comment line {i} describing port_{i}\nport_{i} = {8000 + i}\n" for i in range(30)+)+++class _Flaky(fakeredis.FakeRedis):+ """A Redis that refuses writes (``oom``) or cannot be reached (``down``)."""++ outage: str | None = None++ def execute_command(self, *args, **kwargs):+ import redis++ if self.outage == "down":+ raise redis.ConnectionError("connection refused")+ if self.outage == "oom" and args[0] == "SET":+ raise redis.ResponseError("OOM command not allowed")+ return super().execute_command(*args, **kwargs)+++def flaky_store(server, monkeypatch):+ from headroom.cache import compression_store, redis_client++ monkeypatch.setattr(redis_client, "BACKOFF_SECONDS", 0.0) # recovery is immediate+ client = _Flaky(server=server)+ store = CompressionStore(backend=RedisBackend("redis://localhost", client=client))+ # Global too: executor threads (the MCP tools) and startup do not see the+ # request-scoped store.+ monkeypatch.setattr(compression_store, "_compression_store", store)+ compression_store.set_request_compression_store(store)+ yield store, client+ compression_store.clear_request_compression_store()+++def _marker_hash(text: str) -> str | None:+ import re++ found = re.search(r"hash=([0-9a-f]{24})", text)+ return found.group(1) if found else None++[email protected]("outage", ["oom", "down"])+def test_config_elision_keeps_the_original_while_redis_fails_then_resumes(flaky_store, outage):+ from headroom.transforms.config_compressor import ConfigCompressor++ store, client = flaky_store+ client.outage = outage+ failed = ConfigCompressor().compress(_CONFIG)+ assert failed.compressed == _CONFIG and failed.ccr_hash is None and failed.lines_elided == 0++ client.outage = None+ resumed = ConfigCompressor().compress(_CONFIG)+ assert resumed.lines_elided == 30+ entry = store.retrieve(_marker_hash(resumed.compressed))+ assert entry is not None and entry.original_content == _CONFIG++[email protected]("outage", ["oom", "down"])+def test_read_maturation_keeps_the_read_while_redis_fails_then_resumes(flaky_store, outage):+ from headroom.config import ReadMaturationConfig+ from headroom.transforms.read_maturation import ReadMaturationManager++ store, client = flaky_store+ content = " 1\tdef foo():\n 2\t return 42\n" * 60+ messages = [+ {"role": "user", "content": "look"},+ {+ "role": "assistant",+ "content": [+ {"type": "tool_use", "id": "r1", "name": "Read", "input": {"file_path": "/x.py"}}+ ],+ },+ {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "r1", "content": content}],+ },+ *[{"role": "assistant", "content": [{"type": "text", "text": "t"}]} for _ in range(5)],+ ]+ manager = ReadMaturationManager(+ ReadMaturationConfig(enabled=True, quiesce_turns=5), compression_store=store+ )+ client.outage = outage+ assert manager.apply(messages).messages[2]["content"][0]["content"] == content++ client.outage = None+ matured = manager.apply(messages).messages[2]["content"][0]["content"]+ entry = store.retrieve(_marker_hash(matured))+ assert entry is not None and entry.original_content == content++[email protected]("outage", ["oom", "down"])+def test_read_lifecycle_keeps_a_stale_read_while_redis_fails(flaky_store, outage):+ from headroom.config import ReadLifecycleConfig+ from headroom.transforms.read_lifecycle import ReadLifecycleManager++ store, client = flaky_store+ content = "x = 1\n" * 200++ def call(tc_id, name, args):+ fn = {"name": name, "arguments": json.dumps(args)}+ return {"role": "assistant", "content": None, "tool_calls": [{"id": tc_id, "function": fn}]}++ messages = [+ call("r1", "Read", {"file_path": "/a.py"}),+ {"role": "tool", "tool_call_id": "r1", "content": content},+ call("e1", "Edit", {"file_path": "/a.py", "old_string": "x", "new_string": "y"}),+ {"role": "tool", "tool_call_id": "e1", "content": "ok"},+ ]+ manager = ReadLifecycleManager(ReadLifecycleConfig(enabled=True), compression_store=store)+ client.outage = outage+ assert manager.apply(messages).messages[1]["content"] == content++ client.outage = None+ entry = store.retrieve(_marker_hash(manager.apply(messages).messages[1]["content"]))+ assert entry is not None and entry.original_content == content++[email protected]("outage", ["oom", "down"])+def test_rust_log_compression_keeps_the_log_while_redis_fails(flaky_store, outage):+ pytest.importorskip("headroom._core")+ from headroom.transforms.log_compressor import LogCompressor, LogCompressorConfig++ store, client = flaky_store+ log = "\n".join(["npm WARN deprecated x"] * 30 + ["npm ERR! something broke"] * 5)+ compressor = LogCompressor(LogCompressorConfig(enable_ccr=True, min_lines_for_ccr=3))+ client.outage = outage+ failed = compressor.compress(log)+ assert failed.compressed == log and failed.cache_key is None++ client.outage = None+ resumed = compressor.compress(log)+ assert resumed.cache_key is not None+ assert store.retrieve(resumed.cache_key).original_content == log+++def test_mcp_read_returns_the_file_and_caches_no_hash_while_redis_is_down(flaky_store, tmp_path):+ import asyncio++ from tests._mcp_stub import import_module_with_mcp_stub++ mcp_server = import_module_with_mcp_stub("headroom.ccr.mcp_server")+ store, client = flaky_store+ path = tmp_path / "a.py"+ source = "x = 1\n" * 50+ path.write_bytes(source.encode()) # exact bytes: write_text would emit CRLF on Windows+ server = mcp_server.HeadroomMCPServer(check_proxy=False)+ client.outage = "down"+ response = asyncio.run(server._handle_read({"file_path": str(path)}))+ assert "x = 1" in response[0].kwargs["text"] and not server._file_cache++ client.outage = None+ asyncio.run(server._handle_read({"file_path": str(path)}))+ (_, ccr_hash, _, _) = next(iter(server._file_cache.values()))+ assert store.retrieve(ccr_hash).original_content == source++[email protected]("outage", ["oom", "down"])+def test_mcp_compress_returns_the_original_while_redis_fails_then_resumes(flaky_store, outage):+ import asyncio++ from tests._mcp_stub import import_module_with_mcp_stub++ mcp_server = import_module_with_mcp_stub("headroom.ccr.mcp_server")+ store, client = flaky_store+ content = json.dumps([{"id": i, "status": "ok", "tag": "alpha"} for i in range(60)])+ server = mcp_server.HeadroomMCPServer(check_proxy=False)++ def compress() -> dict:+ response = asyncio.run(server._handle_compress({"content": content}))+ return json.loads(response[0].kwargs["text"])++ client.outage = outage+ failed = compress()+ assert (failed["compressed"], failed["hash"], failed["tokens_saved"]) == (content, None, 0)++ client.outage = None+ resumed = compress()+ assert resumed["compressed"] != content+ assert store.retrieve(resumed["hash"]).original_content == content++[email protected]("outage", ["oom", "down"])+def test_proxy_starts_when_redis_fails_restoring_prefix_state(+ server, flaky_store, outage, monkeypatch, tmp_path+):+ pytest.importorskip("fastapi")+ import contextvars++ from fastapi.testclient import TestClient++ from headroom.cache.prefix_tracker import PREFIX_STATE_FILE_ENV, SessionTrackerStore+ from headroom.proxy.server import ProxyConfig, create_app+ from tests.test_anthropic_fork_lineage_cache import _send++ store, client = flaky_store+ hash_key = store.store(json.dumps(list(range(400))), "[0, 1]", ttl=900)+ saved = SessionTrackerStore()+ text = f"[400 items compressed to 2. Retrieve more: hash={hash_key}]"+ contextvars.Context().run(_send, saved, [{"role": "user", "content": text}])+ path = tmp_path / "prefix-state.json"+ assert saved.save_state(str(path)) == 1+ fakeredis.FakeRedis(server=server).flushall() # Redis lost it; only the state file has it+ monkeypatch.setenv(PREFIX_STATE_FILE_ENV, str(path))++ def start() -> int:+ config = ProxyConfig(optimize=False, rate_limit_enabled=False, cost_tracking_enabled=False)+ with TestClient(create_app(config)) as app_client:+ return app_client.app.state.proxy.session_tracker_store.active_sessions++ client.outage = outage+ # load_state treats the failed import like a bad file: the proxy starts and+ # installs no tracker, so none replays a marker whose original is gone.+ assert start() == 0+++def _router(**config):+ from headroom.transforms.content_router import ContentRouter, ContentRouterConfig++ return ContentRouter(ContentRouterConfig(enable_kompress=False, **config))++[email protected]("outage", ["oom", "down"])+def test_smart_crusher_row_drop_keeps_the_rows_while_redis_fails_then_resumes(+ flaky_store, outage, monkeypatch+):+ pytest.importorskip("headroom._core")+ import re++ monkeypatch.setenv("HEADROOM_DETECT_BACKEND", "python")+ store, client = flaky_store+ rows = [{"id": i, "status": "ok", "tag": "alpha"} for i in range(60)]+ router = _router(smart_crusher_with_compaction=False) # the row-drop path+ client.outage = outage+ assert "<<ccr:" not in router.compress(json.dumps(rows)).compressed++ client.outage = None+ resumed = router.compress(json.dumps(rows)).compressed+ entry = store.retrieve(re.search(r"<<ccr:([0-9a-f]+)", resumed).group(1))+ assert entry is not None and json.loads(entry.original_content) == rows++[email protected]("outage", ["oom", "down"])+def test_external_compressor_output_is_dropped_while_redis_fails_then_resumes(+ flaky_store, outage, monkeypatch+):+ import hashlib++ from headroom.transforms.compressor_registry import CompressorDescriptor, CompressOutput++ monkeypatch.setenv("HEADROOM_DETECT_BACKEND", "python")+ store, client = flaky_store++ class External:+ descriptor = CompressorDescriptor(+ name="ext_json",+ content_types=["application/json"],+ lossless=False,+ cost_tier="fast",+ recoverable=True,+ )++ def compress(self, inp):+ digest = hashlib.sha256(inp.content.encode()).hexdigest()[:24]+ return CompressOutput(+ content=f"[external <<ccr:{digest}>>]",+ tokens_before=len(inp.content.split()),+ tokens_after=2,+ lossless=False,+ markers=[],+ recoverable={digest: inp.content},+ warnings=[],+ )++ content = json.dumps([{"id": i, "note": f"descriptive field {i} " * 3} for i in range(40)])+ router = _router(active_external_compressors=["ext_json"])+ router.compressor_registry.register(External(), replace=True)+ router._active_external_compressors = router._resolve_active_external_compressors()+ client.outage = outage+ failed = router.compress(content)+ assert "external:ext_json" not in failed.strategy_chain+ assert "<<ccr:" not in failed.compressed++ client.outage = None+ resumed = router.compress(content)+ assert "external:ext_json" in resumed.strategy_chain+ digest = hashlib.sha256(content.encode()).hexdigest()[:24]+ assert store.retrieve(digest).original_content == contentdiff --git a/tests/test_ccr_rust_marker_hash_bridge.py b/tests/test_ccr_rust_marker_hash_bridge.pyindex 4ebd6bf11..2c1a0c9bd 100644--- a/tests/test_ccr_rust_marker_hash_bridge.py+++ b/tests/test_ccr_rust_marker_hash_bridge.py@@ -50,7 +50,7 @@ def test_persist_warning_rejects_malformed_exception_names(monkeypatch, caplog,monkeypatch.delenv("HEADROOM_DEBUG_DUMP", raising=False)monkeypatch.setattr(compression_store, "get_compression_store", lambda: BrokenStore())with caplog.at_level(level, logger=base.logger.name):- assert persist_rust_ccr_entry("original", "compressed", "a" * 24, source="diff") is None+ assert persist_rust_ccr_entry("original", "compressed", "a" * 24, source="diff") is Falseassert len([record for record in caplog.records if record.levelno == logging.WARNING]) == 1for record in caplog.records:rendered = logging.Formatter().format(record)diff --git a/tests/test_router_external_dispatch.py b/tests/test_router_external_dispatch.pyindex 7a5f9c3b0..47b2a66da 100644--- a/tests/test_router_external_dispatch.py+++ b/tests/test_router_external_dispatch.py@@ -281,15 +281,17 @@ def test_recoverable_map_is_retrievable(_memory_ccr):assert entry.compression_strategy == "external:ext_json"-def test_non_hex_recoverable_hash_is_skipped_without_breaking(_memory_ccr):- # A malformed (non-hex) recovery hash must not break the request; the block- # is still compressed, only that entry is not retrievable.+def test_non_hex_recoverable_hash_falls_back_to_builtin(_memory_ccr):+ # A malformed (non-hex) recovery hash must not break the request; the store+ # cannot keep that entry, so the external output (whose marker would point+ # nowhere) is discarded and the built-in path runs.comp = _RecordingExternal(name="ext_json", content_types=("application/json",), bad_hash=True)router = _router_with_external(comp, ["ext_json"])result = router.compress(_JSON_ARRAY)- assert "external:ext_json" in result.strategy_chain+ assert "external:ext_json" not in result.strategy_chain+ assert "external-compressed" not in result.compressedassert get_compression_store().retrieve("zznothex") is Nonediff --git a/uv.lock b/uv.lockindex cd5a0d0c4..74ca2e3af 100644--- a/uv.lock+++ b/uv.lock@@ -1139,6 +1139,20 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },]+[[package]]+name = "fakeredis"+version = "2.40.0"+source = { registry = "https://pypi.org/simple/" }+dependencies = [+ { name = "redis" },+ { name = "sortedcontainers" },+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/61/d0/8cbd1339c2a606a0ceda74e1a181248d372bb2c66bc6cf9d954871839ff9/fakeredis-2.40.0.tar.gz", hash = "sha256:16eb05a3e97c37a033c73d1da7e885eb2aa47ba7604cc377144339efa2780a02", size = 332674, upload-time = "2026-10-14T12:46:01.851Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c7/e4/6919d3653d72c53d1fb22c97ceb6fa3664cad302994e90ee52279f7eb394/fakeredis-2.40.0-py3-none-any.whl", hash = "sha256:b155ef2442134372eb1cc5664cf5638ccbe0a6dde9d1942153708e2782f315c9", size = 204148, upload-time = "2026-10-14T12:46:00.014Z" },+]+[[package]]name = "fastapi"version = "0.136.3"@@ -1691,6 +1705,7 @@ code = [dev = [{ name = "anthropic" },{ name = "cryptography" },+ { name = "fakeredis" },{ name = "fastapi" },{ name = "hnswlib" },{ name = "httpx", extra = ["http2", "socks"] },@@ -1809,6 +1824,9 @@ pytorch-mps = [{ name = "sentence-transformers", marker = "sys_platform == 'darwin'" },{ name = "torch", marker = "sys_platform == 'darwin'" },]+redis = [+ { name = "redis" },+]relevance = [{ name = "fastembed", marker = "python_full_version < '3.14' or platform_machine != 'x86_64' or sys_platform != 'darwin'" },{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple/" }, marker = "python_full_version < '3.11'" },@@ -1885,6 +1903,7 @@ requires-dist = [{ name = "cryptography", marker = "extra == 'dev'", specifier = ">=50.0.0" },{ name = "datasets", marker = "extra == 'evals'", specifier = ">=5.0.1" },{ name = "datasets", marker = "extra == 'voice-train'", specifier = ">=5.0.1" },+ { name = "fakeredis", marker = "extra == 'dev'", specifier = ">=2.20.0" },{ name = "fastapi", marker = "extra == 'dev'", specifier = ">=0.100.0" },{ name = "fastapi", marker = "extra == 'proxy'", specifier = ">=0.100.0" },{ name = "fastembed", marker = "(python_full_version < '3.14' and extra == 'relevance') or (platform_machine != 'x86_64' and extra == 'relevance') or (sys_platform != 'darwin' and extra == 'relevance')", specifier = ">=0.6.0" },@@ -1946,6 +1965,7 @@ requires-dist = [{ name = "qdrant-client", marker = "extra == 'memory-stack'", specifier = ">=1.9.0,<2.0" },{ name = "rapidocr", marker = "(python_full_version == '3.13.*' and platform_machine == 'x86_64' and sys_platform == 'darwin' and extra == 'image') or (python_full_version >= '3.13' and platform_machine != 'x86_64' and extra == 'image') or (python_full_version >= '3.13' and sys_platform != 'darwin' and extra == 'image')", specifier = ">=3.0,<4" },{ name = "rapidocr-onnxruntime", marker = "python_full_version < '3.13' and extra == 'image'", specifier = ">=1.4.0,<2" },+ { name = "redis", marker = "extra == 'redis'", specifier = ">=5.0.0" },{ name = "respx", marker = "extra == 'dev'", specifier = ">=0.20.0" },{ name = "rich", specifier = ">=13.0.0" },{ name = "ruff", marker = "extra == 'dev'", specifier = "==0.17.0" },@@ -1984,7 +2004,7 @@ requires-dist = [{ name = "xlwt", marker = "extra == 'dev'", specifier = ">=1.3.0" },{ name = "zstandard", marker = "extra == 'proxy'", specifier = ">=0.20.0" },]-provides-extras = ["proxy", "proxy-prod", "code", "ml", "memory", "vector", "memory-stack", "pytorch-mps", "relevance", "image", "reports", "spreadsheet", "otel", "anyllm", "langchain", "langgraph", "agno", "strands", "autogen", "mcp", "voice", "voice-train", "evals", "bedrock", "html", "dev", "all", "sandbox"]+provides-extras = ["proxy", "proxy-prod", "code", "ml", "memory", "vector", "memory-stack", "pytorch-mps", "relevance", "image", "reports", "spreadsheet", "otel", "anyllm", "langchain", "langgraph", "agno", "strands", "autogen", "mcp", "voice", "voice-train", "evals", "bedrock", "redis", "html", "dev", "all", "sandbox"][[package]]name = "hf-xet"@@ -5358,6 +5378,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/ba/12/1e5497183bdbe782dbb91bad1d0d2297dba4d2831b2652657f7517bfc6df/rapidocr_onnxruntime-1.4.4-py3-none-any.whl", hash = "sha256:971d7d5f223a7a808662229df1ef69893809d8457d834e6373d3854bc1782cbf", size = 14915192, upload-time = "2025-01-17T01:48:25.104Z" },]+[[package]]+name = "redis"+version = "8.1.0"+source = { registry = "https://pypi.org/simple/" }+dependencies = [+ { name = "async-timeout", marker = "python_full_version < '3.11.3'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/a8/99/604f0b666d4c616d891cf77ebb9db6bb21601344c051aebf1b72b9ff915f/redis-8.1.0.tar.gz", hash = "sha256:6e1a19beef9225c83efd689c7e6b7da2d5215b1f42cd13b7fc3714d0a09c7b25", size = 5254356, upload-time = "2026-07-30T08:51:00.269Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/66/9d/c5731f6e3608663d4d3656fd8d3aecee8b509c3082818f5a13eae925baea/redis-8.1.0-py3-none-any.whl", hash = "sha256:a4fe1aac3d3b3cc791d4b3d5931c5a956045dc951ee74d1c913ee3ac4d2ee9fb", size = 560618, upload-time = "2026-07-30T08:50:58.497Z" },+]+[[package]]name = "referencing"version = "0.37.0"@@ -6200,6 +6232,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/37/c3/6eeb6034408dac0fa653d126c9204ade96b819c936e136c5e8a6897eee9c/socksio-1.0.0-py3-none-any.whl", hash = "sha256:95dc1f15f9b34e8d7b16f06d74b8ccf48f609af32ab33c608d08761c5dcbb1f3", size = 12763, upload-time = "2020-04-17T15:50:31.878Z" },]+[[package]]+name = "sortedcontainers"+version = "2.4.0"+source = { registry = "https://pypi.org/simple/" }+sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594, upload-time = "2021-05-16T22:03:42.897Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" },+]+[[package]]name = "sqlalchemy"version = "2.0.49"