mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 11:31:17 +08:00
feat/https-compose-caddy
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 ( |
||
|
|
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> |
||
|
|
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>
|
||
|
|
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> |
||
|
|
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).
|