Skip to content

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.

perf(cache): purge expired CCR rows by deadline instead of decoding every payload (#3465)

trs-80389e45cdde3b
diff --git a/benchmarks/ccr_sqlite_expiry_benchmark.py b/benchmarks/ccr_sqlite_expiry_benchmark.py
new file mode 100644
index 000000000..28463d988
--- /dev/null
+++ b/benchmarks/ccr_sqlite_expiry_benchmark.py
@@ -0,0 +1,83 @@
+#!/usr/bin/env python3
+"""Measure SQLite CCR insertion cleanup without expiring live entries."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import statistics
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+# Run as a script sys.path[0] is benchmarks/, so an editable install of another
+# checkout would win and we would silently measure the wrong tree.
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+from headroom.cache.backends.sqlite import SQLiteBackend
+from headroom.cache.compression_store import CompressionEntry, CompressionStore
+
+
+def benchmark(entry_count: int, payload_bytes: int, runs: int) -> dict[str, object]:
+ with tempfile.TemporaryDirectory(prefix="headroom-ccr-expiry-") as tmp:
+ backend = SQLiteBackend(Path(tmp) / "ccr.db")
+ payload = "x" * payload_bytes
+ for index in range(entry_count):
+ key = str(index)
+ backend.set(
+ key,
+ CompressionEntry(
+ hash=key,
+ original_content=payload,
+ compressed_content="compact",
+ original_tokens=payload_bytes // 4,
+ compressed_tokens=2,
+ original_item_count=0,
+ compressed_item_count=0,
+ tool_name=None,
+ tool_call_id=None,
+ query_context=None,
+ created_at=time.time(),
+ ttl=3600,
+ ),
+ )
+
+ store = CompressionStore(
+ max_entries=entry_count + runs + 1,
+ backend=backend,
+ enable_feedback=False,
+ )
+ samples_ms: list[float] = []
+ for index in range(runs):
+ start = time.perf_counter()
+ key = store.store(f"new original {index}", f"new compact {index}")
+ samples_ms.append((time.perf_counter() - start) * 1000)
+ assert store.retrieve(key) is not None
+
+ backend._conn.close()
+ return {
+ "preexisting_entries": entry_count,
+ "original_bytes_each": payload_bytes,
+ "runs": runs,
+ "median_insert_ms": statistics.median(samples_ms),
+ }
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--entries", type=int, nargs="+", default=[100, 500, 1000])
+ parser.add_argument("--payload-bytes", type=int, nargs="+", default=[1024, 16384])
+ parser.add_argument("--runs", type=int, default=7)
+ args = parser.parse_args()
+
+ results = [
+ benchmark(entry_count, payload_bytes, args.runs)
+ for payload_bytes in args.payload_bytes
+ for entry_count in args.entries
+ ]
+ print(json.dumps(results, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/headroom/cache/backends/sqlite.py b/headroom/cache/backends/sqlite.py
index 35d9cacb5..fe4233d41 100644
--- a/headroom/cache/backends/sqlite.py
+++ b/headroom/cache/backends/sqlite.py
@@ -40,7 +40,10 @@ CREATE TABLE IF NOT EXISTS ccr_entries (
created_at REAL NOT NULL,
ttl INTEGER NOT NULL
);
-CREATE INDEX IF NOT EXISTS idx_ccr_expiry ON ccr_entries (created_at);
+CREATE INDEX IF NOT EXISTS idx_ccr_expiry_deadline ON ccr_entries (created_at + ttl);
+-- Superseded by idx_ccr_expiry_deadline: no query searches or orders by bare
+-- created_at, so the old index only cost writes. Drop it from existing files.
+DROP INDEX IF EXISTS idx_ccr_expiry;
"""
# Purge expired rows at most this often (seconds). Purging is hygiene,
@@ -153,17 +156,31 @@ class SQLiteBackend:
known = {f.name for f in fields(CompressionEntry)}
return CompressionEntry(**{k: v for k, v in data.items() if k in known})
+ def _purge_expired(self, now: float) -> int:
+ """Delete expired rows using metadata; caller holds ``_lock``."""
+ cursor = self._conn.execute(
+ "DELETE FROM ccr_entries WHERE created_at + ttl < ?",
+ (now,),
+ )
+ self._conn.commit()
+ self._last_purge = now
+ return cursor.rowcount
+
+ def purge_expired(self, now: float | None = None) -> int:
+ """Delete expired rows without deserializing their payloads."""
+ with self._lock:
+ try:
+ return self._purge_expired(time.time() if now is None else now)
+ except sqlite3.DatabaseError as e:
+ self._handle_db_error(e, "purge")
+ return 0
+
def _maybe_purge(self) -> None:
"""Delete expired rows; called opportunistically under the lock."""
now = time.time()
if now - self._last_purge < _PURGE_INTERVAL:
return
- self._last_purge = now
- self._conn.execute(
- "DELETE FROM ccr_entries WHERE created_at + ttl < ?",
- (now,),
- )
- self._conn.commit()
+ self._purge_expired(now)
def get(self, hash_key: str) -> CompressionEntry | None:
with self._lock:
diff --git a/headroom/cache/compression_store.py b/headroom/cache/compression_store.py
index 3a815df2c..379ef5721 100644
--- a/headroom/cache/compression_store.py
+++ b/headroom/cache/compression_store.py
@@ -768,6 +768,11 @@ class CompressionStore:
CRITICAL FIX: Track stale heap entries when deleting to prevent memory leak.
"""
+ purge_expired = getattr(self._backend, "purge_expired", None)
+ if callable(purge_expired):
+ self._stale_heap_entries += purge_expired()
+ return
+
expired_keys = [key for key, entry in self._backend.items() if entry.is_expired()]
for key in expired_keys:
self._backend.delete(key)
diff --git a/tests/test_ccr_sqlite_backend.py b/tests/test_ccr_sqlite_backend.py
index fbdd87ef7..6ca750dea 100644
--- a/tests/test_ccr_sqlite_backend.py
+++ b/tests/test_ccr_sqlite_backend.py
@@ -86,6 +86,74 @@ class TestSQLiteBackend:
assert stats["entry_count"] == 2
assert stats["bytes_used"] > 0
+ def test_opening_a_db_with_the_old_index_drops_it_and_keeps_the_rows(self, db_path):
+ # Databases written before idx_ccr_expiry_deadline still carry the
+ # superseded idx_ccr_expiry; opening them must migrate, not fail.
+ seeded = SQLiteBackend(db_path)
+ seeded.set("h1", make_entry("h1"))
+ seeded._conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_ccr_expiry ON ccr_entries (created_at)"
+ )
+ seeded._conn.commit()
+ seeded._conn.close()
+
+ b = SQLiteBackend(db_path)
+ indexes = {
+ row[0]
+ for row in b._conn.execute(
+ "SELECT name FROM sqlite_master WHERE type = 'index' AND name LIKE 'idx_%'"
+ )
+ }
+ assert indexes == {"idx_ccr_expiry_deadline"}
+ entry = b.get("h1")
+ assert entry is not None
+ assert entry.original_content == make_entry("h1").original_content
+
+ def test_purge_expired_deletes_by_deadline_and_keeps_the_boundary_row(self, db_path):
+ b = SQLiteBackend(db_path)
+ now = time.time()
+ expired = make_entry("expired", ttl=10)
+ expired.created_at = now - 11
+ boundary = make_entry("boundary", ttl=10)
+ boundary.created_at = now - 10
+ live = make_entry("live", ttl=60)
+ live.created_at = now - 11
+
+ # Keep backend.set() from performing its opportunistic purge first.
+ b._last_purge = now
+ for entry in (expired, boundary, live):
+ b.set(entry.hash, entry)
+
+ assert b.purge_expired(now) == 1
+ assert set(b.keys()) == {"boundary", "live"}
+
+ def test_new_insert_purges_expired_sqlite_entry_without_decoding_live_payloads(
+ self, db_path, monkeypatch
+ ):
+ backend = SQLiteBackend(db_path)
+ store = CompressionStore(max_entries=4, backend=backend, enable_feedback=False)
+ expired_hash = store.store("expired original", "expired compact", ttl=10)
+ live_hash = store.store("live original", "live compact", ttl=60)
+ other_live_hash = store.store("other live original", "other live compact", ttl=60)
+
+ expired = backend.get(expired_hash)
+ assert expired is not None
+ expired.created_at = time.time() - 11
+ backend.set(expired_hash, expired)
+
+ monkeypatch.setattr(
+ backend,
+ "_entry_from_json",
+ lambda _raw: pytest.fail("new insertion decoded existing CCR payloads"),
+ )
+
+ new_hash = store.store("new original", "new compact", ttl=60)
+
+ assert not backend.exists(expired_hash)
+ assert backend.exists(live_hash)
+ assert backend.exists(other_live_hash)
+ assert backend.exists(new_hash)
+
def test_clear(self, db_path):
b = SQLiteBackend(db_path)
b.set("h1", make_entry())