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(router): validate lossless provider output on the excluded-tool path (#4486)
HetCreep9f068a6c1357
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.pyindex 88c2eef13..c0c5c9304 100644--- a/headroom/transforms/content_router.py+++ b/headroom/transforms/content_router.py@@ -3778,6 +3778,31 @@ class ContentRouter(Transform):return cand, f"lossless_{kind}"+ @staticmethod+ def _validate_provider_output(supplied: Any) -> tuple[str, str] | None:+ """Contract check shared by the general and excluded-tool provider paths.++ Returns ``(candidate, safe_kind)`` or ``None`` ("ignore"). Never raises.+ """+ if supplied is None:+ return None+ if not isinstance(supplied, tuple | list) or len(supplied) != 2:+ logger.debug("lossless provider returned a malformed result; ignoring")+ return None+ if not isinstance(supplied[0], str) or not isinstance(supplied[1], str):+ logger.debug("lossless provider returned non-str members; ignoring")+ return None+ # An empty / whitespace-only "fold" wins every length comparison and+ # would silently delete the block's content. That is not lossless.+ if not supplied[0].strip():+ logger.debug("lossless provider returned an empty result; ignoring")+ return None+ # fullmatch, not match: Python's `$` also matches just BEFORE a+ # trailing newline, so `re.match` would let "log\n" through and+ # put a newline into a metric label.+ kind = supplied[1] if _PROVIDER_KIND_RE.fullmatch(supplied[1]) else _PROVIDER_KIND_FALLBACK+ return (supplied[0], kind)+def _lossless_provider_result(self, content: str) -> tuple[str, str] | None:"""Validated + memoized ``(candidate, safe_kind)`` from the provider.@@ -3808,29 +3833,7 @@ class ContentRouter(Transform):result: tuple[str, str] | None = Nonetry:- supplied = provider(content)- if supplied is None:- result = None- # Validate defensively *inside* the try: unpacking a 3-tuple / a bare- # string / a non-sequence raises, and that exception used to escape- # all the way out of the request.- elif not isinstance(supplied, tuple | list) or len(supplied) != 2:- logger.debug("lossless provider returned a malformed result; ignoring")- elif not isinstance(supplied[0], str) or not isinstance(supplied[1], str):- logger.debug("lossless provider returned non-str members; ignoring")- # An empty / whitespace-only "fold" wins every length comparison and- # would silently delete the block's content. That is not lossless.- elif not supplied[0].strip():- logger.debug("lossless provider returned an empty result; ignoring")- else:- raw_kind = supplied[1]- # fullmatch, not match: Python's `$` also matches just BEFORE a- # trailing newline, so `re.match` would let "log\n" through and- # put a newline into a metric label.- kind = (- raw_kind if _PROVIDER_KIND_RE.fullmatch(raw_kind) else _PROVIDER_KIND_FALLBACK- )- result = (supplied[0], kind)+ result = self._validate_provider_output(provider(content))except Exception: # noqa: BLE001 - a broken provider must not break routinglogger.debug("lossless provider failed in _lossless_first", exc_info=True)result = None@@ -7337,7 +7340,7 @@ class ContentRouter(Transform):try:# A registered provider is authoritative for excluded-tool# compaction; fall back to the built-in folds only if it raises.- return provider(content)+ return self._validate_provider_output(provider(content))except Exception: # noqa: BLE001logger.debug("lossless provider failed; using built-in compaction",diff --git a/tests/test_lossless_excluded_compaction.py b/tests/test_lossless_excluded_compaction.pyindex 20a4fc86d..2efe2588d 100644--- a/tests/test_lossless_excluded_compaction.py+++ b/tests/test_lossless_excluded_compaction.py@@ -281,3 +281,52 @@ def test_provider_exception_falls_back_to_builtin():# Falls back to the built-in fold rather than crashing or passing through raw.out, kind = _compact(GREP)assert kind == "search" and search_unheading(out) == GREP+++# --- excluded path enforces the same provider contract as the general path ----+++def _run_excluded_anthropic(tokenizer):+ router = ContentRouter(ContentRouterConfig())+ messages = [+ {"role": "user", "content": "find it"},+ {+ "role": "assistant",+ "content": [{"type": "tool_use", "id": "t1", "name": "Grep", "input": {}}],+ },+ {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "t1", "content": GREP}],+ },+ ]+ result = router.apply(messages, tokenizer, compress_user_messages=True)+ return result.messages[2]["content"][0]["content"], result.transforms_applied+++def test_excluded_valid_two_tuple_still_applied(tokenizer):+ set_lossless_provider(lambda content: ("compact", "myfold"))+ out, applied = _run_excluded_anthropic(tokenizer)+ assert out == "compact"+ assert "router:excluded:lossless_myfold" in applied+++def test_excluded_three_tuple_is_ignored_not_fatal(tokenizer):+ set_lossless_provider(lambda content: ("compact", "k", "extra"))+ out, applied = _run_excluded_anthropic(tokenizer)+ assert out == GREP+ assert not any(t.startswith("router:excluded:lossless_") for t in applied)+++def test_excluded_empty_fold_leaves_content_unchanged(tokenizer):+ set_lossless_provider(lambda content: (" ", "k"))+ out, applied = _run_excluded_anthropic(tokenizer)+ assert out == GREP+ assert not any(t.startswith("router:excluded:lossless_") for t in applied)+++def test_excluded_hostile_kind_is_replaced(tokenizer):+ set_lossless_provider(lambda content: ("compact", "BAD LABEL{x=1}" + chr(10)))+ out, applied = _run_excluded_anthropic(tokenizer)+ assert out == "compact"+ labels = [t for t in applied if t.startswith("router:excluded:lossless_")]+ assert labels == ["router:excluded:lossless_provider"]