headroom/tests/test_content_router_single_item_deadline.py
Rod Boev 5bd2266f16
fix(kompress): raise the default execution-slot wait (#2456)
## Description

Concurrent Kompress requests currently fail open after a 25 ms
execution-slot wait even though ordinary ONNX inference can hold the
single slot for hundreds of milliseconds. This raises the existing
default wait to 3000 ms while retaining concurrency one, the
`HEADROOM_KOMPRESS_EXECUTION_TIMEOUT_MS` override, the tighter acquire
and request budgets, and passthrough after a genuine timeout.

The reproduction and validated 3000 ms setting come from
https://github.com/headroomlabs-ai/headroom/issues/2451

Closes #2451

## 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

- Raise the default Kompress execution-slot wait from 25 ms to 3000 ms.
- Start the Kompress request deadline at call entry and carry it through
single-item acquire, single-to-batch delegation, and sequential-fallback
lineage.
- Cap the raised execution-slot wait by that live request deadline on
both single-item and batch acquire paths.
- Keep the per-backend default concurrency at one and preserve all
tighter time budgets.
- Add queued single-item, batch, request-deadline, carried-deadline
lineage, and router-watchdog lifecycle regressions at the same owner
layer that currently fails.
- Preserve the explicit short-timeout fail-open path.

## Testing

- [x] Unit tests pass (`uv run pytest tests/test_kompress_failsafe.py
tests/test_kompress_request_nonblocking.py
tests/test_content_router_single_item_deadline.py
tests/test_transforms/test_kompress_deadline.py -v`)
- [x] Linting passes (`uv run ruff check
headroom/transforms/kompress_compressor.py
tests/test_kompress_failsafe.py
tests/test_content_router_single_item_deadline.py
tests/test_transforms/test_kompress_deadline.py`)
- [x] Formatting passes (`uv run ruff format
headroom/transforms/kompress_compressor.py
tests/test_kompress_failsafe.py
tests/test_content_router_single_item_deadline.py
tests/test_transforms/test_kompress_deadline.py --check`)
- [x] New regression tests prove the saturation fix
- [ ] Manual testing performed

### Test Output

```text
uv run pytest tests/test_kompress_failsafe.py tests/test_kompress_request_nonblocking.py tests/test_content_router_single_item_deadline.py tests/test_transforms/test_kompress_deadline.py -v
37 passed in 4.22s

uv run ruff check headroom/transforms/kompress_compressor.py tests/test_kompress_failsafe.py tests/test_content_router_single_item_deadline.py tests/test_transforms/test_kompress_deadline.py
All checks passed!

uv run ruff format headroom/transforms/kompress_compressor.py tests/test_kompress_failsafe.py tests/test_content_router_single_item_deadline.py tests/test_transforms/test_kompress_deadline.py --check
4 files already formatted
```

## Real Behavior Proof

- Environment: worktree Python environment from `uv sync --extra dev`,
focused pytest with real Python threads and `threading.BoundedSemaphore`
- Exact command / steps: hold the sole execution slot with the
environment override unset, start queued single-item and batch
compression workers, wait until each worker proves it reached a blocked
acquire on the shared execution semaphore, release the slot, rerun the
explicit 1 ms timeout preservation case, then set
`HEADROOM_COMPRESSION_DEADLINE_MS=10` and repeat the held-slot
single-item and batch acquires plus a router single-cache-miss run whose
Kompress load sleeps past the request deadline.
- Observed result: The queued single-item and batch workers each proved
a real blocked acquire before release, then acquired after release and
compressed, while `HEADROOM_KOMPRESS_EXECUTION_TIMEOUT_MS=1` still
passed through promptly, the 10 ms request deadline capped the raised
default wait so both held-slot paths failed open before 200 ms without
reaching model inference, the single-to-batch and sequential-fallback
lineage regressions proved later branches inherit the original request
start instead of resetting it, and the router lifecycle proof showed the
carried deadline now allows slow Kompress load to start but still
expires before model inference after the outer request has already
failed open.
- Not tested: live ONNX proxy savings under sustained concurrent load

## 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] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective
- [x] New and existing unit tests pass locally with my changes
- [x] I have updated the CHANGELOG.md if applicable

## Additional Notes

`CHANGELOG.md` stays unchanged because the release pipeline generates
changelog entries from conventional commits. The fail-open path from
#1430 stays intact; this change stops it from firing spuriously under
ordinary queueing.
2026-07-22 06:17:33 -07:00

184 lines
5.4 KiB
Python

from __future__ import annotations
import time
import headroom.transforms.kompress_compressor as kc
from headroom.transforms.content_detector import ContentType
from headroom.transforms.content_router import (
CompressionStrategy,
ContentRouter,
ContentRouterConfig,
RouterCompressionResult,
RoutingDecision,
)
from headroom.transforms.kompress_compressor import KompressCompressor, KompressConfig
class _Tokenizer:
def count_text(self, content: str) -> int:
return len(content.split())
def _compression_result(content: str, compressed: str) -> RouterCompressionResult:
return RouterCompressionResult(
compressed=compressed,
original=content,
strategy_used=CompressionStrategy.TEXT,
routing_log=[
RoutingDecision(
content_type=ContentType.PLAIN_TEXT,
strategy=CompressionStrategy.TEXT,
original_tokens=len(content.split()),
compressed_tokens=len(compressed.split()),
)
],
)
def _router() -> ContentRouter:
return ContentRouter(
ContentRouterConfig(
protect_recent_code=0,
protect_analysis_context=False,
skip_user_messages=False,
)
)
def _messages() -> list[dict[str, str]]:
return [
{"role": "assistant", "content": "frozen prefix content remains unchanged"},
{
"role": "assistant",
"content": "pending cache miss content takes the inline compression branch today",
},
]
def test_single_cache_miss_fails_open_at_deadline(monkeypatch, caplog):
router = _router()
def slow_compress(content, *, context="", bias=1.0):
time.sleep(0.2)
return _compression_result(content, "compressed output")
monkeypatch.setattr(router, "compress", slow_compress)
monkeypatch.setenv("HEADROOM_COMPRESSION_DEADLINE_MS", "10")
started = time.perf_counter()
result = router.apply(
_messages(),
_Tokenizer(),
frozen_message_count=1,
min_tokens_to_compress=1,
)
assert time.perf_counter() - started < 0.12
assert result.messages[1]["content"] == _messages()[1]["content"]
assert "failing open via PASSTHROUGH" in caplog.text
def test_single_cache_miss_preserves_under_deadline_output(monkeypatch):
router = _router()
monkeypatch.setattr(
router,
"compress",
lambda content, *, context="", bias=1.0: _compression_result(content, "compressed output"),
)
monkeypatch.setenv("HEADROOM_COMPRESSION_DEADLINE_MS", "1000")
result = router.apply(
_messages(),
_Tokenizer(),
frozen_message_count=1,
min_tokens_to_compress=1,
)
assert result.messages[1]["content"] == "compressed output"
def test_single_cache_miss_preserves_disabled_deadline(monkeypatch):
router = _router()
monkeypatch.setattr(
router,
"compress",
lambda content, *, context="", bias=1.0: _compression_result(content, "compressed output"),
)
monkeypatch.setenv("HEADROOM_COMPRESSION_DEADLINE_MS", "0")
result = router.apply(
_messages(),
_Tokenizer(),
frozen_message_count=1,
min_tokens_to_compress=1,
)
assert result.messages[1]["content"] == "compressed output"
def test_single_cache_miss_deadline_starts_before_kompress_load(monkeypatch, caplog):
router = _router()
class _Encoding(dict):
def __init__(self, rows: list[list[str]]):
super().__init__(
input_ids=[[0] * len(row) for row in rows],
attention_mask=[[1] * len(row) for row in rows],
)
self._rows = rows
def word_ids(self, batch_index: int = 0):
return list(range(len(self._rows[batch_index])))
class _Tokenizer:
def count_text(self, content: str) -> int:
return len(content.split())
def __call__(self, words, **_kwargs):
rows = words if words and isinstance(words[0], list) else [words]
return _Encoding(rows)
class _Model:
def __init__(self):
self.calls = 0
def get_keep_mask(self, input_ids, attention_mask):
self.calls += 1
return [[i % 2 == 0 for i in range(len(row))] for row in input_ids]
model = _Model()
compressor = KompressCompressor(config=KompressConfig(enable_ccr=False))
monkeypatch.setattr(compressor, "_should_batch_single_content", lambda *a, **k: False)
load_state = {"calls": 0}
def _slow_load(*_args, **_kwargs):
load_state["calls"] += 1
time.sleep(0.05)
return model, _Tokenizer(), "onnx"
monkeypatch.setattr(kc, "_load_kompress", _slow_load)
monkeypatch.setattr(
router,
"compress",
lambda content, *, context="", bias=1.0: _compression_result(
content,
compressor.compress(content).compressed,
),
)
monkeypatch.setenv("HEADROOM_COMPRESSION_DEADLINE_MS", "10")
started = time.perf_counter()
result = router.apply(
_messages(),
_Tokenizer(),
frozen_message_count=1,
min_tokens_to_compress=1,
)
elapsed = time.perf_counter() - started
time.sleep(0.1)
assert elapsed < 0.12
assert result.messages[1]["content"] == _messages()[1]["content"]
assert "failing open via PASSTHROUGH" in caplog.text
assert load_state["calls"] == 1
assert model.calls == 0