mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
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 mainc05fbdddand 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 on9df60c7c(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 on7705a4e6) 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>
This commit is contained in:
co-authored by
oxura
JerrettDavis
parent
cf3284675e
commit
3aafdf2dcc
@@ -865,10 +865,11 @@ impl CodeAwareCompressor {
|
||||
|
||||
// Unknown language → fallback (Kompress) or passthrough.
|
||||
if detected_lang == CodeLanguage::Unknown {
|
||||
// Kompress fallback is delegated to the live-zone dispatcher in
|
||||
// the Rust port (the engine doesn't own the model); fixtures are
|
||||
// recorded with fallback_to_kompress=False, so this is the
|
||||
// passthrough branch.
|
||||
// The Rust engine does not own the Kompress model, so this is
|
||||
// always the passthrough branch (fixtures are recorded with
|
||||
// fallback_to_kompress=False). The live-zone dispatcher leaves
|
||||
// the declined block unchanged too: code is never handed to the
|
||||
// prose model, which drops keywords (#4214).
|
||||
return CodeCompressionResult {
|
||||
language: CodeLanguage::Unknown,
|
||||
language_confidence: 0.0,
|
||||
|
||||
@@ -58,9 +58,9 @@
|
||||
//! per-content-type byte thresholds. The gate and the threshold
|
||||
//! plumbing already shipped; **this PR** completes the item by wiring
|
||||
//! the two remaining compressor arms — `SourceCode` →
|
||||
//! CodeAwareCompressor (falling back to cached Kompress when the
|
||||
//! compressor returns its input unchanged) and `PlainText` → cached
|
||||
//! Kompress — and by moving the `SourceCode` / `PlainText` thresholds
|
||||
//! CodeAwareCompressor (left unchanged when the compressor returns its
|
||||
//! input unchanged: code is never handed to the prose model, #4214) and
|
||||
//! `PlainText` → cached Kompress — and by moving the `SourceCode` / `PlainText` thresholds
|
||||
//! off their placeholder 512 to the specified 2048 / 5120. `Html`
|
||||
//! stays no-op.
|
||||
//! - **PR-B7** wires CCR retrieval-marker injection.
|
||||
@@ -133,10 +133,8 @@ const STRATEGY_SEARCH_COMPRESSOR: &str = "search_compressor";
|
||||
const STRATEGY_DIFF_COMPRESSOR: &str = "diff_compressor";
|
||||
/// Strategy tag emitted when CodeAwareCompressor rewrote a source-code block.
|
||||
const STRATEGY_CODE_COMPRESSOR: &str = "code_compressor";
|
||||
/// Strategy tag emitted when Kompress rewrote a plain-text block (also
|
||||
/// used by the SourceCode arm's passthrough fallback — see
|
||||
/// [`dispatch_compressor`]). Only the `ml` build has a Kompress arm to
|
||||
/// emit it.
|
||||
/// Strategy tag emitted when Kompress rewrote a plain-text block. Only
|
||||
/// the `ml` build has a Kompress arm to emit it.
|
||||
#[cfg(feature = "ml")]
|
||||
const STRATEGY_KOMPRESS: &str = "kompress";
|
||||
|
||||
@@ -704,14 +702,9 @@ fn kompress_cached() -> Option<&'static Kompress> {
|
||||
}
|
||||
|
||||
/// Route `text` through Kompress when the model is cache-resident;
|
||||
/// otherwise fall back to a deterministic no-op. Shared by the
|
||||
/// `PlainText` arm and the `SourceCode` arm's passthrough fallback.
|
||||
///
|
||||
/// Not a full port of the Python router's fallback chain: that one also
|
||||
/// re-runs Kompress when the code compressor returns *changed but not
|
||||
/// smaller* output, whereas this arm sends only an exact passthrough
|
||||
/// here and leaves the changed-but-not-smaller case to the
|
||||
/// tokenizer-rejection gate in `compress_one_block`.
|
||||
/// otherwise fall back to a deterministic no-op. Only the `PlainText`
|
||||
/// arm calls it: source code that the code compressor declines is
|
||||
/// deliberately not routed here (Kompress drops keywords from code).
|
||||
#[cfg(feature = "ml")]
|
||||
fn kompress_or_noop(text: &str, content_type: ContentType) -> DispatchResult {
|
||||
if let Some(k) = kompress_cached() {
|
||||
@@ -805,10 +798,9 @@ fn warm_kompress_blocking() -> bool {
|
||||
// arms to a deterministic no-op, bypassing their compressor entirely.
|
||||
//
|
||||
// One operator-facing caveat: granularity is per ARM, not per
|
||||
// compressor. `plain_text` alone does not stop Kompress runs reached
|
||||
// through the SourceCode arm's passthrough fallback; disabling
|
||||
// `source_code` as well is what removes Kompress from traffic entirely
|
||||
// (at the cost of also disabling the code compressor).
|
||||
// compressor. Only the `PlainText` arm reaches Kompress, so disabling
|
||||
// `plain_text` removes Kompress from traffic; `source_code` governs
|
||||
// the code compressor alone.
|
||||
|
||||
/// Parse the comma-separated arm list. Blank entries are skipped;
|
||||
/// unknown names are ignored with a warning rather than failing the
|
||||
@@ -1637,8 +1629,8 @@ enum DispatchResult {
|
||||
/// - `BuildOutput` → LogCompressor
|
||||
/// - `SearchResults` → SearchCompressor
|
||||
/// - `GitDiff` → DiffCompressor
|
||||
/// - `SourceCode` → CodeAwareCompressor, falling back to cached
|
||||
/// Kompress on exact passthrough (PR-B4)
|
||||
/// - `SourceCode` → CodeAwareCompressor; an exact passthrough stays a
|
||||
/// no-op, never Kompress (PR-B4, #4214)
|
||||
/// - `PlainText` → cached Kompress, cache-cold → no-op (PR-B4)
|
||||
/// - `Html` → no-op (no compressor)
|
||||
///
|
||||
@@ -1726,21 +1718,20 @@ fn dispatch_compressor(text: &str, content_type: ContentType) -> DispatchResult
|
||||
// syntax errors, a min-token floor, and a compression-ratio
|
||||
// guard), so this arm only has to compare its output against
|
||||
// the input; the tokenizer-rejection gate in
|
||||
// `compress_one_block` applies on top of that. When the code
|
||||
// compressor doesn't shrink the block (e.g. it's already
|
||||
// dense, or tree-sitter reverted on a parse error), fall back
|
||||
// to Kompress rather than giving up — mirrors the Python
|
||||
// router's no-shrink → Kompress fallback.
|
||||
// `compress_one_block` applies on top of that.
|
||||
//
|
||||
// When the code compressor declines (exact passthrough), the block
|
||||
// is left UNCHANGED. It is deliberately NOT handed to Kompress:
|
||||
// that is a prose model that drops low-salience words, and for code
|
||||
// those are keywords such as `for`, `in` and `if` (#4214). Mirrors
|
||||
// the Python router, which no longer falls back from code to prose
|
||||
// ML compression either.
|
||||
ContentType::SourceCode => {
|
||||
let result = code_compressor().compress(text);
|
||||
if result.compressed == text {
|
||||
// Exact passthrough only: the compressor declined
|
||||
// (min-token floor, unknown language, parse failure,
|
||||
// ratio guard), so hand the block to Kompress. A
|
||||
// rewrite that changed bytes without shrinking tokens
|
||||
// is NOT retried here — `compress_one_block`'s
|
||||
// tokenizer gate rejects it and forwards the original.
|
||||
return kompress_or_noop(text, content_type);
|
||||
return DispatchResult::NoOp {
|
||||
content_type: content_type.as_str(),
|
||||
};
|
||||
}
|
||||
DispatchResult::Compressed {
|
||||
strategy: STRATEGY_CODE_COMPRESSOR,
|
||||
|
||||
@@ -122,6 +122,26 @@ pub fn python_module_source(n: usize) -> String {
|
||||
code
|
||||
}
|
||||
|
||||
/// Go source the tree-sitter code compressor declines (exact
|
||||
/// passthrough: the language has no elision rules), yet which the
|
||||
/// detector still classifies as `SourceCode` and which clears the
|
||||
/// 2048-byte threshold. This is the shape that used to fall through to
|
||||
/// Kompress (#4214).
|
||||
pub fn go_handlers_source(n: usize) -> String {
|
||||
use std::fmt::Write as _;
|
||||
|
||||
let mut code = String::new();
|
||||
for i in 0..n {
|
||||
let _ = write!(
|
||||
code,
|
||||
"func Handle{i}(w http.ResponseWriter, r *http.Request) {{\n\t\
|
||||
id := r.URL.Query().Get(\"id\")\n\t\
|
||||
fmt.Fprintf(w, \"%s-{i}\", id)\n}}\n\n"
|
||||
);
|
||||
}
|
||||
code
|
||||
}
|
||||
|
||||
/// Repetitive plain prose of at least `min_bytes`, varied enough to
|
||||
/// classify as `PlainText`.
|
||||
pub fn plain_prose(min_bytes: usize) -> String {
|
||||
|
||||
@@ -14,10 +14,47 @@
|
||||
|
||||
mod common;
|
||||
|
||||
use common::{body_with_tool_result, dispatch, kompress_available, python_module_source, sha256};
|
||||
use common::{
|
||||
body_with_tool_result, dispatch, go_handlers_source, kompress_available, python_module_source,
|
||||
sha256, tool_result_action,
|
||||
};
|
||||
use headroom_core::transforms::{BlockAction, LiveZoneOutcome};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// The script from #4214 (a fenced Python snippet whose keywords Kompress
|
||||
/// deleted). The reporter's own fence is not published; this reconstruction
|
||||
/// keeps the lines quoted in the issue and parses as Python.
|
||||
const ISSUE_4214_SCRIPT: &str = r#"import json, collections
|
||||
|
||||
d = json.load(open('turns.json'))
|
||||
segs=[s for s in open('segs.txt').read().split() if s]
|
||||
def load(path):
|
||||
try:
|
||||
return json.load(open(path))
|
||||
except Exception as e: return None
|
||||
for i,s in enumerate(segs):
|
||||
t0=(d or {}).get('turns') or []
|
||||
if not t0 or len(t0) < 2:
|
||||
continue
|
||||
else:
|
||||
label = s if s else 'unknown'
|
||||
counts = collections.Counter(x.get('role') for x in t0)
|
||||
for role, n in counts.items():
|
||||
if n > 1 or role == 'tool':
|
||||
print(i, label, role, n)
|
||||
else:
|
||||
print(i, label, role)
|
||||
total = sum(counts.values())
|
||||
if total > 10 or label == 'big':
|
||||
print('large session', label, total)
|
||||
out = [k for k in counts if counts[k] > 0]
|
||||
print(json.dumps(out))
|
||||
summary = {s: i for i, s in enumerate(segs)}
|
||||
for k, v in summary.items():
|
||||
if v % 2 == 0 or k.startswith('a'):
|
||||
print(k, v)
|
||||
print('done', len(segs))"#;
|
||||
|
||||
// ─── Routing tests ─────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
@@ -249,6 +286,70 @@ fn source_code_tool_result_routes_to_code_compressor() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_code_declined_by_code_compressor_is_never_kompressed() {
|
||||
// The code compressor leaves Go source untouched (exact passthrough).
|
||||
// That must stay a NoOp: handing it to Kompress, a prose model, drops
|
||||
// keywords such as `func`, `if` and `for` from the code (#4214). The
|
||||
// warmup makes Kompress live when the model is cache-resident, so on
|
||||
// such a host the old fallback would have rewritten this block.
|
||||
let _ = kompress_available();
|
||||
let code = go_handlers_source(30);
|
||||
assert!(
|
||||
code.len() > 2048,
|
||||
"fixture must clear the SourceCode byte threshold (2048); got {} bytes",
|
||||
code.len()
|
||||
);
|
||||
let (body, _) = body_with_tool_result(&code);
|
||||
|
||||
match dispatch(&body) {
|
||||
LiveZoneOutcome::NoChange { manifest } => {
|
||||
let action = manifest
|
||||
.block_outcomes
|
||||
.iter()
|
||||
.find(|b| b.block_type == "tool_result")
|
||||
.expect("tool_result block present")
|
||||
.action
|
||||
.clone();
|
||||
assert!(
|
||||
matches!(&action, BlockAction::NoCompressionApplied { content_type } if content_type == "source_code"),
|
||||
"expected a source_code NoOp, got {action:?}"
|
||||
);
|
||||
}
|
||||
LiveZoneOutcome::Modified { manifest, .. } => panic!(
|
||||
"a declined source-code block must be forwarded unchanged, not rewritten. manifest: {manifest:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issue_4214_script_is_never_kompressed() {
|
||||
// The Python script quoted in #4214, repeated until the block clears the
|
||||
// SourceCode threshold. The code compressor may shrink it (it keeps the
|
||||
// keywords) or leave it alone, but the prose model must never rewrite it.
|
||||
// A guard rather than a discriminator: the code compressor already handles
|
||||
// Python, so this passes before the fix too; the Go test above is the one
|
||||
// that fails without it.
|
||||
let _ = kompress_available();
|
||||
let code = format!("{ISSUE_4214_SCRIPT}\n").repeat(3);
|
||||
assert!(
|
||||
code.len() > 2048,
|
||||
"fixture must clear the SourceCode byte threshold"
|
||||
);
|
||||
let (body, _) = body_with_tool_result(&code);
|
||||
|
||||
match dispatch(&body) {
|
||||
LiveZoneOutcome::NoChange { .. } => {}
|
||||
LiveZoneOutcome::Modified { manifest, .. } => match tool_result_action(&manifest) {
|
||||
BlockAction::Compressed { strategy, .. } => assert_eq!(
|
||||
strategy, "code_compressor",
|
||||
"only the code compressor may rewrite the #4214 script"
|
||||
),
|
||||
other => panic!("unexpected action {other:?}"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiny_source_code_below_threshold_no_op() {
|
||||
// Detector classifies this as SourceCode, but it's well under the
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! A declined source-code block never reaches the Kompress slot — dedicated
|
||||
//! integration test file.
|
||||
//!
|
||||
//! When the code compressor declines a block (exact passthrough), the
|
||||
//! dispatcher used to hand it to Kompress, a prose model that drops
|
||||
//! keywords such as `for`, `in` and `if` (#4214). The Kompress slot is
|
||||
//! process-global and latches on first use, so the cleanest observable of
|
||||
//! "Kompress was consulted" is that the model construction never starts.
|
||||
//! That holds on any host, warm cache or not, which is why this does not
|
||||
//! need the model. It needs a virgin process, so this is a single-test
|
||||
//! binary like `live_zone_kompress_async_init.rs`. Do NOT add more tests
|
||||
//! to this file.
|
||||
//!
|
||||
//! Vacuity note: without the `ml` feature there is no Kompress slot and
|
||||
//! `kompress_init_runs()` is always 0, so the init assertion is trivially
|
||||
//! true there; the byte-identical assertion still holds.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use common::{body_with_tool_result, dispatch, go_handlers_source};
|
||||
use headroom_core::transforms::live_zone;
|
||||
use headroom_core::transforms::LiveZoneOutcome;
|
||||
|
||||
#[test]
|
||||
fn declined_source_code_never_starts_kompress() {
|
||||
let code = go_handlers_source(30);
|
||||
assert!(
|
||||
code.len() > 2048,
|
||||
"fixture must clear the SourceCode byte threshold (2048); got {} bytes",
|
||||
code.len()
|
||||
);
|
||||
let (body, _) = body_with_tool_result(&code);
|
||||
|
||||
assert!(
|
||||
matches!(dispatch(&body), LiveZoneOutcome::NoChange { .. }),
|
||||
"a block the code compressor declines must be forwarded unchanged"
|
||||
);
|
||||
|
||||
// The slot's initializer runs on a background thread started by the
|
||||
// dispatch that first consults it. Give a would-be start ample time to
|
||||
// show up before asserting it never did.
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while Instant::now() < deadline && live_zone::kompress_init_runs() == 0 {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(
|
||||
live_zone::kompress_init_runs(),
|
||||
0,
|
||||
"Kompress must not be consulted for code the code compressor declined"
|
||||
);
|
||||
}
|
||||
@@ -109,7 +109,7 @@ result = compressor.compress(code)
|
||||
| `max_body_lines` | `5` | Max lines to keep per function body |
|
||||
| `min_tokens_for_compression` | `100` | Skip files smaller than this |
|
||||
| `language_hint` | `None` | Override language detection |
|
||||
| `fallback_to_kompress` | `True` | Use Kompress for unsupported languages |
|
||||
| `fallback_to_kompress` | `True` | Use Kompress for unsupported languages. `ContentRouter` (the proxy and `compress()`) always sets it to `False`, so code it routes is never sent to Kompress |
|
||||
|
||||
## Before and After
|
||||
|
||||
@@ -169,5 +169,5 @@ unload_tree_sitter()
|
||||
| Syntax validity | Guaranteed |
|
||||
|
||||
<Callout type="info" title="Routing differs between the proxy and the library API">
|
||||
ContentRouter always *detects* source code automatically, but whether it routes that code to CodeAwareCompressor depends on the entry point. `headroom proxy` enables code-aware routing by default (`HEADROOM_CODE_AWARE_ENABLED` defaults to on; disable with `--no-code-aware` or `HEADROOM_CODE_AWARE_ENABLED=0`). The one-function `compress()` API and `HeadroomClient`, however, build `ContentRouterConfig` with its own default, `enable_code_aware=False` -- there, detected code falls back to Kompress unless you construct your own pipeline with `ContentRouterConfig(enable_code_aware=True)`. Direct usage of `CodeAwareCompressor`, as shown on this page, is unaffected either way. See [How Compression Works](/docs/how-compression-works#content-type-detection).
|
||||
ContentRouter always *detects* source code automatically, but whether it routes that code to CodeAwareCompressor depends on the entry point. `headroom proxy` enables code-aware routing by default (`HEADROOM_CODE_AWARE_ENABLED` defaults to on; disable with `--no-code-aware` or `HEADROOM_CODE_AWARE_ENABLED=0`). The one-function `compress()` API and `HeadroomClient`, however, build `ContentRouterConfig` with its own default, `enable_code_aware=False` -- there, detected code is left unchanged (it is never handed to the prose model, Kompress, which drops keywords) unless you construct your own pipeline with `ContentRouterConfig(enable_code_aware=True)`. Direct usage of `CodeAwareCompressor`, as shown on this page, is unaffected either way. See [How Compression Works](/docs/how-compression-works#content-type-detection).
|
||||
</Callout>
|
||||
|
||||
@@ -29,7 +29,7 @@ The router auto-detects content type by analyzing structure and patterns. No man
|
||||
| Content Type | Detection Signal | Compressor | Typical Savings |
|
||||
|---|---|---|---|
|
||||
| JSON arrays | Valid JSON with array elements | SmartCrusher | Varies with redundancy -- measured 26-54% on realistic (non-duplicate) tool-output arrays of 100-10,000 items; highly repetitive arrays compress far more. See `benchmarks/compression_benchmark.py`. |
|
||||
| Source code | Syntax patterns, indentation, keywords | Kompress via the library `compress()`/`HeadroomClient` path (`enable_code_aware` defaults to `False` there); CodeAwareCompressor via `headroom proxy` (`HEADROOM_CODE_AWARE_ENABLED` defaults to on) | workload-dependent |
|
||||
| Source code | Syntax patterns, indentation, keywords | Left unchanged (passthrough) via the library `compress()`/`HeadroomClient` path (`enable_code_aware` defaults to `False` there); CodeAwareCompressor via `headroom proxy` (`HEADROOM_CODE_AWARE_ENABLED` defaults to on). Source code is never sent to Kompress. | workload-dependent |
|
||||
| Search results | `file:line:content` format | SearchCompressor | 80-95% (measured ~91% on a synthetic 40-file ripgrep-style corpus) |
|
||||
| Build/test logs | Timestamps, log levels, pytest/npm markers | LogCompressor | 85-95% (measured ~93% on a synthetic 1,000-line log with clustered errors) |
|
||||
| Diffs | Unified diff format | DiffCompressor | 60-80% (measured ~70% on a multi-file diff with default `max_context_lines`/`max_hunks_per_file` limits) |
|
||||
|
||||
@@ -1797,6 +1797,13 @@ def content_cache_key(
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
# Bump when a routing change makes earlier cached output wrong for the same
|
||||
# version and config, so the disk tier starts a fresh namespace instead of
|
||||
# replaying it. "code-never-kompress": before #4214, code could reach Kompress
|
||||
# and lose keywords; a cache made then must not be served after the fix.
|
||||
_ROUTING_POLICY_REVISION = "code-never-kompress"
|
||||
|
||||
|
||||
def _config_namespace(config: Any) -> str:
|
||||
"""A prefix for this router's keys in the shared disk tier: a digest of its
|
||||
config and the headroom version. The proxy may run routers configured
|
||||
@@ -1822,7 +1829,9 @@ def _config_namespace(config: Any) -> str:
|
||||
# starts a fresh namespace rather than serving output made under another.
|
||||
settings = sorted((k, v) for k, v in os.environ.items() if k.startswith("HEADROOM_"))
|
||||
h = hashlib.blake2b(digest_size=8)
|
||||
h.update(f"{__version__}|{stable(asdict(config))!r}|{settings!r}".encode())
|
||||
h.update(
|
||||
f"{__version__}|{_ROUTING_POLICY_REVISION}|{stable(asdict(config))!r}|{settings!r}".encode()
|
||||
)
|
||||
return h.hexdigest() + ":"
|
||||
|
||||
|
||||
@@ -4170,6 +4179,12 @@ class ContentRouter(Transform):
|
||||
active = self._active_external_compressors
|
||||
if not active:
|
||||
return None
|
||||
# PASSTHROUGH is the router's explicit "leave this block unmangled"
|
||||
# decision (source code with prefer_code_aware_for_code=False, whole or
|
||||
# as a mixed-content section). Its strategy maps to text/plain below, so
|
||||
# a prose-only external compressor would otherwise rewrite the code.
|
||||
if strategy == CompressionStrategy.PASSTHROUGH:
|
||||
return None
|
||||
content_mime = _CONTENT_TYPE_TO_MIME.get(self._content_type_from_strategy(strategy))
|
||||
if content_mime is None:
|
||||
return None
|
||||
@@ -4539,12 +4554,17 @@ class ContentRouter(Transform):
|
||||
# compressor on the byte-folded remainder and keep it IFF it removes a
|
||||
# further meaningful chunk (Kompress must save >= _lossy_min_extra_savings
|
||||
# beyond the fold). Keeps the fold AND reclaims the semantic word-drop
|
||||
# tail, never doing worse than the fold. DIFF folds are returned verbatim
|
||||
# — Kompressing hunks corrupts `git apply`.
|
||||
# tail, never doing worse than the fold. Code and explicit passthrough
|
||||
# remain lossless; Kompress would also corrupt diff hunks.
|
||||
if _ll_label is not None:
|
||||
_lossy_after_fold = (
|
||||
self._lossless_then_lossy
|
||||
and strategy != CompressionStrategy.DIFF
|
||||
and strategy
|
||||
not in {
|
||||
CompressionStrategy.DIFF,
|
||||
CompressionStrategy.CODE_AWARE,
|
||||
CompressionStrategy.PASSTHROUGH,
|
||||
}
|
||||
and _ll_label != "lossless_diff"
|
||||
and not self._looks_like_diff(content)
|
||||
)
|
||||
@@ -4592,14 +4612,9 @@ class ContentRouter(Transform):
|
||||
compressor = self._get_code_compressor()
|
||||
if compressor:
|
||||
compressor_name = type(compressor).__name__
|
||||
# Registry-resolved dispatch: the built-in "code_aware"
|
||||
# adapter delegates to this same getter+method with the
|
||||
# language passed through ``config``, so on a real
|
||||
# compression the content is byte-identical to the
|
||||
# historical direct call. If the adapter did NOT compress
|
||||
# (``compressed=False``), leave the local ``compressed``
|
||||
# None so the EXISTING Kompress fallback below runs
|
||||
# exactly as today.
|
||||
# The registry adapter passes the language through to
|
||||
# the code-aware compressor. If it declines the block,
|
||||
# preserve the original code rather than trying ML.
|
||||
output = self._registry_compress(
|
||||
"code_aware",
|
||||
strategy,
|
||||
@@ -4616,39 +4631,6 @@ class ContentRouter(Transform):
|
||||
# 55% compression and no fallback could beat it.
|
||||
compressed_tokens = _estimate_tokens(output.content)
|
||||
decision_reason = "code_aware"
|
||||
if compressed is None:
|
||||
# Fallback to Kompress
|
||||
compressed, compressed_tokens = self._try_ml_compressor(
|
||||
content, context, question
|
||||
)
|
||||
strategy = CompressionStrategy.KOMPRESS # Update for TOIN
|
||||
actual_strategy = strategy
|
||||
compressor_name = "KompressCompressor"
|
||||
decision_reason = "code_aware_unavailable_fallback_kompress"
|
||||
strategy_chain.append(CompressionStrategy.KOMPRESS.value)
|
||||
elif (
|
||||
self._lossless_then_lossy
|
||||
and compressed_tokens is not None
|
||||
and compressed_tokens >= original_tokens
|
||||
):
|
||||
# #3 — lossless-then-lossy: code-aware produced NO net shrink
|
||||
# and the lossless fold found nothing either, so this code
|
||||
# block would otherwise pass through uncompressed. Give the
|
||||
# lossy ML compressor (Kompress) a shot so lossy runs even when
|
||||
# lossless has no savings. Reads are protected upstream, so
|
||||
# only NON-read code reaches here. Keep Kompress ONLY if it
|
||||
# actually shrinks (never inflate).
|
||||
# Recorded as tried even if it loses, so the no-savings
|
||||
# fallback below does not run the same inference again.
|
||||
strategy_chain.append(CompressionStrategy.KOMPRESS.value)
|
||||
_k, _ = self._try_ml_compressor(content, context, question)
|
||||
_kt = _estimate_tokens(_k)
|
||||
if _kt < original_tokens and len(_k) < len(content):
|
||||
compressed, compressed_tokens = _k, _kt
|
||||
strategy = CompressionStrategy.KOMPRESS
|
||||
actual_strategy = strategy
|
||||
compressor_name = "KompressCompressor"
|
||||
decision_reason = "code_aware_no_shrink_fallback_kompress"
|
||||
|
||||
elif strategy == CompressionStrategy.SMART_CRUSHER:
|
||||
# SmartCrusher handles its own TOIN recording
|
||||
@@ -4873,15 +4855,11 @@ class ContentRouter(Transform):
|
||||
# some rows and not others with nothing marking which (#3652).
|
||||
fallback_eligible_strategy = strategy in {
|
||||
CompressionStrategy.SMART_CRUSHER,
|
||||
CompressionStrategy.CODE_AWARE,
|
||||
CompressionStrategy.CONFIG,
|
||||
}
|
||||
fallback_no_savings = compressed == content or compressed_tokens >= original_tokens
|
||||
if fallback_eligible_strategy and fallback_no_savings:
|
||||
# Skip if Kompress was already tried by an inline fallback
|
||||
# (e.g. CODE_AWARE's code-compressor-unavailable path at
|
||||
# line 1249). Prevents a duplicate strategy_chain entry
|
||||
# and a wasted second _try_ml_compressor call.
|
||||
# Do not run Kompress twice if an inline fallback already tried it.
|
||||
already_tried_kompress = CompressionStrategy.KOMPRESS.value in strategy_chain
|
||||
if not already_tried_kompress:
|
||||
strategy_chain.append(CompressionStrategy.KOMPRESS.value)
|
||||
@@ -4953,10 +4931,9 @@ class ContentRouter(Transform):
|
||||
# produced and KEEP it only if it removes a further meaningful chunk
|
||||
# (>= _lossy_min_extra_savings beyond the strategy result) and is
|
||||
# actually shorter — never inflating, never doing worse than the
|
||||
# strategy output. DIFF is excluded (Kompress corrupts ``git
|
||||
# apply``); TEXT/KOMPRESS already ran Kompress; CODE_AWARE has its
|
||||
# own inline no-shrink fallback; SMART_CRUSHER uses the
|
||||
# zero-savings fallback above; TABULAR never goes to Kompress.
|
||||
# strategy output. Code, diffs, and tables stay out of lossy ML;
|
||||
# TEXT/KOMPRESS already ran it, and SMART_CRUSHER uses the
|
||||
# zero-savings fallback above.
|
||||
if (
|
||||
self._lossless_then_lossy
|
||||
and compressed is not None
|
||||
@@ -5469,6 +5446,8 @@ class ContentRouter(Transform):
|
||||
|
||||
def _strategy_from_detection_type(self, content_type: ContentType) -> CompressionStrategy:
|
||||
"""Get strategy from ContentType enum."""
|
||||
if content_type == ContentType.SOURCE_CODE and not self.config.prefer_code_aware_for_code:
|
||||
return CompressionStrategy.PASSTHROUGH
|
||||
mapping = {
|
||||
ContentType.SOURCE_CODE: CompressionStrategy.CODE_AWARE,
|
||||
ContentType.JSON_ARRAY: CompressionStrategy.SMART_CRUSHER,
|
||||
@@ -5516,10 +5495,13 @@ class ContentRouter(Transform):
|
||||
self._code_compressor = CodeAwareCompressor(
|
||||
CodeCompressorConfig(
|
||||
enable_ccr=self.config.ccr_inject_marker,
|
||||
# The code compressor's Kompress fallback builds its
|
||||
# own KompressCompressor, so it must honour the same
|
||||
# switch as _get_kompress() (#4719).
|
||||
fallback_to_kompress=self.config.enable_kompress,
|
||||
# Never let the code compressor fall back to Kompress
|
||||
# internally (unknown language, Perl, no tree-sitter,
|
||||
# AST failure). Kompress is a prose model and drops
|
||||
# keywords from code (#4214). A block the code
|
||||
# compressor cannot handle stays unchanged, whether or
|
||||
# not Kompress is enabled for prose (#4719).
|
||||
fallback_to_kompress=False,
|
||||
)
|
||||
)
|
||||
else:
|
||||
|
||||
@@ -58,22 +58,49 @@ def test_disabled_kompress_turns_off_code_aware_fallback() -> None:
|
||||
assert compressor.config.fallback_to_kompress is False
|
||||
|
||||
|
||||
def test_enabled_kompress_keeps_code_aware_fallback() -> None:
|
||||
def test_enabled_kompress_still_turns_off_code_aware_fallback() -> None:
|
||||
# Kompress may be on for prose, but it must never compress code (#4214):
|
||||
# the router's code compressor leaves blocks it cannot handle unchanged.
|
||||
router = ContentRouter(ContentRouterConfig(enable_code_aware=True))
|
||||
|
||||
compressor = router._get_code_compressor()
|
||||
|
||||
assert compressor is not None
|
||||
assert compressor.config.fallback_to_kompress is True
|
||||
assert compressor.config.fallback_to_kompress is False
|
||||
|
||||
|
||||
def test_unknown_language_code_passes_through_without_kompress(
|
||||
kompress_spies: tuple[MagicMock, MagicMock],
|
||||
) -> None:
|
||||
assert detect_language(UNKNOWN_CODE)[0] == CodeLanguage.UNKNOWN
|
||||
router = ContentRouter(ContentRouterConfig(enable_code_aware=True, enable_kompress=False))
|
||||
PERL_CODE = "\n".join(
|
||||
["#!/usr/bin/perl", "use strict;", "use warnings;"]
|
||||
+ [
|
||||
f'my $v{i} = $ARGV[{i % 3}] // {i}; print "$v{i}\\n" if $v{i} =~ /^\\d+$/;'
|
||||
for i in range(60)
|
||||
]
|
||||
)
|
||||
|
||||
PYTHON_CODE = "\n".join(
|
||||
["import json", ""]
|
||||
+ [
|
||||
f"def handler_{i}(event):\n if event.get('k{i}'):\n return json.dumps(event)\n return None\n"
|
||||
for i in range(40)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def _code_aware_entry(enable_kompress: bool):
|
||||
router = ContentRouter(
|
||||
ContentRouterConfig(enable_code_aware=True, enable_kompress=enable_kompress)
|
||||
)
|
||||
entry = router.compressor_registry.get("code_aware")
|
||||
assert entry is not None
|
||||
return router, entry
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enable_kompress", [False, True])
|
||||
def test_unknown_language_code_passes_through_without_kompress(
|
||||
kompress_spies: tuple[MagicMock, MagicMock], enable_kompress: bool
|
||||
) -> None:
|
||||
assert detect_language(UNKNOWN_CODE)[0] == CodeLanguage.UNKNOWN
|
||||
_, entry = _code_aware_entry(enable_kompress)
|
||||
|
||||
out = entry.compress(CompressInput(content=UNKNOWN_CODE, content_type="text/x-code"))
|
||||
|
||||
@@ -81,3 +108,58 @@ def test_unknown_language_code_passes_through_without_kompress(
|
||||
available.assert_not_called()
|
||||
compressor.assert_not_called()
|
||||
assert out.content == UNKNOWN_CODE
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enable_kompress", [False, True])
|
||||
def test_perl_code_passes_through_without_kompress(
|
||||
kompress_spies: tuple[MagicMock, MagicMock], enable_kompress: bool
|
||||
) -> None:
|
||||
# detect_language() reports Perl-dominant code as UNKNOWN on purpose, so the
|
||||
# Perl branch is reached through an explicit language hint.
|
||||
_, entry = _code_aware_entry(enable_kompress)
|
||||
|
||||
out = entry.compress(
|
||||
CompressInput(content=PERL_CODE, content_type="text/x-code", config={"language": "perl"})
|
||||
)
|
||||
|
||||
available, compressor = kompress_spies
|
||||
available.assert_not_called()
|
||||
compressor.assert_not_called()
|
||||
assert out.content == PERL_CODE
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enable_kompress", [False, True])
|
||||
def test_ast_failure_passes_through_without_kompress(
|
||||
kompress_spies: tuple[MagicMock, MagicMock],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
enable_kompress: bool,
|
||||
) -> None:
|
||||
router, entry = _code_aware_entry(enable_kompress)
|
||||
code_compressor = router._get_code_compressor()
|
||||
assert code_compressor is not None
|
||||
|
||||
def _boom(*_args, **_kwargs):
|
||||
raise RuntimeError("simulated AST failure")
|
||||
|
||||
monkeypatch.setattr(code_compressor, "_compress_with_ast", _boom)
|
||||
|
||||
out = entry.compress(CompressInput(content=PYTHON_CODE, content_type="text/x-code"))
|
||||
|
||||
available, compressor = kompress_spies
|
||||
available.assert_not_called()
|
||||
compressor.assert_not_called()
|
||||
assert out.content == PYTHON_CODE
|
||||
|
||||
|
||||
def test_disk_cache_namespace_includes_the_routing_policy_revision(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
# Output cached before #4214 (code sent to Kompress) must not be replayed
|
||||
# after the fix by a restart with the same version and config.
|
||||
import headroom.transforms.content_router as cr
|
||||
|
||||
config = ContentRouterConfig()
|
||||
current = cr._config_namespace(config)
|
||||
monkeypatch.setattr(cr, "_ROUTING_POLICY_REVISION", "earlier-policy")
|
||||
|
||||
assert cr._config_namespace(config) != current
|
||||
|
||||
@@ -394,3 +394,49 @@ def test_wildcard_selection_activates_registered_external(_memory_ccr):
|
||||
|
||||
assert comp.calls
|
||||
assert "external:ext_json" in result.strategy_chain
|
||||
|
||||
|
||||
# ───────────── explicit passthrough code never reaches an external ─────────────
|
||||
|
||||
_PY_FENCE = "\n".join(
|
||||
["import json", ""]
|
||||
+ [
|
||||
f"def handler_{i}(event):\n if event.get('k{i}'):\n return json.dumps(event)\n return None\n"
|
||||
for i in range(30)
|
||||
]
|
||||
)
|
||||
_PROSE = " ".join(
|
||||
["The nightly job failed after the deploy and the operator wants a short summary."] * 40
|
||||
)
|
||||
|
||||
|
||||
def test_passthrough_code_section_is_not_offered_to_a_text_external(_memory_ccr):
|
||||
# With prefer_code_aware_for_code=False the router keeps source code
|
||||
# unmangled (PASSTHROUGH). A selected prose-only external compressor must
|
||||
# not receive that code: mixed content splits the fence into its own section.
|
||||
comp = _RecordingExternal(name="ext_text", content_types=("text/plain",))
|
||||
router = ContentRouter(
|
||||
_cfg(active_external_compressors=["ext_text"], prefer_code_aware_for_code=False)
|
||||
)
|
||||
router.compressor_registry.register(comp, replace=True)
|
||||
router._active_external_compressors = router._resolve_active_external_compressors()
|
||||
content = f"{_PROSE}\n\n```python\n{_PY_FENCE}\n```\n\n{_PROSE}"
|
||||
|
||||
result = router.compress(content)
|
||||
|
||||
assert all("def handler_0" not in call.content for call in comp.calls)
|
||||
assert f"```python\n{_PY_FENCE}\n```" in result.compressed
|
||||
|
||||
|
||||
def test_passthrough_whole_code_block_is_not_offered_to_a_text_external(_memory_ccr):
|
||||
comp = _RecordingExternal(name="ext_text", content_types=("text/plain",))
|
||||
router = ContentRouter(
|
||||
_cfg(active_external_compressors=["ext_text"], prefer_code_aware_for_code=False)
|
||||
)
|
||||
router.compressor_registry.register(comp, replace=True)
|
||||
router._active_external_compressors = router._resolve_active_external_compressors()
|
||||
|
||||
result = router.compress(_PY_FENCE)
|
||||
|
||||
assert not comp.calls
|
||||
assert result.compressed == _PY_FENCE
|
||||
|
||||
@@ -1589,23 +1589,25 @@ class TestSmartCrusherFallback:
|
||||
f"{strategy_chain}"
|
||||
)
|
||||
|
||||
def test_code_aware_fallback_also_uses_unified_block(self, router, monkeypatch):
|
||||
"""CodeAware strategy also uses the unified fallback block.
|
||||
Verify it doesn't double-invoke Kompress either."""
|
||||
def test_code_aware_declining_never_falls_back_to_kompress(self, router, monkeypatch):
|
||||
"""Code-aware declining a block leaves it unchanged; prose ML never runs (#4214).
|
||||
|
||||
Replaces the old "no double Kompress" check: with the CODE_AWARE ->
|
||||
Kompress fallbacks removed, Kompress must not run even once.
|
||||
"""
|
||||
import headroom.transforms.content_router as crm
|
||||
|
||||
monkeypatch.setattr(
|
||||
crm.ContentRouter,
|
||||
"_try_ml_compressor",
|
||||
lambda self, content, context="", question=None: (
|
||||
content,
|
||||
len(content.split()),
|
||||
),
|
||||
)
|
||||
ml_calls: list[str] = []
|
||||
|
||||
def spy(self, content, context="", question=None):
|
||||
ml_calls.append(content)
|
||||
return content, len(content.split())
|
||||
|
||||
monkeypatch.setattr(crm.ContentRouter, "_try_ml_compressor", spy)
|
||||
|
||||
plain = "This is just plain text. " * 200
|
||||
|
||||
compressed, compressed_tokens, strategy_chain, _reversible = (
|
||||
compressed, _compressed_tokens, strategy_chain, _reversible = (
|
||||
router._apply_strategy_to_content(
|
||||
plain,
|
||||
CompressionStrategy.CODE_AWARE,
|
||||
@@ -1613,15 +1615,10 @@ class TestSmartCrusherFallback:
|
||||
)
|
||||
)
|
||||
|
||||
# CodeAware should be in the chain
|
||||
assert "code_aware" in strategy_chain
|
||||
|
||||
# No duplicate fallback entries
|
||||
kompress_count = strategy_chain.count("kompress")
|
||||
assert kompress_count <= 1, (
|
||||
f"Kompress appeared {kompress_count} times; "
|
||||
f"duplicate fallback in CodeAware path: {strategy_chain}"
|
||||
)
|
||||
assert "kompress" not in strategy_chain
|
||||
assert ml_calls == []
|
||||
assert compressed == plain
|
||||
|
||||
|
||||
# =============================================================================
|
||||
|
||||
@@ -2858,30 +2858,39 @@ def _noop_code_aware_router(monkeypatch: pytest.MonkeyPatch, kompress_out: str)
|
||||
return router
|
||||
|
||||
|
||||
def test_code_aware_noop_keeps_a_smaller_kompress_fallback(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
@pytest.mark.parametrize("layer_lossy", [False, True], ids=["default", "lossless-then-lossy"])
|
||||
def test_code_aware_noop_never_hands_code_to_kompress(
|
||||
monkeypatch: pytest.MonkeyPatch, layer_lossy: bool
|
||||
) -> None:
|
||||
"""The fallback is judged in tokens, the unit of the code_aware result.
|
||||
"""A code_aware no-op leaves the block unchanged even if Kompress would shrink it (#4214).
|
||||
|
||||
With code_aware's result counted in words, a Kompress result at ~60% of the
|
||||
tokens still "lost" to the unchanged block, so the inference always ran and
|
||||
was always thrown away.
|
||||
Kompress is a prose model: it drops keywords, so it never sees code, neither as
|
||||
the CODE_AWARE fallback nor as the lossless-then-lossy inline attempt.
|
||||
"""
|
||||
kompressed = "\n".join(f"{i}\tvalue_{i} compute(&items[{i}..])" for i in range(1, 121))
|
||||
assert _estimate_tokens(kompressed) < _estimate_tokens(_NUMBERED_RUST)
|
||||
assert _estimate_tokens(kompressed) > len(_NUMBERED_RUST.split())
|
||||
router = _noop_code_aware_router(monkeypatch, kompressed)
|
||||
router._lossless_then_lossy = layer_lossy
|
||||
calls: list[str] = []
|
||||
kompress = router._try_ml_compressor
|
||||
|
||||
def counting(content: str, *args: object, **kwargs: object) -> tuple[str, int]:
|
||||
calls.append(content)
|
||||
return kompress(content, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(router, "_try_ml_compressor", counting)
|
||||
|
||||
compressed, compressed_tokens, strategy_chain, _reversible = router._apply_strategy_to_content(
|
||||
_NUMBERED_RUST, CompressionStrategy.CODE_AWARE, context=""
|
||||
)
|
||||
|
||||
assert compressed == kompressed
|
||||
assert compressed_tokens == _estimate_tokens(kompressed)
|
||||
assert strategy_chain == ["code_aware", "kompress"]
|
||||
assert compressed == _NUMBERED_RUST
|
||||
assert compressed_tokens == _estimate_tokens(_NUMBERED_RUST)
|
||||
assert strategy_chain == ["code_aware"]
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_code_aware_noop_reports_tokens_when_kompress_passes_through(
|
||||
def test_code_aware_noop_reports_tokens_without_kompress(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""An unchanged block is reported at its own token count, never its word count."""
|
||||
@@ -2895,58 +2904,104 @@ def test_code_aware_noop_reports_tokens_when_kompress_passes_through(
|
||||
assert compressed_tokens == _estimate_tokens(_NUMBERED_RUST)
|
||||
|
||||
|
||||
def test_code_aware_noop_runs_kompress_once_when_it_passes_through(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
@pytest.mark.parametrize(
|
||||
("enabled", "preferred", "layer_lossy"),
|
||||
[(False, True, False), (True, True, False), (True, False, False), (True, True, True)],
|
||||
ids=["unavailable", "declined", "passthrough", "lossless-then-lossy"],
|
||||
)
|
||||
def test_fenced_code_keeps_keywords_when_code_compression_declines(
|
||||
monkeypatch: pytest.MonkeyPatch, enabled: bool, preferred: bool, layer_lossy: bool
|
||||
) -> None:
|
||||
"""Lossless-then-lossy tries Kompress inline; a passthrough must not be retried."""
|
||||
router = _noop_code_aware_router(monkeypatch, _NUMBERED_RUST)
|
||||
router._lossless_then_lossy = True
|
||||
calls: list[str] = []
|
||||
kompress = router._try_ml_compressor
|
||||
code = "\n\n".join(
|
||||
f"def select_{i}(items):\n"
|
||||
" result = []\n"
|
||||
" for item in items:\n"
|
||||
" if item is not None:\n"
|
||||
" result.append(item)\n"
|
||||
" return result"
|
||||
for i in range(6)
|
||||
)
|
||||
router = _noop_code_aware_router(monkeypatch, code.replace("for ", "").replace("if ", ""))
|
||||
router.config.enable_code_aware = enabled
|
||||
router.config.prefer_code_aware_for_code = preferred
|
||||
router._lossless_then_lossy = layer_lossy
|
||||
prose = "\n\n".join(f"Section {i} describes the generated implementation." for i in range(6))
|
||||
mixed = f"{prose}\n\n```python\n{code}\n```\n\nExecution finished."
|
||||
|
||||
def counting(content: str, *args: object, **kwargs: object) -> tuple[str, int]:
|
||||
calls.append(content)
|
||||
return kompress(content, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(router, "_try_ml_compressor", counting)
|
||||
|
||||
compressed, compressed_tokens, _chain, _reversible = router._apply_strategy_to_content(
|
||||
_NUMBERED_RUST, CompressionStrategy.CODE_AWARE, context=""
|
||||
result = router.compress(
|
||||
mixed, precomputed_detection=DetectionResult(ContentType.PLAIN_TEXT, 1.0, {})
|
||||
)
|
||||
|
||||
assert compressed == _NUMBERED_RUST
|
||||
assert compressed_tokens == _estimate_tokens(_NUMBERED_RUST)
|
||||
assert len(calls) == 1
|
||||
assert f"```python\n{code}\n```" in result.compressed
|
||||
|
||||
|
||||
def test_code_aware_noop_keeps_a_smaller_inline_kompress(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
# The ctx_execute shape from #4214: a fenced Python script followed by its output.
|
||||
# The reporter's own 1324-character fence is not published, so this is a
|
||||
# reconstruction: it keeps the four lines quoted in the issue, parses, and is
|
||||
# exactly 1324 characters. The fake Kompress deletes the keywords the issue lists.
|
||||
_ISSUE_4214_SCRIPT = """import json, collections
|
||||
|
||||
d = json.load(open('turns.json'))
|
||||
segs=[s for s in open('segs.txt').read().split() if s]
|
||||
def load(path):
|
||||
try:
|
||||
return json.load(open(path))
|
||||
except Exception as e: return None
|
||||
for i,s in enumerate(segs):
|
||||
t0=(d or {}).get('turns') or []
|
||||
if not t0 or len(t0) < 2:
|
||||
continue
|
||||
else:
|
||||
label = s if s else 'unknown'
|
||||
counts = collections.Counter(x.get('role') for x in t0)
|
||||
for role, n in counts.items():
|
||||
if n > 1 or role == 'tool':
|
||||
print(i, label, role, n)
|
||||
else:
|
||||
print(i, label, role)
|
||||
total = sum(counts.values())
|
||||
if total > 10 or label == 'big':
|
||||
print('large session', label, total)
|
||||
out = [k for k in counts if counts[k] > 0]
|
||||
print(json.dumps(out))
|
||||
summary = {s: i for i, s in enumerate(segs)}
|
||||
for k, v in summary.items():
|
||||
if v % 2 == 0 or k.startswith('a'):
|
||||
print(k, v)
|
||||
print('done', len(segs))"""
|
||||
_ISSUE_4214_FENCE = _ISSUE_4214_SCRIPT + "\n#" + "x" * (1324 - len(_ISSUE_4214_SCRIPT) - 2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [False, True], ids=["code-aware-off", "code-aware-on"])
|
||||
def test_issue_4214_fenced_script_survives_kompress_unchanged(
|
||||
monkeypatch: pytest.MonkeyPatch, enabled: bool
|
||||
) -> None:
|
||||
"""Lossless-then-lossy's inline attempt keeps a Kompress result that wins.
|
||||
import ast
|
||||
import re
|
||||
|
||||
Measured in tokens, a code_aware no-op no longer looks like a shrink, so the
|
||||
inline attempt fires and its smaller result is kept without a second call.
|
||||
"""
|
||||
kompressed = "\n".join(f"{i}\tvalue_{i} compute(&items[{i}..])" for i in range(1, 121))
|
||||
router = _noop_code_aware_router(monkeypatch, kompressed)
|
||||
router._lossless_then_lossy = True
|
||||
calls: list[str] = []
|
||||
kompress = router._try_ml_compressor
|
||||
assert len(_ISSUE_4214_FENCE) == 1324
|
||||
ast.parse(_ISSUE_4214_FENCE)
|
||||
monkeypatch.delenv("HEADROOM_LOSSLESS_THEN_LOSSY", raising=False)
|
||||
router = ContentRouter(ContentRouterConfig(enable_code_aware=enabled))
|
||||
seen: list[str] = []
|
||||
|
||||
def counting(content: str, *args: object, **kwargs: object) -> tuple[str, int]:
|
||||
calls.append(content)
|
||||
return kompress(content, *args, **kwargs)
|
||||
def drop_keywords(content: str, *_args: object, **_kwargs: object) -> tuple[str, int]:
|
||||
seen.append(content)
|
||||
dropped = re.sub(r"\b(for|in|if|as|or|else) ?", "", content)
|
||||
return dropped, _estimate_tokens(dropped)
|
||||
|
||||
monkeypatch.setattr(router, "_try_ml_compressor", counting)
|
||||
|
||||
compressed, compressed_tokens, strategy_chain, _reversible = router._apply_strategy_to_content(
|
||||
_NUMBERED_RUST, CompressionStrategy.CODE_AWARE, context=""
|
||||
monkeypatch.setattr(router, "_try_ml_compressor", drop_keywords)
|
||||
output = "\n".join(
|
||||
f"Segment {i}: The job read the batch, checked each record against the schema "
|
||||
"and wrote a summary line for the report because the operator asked."
|
||||
for i in range(40)
|
||||
)
|
||||
content = f"```python\n{_ISSUE_4214_FENCE}\n```\n\n{output}"
|
||||
|
||||
assert compressed == kompressed
|
||||
assert compressed_tokens == _estimate_tokens(kompressed)
|
||||
assert strategy_chain == ["code_aware", "kompress"]
|
||||
assert len(calls) == 1
|
||||
result = router.compress(content, context="")
|
||||
|
||||
assert f"```python\n{_ISSUE_4214_FENCE}\n```" in result.compressed
|
||||
assert not any("def load" in section for section in seen)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("as_block", [False, True], ids=["string-tool", "tool-result-block"])
|
||||
|
||||
Reference in New Issue
Block a user