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
fix: [BUG] Saved request metrics lose their cache optimization fields (#4584)
Nandana Dileepb4c9bdf100d9
diff --git a/headroom/storage/jsonl.py b/headroom/storage/jsonl.pyindex e87d7b9a0..13c9c0e3e 100644--- a/headroom/storage/jsonl.py+++ b/headroom/storage/jsonl.py@@ -57,6 +57,13 @@ class JSONLStorage(Storage):"stable_prefix_hash": metrics.stable_prefix_hash,"cache_alignment_score": metrics.cache_alignment_score,"cached_tokens": metrics.cached_tokens,+ "cache_optimizer_used": metrics.cache_optimizer_used,+ "cache_optimizer_strategy": metrics.cache_optimizer_strategy,+ "cacheable_tokens": metrics.cacheable_tokens,+ "breakpoints_inserted": metrics.breakpoints_inserted,+ "estimated_cache_hit": metrics.estimated_cache_hit,+ "estimated_savings_percent": metrics.estimated_savings_percent,+ "semantic_cache_hit": metrics.semantic_cache_hit,"transforms_applied": metrics.transforms_applied,"tool_units_dropped": metrics.tool_units_dropped,"turns_dropped": metrics.turns_dropped,@@ -80,6 +87,13 @@ class JSONLStorage(Storage):stable_prefix_hash=data.get("stable_prefix_hash", ""),cache_alignment_score=data.get("cache_alignment_score", 0.0),cached_tokens=data.get("cached_tokens"),+ cache_optimizer_used=data.get("cache_optimizer_used"),+ cache_optimizer_strategy=data.get("cache_optimizer_strategy"),+ cacheable_tokens=data.get("cacheable_tokens", 0),+ breakpoints_inserted=data.get("breakpoints_inserted", 0),+ estimated_cache_hit=data.get("estimated_cache_hit", False),+ estimated_savings_percent=data.get("estimated_savings_percent", 0.0),+ semantic_cache_hit=data.get("semantic_cache_hit", False),transforms_applied=data.get("transforms_applied", []),tool_units_dropped=data.get("tool_units_dropped", 0),turns_dropped=data.get("turns_dropped", 0),diff --git a/headroom/storage/sqlite.py b/headroom/storage/sqlite.pyindex c5106edc6..733fc271d 100644--- a/headroom/storage/sqlite.py+++ b/headroom/storage/sqlite.py@@ -13,6 +13,18 @@ from ..config import RequestMetricsfrom ..utils import format_timestamp, parse_timestampfrom .base import Storage+# Cache optimizer metric columns, shared by the CREATE TABLE schema, the+# legacy-database migration, save() and _row_to_metrics().+_CACHE_OPTIMIZER_COLUMNS: tuple[tuple[str, str], ...] = (+ ("cache_optimizer_used", "TEXT"),+ ("cache_optimizer_strategy", "TEXT"),+ ("cacheable_tokens", "INTEGER DEFAULT 0"),+ ("breakpoints_inserted", "INTEGER DEFAULT 0"),+ ("estimated_cache_hit", "INTEGER DEFAULT 0"),+ ("estimated_savings_percent", "REAL DEFAULT 0.0"),+ ("semantic_cache_hit", "INTEGER DEFAULT 0"),+)+class SQLiteStorage(Storage):"""SQLite-based metrics storage."""@@ -33,44 +45,76 @@ class SQLiteStorage(Storage):path = Path(self.db_path)path.parent.mkdir(parents=True, exist_ok=True)- conn = sqlite3.connect(self.db_path)+ # isolation_level=None so we can take an explicit reserved lock with+ # BEGIN IMMEDIATE rather than a deferred transaction that still lets+ # another constructor read the old schema.+ conn = sqlite3.connect(self.db_path, isolation_level=None, timeout=30.0)try:cursor = conn.cursor()- cursor.execute("""- CREATE TABLE IF NOT EXISTS requests (- id TEXT PRIMARY KEY,- timestamp TEXT NOT NULL,- model TEXT NOT NULL,- stream INTEGER NOT NULL,- mode TEXT NOT NULL,- tokens_input_before INTEGER NOT NULL,- tokens_input_after INTEGER NOT NULL,- tokens_output INTEGER,- block_breakdown TEXT NOT NULL,- waste_signals TEXT NOT NULL,- stable_prefix_hash TEXT,- cache_alignment_score REAL,- cached_tokens INTEGER,- transforms_applied TEXT NOT NULL,- tool_units_dropped INTEGER DEFAULT 0,- turns_dropped INTEGER DEFAULT 0,- messages_hash TEXT,- error TEXT- )- """)-- # Create indices- cursor.execute("""- CREATE INDEX IF NOT EXISTS idx_timestamp ON requests(timestamp)- """)- cursor.execute("""- CREATE INDEX IF NOT EXISTS idx_model ON requests(model)- """)- cursor.execute("""- CREATE INDEX IF NOT EXISTS idx_mode ON requests(mode)- """)-- conn.commit()+ cursor.execute("BEGIN IMMEDIATE")+ try:+ cursor.execute("""+ CREATE TABLE IF NOT EXISTS requests (+ id TEXT PRIMARY KEY,+ timestamp TEXT NOT NULL,+ model TEXT NOT NULL,+ stream INTEGER NOT NULL,+ mode TEXT NOT NULL,+ tokens_input_before INTEGER NOT NULL,+ tokens_input_after INTEGER NOT NULL,+ tokens_output INTEGER,+ block_breakdown TEXT NOT NULL,+ waste_signals TEXT NOT NULL,+ stable_prefix_hash TEXT,+ cache_alignment_score REAL,+ cached_tokens INTEGER,+ cache_optimizer_used TEXT,+ cache_optimizer_strategy TEXT,+ cacheable_tokens INTEGER DEFAULT 0,+ breakpoints_inserted INTEGER DEFAULT 0,+ estimated_cache_hit INTEGER DEFAULT 0,+ estimated_savings_percent REAL DEFAULT 0.0,+ semantic_cache_hit INTEGER DEFAULT 0,+ transforms_applied TEXT NOT NULL,+ tool_units_dropped INTEGER DEFAULT 0,+ turns_dropped INTEGER DEFAULT 0,+ messages_hash TEXT,+ error TEXT+ )+ """)++ # Upgrade databases created before the cache optimizer columns+ # existed, preserving existing rows. The reserved lock above+ # serializes this check-and-alter against concurrent constructors.+ cursor.execute("PRAGMA table_info(requests)")+ existing_columns = {row[1] for row in cursor.fetchall()}+ for column, ddl in _CACHE_OPTIMIZER_COLUMNS:+ if column not in existing_columns:+ try:+ cursor.execute( # nosec B608+ f"ALTER TABLE requests ADD COLUMN {column} {ddl}"+ )+ except sqlite3.OperationalError as exc:+ # Another connection may have added the column+ # between our schema read and this ALTER.+ if "duplicate column name" not in str(exc).lower():+ raise++ # Create indices+ cursor.execute("""+ CREATE INDEX IF NOT EXISTS idx_timestamp ON requests(timestamp)+ """)+ cursor.execute("""+ CREATE INDEX IF NOT EXISTS idx_model ON requests(model)+ """)+ cursor.execute("""+ CREATE INDEX IF NOT EXISTS idx_mode ON requests(mode)+ """)++ conn.commit()+ except Exception:+ conn.rollback()+ raisefinally:conn.close()@@ -93,9 +137,12 @@ class SQLiteStorage(Storage):tokens_input_before, tokens_input_after, tokens_output,block_breakdown, waste_signals,stable_prefix_hash, cache_alignment_score, cached_tokens,+ cache_optimizer_used, cache_optimizer_strategy, cacheable_tokens,+ breakpoints_inserted, estimated_cache_hit, estimated_savings_percent,+ semantic_cache_hit,transforms_applied, tool_units_dropped, turns_dropped,messages_hash, error- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",(metrics.request_id,@@ -111,6 +158,13 @@ class SQLiteStorage(Storage):metrics.stable_prefix_hash,metrics.cache_alignment_score,metrics.cached_tokens,+ metrics.cache_optimizer_used,+ metrics.cache_optimizer_strategy,+ metrics.cacheable_tokens,+ metrics.breakpoints_inserted,+ 1 if metrics.estimated_cache_hit else 0,+ metrics.estimated_savings_percent,+ 1 if metrics.semantic_cache_hit else 0,json.dumps(metrics.transforms_applied),metrics.tool_units_dropped,metrics.turns_dropped,@@ -301,6 +355,13 @@ class SQLiteStorage(Storage):stable_prefix_hash=row["stable_prefix_hash"] or "",cache_alignment_score=row["cache_alignment_score"] or 0.0,cached_tokens=row["cached_tokens"],+ cache_optimizer_used=row["cache_optimizer_used"],+ cache_optimizer_strategy=row["cache_optimizer_strategy"],+ cacheable_tokens=row["cacheable_tokens"] or 0,+ breakpoints_inserted=row["breakpoints_inserted"] or 0,+ estimated_cache_hit=bool(row["estimated_cache_hit"]),+ estimated_savings_percent=row["estimated_savings_percent"] or 0.0,+ semantic_cache_hit=bool(row["semantic_cache_hit"]),transforms_applied=json.loads(row["transforms_applied"]),tool_units_dropped=row["tool_units_dropped"] or 0,turns_dropped=row["turns_dropped"] or 0,diff --git a/tests/test_storage/test_jsonl.py b/tests/test_storage/test_jsonl.pyindex 737a60b5c..d0304dcd5 100644--- a/tests/test_storage/test_jsonl.py+++ b/tests/test_storage/test_jsonl.py@@ -270,3 +270,64 @@ class TestJSONLQuerySingleRowRegression:jsonl.close()sqlite.close()+++class TestJSONLCacheOptimizerMetrics:+ """Cache-optimizer fields must survive a durable JSONL round trip (#4261)."""++ def test_save_close_reopen_preserves_cache_optimizer_fields(self, tmp_path):+ path = str(tmp_path / "metrics.jsonl")+ metrics = RequestMetrics(+ request_id="cache-repro",+ timestamp=datetime(2025, 1, 6, 12, 0, 0),+ model="claude-3-opus",+ stream=False,+ mode="optimize",+ tokens_input_before=1000,+ tokens_input_after=800,+ cache_optimizer_used="anthropic-cache-optimizer",+ cache_optimizer_strategy="explicit_breakpoints",+ cacheable_tokens=789,+ breakpoints_inserted=2,+ estimated_cache_hit=True,+ estimated_savings_percent=42.5,+ semantic_cache_hit=True,+ )++ storage = JSONLStorage(path)+ storage.save(metrics)+ storage.close()++ reopened = JSONLStorage(path)+ restored = reopened.get("cache-repro")+ reopened.close()++ assert restored is not None+ assert restored.cache_optimizer_used == "anthropic-cache-optimizer"+ assert restored.cache_optimizer_strategy == "explicit_breakpoints"+ assert restored.cacheable_tokens == 789+ assert restored.breakpoints_inserted == 2+ assert restored.estimated_cache_hit is True+ assert restored.estimated_savings_percent == 42.5+ assert restored.semantic_cache_hit is True++ def test_legacy_jsonl_lines_get_cache_optimizer_defaults(self, tmp_path):+ path = tmp_path / "metrics.jsonl"+ path.write_text(+ '{"id":"legacy-1","timestamp":"2025-01-06T12:00:00Z","model":"gpt-4o",'+ '"stream":false,"mode":"audit","tokens_input_before":1000,'+ '"tokens_input_after":800}\n'+ )++ storage = JSONLStorage(str(path))+ restored = storage.get("legacy-1")+ storage.close()++ assert restored is not None+ assert restored.cache_optimizer_used is None+ assert restored.cache_optimizer_strategy is None+ assert restored.cacheable_tokens == 0+ assert restored.breakpoints_inserted == 0+ assert restored.estimated_cache_hit is False+ assert restored.estimated_savings_percent == 0.0+ assert restored.semantic_cache_hit is Falsediff --git a/tests/test_storage/test_sqlite.py b/tests/test_storage/test_sqlite.pyindex b645d5ccc..678f6b4ea 100644--- a/tests/test_storage/test_sqlite.py+++ b/tests/test_storage/test_sqlite.py@@ -11,6 +11,52 @@ import pytestfrom headroom.config import RequestMetricsfrom headroom.storage.sqlite import SQLiteStorage+_LEGACY_REQUESTS_SCHEMA = """+ CREATE TABLE requests (+ id TEXT PRIMARY KEY,+ timestamp TEXT NOT NULL,+ model TEXT NOT NULL,+ stream INTEGER NOT NULL,+ mode TEXT NOT NULL,+ tokens_input_before INTEGER NOT NULL,+ tokens_input_after INTEGER NOT NULL,+ tokens_output INTEGER,+ block_breakdown TEXT NOT NULL,+ waste_signals TEXT NOT NULL,+ stable_prefix_hash TEXT,+ cache_alignment_score REAL,+ cached_tokens INTEGER,+ transforms_applied TEXT NOT NULL,+ tool_units_dropped INTEGER DEFAULT 0,+ turns_dropped INTEGER DEFAULT 0,+ messages_hash TEXT,+ error TEXT+ )+"""+++def _seed_legacy_requests_db(db_path: str, request_id: str = "legacy-1") -> None:+ """Create a pre-cache-optimizer database with one surviving row."""+ conn = sqlite3.connect(db_path)+ try:+ cursor = conn.cursor()+ cursor.execute(_LEGACY_REQUESTS_SCHEMA)+ cursor.execute(+ """+ INSERT INTO requests (+ id, timestamp, model, stream, mode,+ tokens_input_before, tokens_input_after, tokens_output,+ block_breakdown, waste_signals, transforms_applied,+ tool_units_dropped, turns_dropped+ ) VALUES (?, '2025-01-06T12:00:00Z', 'gpt-4o', 0, 'audit',+ 1000, 800, 200, '{}', '{}', '[]', 0, 0)+ """,+ (request_id,),+ )+ conn.commit()+ finally:+ conn.close()+class TestSQLiteStorageInit:"""Tests for SQLiteStorage initialization."""@@ -55,6 +101,13 @@ class TestSQLiteStorageInit:"stable_prefix_hash","cache_alignment_score","cached_tokens",+ "cache_optimizer_used",+ "cache_optimizer_strategy",+ "cacheable_tokens",+ "breakpoints_inserted",+ "estimated_cache_hit",+ "estimated_savings_percent",+ "semantic_cache_hit","transforms_applied","tool_units_dropped","turns_dropped",@@ -793,3 +846,139 @@ class TestConcurrency:count = storage.count()assert count == 50 # 5 threads * 10 records eachstorage.close()+++class TestCacheOptimizerMetrics:+ """Cache-optimizer fields must survive a durable SQLite round trip (#4261)."""++ def test_save_close_reopen_preserves_cache_optimizer_fields(self, temp_sqlite_db):+ metrics = RequestMetrics(+ request_id="cache-repro",+ timestamp=datetime(2025, 1, 6, 12, 0, 0),+ model="claude-3-opus",+ stream=False,+ mode="optimize",+ tokens_input_before=1000,+ tokens_input_after=800,+ cache_optimizer_used="anthropic-cache-optimizer",+ cache_optimizer_strategy="explicit_breakpoints",+ cacheable_tokens=789,+ breakpoints_inserted=2,+ estimated_cache_hit=True,+ estimated_savings_percent=42.5,+ semantic_cache_hit=True,+ )++ storage = SQLiteStorage(temp_sqlite_db)+ storage.save(metrics)+ storage.close()++ reopened = SQLiteStorage(temp_sqlite_db)+ restored = reopened.get("cache-repro")+ reopened.close()++ assert restored is not None+ assert restored.cache_optimizer_used == "anthropic-cache-optimizer"+ assert restored.cache_optimizer_strategy == "explicit_breakpoints"+ assert restored.cacheable_tokens == 789+ assert restored.breakpoints_inserted == 2+ assert restored.estimated_cache_hit is True+ assert restored.estimated_savings_percent == 42.5+ assert restored.semantic_cache_hit is True++ def test_cache_optimizer_defaults_round_trip(self, temp_sqlite_db):+ metrics = RequestMetrics(+ request_id="cache-defaults",+ timestamp=datetime(2025, 1, 6, 12, 0, 0),+ model="gpt-4o",+ stream=False,+ mode="audit",+ tokens_input_before=1000,+ tokens_input_after=800,+ )++ storage = SQLiteStorage(temp_sqlite_db)+ storage.save(metrics)+ storage.close()++ reopened = SQLiteStorage(temp_sqlite_db)+ restored = reopened.get("cache-defaults")+ reopened.close()++ assert restored is not None+ assert restored.cache_optimizer_used is None+ assert restored.cache_optimizer_strategy is None+ assert restored.cacheable_tokens == 0+ assert restored.breakpoints_inserted == 0+ assert restored.estimated_cache_hit is False+ assert restored.estimated_savings_percent == 0.0+ assert restored.semantic_cache_hit is False++ def test_opening_legacy_database_migrates_without_dropping_rows(self, temp_sqlite_db):+ _seed_legacy_requests_db(temp_sqlite_db)++ storage = SQLiteStorage(temp_sqlite_db)+ restored = storage.get("legacy-1")+ storage.close()++ assert restored is not None+ assert restored.model == "gpt-4o"+ assert restored.tokens_input_before == 1000+ assert restored.cache_optimizer_used is None+ assert restored.cacheable_tokens == 0+ assert restored.semantic_cache_hit is False++ def test_concurrent_clients_migrate_legacy_database(self, temp_sqlite_db):+ """Several clients can open a pre-optimizer database at once."""+ _seed_legacy_requests_db(temp_sqlite_db)++ worker_count = 8+ barrier = threading.Barrier(worker_count)+ errors: list[str] = []++ def worker(worker_id: int) -> None:+ try:+ barrier.wait(timeout=5)+ storage = SQLiteStorage(temp_sqlite_db)+ try:+ restored = storage.get("legacy-1")+ assert restored is not None+ assert restored.model == "gpt-4o"+ storage.save(+ RequestMetrics(+ request_id=f"concurrent-init-{worker_id}",+ timestamp=datetime(2025, 1, 6, 12, 0, 0),+ model="gpt-4o",+ stream=False,+ mode="audit",+ tokens_input_before=1000,+ tokens_input_after=800,+ cache_optimizer_used="anthropic-cache-optimizer",+ cacheable_tokens=10 + worker_id,+ )+ )+ finally:+ storage.close()+ except Exception as exc:+ errors.append(f"worker {worker_id}: {exc}")++ threads = [threading.Thread(target=worker, args=(i,)) for i in range(worker_count)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ assert errors == [], f"Concurrent setup failed: {errors}"++ storage = SQLiteStorage(temp_sqlite_db)+ try:+ restored = storage.get("legacy-1")+ assert restored is not None+ assert restored.cache_optimizer_used is None+ assert storage.count() == worker_count + 1+ for worker_id in range(worker_count):+ saved = storage.get(f"concurrent-init-{worker_id}")+ assert saved is not None+ assert saved.cacheable_tokens == 10 + worker_id+ finally:+ storage.close()diff --git a/tests/test_storage_backends.py b/tests/test_storage_backends.pyindex 1315a9608..d6018d85b 100644--- a/tests/test_storage_backends.py+++ b/tests/test_storage_backends.py@@ -618,3 +618,43 @@ def test_jsonl_query_retains_at_most_requested_window(# whole match set.assert max(retained) <= window + 1assert max(retained) < len(matches)++[email protected]("backend", [JSONLStorage, SQLiteStorage])+def test_cache_optimizer_fields_survive_durable_reopen(backend, tmp_path: Path) -> None:+ """Both backends must persist every cache-optimizer field across a reopen (#4261)."""+ suffix = "jsonl" if backend is JSONLStorage else "db"+ path = str(tmp_path / f"metrics.{suffix}")+ metrics = RequestMetrics(+ request_id="cache-repro",+ timestamp=datetime(2026, 4, 23, 12, 0, 0),+ model="claude-3-opus",+ stream=False,+ mode="optimize",+ tokens_input_before=1000,+ tokens_input_after=800,+ cache_optimizer_used="anthropic-cache-optimizer",+ cache_optimizer_strategy="explicit_breakpoints",+ cacheable_tokens=789,+ breakpoints_inserted=2,+ estimated_cache_hit=True,+ estimated_savings_percent=42.5,+ semantic_cache_hit=True,+ )++ storage = backend(path)+ storage.save(metrics)+ storage.close()++ reopened = backend(path)+ restored = reopened.get("cache-repro")+ reopened.close()++ assert restored is not None+ assert restored.cache_optimizer_used == metrics.cache_optimizer_used+ assert restored.cache_optimizer_strategy == metrics.cache_optimizer_strategy+ assert restored.cacheable_tokens == metrics.cacheable_tokens+ assert restored.breakpoints_inserted == metrics.breakpoints_inserted+ assert restored.estimated_cache_hit == metrics.estimated_cache_hit+ assert restored.estimated_savings_percent == metrics.estimated_savings_percent+ assert restored.semantic_cache_hit == metrics.semantic_cache_hit