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: pure-Python content detector default on Windows (clean) (#1063)

r00tc9853f30cbaf
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.py
index 3fb319deb..d8b961738 100644
--- a/headroom/transforms/content_router.py
+++ b/headroom/transforms/content_router.py
@@ -40,6 +40,7 @@ import logging
import math
import os
import re
+import sys
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
@@ -56,6 +57,9 @@ from .error_detection import content_has_strong_error_indicators
logger = logging.getLogger(__name__)
+_detect_backend_warned = False
+
+
def _router_debug_dumps(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, default=str, separators=(",", ":"))
@@ -109,20 +113,42 @@ def _section_debug(section: ContentSection, index: int) -> dict[str, Any]:
}
+def _resolve_detect_backend() -> str:
+ """Pick the content-detection backend: ``"rust"`` or ``"python"``."""
+ backend = os.environ.get("HEADROOM_DETECT_BACKEND", "").strip().lower()
+ if backend in ("python", "rust"):
+ return backend
+ return "python" if sys.platform == "win32" else "rust"
+
+
def _detect_content(content: str) -> DetectionResult:
- """Detect content type via the Rust detection chain.
+ """Detect content type via the native chain, with a safe Windows default.
Stage-3d (PR5) wired this through `headroom._core.detect_content_type`,
- which runs the magika→unidiff→PlainText chain. The Python-side
- Magika+regex fallback path was retired here — single detection
- surface, no parallel paths. The Rust extension is a hard dep
- (no Python fallback) per `feedback_no_silent_fallbacks.md`.
+ which runs the magika→unidiff→PlainText chain. On Windows, native Magika
+ initialization can leave an ONNX Runtime thread alive after timeout, so the
+ default backend there is the pure-Python regex detector.
+
+ Set `HEADROOM_DETECT_BACKEND=rust` or `python` to force a backend.
The Rust binding returns the legacy `DetectionResult` shape with
`confidence=1.0` and an empty metadata dict. Existing callers
only consumed `.content_type` from it; the strategy mapping in
`_strategy_from_detection` keys off that field alone.
"""
+ global _detect_backend_warned
+
+ backend = _resolve_detect_backend()
+ if backend == "python":
+ if not _detect_backend_warned:
+ _detect_backend_warned = True
+ logger.warning(
+ "Content detection using pure-Python backend "
+ "(native Magika/ONNX detector is unsafe by default on Windows; "
+ "override with HEADROOM_DETECT_BACKEND=rust)."
+ )
+ return _regex_detect_content_type(content)
+
from headroom._core import detect_content_type as _rust_detect
rust_result = _rust_detect(content)
diff --git a/tests/test_transforms_content_router.py b/tests/test_transforms_content_router.py
index 0d16bb29e..7aba2e3b6 100644
--- a/tests/test_transforms_content_router.py
+++ b/tests/test_transforms_content_router.py
@@ -120,6 +120,11 @@ def test_content_signature_and_detection_helpers(monkeypatch: pytest.MonkeyPatch
# tag back as the Python ContentType enum.
import headroom._core as _core
+ # Pin the Rust backend so this test exercises the native delegation
+ # path on every platform (Windows now defaults to the pure-Python
+ # detector — see content_router._resolve_detect_backend).
+ monkeypatch.setenv("HEADROOM_DETECT_BACKEND", "rust")
+
fake_rust_result = SimpleNamespace(
content_type="source_code",
confidence=1.0,
@@ -645,3 +650,71 @@ def test_pinning_skips_already_compressed(monkeypatch: pytest.MonkeyPatch) -> No
)
# Already-compressed marker keeps proxy idempotent across turns
assert result["content"][0]["text"] == pinned
+
+
+def test_detect_backend_env_python_forces_python_path(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """HEADROOM_DETECT_BACKEND=python forces the pure-Python regex path."""
+ import headroom._core as _core
+
+ monkeypatch.setenv("HEADROOM_DETECT_BACKEND", "python")
+
+ called = []
+
+ def _record(content: str): # type: ignore[return]
+ called.append(content)
+ raise AssertionError("native must not be called with python backend")
+
+ monkeypatch.setattr(_core, "detect_content_type", _record)
+
+ # Should not raise — native detector must be bypassed entirely.
+ result = _detect_content('[{"id": 1}]')
+ assert result.content_type is ContentType.JSON_ARRAY
+ assert called == [], "native detect_content_type was called despite python backend"
+
+
+def test_detect_backend_env_override(monkeypatch: pytest.MonkeyPatch) -> None:
+ """HEADROOM_DETECT_BACKEND pins the detector on any platform."""
+ resolve = content_router_module._resolve_detect_backend
+
+ monkeypatch.setenv("HEADROOM_DETECT_BACKEND", "python")
+ assert resolve() == "python"
+
+ monkeypatch.setenv("HEADROOM_DETECT_BACKEND", "RUST") # case-insensitive
+ assert resolve() == "rust"
+
+ # Unrecognized values fall back to the platform default.
+ monkeypatch.setenv("HEADROOM_DETECT_BACKEND", "bogus")
+ monkeypatch.setattr(content_router_module.sys, "platform", "linux")
+ assert resolve() == "rust"
+
+
+def test_detect_backend_defaults_to_python_on_windows(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Windows defaults to the pure-Python detector (native ONNX hang, #845)."""
+ monkeypatch.delenv("HEADROOM_DETECT_BACKEND", raising=False)
+
+ monkeypatch.setattr(content_router_module.sys, "platform", "win32")
+ assert content_router_module._resolve_detect_backend() == "python"
+
+ monkeypatch.setattr(content_router_module.sys, "platform", "linux")
+ assert content_router_module._resolve_detect_backend() == "rust"
+
+
+def test_detect_content_python_backend_skips_native(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The python backend must not touch the native detector at all."""
+ import headroom._core as _core
+
+ monkeypatch.setenv("HEADROOM_DETECT_BACKEND", "python")
+
+ def _boom(_content: str) -> None:
+ raise AssertionError("native detector must not be called")
+
+ monkeypatch.setattr(_core, "detect_content_type", _boom)
+
+ result = _detect_content('[{"id": 1}, {"id": 2}]')
+ assert result.content_type is ContentType.JSON_ARRAY