Commit Graph
5 Commits
Author SHA1 Message Date
3aafdf2dcc fix(router): keep source code out of the prose (Kompress) fallbacks (#4787)
## Description

When the code compressor declined a block of source code, the router
passed the block to Kompress. Kompress is a prose model. It drops
low-salience words, and in code those words are keywords such as `for`,
`in`, `if` and `import`. The result no longer parses. #4214 shows a
fenced Python script that comes back with `for` and `in` removed.

This PR stops that in the Python router and in the Rust live-zone
dispatcher. When the code compressor declines, the code is forwarded
unchanged.

Closes #4214

Credit: the Python change is oxura's work from
https://github.com/oxura/headroom/tree/fix/fenced-code-routing-4214-20261018
(277ca1f). Their commit is the first commit here, rebased onto `main`,
and oxura is its author. The test, docs and Rust commits were added on
top. oxura asked us to open this PR from our fork
([comment](https://github.com/headroomlabs-ai/headroom/issues/4214#issuecomment-6797572655)),
and said they have not run this branch, so the model and native results
below are ours, not theirs.

## Behaviour change to review

With `enable_code_aware=False` (the default), source code now stays
unchanged. Before this PR, it was sent to Kompress and lost keywords.
With `enable_code_aware=True`, code that the code compressor declines
also stays unchanged. Before, Kompress ran on it.
A code block the code compressor does compress is unaffected. Prose,
logs, JSON and tables are unaffected.

Side effect: a code block that Kompress used to shrink (and break) now
keeps its full size. This is the intended trade, but it means fewer
tokens saved on code when `enable_code_aware=False`.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] Documentation update
- [ ] New feature
- [ ] Breaking change (the default-config behaviour change above is
intended, and it only stops damage to code)

## Changes Made

Five commits:

- `596764c3` `fix(router): keep source code out of prose fallbacks`.
Author: oxura. Removes the CODE_AWARE to Kompress fallbacks in
`headroom/transforms/content_router.py`. This is 277ca1f rebased onto
`main`, and it differs from 277ca1f in two ways only: the two test-file
conflicts are resolved, and its `wiki/proxy.md` hunk is dropped, because
`AGENTS.md` says not to add content under `wiki/`.
- `7705a4e6` `test(router): repin the code-to-Kompress tests and add the
#4214 fence regression`. Author: Tao Hansen, with a `Co-authored-by:
oxura` trailer. Five tests asserted the old fallback. They are rewritten
to assert the new behaviour (code unchanged, Kompress never sees it)
instead of being deleted. Adds a regression test for the script from
#4214, with `enable_code_aware` both off and on. Updates
`docs/content/docs/code-compression.mdx` and
`docs/content/docs/how-compression-works.mdx`, which said that detected
code goes to Kompress.
- `6631668a` `fix(live-zone): leave source code unchanged when the code
compressor declines`. Author: Tao Hansen. Same fix in
`crates/headroom-core/src/transforms/live_zone.rs`: a declined
`SourceCode` block is now a NoOp, not a Kompress input. Tests:
`tests/live_zone_source_code_decline.rs` (single test, needs no model),
and new cases in `tests/live_zone_dispatch.rs`.
- `d8776283` `fix(router): turn off the code compressor's internal
Kompress fallback`. Author: Tao Hansen. Follows review: the router's
code compressor was still built with
`fallback_to_kompress=self.config.enable_kompress` (#4719), so unknown
languages, Perl and AST failures could build a `KompressCompressor`
inside `CodeAwareCompressor`. The router now always sets
`fallback_to_kompress=False`. The #4719 test that pinned `True`
(`test_enabled_kompress_keeps_code_aware_fallback`) is repinned as
`test_enabled_kompress_still_turns_off_code_aware_fallback`, and the
unknown-language, Perl (by language hint, since `detect_language()`
reports Perl-dominant code as unknown) and AST-failure paths are tested
with spies on `is_kompress_available` and `KompressCompressor`, with
`enable_kompress` both off and on.
`docs/content/docs/code-compression.mdx` notes that the router always
turns the option off.
- `c1f8464e` `fix(router): keep passthrough code from external
compressors and stale caches`. Author: Tao Hansen. Follows review:
`_try_external_compressor` skips `PASSTHROUGH` blocks (code with
`prefer_code_aware_for_code=False`, whole or as a mixed section), which
would otherwise be offered to a prose-only external compressor as
`text/plain`. The disk cache namespace now also hashes
`_ROUTING_POLICY_REVISION`, so a same-version restart does not replay
code that Kompress damaged before this change. Tests: two
external-dispatch cases with a `text/plain` external, and one namespace
test. All three fail on the previous head.

I did not touch `CHANGELOG.md`.

## Testing

- [x] Unit tests pass (`pytest`): see below, the failures are
environment failures that also fail on `main`
- [x] Linting passes (`ruff check .`, `ruff format --check .`)
- [x] Type checking passes (`mypy
headroom/transforms/content_router.py`)
- [x] New tests added for new behaviour
- [x] Manual testing performed (real model replay, below)

### Test Output

macOS, Python 3.14. Head is now `c1f8464e`.

```text
After the second review fix (c1f8464e): router, code-aware, code-compressor, cache, external-dispatch and compressor-selection tests (107 files): 2106 passed, 13 skipped. ruff clean.
After the rebase onto main c05fbddd and the review fix (d8776283):
  router, code-aware and code-compressor tests (37 files): 743 passed, 2 skipped
  tests/test_code_aware_kompress_fallback.py: 8 passed; with the router change reverted, 4 fail
    (the enable_kompress=True cases: config pin, unknown language, Perl, AST failure)
  ruff check / ruff format --check headroom tests: clean
  cargo test -p headroom-core: 1151 passed, 0 failed
Earlier run on 9df60c7c (before the rebase):
router tests (28 files incl. both changed files): 557 passed, 2 skipped, 1 failed:
  test_content_router_ml_stage_deadline.py::test_non_ml_prework_does_not_consume_the_ml_budget,
  a timing test the branch does not touch; it passes 3 of 3 times when rerun alone
ruff check .:           All checks passed!
ruff format --check headroom tests: 1714 files already formatted
mypy headroom/transforms/content_router.py: Success: no issues found in 1 source file
cargo test -p headroom-core:   22 test binaries, 1151 passed, 0 failed
cargo fmt --check / cargo clippy -p headroom-core --tests -D warnings: clean
pytest tests (full):     31 failed, 19208 passed, 513 skipped
```

Rust bug-fix tests, fail before and pass after (the router-test commit's
source with the new Rust tests, then the live-zone commit; measured
before the rebase as `9df60c7c`, and the Rust code is unchanged since):

```text
before: declined_source_code_never_starts_kompress ... FAILED (Kompress init ran once, expected 0; rerun on 7705a4e6)
        source_code_declined_by_code_compressor_is_never_kompressed ... FAILED (model loaded: Go source was Kompressed)
after:  all 11 live_zone_dispatch tests ok; live_zone_source_code_decline ok
```

The dispatch fail-before was measured on the earlier, code-identical
branch (only documentation files differ). The dispatch test only fails
before the fix when the Kompress model is loaded (`HF_HOME` with the
model, `ORT_DYLIB_PATH` set). The single-test binary fails before the
fix on any host.

Python regression: with the new tests run against `origin/main`'s router
(no fix), 9 test cases fail (the #4214 fence test in both configs, the
repinned tests, and the fenced-code keyword test). With the fix they
pass.

### Failures in the full `pytest tests` run

The full run on the branch had 31 failures, none in router or
compression code. I compared them with pristine `origin/main`
(200c838c):

- 11 `tests/test_proxy_uds.py` tests fail on `main` too. The socket path
is too long under this checkout directory (`OSError`). They fail the
same way in isolation on `main`.
- 17 other failures are in `test_proxy_health.py`,
`test_read_maturation_handler_nobust.py`, `test_stateless_no_disk.py`,
`test_memory_bridge.py`, `test_cli/*`, `test_image_compression*.py`,
`test_offline_egress_chokepoint.py` and `test_proxy_scalability.py`. A
full run on `main` fails 29 tests, and the set differs from run to run
(the two sets overlap by 17 of 31). I re-ran the 14 failures that were
not in the `main` list in isolation on the branch: 12 pass, the other 2
are the UDS tests above.
- Known flaky test:
`tests/test_content_router_ml_stage_deadline.py::test_saturated_remote_calls_fail_open_without_queueing_their_payloads`
failed once in a loaded run and passes on rerun. File repeated 3 times
on `596764c3` and on `origin/main`: 16 passed each time. It is timing
based and not caused by this change. It passed in the 558-test router
run above.

## Real Behavior Proof

- Environment: macOS arm64, Python 3.14 in the checkout's own `.venv`,
real `kompress-v2-base` int8 ONNX model from an offline copy of the
public HF cache (`HF_HOME`, `HF_HUB_OFFLINE=1`), Rust `ort` via the
venv's onnxruntime.
- Fence: a 1324-character valid Python script. The issue quotes only
four of its lines, so the rest is a reconstruction in the same style,
not the reporter's bytes.
- Exact command / steps: `ContentRouter.compress` on the fence followed
by about 40 lines of prose, for four configs (default;
`enable_code_aware=True`; `prefer_code_aware_for_code=False`;
`enable_code_aware=True` with lossless-then-lossy). Also
`headroom.compress` on a full Anthropic message list with the fence in a
`tool_result`.
- Observed result: Before (v0.44.0): in the default and code-aware
configs the fence comes back as 1144 characters and does not parse
(`import json, collections` becomes `json, collections`; `[s for s in
...]` becomes `[s s in ...]`). After (`9df60c7c`): in all four configs
and in `headroom.compress`, the fence is byte-identical, 1324
characters, and parses. Prose control: the same router on prose still
compresses. A prose-only block went from 5709 to 5357 characters
(strategy TEXT). A prose / fence / prose block went from 12760 to 12056
characters (strategy MIXED), and the fence in it is byte-identical and
parses.
- Not tested: the reporter's exact 1324-character fence (only four lines
are public, so the tests use the reconstructed fence described above);
the Rust live-zone path end to end through the proxy with a real request
(covered by `cargo test` only); platforms other than macOS; the full
proxy on a live deployment.

## Other places where code can still reach a prose model

I checked every path from code to a prose or ML compressor, in Python
and Rust.

| Path | State |
| --- | --- |
| Python `CODE_AWARE` branch, code compressor declines or is disabled |
Fixed here: the block stays unchanged |
| Python post-strategy fallback after "no savings" (`content_router.py`,
`fallback_eligible_strategy`) | Never applied to `CODE_AWARE`. It only
applies to `SMART_CRUSHER` and `CONFIG` (JSON and config files), so
unchanged |
| Python lossless-then-lossy (opt-in) after the lossless fold |
`CODE_AWARE`, `DIFF` and `PASSTHROUGH` are excluded, so unchanged |
| Python lossless-then-lossy layer for `SEARCH`, `LOG`, `HTML` (opt-in)
| Prose-like output, not code. Unchanged |
| Python relevance split for `LOG` and `SEARCH` | Not code. Unchanged |
| Python mixed content with fenced code (`_compress_mixed`) | Each fence
goes through the `CODE_AWARE` branch, so it is fixed by this change.
Covered by the new fence tests |
| Python `prefer_code_aware_for_code=False` | Already PASSTHROUGH before
this PR |
| Python `_experimental_compress_read`
(`HEADROOM_EXPERIMENTAL_READ_KEEP_RATIO`) | Deliberate opt-in experiment
that runs Kompress on file reads, which can be code. Off by default.
Left as is |
| Python size gate and deadline fallbacks in `_try_ml_compressor` | Run
only after a caller chose Kompress, so code no longer reaches them |
| Python `CodeAwareCompressor` internal fallback
(`fallback_to_kompress`: unknown language, Perl, no tree-sitter, AST
failure) | Fixed in commit 4: the router always builds it with
`fallback_to_kompress=False`. Covered by Kompress-spy tests |
| Python external compressor dispatch for `PASSTHROUGH` code | Fixed in
commit 5: never offered to an external compressor |
| Disk result cache made before this change | Fixed in commit 5: a new
namespace through `_ROUTING_POLICY_REVISION` |
| Rust `live_zone.rs` `SourceCode` arm | Fixed here (commit 3) |
| Rust `live_zone.rs` `PlainText` arm to Kompress | Only plain text. It
is the single remaining call to `kompress_or_noop` |
| Rust: prose text with an embedded fenced code block | **Not
reproduced.** I built synthetic tool results of prose around the fenced
Python script, at 6 KB, 20 KB and 71 KB. On this branch the dispatcher
classified each one as `source_code`, so commit 3 leaves it unchanged,
and Kompress was never consulted (`kompress_init_runs() == 0`). Rust has
no fence-aware splitting, but I found no input where that sends code to
Kompress, so this PR files no follow-up. |
| Python `config_compressor.py` docstring says YAML/TOML/INI "fall
through to the lossy prose path" | Documentation only: a stale comment,
not a code path. Config content has its own `CONFIG` strategy. Can be
refreshed in a later change |

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: n/a.
- Stable/default behavior changed: yes, in the default config code is no
longer sent to Kompress (see "Behaviour change to review"). Tokens saved
on code drop in return for code that stays valid.
- Kill switch / disable path: none added. Revert the PR to restore the
old fallback.
- Unsafe override required: no.
- Qualification impact: none expected. Compression of code by the code
compressor is unchanged.
- Rollback path: revert the three commits. No data, schema or config
migration.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines (`ruff`, `cargo
fmt`, `clippy` clean)
- [x] I have made corresponding changes to the documentation
(`docs/content/docs/code-compression.mdx`,
`docs/content/docs/how-compression-works.mdx`)
- [x] I have added tests that prove my fix is effective
- [x] I did **not** edit `CHANGELOG.md`
- [ ] New and existing unit tests pass locally: the only failures are
environment failures that also fail on `main`, listed above

## Additional Notes

- Rust has no fence-aware splitting like the Python router has. A
synthetic prose-plus-fence repro did not reach Kompress (see the table
above), so no follow-up issue is filed.
- One stale comment remains in `content_router.py`
(`_try_ml_compressor`, the Phase 0 size-gate note lists
`CODE_AWARE->KOMPRESS` as an entry point). It is comment-only; not
changed here to keep the review commits as they are. Say if you want it
fixed in this PR.
- Reviewers: the Python change is easiest to review commit by commit.
Commit 1 is oxura's change, and commits 2 and 3 are the tests, docs and
the Rust fix.

---------

Co-authored-by: oxura <grozafroza44@gmail.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-16 23:25:06 -06:00
Mansurshakh JaparovandJerrettDavis 93279f3208 fix(smart-crusher): preserve unchanged JSON bytes (#4044)
## Description

Closes #3697.

An unchanged SmartCrusher result now keeps the original bytes and
reports no structural compression. Formatting-only savings come from the
existing Rust JsonMinifier, not from pretending the JSON value changed.

The minifier preserves duplicate keys, order, escapes and number
literals. A mixed result cannot use one section's CCR marker to hide
unmarked loss in another.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] Documentation update

## Changes Made

- Keep SmartCrusher's exact-byte no-op behavior; route actual whitespace
savings through JsonMinifier in Python and the eligible native live
zone.
- Keep all records and JSON literals; do not store originals or inject
CCR markers for lossless minification.
- Preserve mixed routing and reject uncovered lossy sections in both
tool-result formats. Explicit no-CCR behavior is unchanged.
- Replace incidental forwarding tests with native minification and
complete-record regressions; document the distinction.

## Testing

- [ ] Entire Python suite — not claimed.
- [x] Four consumer/native modules: `python -m pytest -q
tests/test_recursive_json.py tests/test_transforms_content_router.py
tests/test_transforms/test_smart_crusher_rust_parity.py
tests/test_transforms/test_smart_crusher_lossless_default.py`
- [x] Changed-file Ruff checks; normal commit hooks, including mypy and
commitlint.
- [x] Manual public-API runs, with and without the HTML extra.

### Test Output

Consumer/native modules:

```text
collected 136 items
============================= 136 passed in 36.43s =============================
```

Normal pre-push (fmt, clippy, 1,668 Rust tests with 3 ignored, native
build, Python checks, commitlint):

```text
======================== 180 passed, 1 warning in 8.35s ========================
✅ ci-precheck PASSED — safe to push.
To https://github.com/oxura/headroom.git
   64688217..0002af3e  HEAD -> fix/3697-unchanged-json-passthrough
```

The first push stopped on an inherited commit footer because
`origin/main` was stale. Fetching the actual upstream ref fixed the lint
range; the normal push then passed. No source merge, lint-rule change or
hook bypass.

Hosted checks on `0002af3e` now pass: all four Python shards, Windows
permissions, smoke tests, native wrappers, parity and Docker e2e.
[Checks](https://github.com/headroomlabs-ai/headroom/pull/4044/checks).

## Real Behavior Proof

- Environment: Linux x86-64, Python 3.13.14, Rust 1.95 and the actual
extension built from this checkout. No provider billing calls.
- Exact command / steps: the earlier localhost `/v1/compress` and
TransformPipeline runs exercised the original fix. For this follow-up,
call `ContentRouter.compress` on a data-only HTML page containing 60
complete records, with `smart_crusher_lossless_only=True`,
`smart_crusher_with_compaction=False`, and `enable_kompress=False`. Run
it once without trafilatura, then with the locked 2.0.0 extra. The new
public-API test contains the full input/config. Separately call
`route_embedded_json` on a compact array followed by a padded array,
with Unicode and CRLF surroundings.
- Observed result: both HTML modes keep all 60 records and the
surrounding markup, with no unrecoverable section. The unchanged first
JSON span does not stop the second span's compaction; surrounding text
stays exact. Final Codecov is 96%; the two remaining lines are the
deferred HTML fallback return. The real no-HTML-extra API run executed
both, and local coverage also exercises the unchanged-span branch.
- Not tested: live provider acceptance, invoices or production cache hit
rates. No native eligibility or admission gates changed.

## Runtime Rollout Safety

- Rollout-managed feature(s): none; existing JSON routing.
- Minimum rollout channel: unchanged.
- Stable/default behavior changed: eligible formatting savings return as
json_minifier; standalone SmartCrusher remains byte-exact on no-ops.
- Kill switch / disable path: existing routing configuration and
HEADROOM_LIVE_ZONE_DISABLE_ARMS.
- Unsafe override required: no.
- Qualification impact: no-op, formatting, structural and CCR paths
exercised separately.
- Rollback path: revert the minifier integration; no persistence
migration.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have made corresponding changes to the documentation
- [x] I did not edit CHANGELOG.md — release-please owns it

## Additional Notes

Addresses the [minifier
review](https://github.com/headroomlabs-ai/headroom/pull/4044#issuecomment-6157583285).
The maintainer’s main merge is retained. The latest follow-up only
changes consumer tests.

AI-assisted; no subagents.

---------

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
2026-11-03 21:32:42 -06:00
Tejas ChopraandClaude Opus 5.5 185454be49 feat(ccr): Redis backend, one CCR store for every replica (#4368)
## Why
A `<<ccr:hash>>` marker points at an original kept by the replica that
compressed it. Behind a gateway that spreads requests across replicas,
the retrieval can land on a replica that doesn't have it. Kong's AI
Gateway runs several Headroom instances without sticky sessions. The
`headroom.ccr_backend` entry point allowed a Redis store, but none
shipped.

## Change
- **Backend:** `HEADROOM_CCR_BACKEND=redis` + `HEADROOM_REDIS_URL`
(`headroom/cache/backends/redis.py`). One key per entry
(`<prefix>:ccr:<hash>`), stored as JSON and expiring with the entry's
TTL. A plugin registered as `redis` still takes precedence.
- **Connection helper** `headroom/cache/redis_client.py`, shared with
the follow-up sessions PR:
  - checks the URL scheme;
  - 1 s timeouts;
- `HEADROOM_REDIS_KEY_PREFIX` (default `headroom`; glob-escaped in SCAN
patterns);
- warns on plain `redis://` to a remote host, since Redis holds tool
output verbatim.
- Its `Guard` makes any Redis error a miss and logs when each kind of
call starts and stops failing. It skips Redis for 5 s after a connection
error, so an outage never fails or stalls a request.
- **`CompressionStore`** keeps no per-process cap or eviction/expiration
index for a backend that expires entries itself (`expires_entries`).
Counting the store would SCAN the shared keyspace on every write,
rebuilding the index would read every replica's entries under the store
lock, and a per-replica cap would evict other replicas' live entries.
- Optional extra: `[redis]`.

## Tests
`tests/test_ccr_redis_backend.py`:
- a marker stored by one replica is retrieved on another;
- Redis TTL matches the entry's TTL;
- key prefixes isolate deployments, including glob characters in a
prefix;
- Redis down is a miss;
- a corrupt entry is a miss;
- env selection, and fallback on a bad URL;
- back-off after a connection error;
- no SCAN and no index growth on new stores, 300 re-stores and
retrievals;
- a Redis that reads but refuses writes logs once.

1317 CCR, store and retrieve tests pass. ruff and mypy are clean.

**Real run:** 3 proxy processes shared one Redis-protocol server
(fakeredis TCP server; no Redis on the test machine). A marker returned
by one replica resolved via `GET /v1/retrieve/{hash}` on all three.

Docs (configuration page, security model) follow in the docs PR.

## Real Behavior Proof
- **Environment:** macOS 26.7.1 (arm64), Python 3.12.13, redis-py 8.1.0.
Redis is a fakeredis 2.40.0 `TcpFakeServer`, which speaks the Redis
protocol over TCP; no Redis server was on the test machine. Docker was
not available.
- **Configuration:** every replica has
`HEADROOM_COMPRESS_SESSION_STORE=redis://127.0.0.1:6391/0` (the CCR
store follows it) and its own `HEADROOM_WORKSPACE_DIR`.
- **Steps:**
  1. Start the fake server:
`python -c "from fakeredis import TcpFakeServer;
TcpFakeServer(('127.0.0.1', 6391),
server_type='redis').serve_forever()"`
  2. Start three proxies, one each on ports 8901, 8902 and 8903:
`HEADROOM_COMPRESS_SESSION_STORE=redis://127.0.0.1:6391/0
HEADROOM_WORKSPACE_DIR=<own dir> python -m headroom.cli proxy --port
<port>`
3. Drive one session for 20 turns, round-robin across the three: `POST
/v1/compress` with `{"messages": …, "session_id": "kong-e2e", "mode":
"ccr"}`. The transcript is the 25 KB tool history from
`tests/test_compress_session_mode.py`. Every third turn adds a 120-row
grep result; the other turns add a user line.
  4. After each turn, check:
- the returned messages start with the previous turn's returned
messages, byte for byte;
     - how many bytes the turn wrote to the `:msgs` hash.
5. Fetch each `<<ccr:hash>>` marker via `GET /v1/retrieve/{hash}` on all
three proxies.
- **Result** (after the review fixes, at 95b2d93a):
  - every turn's prefix is byte-identical to the previous turn's;
- Redis received 378 KB in total (63 KB at most in one turn), against
about 4.9 MB if the whole transcript were rewritten each turn;
  - the CCR marker resolved on all three replicas.
- **Not tested:**
- a real Redis or Redis Cluster (the Lua script and hash-tagged keys are
written for it);
  - TLS (`rediss://`) and AUTH;
  - Kong's AI Gateway in front of the replicas;
  - Windows;
  - real `maxmemory` eviction (simulated in tests by deleting keys);
  - sustained load.

## Dependencies
- **`redis` (redis-py, `>=5.0`)**, in a new optional extra `[redis]`. It
is the Redis project's own Python client (maintained by Redis Inc.),
MIT-licensed and pure Python. Only deployments that set a Redis URL
install it; the default install and the other extras are unchanged. The
5.0 floor gives `register_script`/`scan_iter`/`from_url` with socket
timeouts as used here.
- **`fakeredis` (dev only, `>=2.20.0`)** runs the tests against an
in-process Redis without a server. 2.20 is the first release whose
`TcpFakeServer` and pipeline behaviour the tests rely on.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4368"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 23:48:33 -07:00
Mansurshakh JaparovandJD Davis a42fb2b9a1 fix(router): preserve human-readable Git status losslessly (#4020)
## Description

Addresses the still-reproducible Git status corruption in #3652. The
aligned `ls`/`ps`/`df` portions are already protected in current main;
this PR does not claim them as new fixes. Human-readable Git status is
still classified as prose and can lose staged/unstaged/untracked paths
through Kompress.

This is a narrow content-preservation bug fix, not the separate policy
proposal to exclude all `Bash` outputs by default.

## Type of Change

- [x] Bug fix
- [x] Documentation update

## Changes Made

- Recognize the standard English branch/detached-HEAD header plus Git
status sections/entries as structured tabular content.
- Preserve this non-rectangular `git_status` format verbatim instead of
forcing it into CSV or a prose model.
- Keep Python detection and the native Rust content/live-zone route
aligned; Rust detection uses iterator-based scans without
collection/cloning of the input.
- Leave ordinary prose, bullet lists, and other Bash output on their
existing routes.
- Guard Git status before native model classification and before
external CSV/wildcard compressor dispatch; retain the locked native
Magika production chain.
- Replace the stale `PLAIN_TEXT` status expectation with
`format=git_status` and `parse_tabular(status) is None`; keep
prose/git-log negative cases.
- Document the English-format scope and lossless/no-savings tradeoff.

## Testing

- [x] Unit tests pass (`pytest`), including the consumer-visible
lossless regression.
- [x] Native regression tests, changed-file lint, configured pre-commit
mypy and manual production runtime checks pass.

### Test Output

```text
Review correction:
Python router/external-dispatch regressions: 121 passed, 2 skipped
Existing tabular parser/detection suite: 73 passed in 7.76s
Native Git-status regressions: 3 passed
Final mixed-content correction (router, external dispatch, tabular suites):
184 passed, 2 skipped in 52.14s
```

The mandatory pre-push `make ci-precheck` passed: workspace Rust
fmt/clippy/tests, native extension build/import verification, the
complete configured Python gate, and Commitlint. The native gate used
the explicitly installed CPU `libonnxruntime.so.1.26.0` via
`ORT_DYLIB_PATH`, with cached-model assertions enabled.

```text
[build_rust_extension] headroom._core build + install + verify: OK
================== 177 passed, 4 skipped, 1 warning in 27.72s ==================
✅ ci-precheck PASSED — safe to push.
```

```sh
python -m pytest -q tests/test_transforms_content_router.py
cargo test -p headroom-core git_status
cargo test -p headroom-core ordinary_bullet
```

Python content-router suite: **84 passed, 2 skipped**, with an existing
Hugging Face deprecation warning. Native focused regressions: **2 Git
status tests passed**, **1 ordinary-bullet negative passed**. The native
extension was rebuilt and the build/import verification passed. The
final deterministic consumer regression uses a ready lossy prose
compressor so a cold model cannot accidentally mask missing protection;
it asserts direct and tool-result output bytes, not internal call
counts.

The deterministic regression fails against the unchanged baseline with
missing status rows. After rebasing onto current main
`1ad92f0cbc3dea27676e253588100f64a2af6994`, ran the status regression
plus main's six small-MCP result tests: **7 passed**, and reran the
native Git status cases: **2 passed**.

Changed-file Ruff and formatting passed. The installed pre-commit hooks,
including `mypy headroom` and Commitlint, passed for this commit.
Full-tree Ruff is locally blocked by executable filesystem permissions
on five unchanged OAuth2 plugin files (tracked 100644); they are not
modified. A separate full dev-environment mypy run found an unchanged
optional LangChain `truthy-function` error; the configured isolated
pre-commit environment passed. No unrelated source/permissions were
changed.

## Real Behavior Proof

- Environment: Linux x86_64, CPython 3.13.14; unchanged
`dea9092e19385f286b7f67a64f4d85de2708d756` and this branch; actual Git
fixture, real content router and Anthropic token counter, rebuilt Rust
extension, **real ONNX Kompress fully preloaded before each run**, no
mocked compression backend in this smoke.
- Exact command / steps: initialize a throwaway Git repo; commit 120
files named `modified path NNN α.txt`; modify those, stage 120 new files
named `staged path NNN β.txt`, and add 120 untracked files named
`untracked path NNN γ.txt`. Capture:
  ```sh
LC_ALL=C git -c core.quotePath=false -c color.status=false status
--branch
  ```
Load the actual model with
`KompressCompressor().preload(allow_download=True)`, run
`ContentRouter(ContentRouterConfig()).compress(status)`, then run the
same router's `apply` on an Anthropic `Bash` tool-use/tool-result pair
using
`AnthropicProvider(warn=False).get_token_counter('claude-sonnet-4-5')`
and model limit 200000. Compare output bytes to the same captured
status.
- Same input in both runs: **12,469 bytes**, SHA256
`78ed6a39f2f994159099f8d4c0fe052ca09a37fa6d9f6248e8c5ebb655b19a32`.
- Before: detected as `text`; direct and Bash tool-result routes both
returned **10,748 bytes**, neither byte-exact; transform
`router:tool_result:text`.
- Observed result: after the fix, detected as `tabular`; both routes
returned **12,469 bytes**, both byte-exact; `router:noop`.
- External-compressor review proof against published head `3b035027`: a
real Git repository with 120 untracked paths produced the same
**3,415-byte** input (SHA256
`e0164d25f3f47428686d102a73018d0e00bcda53ff9674e658aa7128c038896b`).
With an operational row-trimming plugin selected for `text/csv` and
`*/*`, direct and tool-output paths both shrank to **318 bytes** before;
both preserve all **3,415 bytes** after. The same plugin still
compresses ordinary CSV. This separate plugin smoke uses the production
Tiktoken counter and disables Kompress to isolate external dispatch.
- Final mixed-content review: on published `539669c6`, appended JSON
selected `MIXED` and changed both direct and Bash tool-result bytes; the
fenced-code example was already preserved. The strategy selector now
honors `git_status` before mixed splitting. Both appended JSON and
fenced code preserve the complete payload on both routes with a ready
lossy compressor available.
- Not tested: localized Git status formats, every platform-specific Git
variant, or a paid upstream model response. The recognizer deliberately
covers standard English status output. The local real compression path
was exercised after model warmup; the initial cold-model no-op was not
treated as proof.

## Runtime Rollout Safety

- Rollout-managed feature(s): none; content-routing data-preservation
fix.
- Minimum rollout channel: stable; no rollout-managed feature is
enabled.
- Stable/default behavior changed: recognized Git status is no longer
compressed lossily, sacrificing savings for path/state integrity.
- Kill switch / disable path: existing global Bash exclusion can bypass
compression; no new flag.
- Unsafe override required: no.
- Qualification impact: Python/Rust route parity for the recognized
status format only.
- Rollback path: revert this commit; no persistent schema migration.
Global Bash exclusions remain unchanged.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] Existing tabular lossless route reused; compression docs updated.
- [x] Consumer regression and native positive/negative tests added.
- [x] `CHANGELOG.md` not edited; Conventional Commit title supplied.

This PR completes the remaining Git status defect, but intentionally
does not close #3652's separate Bash-default policy request. Remote CI
is reported by GitHub, not assumed from local tests.

---------

Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-10-07 17:46:57 -05:00
Tejas Chopra e3c7964038 feat(proxy): route selected external compressors through the content router (#2388)
## What
Scope 3 of the pluggable-compressor system: a **selected external
`headroom.compressor` plugin now compresses real traffic**. Opt-in via
`--compressor` / `HEADROOM_COMPRESSORS` — external (non-built-in) names
flow to `ContentRouterConfig.active_external_compressors`, resolved once
against the registry in `__init__` (built-in inventory entries filtered
out).

## How
A single guarded branch at the top of `_apply_strategy_to_content`,
immediately before the built-in if/elif. When a selected external
compressor declares the block's detected content type (exact MIME,
`text/*`, or `*` wildcard), the block runs through the pure-data
`Compressor` contract; otherwise it falls through to the built-in path
unchanged.

## Cache safety (by construction)
The branch lives **inside the per-block strategy dispatch**, which only
runs on non-frozen, already-compressible blocks — the frozen/cached
prefix is split off upstream in `apply()`. So a selected external
compressor **can never rewrite cached-prefix content and bust the prompt
cache**; it inherits the exact same cache-preservation the built-ins
have.

## Fail-open + fidelity
Raise, malformed/non-`CompressOutput`, empty-from-non-empty, or
expansion all fall back to the built-in path. Tokens are counted with
the router's own estimator (never the compressor's self-report). Any
`recoverable` (hash→original) map is mirrored to the CCR store like
SmartCrusher, so `/v1/retrieve/{hash}` resolves. Reached only in
lossy/CCR mode (lossless-only sessions return earlier), so it can't
inject unrecoverable loss.

## Behavior change
**None by default.** With no external compressor selected, the branch is
a single cheap guard and everything below is byte-identical to today.

## Testing
`tests/test_router_external_dispatch.py` — end-to-end dispatch of a
selected external compressor, recoverable-map retrievability,
non-hex-hash skip, fail-open on raise/malformed/empty/expansion,
not-selected & non-matching-content-type leave the built-in path
unchanged, wildcard selection. Offline suite: 84 passed (this file +
selection + registry + settings_store). ruff + mypy clean.

Note: the broad content-router/compression suite exercises real HF-Hub
model downloads + local ONNX inference and is slow/flaky in some local
envs — deferred to CI.

Stacks on #2370/#2371/#2373 (all merged).
2026-07-18 10:02:10 -07:00