Establish `crates/headroom-core/src/signals/` as a top-level module holding cross-cutting detection traits. Phase 3e.1 ports `error_detection.py` to a `LineImportanceDetector` trait + a `Tiered<T>` combinator + a single concrete `KeywordDetector` impl backed by aho-corasick. Three traits at three granularities are sketched (line / blob / item); only line-importance is implemented today. Two bug fixes from the Python source bake into both the Rust impl and the Python regex shim: 1. `ERROR_KEYWORDS` listed `timeout|abort|denied|rejected` but `ERROR_PATTERN` regex omitted them. Lines like `"Connection timeout"` were silently neutral despite the keyword being canonical. Both surfaces now flag them. 2. `SECURITY_KEYWORDS` carried `token`, which false-positived on every reference to LLM tokens (`input_tokens`, `tokens_saved`, ...) in our own product. Dropped from the security set. The Python `error_detection.py` shim now reflects keyword data out of Rust via `keyword_registry_snapshot()` and recompiles the legacy `re.Pattern` objects on the fly. Existing callers (text_compressor, search_compressor, intelligent_context) continue to import the same names with no source changes; caller migration to the trait API happens in their own port PRs. The trait architecture is the seam where a future ML detector slots in without touching `KeywordDetector` or any caller. The canonical extension is documented in `signals/README.md` as a classifier head on the existing `bge-small-en-v1.5` embedder loaded by `relevance::EmbeddingScorer` -- 384-dim -> 4-class softmax, ~1.5 KB head, ~1 ms inference, no extra model file. Two alternatives (distilled tinyBERT in ONNX, logistic regression on lexical features) are kept open in case BGE-head underfits. Per the no-silent-fallbacks rule: only `KeywordDetector` lands as a concrete impl. No NoOp, no MockDetector, no stub-ML -- those will arrive with their real implementations. Phase 3g (Compression Pipeline Formalization, issue #315) is queued as the cross-cutting follow-up that will make lossless-then-lossy- then-CCR ordering an explicit, observable architecture rather than implicit per-compressor logic. Trait shapes there will reuse the signals primitive landed in this PR.
13 KiB
Headroom Rust Rewrite — Developer Guide
This document covers the Rust port of Headroom. It is the only new top-level doc created in Phase 0; longer-form design/plan writeups live elsewhere and are not versioned in this repo.
Workspace layout
Cargo.toml # workspace root
rust-toolchain.toml # pins stable rustc with rustfmt+clippy
crates/
headroom-core/ # library: shared types + transform trait surface
headroom-proxy/ # binary: axum /healthz (Phase 2 grows this)
headroom-py/ # PyO3 cdylib exposing `headroom._core`
headroom-parity/ # lib + `parity-run` CLI for Python parity tests
tests/parity/
fixtures/<transform>/*.json # recorded Python outputs (Phase 1 ports match)
recorder.py # Python-side fixture recorder
scripts/record_fixtures.py # entry point for running the recorder
cargo build --workspace builds every crate. default-members drops
headroom-py from cargo run/bare-cargo test flows so that cargo test --workspace does not try to execute the PyO3 cdylib standalone (it can't
find libpython without a Python interpreter hosting it).
Common commands
just is not installed on dev boxes here; a Makefile at the repo root
exposes the same targets:
| Target | What it does |
|---|---|
make test |
cargo test --workspace |
make test-parity |
Builds headroom-py via maturin, runs parity-run run |
make bench |
cargo bench --workspace |
make build-proxy |
Release-builds headroom-proxy, strips, prints size |
make build-wheel |
maturin build --release -m crates/headroom-py/pyproject.toml |
make fmt |
cargo fmt --all |
make lint |
cargo fmt --check + cargo clippy --workspace -- -D warnings |
Running the proxy
headroom-proxy is a transparent reverse proxy. Phase 1 forwards HTTP/1.1,
HTTP/2, SSE, and WebSocket traffic verbatim to a configured upstream — no
provider logic yet. The intent is that operators run the existing Python
proxy on a private port and put headroom-proxy on the public port pointed
at it; end users notice nothing.
# Build
make build-proxy
./target/release/headroom-proxy --help
# Run against a local upstream
./target/release/headroom-proxy \
--listen 0.0.0.0:8787 \
--upstream http://127.0.0.1:8788
# Health checks
curl -s http://127.0.0.1:8787/healthz # => {"ok":true,...}
curl -s http://127.0.0.1:8787/healthz/upstream # => 200 if upstream reachable
Operator runbook (Phase 1 cutover)
# 1. Move the Python proxy to a private port (e.g. 8788)
HEADROOM_BIND=127.0.0.1:8788 python -m headroom.proxy & # or your existing launcher
# 2. Run the Rust proxy on the previously-public port (8787) pointing at it
./target/release/headroom-proxy --listen 0.0.0.0:8787 --upstream http://127.0.0.1:8788 &
# 3. End users keep hitting :8787 unchanged.
# 4. Confirm passthrough:
curl -si http://127.0.0.1:8787/v1/models
# 5. Rollback = stop the Rust proxy and rebind Python back to 8787.
Configuration flags
| Flag | Env var | Default | Notes |
|---|---|---|---|
--listen |
HEADROOM_PROXY_LISTEN |
0.0.0.0:8787 |
bind address |
--upstream |
HEADROOM_PROXY_UPSTREAM |
(required) | base URL the proxy forwards to |
--upstream-timeout |
600s |
end-to-end request timeout (long for streams) | |
--upstream-connect-timeout |
10s |
TCP/TLS connect timeout | |
--max-body-bytes |
100MB |
for buffered cases; streams bypass | |
--log-level |
info |
RUST_LOG-style filter |
|
--rewrite-host / --no-rewrite-host |
rewrite | rewrite Host to upstream (default) | |
--graceful-shutdown-timeout |
30s |
wait for in-flight on SIGTERM/SIGINT |
Reserved paths
/healthz and /healthz/upstream are intercepted by the Rust proxy and
not forwarded. Operators must not name a real upstream route either of
these. Everything else is a catch-all forward.
Maturin + Python wiring
headroom-py is a PyO3 cdylib that exposes headroom._core in Python. The
extension-module feature is opt-in so plain cargo build --workspace does
not try to link against libpython on systems that don't have it.
First-time setup (clean venv recommended)
python3.11 -m venv /tmp/hr-rust-venv
source /tmp/hr-rust-venv/bin/activate
pip install maturin
cd crates/headroom-py
maturin develop # editable dev build, installs headroom._core
cd /tmp # IMPORTANT: step out of the repo root first
python -c "from headroom._core import hello; print(hello())"
# => headroom-core
Why
cd /tmp? The repo root also contains the Pythonheadroom/package. Running the smoke import from the repo root makes Python resolveheadroomto./headroom/__init__.py(the full SDK, which pulls in heavy deps) instead of the lightweight namespace package installed by maturin. Tests should either run outside the repo root, or ensureheadroomis installed into the same venv (then the maturin-installed_core.solands alongside it and both imports resolve).
Release wheels
make build-wheel
# wheels land under target/wheels/
CI (.github/workflows/rust.yml) builds linux-x86_64, macos-arm64, and
macos-x86_64 wheels via PyO3/maturin-action and uploads them as artifacts.
Parity harness
crates/headroom-parity owns the Rust-vs-Python oracle:
- JSON fixtures under
tests/parity/fixtures/<transform>/(schema:{ transform, input, config, output, recorded_at, input_sha256 }). TransformComparatortrait — one impl per transform. Phase 0 stubs returnErr(...); the harness flags those asSkipped, not panics.parity-runCLI:cargo run -p headroom-parity -- run [--only TRANSFORM].- Unit tests in
crates/headroom-parity/src/lib.rsinclude a negative test (harness_reports_diff_for_divergent_comparator) proving the harness detects mismatched output before any real port lands.
Recording fresh fixtures
source .venv/bin/activate # the main Python SDK venv
python scripts/record_fixtures.py # uses tests/parity/recorder.py
ls tests/parity/fixtures/*/ | sort | uniq -c
The recorder monkey-patches the in-process transform classes (see
record_all() in tests/parity/recorder.py). It does not modify any
file under headroom/.
Known regressions in retired-Python components
The Stage 3b/3c.1b retirements deleted Python source for DiffCompressor
and SmartCrusher and replaced them with PyO3-delegating shims. The
2026-04-28 audit found that the retirements shipped with subsystems
silently disconnected. This section tracks each gap and its disposition
so they don't regress further or get forgotten.
SmartCrusher
| Subsystem | State | Tracked by |
|---|---|---|
| TOIN learning loop | Re-attached 2026-04-28. Shim's crush() and _smart_crush_content() now call toin.record_compression() after a real compression. Filtered on strategy != "passthrough" to ignore JSON re-canonicalization. Best-effort: TOIN failures are logged at debug level and don't break compression. |
tests/test_smart_crusher_toin_attachment.py |
| CCR marker emission knob | Honored end-to-end 2026-04-29. New enable_ccr_marker: bool field on Rust SmartCrusherConfig; crush_array checks it before emitting the <<ccr:HASH>> marker text and the CCR store write. Python shim flips it from ccr_config.enabled and ccr_config.inject_retrieval_marker — both flags collapse to the same Rust gate, since storing payloads under either off-switch makes no sense. Scope: gates only the row-drop sentinel path; Stage-3c.2 opaque-string CCR substitutions still emit always (no Python equivalent, no production caller asks for suppression). |
tests/test_smart_crusher_toin_attachment.py + crates/headroom-core/.../crusher.rs::tests::enable_ccr_marker_* |
| Custom relevance scorer | Closed (fail-loud) 2026-04-29. relevance_config and scorer constructor args remain in the signature for source compat, but the shim raises NotImplementedError when either is non-None — silently dropping a user-supplied scorer is a textbook silent-fallback bug. Full plumbing waits on Stage-3c.2's relevance-crate Python bridge. |
tests/test_smart_crusher_toin_attachment.py::test_custom_*_arg_raises_not_implemented |
| Per-tool TOIN learning hook | Re-attached partially. _smart_crush_content accepts tool_name and now threads it into the TOIN record. The hook is best-effort — it improves query_context aggregation but doesn't drive per-tool overrides yet. |
tests/test_smart_crusher_toin_attachment.py::test_smart_crush_content_records_to_toin |
DiffCompressor
| Subsystem | State |
|---|---|
| Adaptive context windows | Honored byte-for-byte (parity fixture-locked). |
| TOIN integration | Never had one — DiffCompressor records via _record_to_toin in ContentRouter, which already runs for non-SmartCrusher strategies. No regression. |
Phase 3e.1 — signals/ trait module + KeywordDetector (2026-04-29)
The Python error_detection.py regex registry was retired and reborn as a
trait + tier system in crates/headroom-core/src/signals/. See
signals/README.md for the full architecture; the highlights:
- Per-granularity traits.
LineImportanceDetectorships today; futureContentTypeDetectorandItemImportanceDetector<I>will follow as their consumers get touched. Tiered<T>combinator. Composition, not inheritance. Future ML detectors slot in as new tiers without changes toKeywordDetectoror any caller.- One concrete impl.
KeywordDetector(aho-corasick) is the only tier registered today. No NoOp/stub impls — per project no-silent-fallbacks rule, future tiers land with their real implementations. - Bug fixes baked in.
ERROR_KEYWORDSregex now includestimeout|abort|denied|rejected(previously drifted from the keyword set);tokendropped fromSECURITY_KEYWORDS(false-positived on every LLM metric reference). Both fixed in the Python regex too via the shim that recompiles patterns from the Rust-exposed keyword tables. - Companion canonical extension path.
signals/README.mddocuments the BGE classifier head — a 384-dim → 4-class softmax on top of the already-loadedbge-small-en-v1.5embedder — as the natural ML tier. Two alternatives kept open: distilled tinyBERT in ONNX, logistic regression on lexical features.
Phase 3g (queued) — Compression Pipeline Formalization (issue #315)
Strategic decision 2026-04-29: after Phase 3e (compressor ports) and
Phase 3f (Rust MCP scaffold) wrap, formalize the lossless-then-lossy-
then-CCR ordering as a cross-cutting CompressionPipeline orchestrator
LosslessTransform/LossyTransformtraits incrates/headroom-core/src/pipeline/. Existing compressors get refactored as compositions of pluggable transforms. The crucial design choice — parsers for structure, models at the prose/structure boundary — is captured in issue #315 andmemory/project_lossless_first_pipeline.md. Do NOT start coding before 3e/3f finish.
Watch list (potential regressions, not yet audited)
CCRConfig.enabled=Falseend-to-end — closed 2026-04-29. Bothenabled=Falseandinject_retrieval_marker=Falsecollapse to the same Rustenable_ccr_marker=Falsegate (no marker, no store write). See the SmartCrusher table above.SmartCrusherConfig.use_feedback_hints=False— config field is forwarded to Rust but its honoring inside the Rust crusher hasn't been verified against a parity fixture for the disabled path.
When any item above changes, update both this section and the test file. The shim's docstring also references this section — keep them aligned.
Phase 0 Blockers
These are known limitations for Phase 0. They are tracked here so Phase 1 doesn't rediscover them.
cache_alignerfixtures:CacheAligner.apply()takes(messages, tokenizer, **kwargs)— aTokenizeris provider-specific and its cheapestNoopTokenCounter/TiktokenTokenCounterconstruction still requires pullingheadroom.providers.*which imports the full observability stack (opentelemetry, etc). The recorder recordscache_aligneronly if a usable tokenizer is cheaply available; otherwise it logs a blocker and skips. Seerecorder.py::_build_cache_aligner_tokenizer.ccris not a single class: The repo hasCCRToolInjector,CCRResponseHandler,CCRToolCall,CCRToolResultetc. rather than a singleCCRclass. The recorder targets the encoder-style entry point most analogous to the Rust port (CCRToolInjector.inject_toolandCCRResponseHandler.parse_response). If Phase 1 wants a different split it should updaterecorder.py::record_allaccordingly.- Pre-commit hook noise:
scripts/sync-plugin-versions.pymutates.claude-plugin/marketplace.json,.github/plugin/marketplace.json, andplugins/headroom-agent-hooks/**/plugin.jsonon every commit. Those changes are harmless but each commit in Phase 0 picks them up. Phase 1 does not need to do anything special — just let the hook run. rust-toolchain.tomlpinschannel = "stable"rather than a specific version so CI picks up the same toolchain the local box uses. Tighten to a pinned version (e.g.1.78) once the port stabilizes.