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(compression): pause AST compression per language after repeated invalid-syntax discards (#3387)

gglucassdde83c914687
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index 1bb9f7bbe..8ff2e7eca 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -476,6 +476,16 @@ logging.basicConfig(
logger = logging.getLogger("headroom.proxy")
+def _code_syntax_breaker_status() -> dict[str, Any]:
+ """Per-language AST-compression breaker state, or {} if unavailable."""
+ try:
+ from headroom.transforms.code_compressor import syntax_breaker_status
+
+ return syntax_breaker_status()
+ except Exception: # pragma: no cover - defensive; stats must not fail
+ return {}
+
+
class _SuppressCancelledErrorFilter(logging.Filter):
"""Hide expected uvicorn CancelledError tracebacks during shutdown."""
@@ -4603,6 +4613,9 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"ccr_retrievals": compression_stats.get("total_retrievals", 0),
},
"compression_cache": compression_cache_stats,
+ # Per-language AST compression pauses. Empty on a healthy install;
+ # non-empty is the explanation for a savings drop in one language.
+ "code_syntax_breaker": _code_syntax_breaker_status(),
# Always False: the anonymous telemetry beacon was removed, so no
# telemetry is ever shipped externally (local collection only).
"anon_telemetry_shipping": False,
diff --git a/headroom/transforms/code_compressor.py b/headroom/transforms/code_compressor.py
index 77ccc8ea8..d95b7265e 100644
--- a/headroom/transforms/code_compressor.py
+++ b/headroom/transforms/code_compressor.py
@@ -43,8 +43,11 @@ Reference:
from __future__ import annotations
import logging
+import os
import re
import threading
+import time
+from collections import deque
from collections.abc import Callable
from dataclasses import dataclass, field
from enum import Enum
@@ -105,6 +108,109 @@ def _tree_sitter_importable() -> bool:
_UNSAFE_TREE_SITTER_LANGUAGES: frozenset[str] = frozenset({"perl"})
+# ---------------------------------------------------------------------------
+# Per-language invalid-syntax circuit breaker.
+#
+# The AST pass validates its own output and discards anything that no longer
+# parses ("never serve broken code"), so a misbehaving grammar costs the full
+# compression latency and then throws the work away — measured in the field at
+# 270 discarded TypeScript compressions in one install's retained logs, each
+# preceded by ~1.2s of compressor time. When a language keeps failing its own
+# validation, stop attempting it for a cooldown instead of burning the latency
+# on every request. The static _UNSAFE_TREE_SITTER_LANGUAGES set above is for
+# grammars unsafe to LOAD; this breaker is for grammars that load fine but
+# mangle real code.
+#
+# SCOPE: process-global, deliberately. One pathological payload pauses that
+# language for every session served by this process, which is right for the
+# single-user local proxy this ships as (a failing grammar is a property of the
+# process's tree-sitter build, not of the caller) and wrong for a shared or
+# hosted deployment, where one tenant would pause a language for the others.
+# Keying by tenant needs a caller identity plumbed through the Transform
+# interface, which carries code and language only; until something needs that,
+# HEADROOM_CODE_SYNTAX_BREAKER=0 is the per-deployment opt-out.
+_SYNTAX_BREAKER_WINDOW = 20
+_SYNTAX_BREAKER_MIN_FAILURES = 10
+_SYNTAX_BREAKER_COOLDOWN_S = 1800.0
+_syntax_breaker_lock = threading.Lock()
+_syntax_breaker_outcomes: dict[str, deque[bool]] = {}
+_syntax_breaker_open_until: dict[str, float] = {}
+_syntax_breaker_trips: dict[str, int] = {}
+
+
+def _now() -> float:
+ """Monotonic clock behind one indirection, so tests patch this instead of
+ the real ``time`` module (which anything else running concurrently reads)."""
+ return time.monotonic()
+
+
+def syntax_breaker_status() -> dict[str, dict[str, Any]]:
+ """Per-language breaker state, surfaced on /stats.
+
+ While the breaker is open that language compresses at ratio 1.0, so savings
+ drop with nothing in the payload explaining why. Empty until something
+ trips, so a healthy install carries no extra keys.
+ """
+ now = _now()
+ with _syntax_breaker_lock:
+ languages = set(_syntax_breaker_trips) | set(_syntax_breaker_open_until)
+ return {
+ language: {
+ "open": _syntax_breaker_open_until.get(language, 0.0) > now,
+ "trips": _syntax_breaker_trips.get(language, 0),
+ "reopens_in_seconds": max(
+ 0.0, round(_syntax_breaker_open_until.get(language, 0.0) - now, 1)
+ ),
+ }
+ for language in sorted(languages)
+ }
+
+
+def _syntax_breaker_enabled() -> bool:
+ return os.environ.get("HEADROOM_CODE_SYNTAX_BREAKER", "1").strip().lower() not in (
+ "0",
+ "false",
+ "off",
+ )
+
+
+def _syntax_breaker_open(language: str) -> bool:
+ """True while AST compression for *language* is paused after repeat failures."""
+ if not _syntax_breaker_enabled():
+ return False
+ with _syntax_breaker_lock:
+ if _syntax_breaker_open_until.get(language, 0.0) <= _now():
+ return False
+ logger.debug("Code compression for %s skipped: syntax breaker open", language)
+ return True
+
+
+def _record_syntax_outcome(language: str, valid: bool) -> None:
+ """Track validation outcomes; trip the breaker on a failing window."""
+ if not _syntax_breaker_enabled():
+ return
+ tripped_failures = 0
+ with _syntax_breaker_lock:
+ window = _syntax_breaker_outcomes.setdefault(language, deque(maxlen=_SYNTAX_BREAKER_WINDOW))
+ window.append(valid)
+ failures = sum(1 for ok in window if not ok)
+ if failures >= _SYNTAX_BREAKER_MIN_FAILURES:
+ _syntax_breaker_open_until[language] = _now() + _SYNTAX_BREAKER_COOLDOWN_S
+ _syntax_breaker_trips[language] = _syntax_breaker_trips.get(language, 0) + 1
+ # A fresh window after the cooldown must re-earn the trip.
+ window.clear()
+ tripped_failures = failures
+ if tripped_failures:
+ logger.warning(
+ "Code compression for %s paused for %.0f min: %d of the last %d attempts "
+ "produced invalid syntax and were discarded "
+ "(HEADROOM_CODE_SYNTAX_BREAKER=0 disables this breaker)",
+ language,
+ _SYNTAX_BREAKER_COOLDOWN_S / 60.0,
+ tripped_failures,
+ _SYNTAX_BREAKER_WINDOW,
+ )
+
def _get_parser(language: str) -> Any:
"""Get a tree-sitter parser for the given language.
@@ -1227,6 +1333,22 @@ class CodeAwareCompressor(Transform):
syntax_valid=True,
)
+ # A language that keeps failing its own output validation gets its
+ # attempts paused (see _record_syntax_outcome) — return the original
+ # without paying the parse/compress latency for work that would be
+ # discarded anyway.
+ if _syntax_breaker_open(detected_lang.value):
+ return CodeCompressionResult(
+ compressed=code,
+ original=code,
+ original_tokens=original_tokens,
+ compressed_tokens=original_tokens,
+ compression_ratio=1.0,
+ language=detected_lang,
+ language_confidence=confidence,
+ syntax_valid=True,
+ )
+
# Parse and compress
try:
compressed, structure, symbol_scores = self._compress_with_ast(
@@ -1251,6 +1373,8 @@ class CodeAwareCompressor(Transform):
compressed_tokens = self._estimate_tokens(compressed, tokenizer)
syntax_valid = self._verify_syntax(compressed, detected_lang)
+ _record_syntax_outcome(detected_lang.value, syntax_valid)
+
# If syntax invalid, return original (never serve broken code)
if not syntax_valid:
logger.warning(
diff --git a/tests/test_code_compressor_syntax_breaker.py b/tests/test_code_compressor_syntax_breaker.py
new file mode 100644
index 000000000..c344127ee
--- /dev/null
+++ b/tests/test_code_compressor_syntax_breaker.py
@@ -0,0 +1,107 @@
+"""Per-language circuit breaker for AST compression that keeps failing.
+
+The compressor validates its own output and discards invalid results, so a
+misbehaving grammar burns the full compression latency on every request and
+throws the work away (field measurement: 270 discarded TypeScript compressions
+in one install's retained logs at ~1.2s each). After enough failures in the
+recent window the breaker pauses that language for a cooldown; other languages
+and the original content are unaffected.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from headroom.transforms import code_compressor as cc
+
+
[email protected](autouse=True)
+def reset_breaker_state():
+ cc._syntax_breaker_outcomes.clear()
+ cc._syntax_breaker_open_until.clear()
+ cc._syntax_breaker_trips.clear()
+ yield
+ cc._syntax_breaker_outcomes.clear()
+ cc._syntax_breaker_open_until.clear()
+ cc._syntax_breaker_trips.clear()
+
+
+def test_breaker_trips_after_min_failures_in_window():
+ for _ in range(cc._SYNTAX_BREAKER_MIN_FAILURES - 1):
+ cc._record_syntax_outcome("typescript", False)
+ assert not cc._syntax_breaker_open("typescript")
+ cc._record_syntax_outcome("typescript", False)
+ assert cc._syntax_breaker_open("typescript")
+ # Per-language isolation: python keeps compressing.
+ assert not cc._syntax_breaker_open("python")
+
+
+def test_successes_keep_the_breaker_closed():
+ for _ in range(cc._SYNTAX_BREAKER_WINDOW * 2):
+ cc._record_syntax_outcome("typescript", True)
+ for _ in range(cc._SYNTAX_BREAKER_MIN_FAILURES - 1):
+ cc._record_syntax_outcome("typescript", False)
+ assert not cc._syntax_breaker_open("typescript")
+
+
+def test_breaker_reopens_after_cooldown(monkeypatch):
+ now = [1000.0]
+ # Patch the module-local indirection, not the real time module: anything
+ # else running concurrently (xdist worker, background thread) reads that one.
+ monkeypatch.setattr(cc, "_now", lambda: now[0])
+ for _ in range(cc._SYNTAX_BREAKER_MIN_FAILURES):
+ cc._record_syntax_outcome("typescript", False)
+ assert cc._syntax_breaker_open("typescript")
+ now[0] += cc._SYNTAX_BREAKER_COOLDOWN_S + 1
+ assert not cc._syntax_breaker_open("typescript")
+ # The cleared window means one more failure does not instantly re-trip.
+ cc._record_syntax_outcome("typescript", False)
+ assert not cc._syntax_breaker_open("typescript")
+
+
+def test_env_kill_switch(monkeypatch):
+ monkeypatch.setenv("HEADROOM_CODE_SYNTAX_BREAKER", "0")
+ for _ in range(cc._SYNTAX_BREAKER_WINDOW):
+ cc._record_syntax_outcome("typescript", False)
+ assert not cc._syntax_breaker_open("typescript")
+
+
+def test_compress_short_circuits_while_open(monkeypatch):
+ monkeypatch.setattr(cc, "_check_tree_sitter_available", lambda: True)
+
+ def _boom(self, *a, **kw): # pragma: no cover - must not run
+ raise AssertionError("AST compression attempted while breaker open")
+
+ monkeypatch.setattr(cc.CodeAwareCompressor, "_compress_with_ast", _boom)
+ cc._syntax_breaker_open_until["python"] = cc._now() + 60.0
+
+ compressor = cc.CodeAwareCompressor(cc.CodeCompressorConfig(min_tokens_for_compression=1))
+ code = "def f():\n return 1\n" * 20
+ result = compressor.compress(code, language="python")
+ assert result.compressed == code
+ assert result.compression_ratio == 1.0
+ assert result.syntax_valid is True
+
+
+def test_status_reports_open_languages_for_stats(monkeypatch):
+ """While the breaker is open the language compresses at ratio 1.0, so /stats
+ needs to say why rather than leaving an unexplained savings drop."""
+ now = [1000.0]
+ monkeypatch.setattr(cc, "_now", lambda: now[0])
+
+ assert cc.syntax_breaker_status() == {}
+
+ for _ in range(cc._SYNTAX_BREAKER_MIN_FAILURES):
+ cc._record_syntax_outcome("typescript", False)
+ status = cc.syntax_breaker_status()["typescript"]
+ assert status["open"] is True
+ assert status["trips"] == 1
+ assert status["reopens_in_seconds"] == pytest.approx(cc._SYNTAX_BREAKER_COOLDOWN_S)
+
+ now[0] += cc._SYNTAX_BREAKER_COOLDOWN_S + 1
+ reopened = cc.syntax_breaker_status()["typescript"]
+ assert reopened["open"] is False
+ # The trip count survives the cooldown: a language that keeps tripping is
+ # the field diagnosis, and it would be invisible if this reset.
+ assert reopened["trips"] == 1
+ assert reopened["reopens_in_seconds"] == 0.0