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.

fix(cache): build semantic entry before evicting so a failed embedding keeps live entries (#4581)

Parideboy0d4c450d7746
diff --git a/headroom/cache/semantic.py b/headroom/cache/semantic.py
index 8e14f9359..a8b8dce07 100644
--- a/headroom/cache/semantic.py
+++ b/headroom/cache/semantic.py
@@ -225,15 +225,6 @@ class SemanticCache:
base = messages_hash or self._generate_key(query)
key = self._combined_key(namespace, base)
- # Evict if adding a NEW key would exceed capacity. Overwriting a key that
- # is already present is an in-place update that does not grow the map, so
- # it must NOT evict — the old code ran the eviction loop before computing
- # the key, so re-storing an existing entry at capacity dropped an
- # unrelated live entry and turned a later lookup for it into a false miss.
- # (Mirrors CompressionCache.store_compressed, which deletes-then-inserts.)
- while key not in self._cache and len(self._cache) >= self.config.max_entries:
- self._evict_oldest()
-
# Generate embedding if available — but never for an empty/blank query.
# A stored empty-query entry with an embedding would be a false-match
# target for the semantic get() path; leaving its embedding empty makes
@@ -254,6 +245,18 @@ class SemanticCache:
namespace=namespace,
)
+ # Evict if adding a NEW key would exceed capacity. Overwriting a key that
+ # is already present is an in-place update that does not grow the map, so
+ # it must NOT evict — the old code ran the eviction loop before computing
+ # the key, so re-storing an existing entry at capacity dropped an
+ # unrelated live entry and turned a later lookup for it into a false miss.
+ # (Mirrors CompressionCache.store_compressed, which deletes-then-inserts.)
+ # The embedding call above may raise, so evict only once the new entry is
+ # built — never before, or a failed store would drop a live entry without
+ # replacing it.
+ while key not in self._cache and len(self._cache) >= self.config.max_entries:
+ self._evict_oldest()
+
self._cache[key] = entry
# Index by hash for fast exact matching
diff --git a/tests/test_cache/test_semantic.py b/tests/test_cache/test_semantic.py
index 4143762e0..90ec45004 100644
--- a/tests/test_cache/test_semantic.py
+++ b/tests/test_cache/test_semantic.py
@@ -123,6 +123,52 @@ class TestSemanticCache:
got2 = cache.get("query2", messages_hash="h2")
assert got2 is not None and got2.response == "response2b"
+ def test_put_failure_after_eviction_keeps_live_entry(self):
+ """A failed embedding must not silently drop an already-evicted entry.
+
+ The eviction loop used to run before the embedding call, so if the
+ embedding function raised, an old live entry was already evicted while
+ the new entry was never stored — a permanent data loss on a transient
+ error. The exception must still propagate.
+ """
+ config = SemanticCacheConfig(max_entries=1, similarity_threshold=0.9)
+ cache = SemanticCache(config)
+
+ call_count = {"n": 0}
+
+ def flaky_embedding(text: str) -> list[float]:
+ call_count["n"] += 1
+ if call_count["n"] == 1:
+ return [1.0, 0.0]
+ raise RuntimeError("embedding backend unavailable")
+
+ cache._embedding_fn = flaky_embedding
+
+ # First put succeeds and fills the cache to capacity.
+ cache.put("a", "response-a", messages_hash="ha")
+ assert cache.get("a", messages_hash="ha") is not None
+ assert len(cache._cache) == 1
+
+ # Second put raises, but the live entry must survive untouched.
+ with pytest.raises(RuntimeError, match="embedding backend unavailable"):
+ cache.put("b", "response-b", messages_hash="hb")
+
+ assert cache.get("a", messages_hash="ha") is not None
+ assert len(cache._cache) == 1
+
+ # With the embedding working again, a new put evicts "a" normally.
+ def stable_embedding(text: str) -> list[float]:
+ # Distinct vectors per query so "a" and "c" never false-hit.
+ if text == "a":
+ return [1.0, 0.0]
+ return [0.0, 1.0]
+
+ cache._embedding_fn = stable_embedding
+ cache.put("c", "response-c", messages_hash="hc")
+ assert cache.get("a", messages_hash="ha") is None
+ assert cache.get("c", messages_hash="hc") is not None
+ assert len(cache._cache) == 1
+
def test_ttl_expiration(self):
"""Test TTL expiration."""
config = SemanticCacheConfig(ttl_seconds=1)