mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 03:16:20 +08:00
feat/https-compose-caddy
4
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
a538740ee4 |
fix(search_compressor): keep kept rows byte-for-byte and in input order (#3982)
## Description
`SearchCompressor` rebuilt every row it kept from its parsed parts
(`file:N:content`) instead of copying it. The agent then read text that
was never in the tool output:
- a time or date in the content was taken as a line number: `12:00:01`
printed as `12:0:01`, and `2026-10-03 12:05` as `2026:10:03 12:05`;
- a grep context line (`file-N-text`, from `grep -C`/`rg -C`) was
printed with `:`, turning it into a match line;
- kept rows within a file could come out in a different order than the
input.
This PR makes the compressor copy kept rows instead of rebuilding them.
(No existing issue covers it.) It complements #3788 (merged after
0.39.1, same file), which fixed a context line's body becoming its line
marker; this PR applies on top of it without conflicts and all of
#3788's tests still pass.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
All in `crates/headroom-core/src/transforms/search_compressor.rs`:
- **Rows render byte-for-byte.** Each parsed match keeps the exact
marker text between the file name and the content (`:12:`, `-12-`), and
output rows are `file + marker + content`, so the original separator
survives.
- **A zero-led digit run is never a line number** (`00`, `05`): real
line numbers never start with 0, so `12:00:01` and dates stay content.
- **Input order is kept within each file**: kept rows stay in the order
they arrived, and files are emitted in order of first appearance (also
on equal scores under `max_files`). Rows of different files that were
interleaved in the input are still grouped by file, as before.
- **The selected occurrence is the one emitted**: rows are selected and
emitted by input index. Previously the output pass matched rows back by
(line, content), so when a later row was selected (`always_keep_last`)
and an earlier row shared its number and content (a match `a.py:12:x`
and a context row `a.py-12-x`), the earlier one was printed instead. The
(line, content) dedup and every cap are unchanged (100,000-case
differential fuzz against the previous selection: same keys, counts and
stats).
- **Indented rows**: leading whitespace is set aside before parsing (so
the row splits at its real marker, not inside its path) and restored on
output.
## Testing
- [x] New tests added
- [x] New and existing unit tests pass locally
New tests: `the_selected_occurrence_is_emitted_not_its_twin`,
`indented_rows_split_at_the_real_marker_and_render_verbatim`,
`rejects_zero_led_line_numbers`,
`compress_output_rows_are_verbatim_and_in_input_order`,
`max_files_keeps_the_earliest_files_on_equal_scores`,
`rendering_reproduces_each_parsed_line_byte_for_byte`.
### Test Output
```text
# this branch
$ cargo test -p headroom-core --lib search_compressor
test result: ok. 34 passed; 0 failed; 0 ignored; 0 measured; 932 filtered out
$ cargo test -p headroom-core --lib
test result: ok. 965 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out
$ cargo fmt -p headroom-core -- --check # clean
$ cargo clippy -p headroom-core --lib -- -D warnings # clean
# fails before: the new tests against origin/main's implementation (the two tests that
# exercise the new render helper cannot compile there and were left out)
test transforms::search_compressor::tests::max_files_keeps_the_earliest_files_on_equal_scores ... FAILED
test transforms::search_compressor::tests::rejects_zero_led_line_numbers ... FAILED
test transforms::search_compressor::tests::compress_output_rows_are_verbatim_and_in_input_order ... FAILED
test result: FAILED. 28 passed; 3 failed
```
## Real Behavior Proof
- Environment: Linux (WSL2), Python 3.13, headroom-ai 0.39.1 installed
with uv; the same compiled `_core.abi3.so` swapped between the stock
wheel and one built from these commits on 0.39.1.
- Exact command / steps:
`headroom._core.SearchCompressor().compress(text)` on 120 rows of `grep
-n -C1`-style output (`app.log-2-2026-10-03 12:00:01 DEBUG tick` context
rows interleaved with `app.log:3:... ERROR ...` match rows); counted
kept rows that are not byte-identical to an input row.
- Observed result: stock core: 1 of 5 kept rows not in the input
(`app.log:2:2026-10-03 12:00:01 DEBUG tick`, a context row turned into a
match row). Fixed core: 0 of 5. The fix has also been running in my
local Headroom proxy (0.39.1) since 2026-10-03.
- Not tested: a full Python wheel built from main with this change (the
behavior proof used a 0.39.1-based build of the first three commits; the
unit tests above ran on main); Windows.
## Runtime Rollout Safety
- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: yes, only in that kept search rows
are now exact copies of input rows and keep their order
- Kill switch / disable path: none needed; existing search compression
settings are unchanged
- Unsafe override required: no
- Qualification impact: none expected
- Rollback path: revert this PR
## 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 commented my code, particularly in hard-to-understand areas
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`
## Additional Notes
Known, out of scope (same on main): a standalone date line whose month
has no leading zero (`2026-10-03 12:05 ...`) still parses as file
`2026`, line 10. The row is still printed verbatim; only its grouping is
wrong, and it can take a file slot under `max_files`. Happy to follow up
separately.
Python-side tests (`pytest`, `ruff`, `mypy`) were not run: the change is
Rust-only and touches no Python file.
One visible effect on the Python surface: `parse_search_lines`
(crates/headroom-py) now returns each row's content with its trailing
whitespace and `\r` intact (main trimmed them). File and line numbers
are unchanged for every row tested, indented or not. This is deliberate,
as the content is what gets copied back into the output; if the legacy
Python `SearchMatch.content` should stay trimmed, `m.content.trim_end()`
in the shim restores main's behavior.
<!-- devin-review-badge-begin -->
---
<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3982"
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 -->
### Maintainer current-main requalification
Exact head `545c18c771817cd97f4f9f716714161bb0ce3b6c`, upstream main
`c01cf07d943d816cfd9d97e6838ed4e38f1ff9a4`.
Clean mechanical synchronization with upstream main
|
||
|
|
47f8710817 |
refactor(transforms): drop the Python mirror of the Rust search selector (#4103)
## Description
`SearchCompressor.compress()` runs entirely in Rust. The class still
carried a Python re-implementation of the scorer, selector and
formatter, plus a parser wrapper, kept only so old tests could call
them. Production never ran them, and the module's own docstring noted
the Python error-boost keywords had drifted from Rust. All removed names
are private (leading underscore).
Refs #4136
## Type of Change
- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [x] Code refactoring (no functional changes)
## Changes Made
- Remove `_parse_search_results`, `_score_matches`, `_select_matches`,
`_format_output`, `_cjk_bigrams` and `_is_cjk_char`.
- Parser tests now call `headroom._core.parse_search_lines`, the live
Rust parser, through a small test helper.
- These tests are converted to `compress()`-level tests, because Rust
only unit-tests error boosting and bigram extraction: context-word
overlap, error/warning/TODO boost, `context_keywords`, the short-word
filter, `boost_errors=False`, the CJK query bigram boost, and the
combined parse/score/select/format test.
- `test_score_capped_at_one` is dropped: the cap cannot be observed
through `compress()`.
- The `_cjk_bigrams` unit test is dropped: Rust covers it in
`cjk_bigrams_from_runs`.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed
### Test Output
```text
$ pytest tests/test_search_compressor.py tests/test_transforms_search_compressor.py tests/test_search_compressor_cjk.py tests/test_ccr_rust_marker_hash_bridge.py tests/test_transforms_content_router.py tests/test_error_detection.py tests/test_signals_keyword_parity.py
170 passed in 7.31s
$ ruff check / format: All checks passed; mypy search_compressor.py: Success
```
## Real Behavior Proof
- Environment: macOS, Python 3.12, repo `.venv`, this branch's worktree
with the prebuilt `headroom._core`. Temp `HOME`,
`HEADROOM_WORKSPACE_DIR` and `CODEX_HOME`; nothing touched the real
home.
- Exact command / steps: (1) shared smoke harness: a real proxy from
this checkout against a local fake upstream, with one Anthropic and one
OpenAI request carrying a compressible tool result (`smoke.sh
<worktree>`); (2) a real `SearchCompressor.compress()` keeping one match
per file, with a CJK query whose bigrams match only one row.
- Observed result: The proxy serves both requests (200) with the same
savings as main. The direct check keeps the CJK row ranked first by the
Rust scorer. Output below.
- Not tested: Nothing beyond the listed files.
```text
branch: cleanup/transforms-search-drop-python-mirror @
|
||
|
|
f3f2e0077a |
fix(search): stop a context line's body from becoming its line marker (#3788)
## Description Closes #3545 I could not reproduce the exact `Line 476: … 497: 535: 556: …` output in the report, and I think the reason is worth stating up front, because it changes what this PR does. That shape cannot come out of the search compressor. `parse_match_line` splits **one input line at a time**, and `format_output` emits **one match per line**, so no code path can move line 497's number onto line 476's body. Feeding the shipped build a body that genuinely contains those numbers reproduces the reported string exactly: ``` input app/settings.py:476:settings: settings({contact_precedence: 497: 535: 556: app/settings.py:497:... app/settings.py:535:... app/settings.py:556:... output app/settings.py:476:settings: settings({contact_precedence: 497: 535: 556: [... and 3 more matches in app/settings.py] ``` — i.e. the numbers were part of line 476's own content all along, and 497/535/556 were dropped as ordinary matches. `Line N:` rows are not parsed as matches at all and pass through untouched, which matches @TigerkidYang's finding on `main`. **But the class of bug the issue is about is real, and it is in the parser.** Here is the same failure with different numbers, on a shape that grep emits routinely — a `-`-separated *context* line (`path-line-content`) whose body carries a whitespace-free `name:N:` reference: ``` input app/settings.py-476-a:7:b:8:c parsed ("app/settings.py-476-a", 7, "b:8:c") correct ("app/settings.py", 476, "a:7:b:8:c") ``` Three separate falsehoods in one row: 1. the path swallows the real `-476-` marker and invents `app/settings.py-476-a`, a file that does not exist; 2. **the reported line number is the body's `7`, not the row's `476`** — this is the manufactured line↔content association the issue is about; 3. the body is truncated to `b:8:c`. Worse, the bogus path becomes the grouping key in `parse_search_results`, so every match in that file is filed under a nonexistent path. This is not speculative. On the shipped `headroom-ai==0.38.0` build, over a generated corpus of tricky paths/line numbers/bodies: ``` $ uv run --with headroom-ai==0.38.0 python probe_parse.py checked 2394 colon-form rows; 0 mismatched dash-form mismatches: 279 ``` `path:line:content` (match lines — the dominant shape) is clean. Every one of the 279 failures is a `path-line-content` context line with a whitespace-free `name:N:` in its body. ### Root cause `parse_match_line` tries the **colon tier first** and it commits unconditionally on the first `:\d+:` whose prefix has no whitespace. Its own doc comment (search_compressor.rs:646-651) claims: > The no-whitespace guard keeps a `foo.rs:12:` reference *inside the body* of a > `-`-separated context line from hijacking the parse. The guard only holds when the body happens to contain whitespace ahead of the reference. `a:7:b` has none, so the colon tier takes it, and the dash tier — which reads the row correctly — is never consulted. ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - `crates/headroom-core/src/transforms/search_compressor.rs` - `parse_match_line` now hands priority back to the dash tier for exactly one shape: the dash tier *positively confirmed* a boundary that sits before the colon marker, **and** nothing path-like (separator or extension dot) lies between the two. The colon triplet is then body text, not a marker. - The colon tier keeps priority everywhere else, so `path:line:content` rows and rows whose **path** holds the dash triplet are untouched — `logs/2026-05-03/app.log:12:ERROR` and `migrations/20240101-002-add_users.sql:12:SELECT` still resolve correctly, because the dash tier never confirmed a boundary there. - `scan_match_line` becomes `scan_marker`, returning the marker it settled on **plus a flag** for whether that marker was a confirmed boundary (`chosen`) or merely the leftmost fallback (`first`). The caller needs that proven-vs-guessed distinction; it is the whole safety condition. - Doc comment updated — it previously asserted a guarantee the code did not provide. - New unit test `dash_context_line_wins_over_a_colon_marker_in_its_body`. - `tests/test_search_compressor.py`: new `TestContextLineBodyReference` class (4 tests) covering the repro, the extension-less path variant, the must-not-regress colon row with a dated path, and a 12-row sweep asserting every surviving coordinate and body. **Deliberately not changed:** the `Dockerfile-3-1-` shape is genuinely ambiguous in text (`Dockerfile-3` line 1, or `Dockerfile` line 3) and keeps its existing reading. The dash tier's comments already document that trade-off, and this PR does not widen or narrow it. ## Testing - [x] New tests added for new functionality - [ ] Unit tests pass (`pytest`) — see the note below - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [x] Manual testing performed — against the shipped wheel and a compiled harness **Why `pytest` is unticked:** the Python tests need the compiled `headroom._core` extension, which requires a checkout of the repo. I worked remote-only, so I could not run them. I validated every assertion they make by running the identical expectations as a Rust test against the patched parser (below, case `python_test_expectations`) — but that is not the same as having run pytest, and I would rather say so than imply otherwise. The Rust unit test in the crate is exercised by the repo's `cargo` CI. I also could not run the 8 crate-level tests that need the compressor types (`select_respects_per_file_cap_and_global_cap`, the four `ccr_*` tests, etc.). They are untouched by this diff and CI will run them. ### Rust: the parser compiled and run for real The parser is self-contained, so I extracted the functions I touched plus all 20 parser-only tests **verbatim** from the patched file and compiled them with the real toolchain (rustc 1.93.1, `--target x86_64-pc-windows-gnu`; the repo pins 1.95.0 in `rust-toolchain.toml`): ``` $ rustc --test --edition 2021 --target x86_64-pc-windows-gnu -o parser_harness.exe parser_harness.rs $ ./parser_harness.exe running 20 tests test tests::dash_context_line_wins_over_a_colon_marker_in_its_body ... ok test tests::body_line_reference_does_not_hijack_a_context_line ... ok test tests::dash_tier_does_not_run_past_the_path_into_the_body ... ok test tests::date_stamped_path_is_not_misread_as_line_number_marker ... ok test tests::dated_path_inside_a_context_body_is_not_hijacked ... ok test tests::parses_context_line_for_extensionless_path ... ok test tests::fixed_in_3e2_handles_windows_path_with_backslash ... ok test tests::ambiguous_dash_line_falls_back_to_the_leftmost_marker ... ok ... test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out ``` With **only** `parse_match_line` reverted to the pre-fix three-tier chain and nothing else changed, the new test fails exactly as the bug predicts: ``` thread 'tests::dash_context_line_wins_over_a_colon_marker_in_its_body' panicked: left: Some(("app/settings.py-476-a", 7, "b:8:c")) right: Some(("app/settings.py", 476, "a:7:b:8:c")) test result: FAILED. 19 passed; 1 failed; 0 ignored ``` All 19 pre-existing parser tests still pass in both runs — dated paths, CVE paths, Windows drive letters, dashes in filenames, the ambiguous fallback, the `foo.rs:12:`-with-whitespace case, and CJK. ### Rust: blast radius over a generated corpus I also transcribed the tier logic and diffed current-order vs patched-order across `19 paths × 9 line numbers × 17 bodies` in both separators: ``` colon-form (2907 rows): current-order wrong=0 patched wrong=0 dash-form (2907 rows): current-order wrong=612 patched wrong=153 ``` All 153 remaining are the single `Dockerfile-3` path, and they are **identical before and after** — the documented ambiguity, unchanged. Every unambiguous mis-parse is fixed and no colon-form row changes. ### Lint / format ``` $ uv run --with "ruff==0.16.8" ruff check --line-length 100 --target-version py310 \ --select E,W,F,I,B,C4,UP --ignore E501,B008,B905 tests/test_search_compressor.py All checks passed! $ uv run --with "ruff==0.16.8" ruff format --check --line-length 100 \ --target-version py310 tests/test_search_compressor.py 1 file already formatted $ rustfmt --edition 2021 --check crates/headroom-core/src/transforms/search_compressor.rs (no diff; exit 0) ``` ## Real Behavior Proof - Environment: Windows, Python 3.13.15, rustc 1.93.1. No repo checkout for this branch (remote-only contribution), so no end-to-end proxy run and no `cargo test` on the full crate. - Exact command / steps: `uv run --with headroom-ai==0.38.0 python probe_parse.py` against the shipped compiled parser, then `rustc --test --edition 2021 --target x86_64-pc-windows-gnu -o parser_harness.exe parser_harness.rs` on the patched parser extracted verbatim, then `./parser_harness.exe`. Both command sets are quoted in full under *Testing*. - Observed result: the defect reproduces in the **shipped** build — `parse_search_lines("app/settings.py-476-a:7:b:8:c")` returns `("app/settings.py-476-a", 7, "b:8:c")`, i.e. a wrong line number (7 for 476), a path that does not exist, and a truncated body. Over a generated corpus it reports `checked 2394 colon-form rows; 0 mismatched` / `dash-form mismatches: 279`. After the change the same input returns `("app/settings.py", 476, "a:7:b:8:c")` and the harness reports `20 passed; 0 failed`, with the 19 pre-existing parser tests still green. - Not tested: the full `cargo test` suite for the crate; the 8 crate-level compressor tests that need the compressor types; `pytest` (needs the built Rust extension); a live proxy request carrying a context line; ripgrep `-C` output end-to-end through the proxy. If you want the last row closed before merge, the check is a `grep -rn -C2` whose context lines contain a `name:N:` reference, run through `headroom compress` — the parsed coordinates should be the row's own. ## Runtime Rollout Safety - Rollout-managed feature(s): none. - Minimum rollout channel: the change is in the Rust core, so it ships with the next wheel. - Stable/default behavior changed: yes, for one input shape only. Rows that previously mis-parsed now parse correctly; every other row is byte-identical (0 changes across 2907 colon-form rows, and the only changed dash-form rows are the 459 that were wrong). - Kill switch / disable path: revert this commit. - Unsafe override required: none. - Qualification impact: none. No config, flag, or metric changes. - Rollback path: revert; the mis-parse returns. ## 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 commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [ ] New and existing unit tests pass locally with my changes — see *Testing* - [x] I did **not** edit `CHANGELOG.md` ## Additional Notes - **On the report itself:** if you can still get the original failure, the raw tool result as your harness delivered it (plus `headroom inspect --last 1`) is what would settle it. My working theory is the `grep_numbers_in_content` case above — the numbers were in line 476's own content and 497/535/556 were dropped as ordinary matches, which reads exactly like fusion. If the raw result shows a genuinely different transform (e.g. `smart_crusher` / `text_block`), this fix will not address it and the issue should stay open on that thread. - The parser is a deliberate three-tier design with carefully documented trade-offs, so I kept the change to a single override condition rather than reordering the tiers. Reordering outright is the obvious alternative and it **regresses** real rows — `logs/2026-05-03/app.log:12:ERROR` and `migrations/20240101-002-add_users.sql:12:SELECT` both break — which is why the override is gated on a *confirmed* dash boundary. - The `chosen.is_some()` flag is the safety property: the permissive tier's leftmost fallback never counts as a confirmed boundary, so a line the parser merely guessed at keeps today's behaviour. - The sibling defect raised in this thread (Kompress dropping ` or ` from code) was already fixed by #3687, so it is out of scope here. --------- Co-authored-by: JD Davis <mxjerrett@gmail.com> |
||
|
|
d3298368bf |
fix: improve error handling and add comprehensive test coverage
Bug fixes: - Replace bare except handlers with specific exception types and logging in proxy/server.py (6 instances for CCR, SSE parsing, cost tracking) - Fix session_id filtering security bug in memory/backends/local.py (sessions were not properly isolated in vector search) New tests (344 total): - test_ccr_batch_processor.py: 51 tests for batch result processing - test_compression_store.py: 76 tests for compression cache - test_log_compressor.py: 47 tests for log format detection/compression - test_search_compressor.py: 48 tests for grep output compression - test_integrations/langchain/: 122 tests for LangChain integration (agents, memory, retriever, streaming) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> |