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): guard None exemplar embeddings in dynamic detector (#950)
Ashish1ec93208883f
diff --git a/headroom/cache/dynamic_detector.py b/headroom/cache/dynamic_detector.pyindex 44ce5a4ed..5030862e9 100644--- a/headroom/cache/dynamic_detector.py+++ b/headroom/cache/dynamic_detector.py@@ -785,7 +785,12 @@ class SemanticDetector:convert_to_numpy=True,)- # Compute similarities+ # Compute similarities. `is_available` only guarantees `_model` is+ # set; guard the exemplar matrix explicitly so a None never reaches+ # `.T` (real crash) and mypy can narrow the `Any | None` attribute.+ if self._exemplar_embeddings is None:+ return [], "exemplar embeddings not initialized"+similarities = np.dot(sentence_embeddings, self._exemplar_embeddings.T)for i, (text, start, end) in enumerate(sentences):diff --git a/tests/test_cache/test_dynamic_detector.py b/tests/test_cache/test_dynamic_detector.pyindex f9ae3bba8..154a309d9 100644--- a/tests/test_cache/test_dynamic_detector.py+++ b/tests/test_cache/test_dynamic_detector.py@@ -525,3 +525,31 @@ Be helpful and accurate."""assert len(result.spans) == 1assert result.spans[0].tier == "regex"+++class TestSemanticDetectorGuards:+ """Defensive guards in SemanticDetector.detect()."""++ def test_none_exemplars_early_return(self):+ """detect() must early-return, not crash, when exemplar embeddings+ are unset while a model is present.++ Regression for the `None.T` guard: `is_available` only checks+ `_model`, so `_exemplar_embeddings` can be None at the `np.dot`+ call. The guard returns the method's `(spans, warning)` contract.+ """+ np = pytest.importorskip("numpy")+ from unittest.mock import MagicMock++ from headroom.cache.dynamic_detector import SemanticDetector++ det = object.__new__(SemanticDetector)+ det._model = MagicMock()+ det._model.encode.return_value = np.zeros((1, 3))+ det._exemplar_embeddings = None+ det._load_error = None++ spans, warning = det.detect("This is a sentence here. Here is another long one.")++ assert spans == []+ assert warning == "exemplar embeddings not initialized"