Files
headroom/tests/test_search_compressor_cjk.py
Tejas Chopra 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 @ 0384d610
health: 200
POST /v1/messages        -> HTTP200 smoke-ok
POST /v1/chat/completions -> HTTP200 smoke-ok
stats: requests=2 failed=0 tokens_saved=13574 savings_percent=99.82
proxy.log WARNING/ERROR lines ($SMOKE/ws/logs/proxy-51340.log):
   2 headroom.proxy - WARNING - event=proxy_offline_mode air-gap active — every connection Headroom initiates is refused (telemetry, update check, license reporter, model/tokenizer/binary/dataset downloads, remote Kompress, OTLP/Langfuse export, Copilot auth, subscription polling, OpenAI embedders, Headroom Cloud compression). Still allowed on purpose: forwarding your requests to the upstream you configured, operator-configured local endpoints, loopback health probes.
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch found no usable file for chopratejas/kompress-v2-base
   4 headroom.transforms.kompress_compressor - WARNING - Kompress: artifact prefetch refused for chopratejas/kompress-v2-base (HEADROOM_OFFLINE is set): HEADROOM_OFFLINE is set: refusing outbound network access for HuggingFace download of chopratejas/kompress-v2-base/onnx/kompress-int8-wo.onnx to huggingface.co. Unset HEADROOM_OFFLINE, or turn off the feature that needs this connection.
(smoke dir: $SMOKE)
```

```text
$ python -c "<SearchCompressor(max_matches_per_file=1, ...).compress(3 rows, context=CJK query)>"
src/a.py:20:认证令牌已过期需要重新登录
[... and 2 more matches in src/a.py]
```

## Runtime Rollout Safety

- Rollout-managed feature(s): None.
- Minimum rollout channel: Not applicable; no rollout-managed behaviour
is touched.
- Stable/default behavior changed: No. Only unused private methods are
removed.
- Kill switch / disable path: Not applicable; nothing that runs changes.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this single commit.

## 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
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

Not applicable.

## Additional Notes

Part of maintainer-requested cleanup #4136 (dead code, duplication,
debuggability), split into small PRs for review.

Documentation changes are not in this PR. They are recorded in the
cleanup docs ledger for the single follow-up docs PR.

`adaptive_sizer.py` stays. The log-mirror PR still needs it until both
PRs land, and then it can go in a one-file follow-up.
`error_detection.PRIORITY_PATTERNS_SEARCH` is now unused in product code
but is in an `__all__`, so it is left for a later deprecation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-10-10 08:59:40 -07:00

41 lines
1.6 KiB
Python

"""CJK-aware relevance scoring in the search compressor.
The relevance scorer tokenized the query on whitespace, so a spaceless CJK query
matched content only when the WHOLE query was a literal substring of a line. CJK
char bigrams now let a longer CJK query boost lines that share a substring.
Bigram extraction itself is unit-tested in Rust (``cjk_bigrams_from_runs``);
this pins the end-to-end ranking through ``compress()``.
"""
from headroom.transforms.search_compressor import (
SearchCompressor,
SearchCompressorConfig,
)
def test_cjk_query_bigrams_boost_ranking():
# Keep only the top-scored match per file, so the output shows the ranking.
compressor = SearchCompressor(
SearchCompressorConfig(
max_matches_per_file=1,
always_keep_first=False,
always_keep_last=False,
boost_errors=False,
context_keywords=[],
enable_ccr=False,
)
)
content = "\n".join(
[
"src/a.py:10:plain ascii content here",
"src/a.py:20:认证令牌已过期需要重新登录",
"src/a.py:30:more plain content",
]
)
# The whole query is NOT a substring of the CJK line, but its bigrams are.
result = compressor.compress(content, context="认证令牌缓存淘汰策略")
assert result.compressed.startswith("src/a.py:20:认证令牌已过期需要重新登录")
# Without a matching query the earliest line wins the tie.
baseline = compressor.compress(content, context="缓存淘汰策略")
assert baseline.compressed.startswith("src/a.py:10:plain ascii content here")