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(cache): normalize embeddings before the semantic similarity check (#2122)
Abhay Singhf8eaaeb26a65
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d75700f5..41f9d9b1a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -133,6 +133,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0* **tokenizers:** resolve HuggingFace tokenizer names by the most-specific prefix. `get_tokenizer_name` scanned `MODEL_TO_TOKENIZER` in dict-insertion order and returned the first key the model merely starts with, so a short family key shadowed a more-specific one — `qwen2-7b-instruct` matched `qwen` before `qwen2`/`qwen2-7b` and resolved to the Qwen1 tokenizer (a different vocabulary, hence wrong token counts); `qwen2.5-*` and `deepseek-v2.x` were mis-resolved the same way. It now picks the longest matching prefix, mirroring the order-dependent-prefix guard the sibling tiktoken `get_encoding_for_model` already documents.* **pricing:** map retired `claude-3-sonnet-20240229` to a Sonnet-tier price instead of Haiku. When LiteLLM's cost DB lacks the retired model, resolution falls through to `MODEL_ALIASES`, which pointed Claude 3 Sonnet (a $3/$15-per-1M model) at `claude-3-haiku-20240307` ($0.25/$1.25) — a different tier that underpriced every cost/savings figure for that model ~12x on both input and output. It now aliases to `claude-sonnet-4-20250514`, the same-price target the other retired-Sonnet aliases already use.* **cache/semantic:** don't evict an unrelated entry when re-storing a key that is already cached. `SemanticCache.put` ran its at-capacity eviction loop before computing the entry's key, so overwriting a key that was already present (a duplicate or retried store) still evicted the LRU-oldest distinct entry even though an in-place update grows nothing. That silently dropped a live entry and turned a later lookup for it into a false cache miss. The key is now computed first and the eviction loop only runs when the key is genuinely new (mirroring `CompressionCache.store_compressed`, which deletes-then-inserts).+* **cache:** normalize embeddings before the semantic dynamic-content similarity check. `SemanticDetector` scored sentences with `np.dot` against exemplar embeddings and compared the result to `semantic_threshold` (a 0-1 cosine value), but `sentence_transformers.encode(..., convert_to_numpy=True)` does not normalize, so the dot product was an unbounded inner product (vector norms ~5-15) rather than a cosine similarity. Nearly every sentence cleared the 0.7 threshold, so the semantic tier flagged almost all text as dynamic and stripped static content, busting the cache it is meant to protect (a standalone repro scores an unrelated sentence, true cosine ~0.1, at a raw dot of ~9). Both `encode` calls now pass `normalize_embeddings=True`, matching the siblings in `prediction/feature_extractor.py` and `memory/adapters/embedders.py`, so the dot product is a true cosine in [-1, 1].* **subscription:** cap `HeadroomContribution.efficiency_pct` at a real removal ratio so it can't exceed 100%. The numerator used `total_saved()` (which includes `tokens_saved_cache_reads`) while the denominator `raw_without_headroom()` excludes cache reads, so a contribution with large prefix-cache reads and small forwarded input reported impossible values (e.g. `tokens_submitted=100`, `tokens_saved_cache_reads=1000` → `1000.0%` on the dashboard). Cache reads are a provider-side discount on tokens that were still forwarded, not tokens Headroom removed, so the ratio now uses the sibling `compression_saved()` (compression + CLI filtering) as the numerator — bounded by its own denominator. `total_saved()` is unchanged for its other callers.* **proxy/anthropic:** cache the response under the same messages it was looked up by. The non-streaming `/v1/messages` path snapshots the scalar cache-key fields (system, tools, etc.) once before upstream to avoid post-mutation key drift (#327), but `messages` — the primary key component — was passed live at both `cache.get` and `cache.set`. Between the two, `messages` is reassigned by the enterprise security scan, the `pre_compress` hook, and image compression, so when any of those fired the response was stored under a different key than it was read by: the response cache never hit and accumulated unreachable entries until eviction. The lookup messages are now snapshotted alongside the other key fields and reused verbatim at `cache.set`.* **tokenizers:** stop `TiktokenCounter.count_messages` from exploding on non-text content blocks. Its multi-part branch handled only `text` and OpenAI `image_url`; every other shape (Anthropic `image`/`tool_result`/`tool_use`, Strands blocks) fell through to `count_text(str(part))`, which json-stringified the base64 payload and tokenized it as text — a 1MB image counted as ~330K phantom tokens (~218x overcount in a standalone repro), corrupting every downstream budgeting/compression decision for multimodal OpenAI-model requests. Unknown block shapes now delegate to the base `_count_content_parts`, which prices images/documents by a bounded estimate (the overcount that helper already exists to prevent).diff --git a/headroom/cache/dynamic_detector.py b/headroom/cache/dynamic_detector.pyindex 83e78e01f..dc9826eda 100644--- a/headroom/cache/dynamic_detector.py+++ b/headroom/cache/dynamic_detector.py@@ -742,10 +742,18 @@ class SemanticDetector:from headroom.models.ml_models import MLModelRegistryself._model = MLModelRegistry.get_sentence_transformer(config.embedding_model)- # Pre-compute exemplar embeddings+ # Pre-compute exemplar embeddings. normalize_embeddings=True is+ # required: detect() scores sentences with np.dot against these and+ # compares to semantic_threshold (a 0-1 cosine value). Without+ # normalization sentence_transformers returns raw vectors (norm+ # ~5-15), so the dot product is an unbounded inner product, not a+ # cosine similarity — nearly every sentence would clear the 0.7+ # threshold and be misflagged as dynamic. Matches the siblings in+ # prediction/feature_extractor.py and memory/adapters/embedders.py.self._exemplar_embeddings = self._model.encode(self.DYNAMIC_EXEMPLARS,convert_to_numpy=True,+ normalize_embeddings=True,)except ImportError:self._load_error = (@@ -812,9 +820,13 @@ class SemanticDetector:if self._exemplar_embeddings is None:return [], "exemplar embeddings not initialized"+ # normalize_embeddings=True so np.dot below is a true cosine similarity+ # in [-1, 1], comparable to semantic_threshold; must match the exemplar+ # encoding above (both normalized or the dot product is meaningless).sentence_embeddings = self._model.encode(sentence_texts,convert_to_numpy=True,+ normalize_embeddings=True,)similarities = np.dot(sentence_embeddings, self._exemplar_embeddings.T)diff --git a/tests/test_cache/test_dynamic_detector.py b/tests/test_cache/test_dynamic_detector.pyindex 82faabc8a..bf5e0f066 100644--- a/tests/test_cache/test_dynamic_detector.py+++ b/tests/test_cache/test_dynamic_detector.py@@ -631,3 +631,62 @@ class TestSemanticDetectorGuards:assert spans == []assert warning == "exemplar embeddings not initialized"+++class _RecordingEncoder:+ """A stand-in sentence-transformers model that records encode kwargs and+ returns unit vectors (so the detector's np.dot math still runs)."""++ def __init__(self) -> None:+ self.encode_calls: list[dict] = []++ def encode(self, texts, **kwargs):+ import numpy as np++ self.encode_calls.append(kwargs)+ n = len(texts) if isinstance(texts, list) else 1+ return np.tile(np.array([1.0, 0.0, 0.0]), (n, 1))+++class TestSemanticDetectorNormalization:+ """Embeddings must be L2-normalized before the np.dot cosine comparison."""++ def test_detect_normalizes_sentence_embeddings(self):+ """The sentence encode in detect() must pass normalize_embeddings=True.++ Without it np.dot is an unbounded inner product (vector norms ~5-15),+ not a cosine similarity, so nearly every sentence clears the 0.7+ threshold and static content is wrongly flagged dynamic.+ """+ np = pytest.importorskip("numpy")++ from headroom.cache.dynamic_detector import SemanticDetector++ det = object.__new__(SemanticDetector)+ det.config = DetectorConfig(tiers=["semantic"])+ model = _RecordingEncoder()+ det._model = model+ det._exemplar_embeddings = np.array([[1.0, 0.0, 0.0]])+ det._load_error = None++ det.detect("The current stock price changes every minute.")++ assert model.encode_calls, "encode was never called"+ assert all(c.get("normalize_embeddings") is True for c in model.encode_calls)++ def test_init_normalizes_exemplar_embeddings(self, monkeypatch):+ """The exemplar encode in __init__ must also pass normalize_embeddings=True+ (both sides of the dot product must be normalized to be comparable)."""+ pytest.importorskip("numpy")++ import headroom.cache.dynamic_detector as dd+ from headroom.models.ml_models import MLModelRegistry++ model = _RecordingEncoder()+ monkeypatch.setattr(dd, "_SENTENCE_TRANSFORMERS_AVAILABLE", True)+ monkeypatch.setattr(MLModelRegistry, "get_sentence_transformer", lambda *a, **k: model)++ dd.SemanticDetector(DetectorConfig(tiers=["semantic"]))++ assert model.encode_calls, "exemplar encode was never called"+ assert model.encode_calls[0].get("normalize_embeddings") is True