headroom/tests/test_transforms/test_kompress_deadline.py
Zhenjia ZHOU 6c68ff4e9f
perf(compression): take large cold-start contexts off the synchronous kompress path (#1171) (#1298)
## Description

On a cold-start large context, kompress (ModernBERT ONNX) runs
**synchronously on the request thread** — ~200–300s for ~1M tokens. It
blows the 30s compression budget, leaks a non-preemptible worker, and
cascades (executor saturation → queue timeouts on healthy requests); on
timeout the request is forwarded **uncompressed** after eating 30s. This
adds four layered, **default-off, fail-open** mitigations so the request
path is never blocked on ML compression.

Closes #1171

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [x] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- **Phase 0 — size gate** (`HEADROOM_KOMPRESS_MAX_TOKENS`, default
50000): route oversized text away from ModernBERT (→ LogCompressor /
TextCrusher / passthrough) at the single `_try_ml_compressor` boundary.
- **Phase 1 — cooperative deadline**
(`HEADROOM_COMPRESSION_DEADLINE_MS`, default 20000): any kompress run
self-terminates at the next chunk boundary past the budget, keeping the
unprocessed tail verbatim.
- **Phase 2 — TextCrusher** (`HEADROOM_TEXT_CRUSHER`): a new **native
Rust** extractive prose compressor in
`crates/headroom-core/src/transforms/text_crusher/`, exposed via PyO3 as
`headroom._core.TextCrusher` with a thin Python wrapper. It **reuses the
shared `crate::relevance::BM25Scorer`** rather than reimplementing BM25,
and ships record/replay parity fixtures (mirroring the SmartCrusher
Rust-core + Python-shim pattern).
- **Phase 3 — off-path compression**
(`HEADROOM_BACKGROUND_COMPRESSION`): forward uncompressed immediately
and compress in a per-process background drain; a byte-identical cache
hit on a later turn means the request never blocks on ML.
- Benchmark (`benchmarks/text_crusher_quality_eval.py`), CHANGELOG
entry, and docstrings documenting the fail-open limits.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check`)
- [x] Type checking passes (`mypy`, new modules)
- [x] New tests added for new functionality
- [ ] Manual testing performed (Phase 0/1 gate-fire + deadline observed
on real traffic in earlier iterations; Phase 3 off-path is unit- +
byte-identity-tested, not yet live-validated)

### Test Output

```text
$ pytest tests/test_transforms/ tests/test_cache/ \
    tests/test_proxy/test_background_compression.py tests/test_proxy/test_phase3_byte_identity.py -q
501 passed, 37 skipped in 40.33s

$ cargo test -p headroom-core --lib text_crusher
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 834 filtered out

$ ruff check <changed files>
All checks passed!

$ mypy headroom/proxy/background_compression.py headroom/transforms/text_crusher.py
Success: no issues found in 2 source files
```

New coverage: size-gate incl. the strategy-dispatch funnel (KOMPRESS +
TEXT); partial-run deadline (chunk-0 compressed + chunk-1 verbatim
tail); BackgroundCompressor (dedup / queue-full / fail-open); Phase 3
byte-identity round-trip; TextCrusher unit + parity.

## Real Behavior Proof

- Environment: macOS, local dev — `uv` venv, Rust `_core` built via `uv
pip install -e .`.
- Exact command / steps: the `pytest` / `cargo test` / `ruff` / `mypy`
commands shown under Test Output; quality eval `python
benchmarks/text_crusher_quality_eval.py /tmp/squad_dev.json`.
- Observed result: 501 Python + 3 Rust tests pass; ruff + mypy clean on
changed/new modules. Quality eval: TextCrusher keeps ~94% of buried
SQuAD answers at 30% size vs ~36% truncate/random; self-contained speed
run ~333k words in ~76ms (one O(n) pass) — sub-second where ModernBERT
takes minutes (fast-vs-slow contrast, not a same-input run).
- Not tested: Phase 3 off-path on live traffic; multi-worker
(per-process by design — see Additional Notes).

## 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] 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 have updated the CHANGELOG.md if applicable

## Additional Notes

- **All four features are off by default and fail-open** — with the env
flags unset the paths are no-ops for realistic inputs; on any error the
request is forwarded (compressed if possible, else verbatim), never
dropped. A full background queue / duplicate key surfaces as
`deferred:dropped`.
- **Known limits (documented in `background_compression.py`):** Phase 3
is per-process, in-memory, and token-mode-only — these are
**lost-savings, never lost-correctness**, and consistent with the
project's existing per-process compression cache + sticky-session
multi-worker model. The startup multi-worker warning now names off-path
background compression.
- Phase 2 reuses the existing BM25 scorer; reuse did not improve
answer-retention over a Python prototype (query-awareness dominates) —
its value is the Rust speed + repo-conventional Rust-core/Python-shim
shape.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 10:48:06 -05:00

82 lines
3.6 KiB
Python

"""Phase 1 (#1171): kompress cooperative chunk-boundary deadline.
Kompress ONNX inference is O(tokens) and non-preemptible once the request's
asyncio timeout fires, so one large block can run for minutes holding a worker
(the leak -> executor-saturation -> queue-timeout cascade). compress() checks a
wall-clock budget at each chunk boundary and, when over, keeps the unprocessed
tail verbatim and returns -- a partial compression that returns now beats a full
one that leaks.
"""
from __future__ import annotations
from headroom.transforms import kompress_compressor as kc
def test_compress_bails_at_deadline_keeping_tail_verbatim(monkeypatch):
# Fake clock: the pre-loop stamp reads 0s, the first loop-top check reads
# 999s elapsed -> deadline trips on chunk 0 before any model/tokenizer use.
clock = iter([0.0] + [999.0] * 50)
monkeypatch.setattr(kc.time, "perf_counter", lambda: next(clock))
monkeypatch.setattr(kc, "_load_kompress", lambda *a, **k: (object(), object(), "onnx"))
monkeypatch.setenv("HEADROOM_COMPRESSION_DEADLINE_MS", "20000")
comp = kc.KompressCompressor()
monkeypatch.setattr(comp, "_should_batch_single_content", lambda *a, **k: False)
content = " ".join(f"w{i}" for i in range(1000))
result = comp.compress(content)
# Deadline tripped on the first chunk -> nothing dropped, tail kept verbatim.
assert result.compressed_tokens == 1000
assert result.compressed.split() == content.split()
def test_compress_partial_run_keeps_processed_head_plus_verbatim_tail(monkeypatch):
# The real partial case: chunk 0 processes (gets compressed), chunk 1 trips
# the deadline (kept verbatim). Output must be compressed-head + verbatim-tail.
# Clock: call1=t_deadline(0); calls 2-4 are chunk-0's check+inference reads
# (under budget); call 5+ is chunk-1's check -> trips.
# Robust clock: jump past the deadline only AFTER chunk 0 is processed
# (tracked via the model mock), so adding perf_counter calls inside the chunk
# body -- e.g. sub-stage timing -- can't shift when the deadline trips.
state = {"chunks_done": 0}
def fake_clock():
return 999.0 if state["chunks_done"] >= 1 else 0.0
monkeypatch.setattr(kc.time, "perf_counter", fake_clock)
class _Enc(dict):
def word_ids(self, batch_index=0):
return self["_word_ids"]
class _Tok:
def __call__(self, chunk_words, **kw):
n = len(chunk_words)
return _Enc(input_ids=[[0] * n], attention_mask=[[1] * n], _word_ids=list(range(n)))
class _Model:
def get_keep_mask(self, input_ids, attention_mask):
n = len(input_ids[0])
mask = [[i < n // 2 for i in range(n)]] # keep first half of the chunk
state["chunks_done"] += 1 # after chunk 0, the clock trips the deadline
return mask
monkeypatch.setattr(kc, "_load_kompress", lambda *a, **k: (_Model(), _Tok(), "onnx"))
monkeypatch.setattr(kc, "_model_device_type", lambda *a, **k: "cpu")
monkeypatch.setenv("HEADROOM_COMPRESSION_DEADLINE_MS", "20000")
comp = kc.KompressCompressor()
comp.config.chunk_words = 10 # 20 words -> 2 chunks
monkeypatch.setattr(comp, "_should_batch_single_content", lambda *a, **k: False)
words = [f"w{i}" for i in range(20)]
out = comp.compress(" ".join(words)).compressed.split()
# chunk 0 processed: first half kept (w0..w4), second half dropped (w5..w9)
assert "w0" in out and "w4" in out
assert "w5" not in out and "w9" not in out
# chunk 1 tripped the deadline -> its words kept verbatim (w10..w19 all present)
for i in range(10, 20):
assert f"w{i}" in out