mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-08-27 14:17:10 -04:00
## Description Two related changes to the compression seams, plus the review fixes for both. Supersedes #2661 and #2662, which are closed in favour of this branch — the fixes are inseparable from the code they fix, so reviewing them together is cheaper than landing two PRs and patching them afterwards. **1. A registered lossless provider now competes on the general path.** The `headroom.transforms.lossless_provider` seam was only ever consulted from `_lossless_compact_excluded`, gated on `DEFAULT_EXCLUDE_TOOLS` (`config.py:216` — `Read/Grep/Glob/Write/Edit/WebSearch/WebFetch`). Gateway traffic carries the caller's own tool names — LiteLLM's `headroom` guardrail (https://docs.litellm.ai/docs/proxy/headroom) posts requests containing tools like `search_docs` / `run_ci` / `fetch_rows` — so a registered provider was structurally unreachable for every gateway/sidecar deployment. The seam existed; nothing could get to it. **2. `POST /v1/compress` is marker-free by default.** A CCR marker is only useful to a caller that also injects the `headroom_retrieve` tool AND can reach `/v1/retrieve`. Neither holds here: tool injection lives in the provider request handlers (`handlers/anthropic.py:1894`), never in `handle_compress`; and every `/v1/retrieve*` route is `Depends(_require_loopback)` (`server.py:4422, 4470, 4749, 4781`) with no remote opt-in — `HEADROOM_COMPRESS_ALLOW_REMOTE` drops the loopback dependency on `/v1/compress` only. So a gateway forwards a `Retrieve more: hash=…` pointer the model cannot follow, and the proxy pays a CCR store write nobody reads. `config.mode="ccr"` opts back in. Closes # ## Type of Change - [ ] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [x] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made ### Seam — `content_router.py`, `lossless_provider.py` - `_lossless_first` (STAGE 0, every block on every path) consults `get_lossless_provider()` and keeps whichever output is smaller. **Strict no-op when no provider is registered**, which is the default; and because it is best-of rather than authoritative, a provider can never do worse than the built-in folds. - Malformed provider output can no longer escape. Every shape check runs inside the `try`: result must be `None`, or a 2-element tuple/list of two `str`. Anything else is ignored at debug level. (Previously the unpack sat outside the `try`, so a 3-tuple raised `ValueError` up through `TransformPipeline.apply`, which re-raises.) - Empty / whitespace-only candidates are rejected rather than silently replacing block content. - **Providers are never offered diff content.** Diff folding is subtractive with no inverse check and a reflowed hunk breaks `git apply` — the same reason the built-in `diff` fold is restricted at `content_router.py:2481`. - The third-party `kind` label is sanitised against `^[a-z0-9_]{1,32}$` before reaching `transforms_applied` and the per-strategy metric dicts, so a caller-controlled string cannot explode Prometheus label cardinality. `fullmatch`, not `match`: `$` also matches before a trailing newline, which would put a newline in a label. - `set_lossless_provider(provider, *, verifier=None)` — in lossless-only mode, where STAGE 0's output is final and there is no marker to recover from, a registered verifier must confirm the fold or the candidate is dropped. No verifier registered = today's behaviour. `provider=None` clears both. - The provider is invoked once per block, not twice (`_has_lossless_fold` probes `_lossless_first` and discards the result, then STAGE 0 recomputes). Bounded memo, wholesale clear on overflow, no lock — a race costs one redundant fold. The memo keys on the provider registration generation, so registering or clearing a provider after a block was already folded takes effect. - The seam docstring now records that the provider runs on the general path and inside the parallel compression pool, so it must be thread-safe as well as deterministic. ### Route — `handlers/openai.py`, `server.py` - `_derived_compress_pipeline(key, **overrides)` replaces the copy-pasted pipeline-derivation block; `_no_ccr_pipeline` (the new default) and `_lossy_inline_pipeline` both use it. - The default pipeline is **built at startup** and included in `_eager_preload_transforms`, so a fresh pod does not pay ContentRouter construction and compressor load on its first request, inside the compression-executor budget. - An unrecognised `config.mode` returns 400 naming the valid values instead of silently falling back to the default. - Claude-family model names resolve their context limit from the Anthropic provider. Real divergence: `bedrock/anthropic.claude-3-5-sonnet` is 200000 there and 128000 on the OpenAI provider. The tokenizer still comes from the OpenAI pipeline's provider — a separate, larger change, noted in a comment. - Documents why the derived router deliberately does **not** share the base router's compression cache: keys do not encode CCR-marker mode, so sharing would leak marker-laden entries into the marker-free path. ### Behavior change A `/v1/compress` caller that relied on default markers now gets none. The only in-tree caller that can resolve them is the TypeScript SDK (`sdk/typescript/src/client.ts:398 retrieve`, `:422 handleToolCall`); it needs `config: {"mode": "ccr"}` to keep today's behaviour, and landing that SDK default in the same release would leave only gateway callers — for whom markers were never resolvable — seeing a difference. No `HEADROOM_COMPRESS_DEFAULT_MODE` compat env deliberately: a flag nobody sets becomes permanent debt, and the wire-level `mode` already covers the one caller that needs it. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [x] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ python -m pytest tests/test_lossless_first_dispatch.py tests/test_lossless_excluded_compaction.py \ tests/test_lossless_mode.py tests/test_lossless_then_lossy.py tests/test_lossless_diff_fold_guard.py \ tests/test_bash_search_lossless_fold.py tests/test_proxy_compress_endpoint.py \ tests/test_ccr_row_drop_store_bridge.py tests/test_gateway_sidecar_ports.py tests/test_compress_api.py \ tests/test_platform_stabilization_functional.py tests/test_proxy_eager_preload_bind.py \ tests/test_proxy_warmup.py tests/test_router_registry_smartcrusher.py -q 189 passed in 32.04s $ ruff check <all 9 changed files> All checks passed! $ ruff format --check <all 9 changed files> 9 files already formatted $ mypy headroom/transforms/content_router.py headroom/transforms/lossless_provider.py \ headroom/proxy/handlers/openai.py headroom/proxy/server.py Success: no issues found in 4 source files ``` New tests cover, one concern each: every malformed provider shape; empty and whitespace-only results; diff content never reaching a provider (call-recording); `kind` sanitisation including the trailing-newline case; the verifier accepting / rejecting / raising; clearing a provider clearing its verifier; single provider invocation per block; memo invalidation on re-registration; unknown and valid `mode` values; the default pipeline existing before any request; and Claude vs OpenAI context-limit resolution with `token_budget` precedence preserved. ## Real Behavior Proof - **Environment:** macOS arm64, Python 3.12.6, proxy built from `_proxy_config_from_env()` with the default `coding` savings profile; Kompress both disabled and offloaded to a remote `kompress-v2-base` endpoint; `HEADROOM_COMPRESSION_TIMEOUT_SECONDS=300`. - **Steps:** `POST /v1/compress` over `TestClient` with OpenAI-shaped payloads under non-excluded tool names (`run_ci`, `list_files`, `code_search`, `fetch_rows`) — a CI log with ANSI escapes and repeated lines, a 160-path listing, a 150-line grep dump, a 150-row JSON array; plus a second payload with a RAG user blob, a 200-row JSON tool result and a 300-line log. Ran with and without a provider registered via `set_lossless_provider`. - **Observed — seam reachability:** | Kompress | no provider registered | provider registered | |---|---|---| | off | 19,284 → 10,265 tokens (46.8%) | 19,284 → **7,879 (59.1%)** | | on (remote) | 19,284 → 9,366 tokens (51.4%) | 19,284 → **7,146 (62.9%)** | Before this change the right-hand column was identical to the left — the registered provider was never called on this payload. - **Observed — marker-free default costs nothing:** | Config | tokens | saved | |---|---|---| | markers on (previous default) | 37,791 → 24,415 | 35.4% | | markers off (new default) | 37,791 → 24,415 | **35.4% — identical** | | `mode="lossy_inline"` | 37,791 → 25,129 | 33.5% | | `--lossless` | 37,791 → 35,100 | 7.1% | - **Observed — memo staleness, before the fix:** registering a provider that folds a grep block to 5 bytes left the block at its 1496-byte built-in fold, and clearing a provider kept serving the provider's output. Both correct after keying on the registration generation. - **Observed — context limit:** `bedrock/anthropic.claude-3-5-sonnet` resolves 200000 via the Anthropic provider, 128000 via the OpenAI provider. - **Not tested:** `tests/test_transforms_content_router.py` was not run — it does not complete on this machine, wedging on its 5th test while that test passes in 5.7s alone. Verified pre-existing before this work: with the diff stashed, the clean tree stalled at the identical test, and it stalled the same way under `HF_HUB_OFFLINE=1 HEADROOM_OFFLINE=1`. The machine was also out of disk at the time, which may be the real cause rather than the suspected native-detector deadlock (#575) — worth a separate issue either way. CI should be the arbiter here. ## 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` ## Additional Notes Two pre-existing test files needed adjusting, both direct consequences rather than scope creep: - `test_platform_stabilization_functional.py::test_v1_compress_success_reports_actual_metrics` patches `openai_pipeline.apply`, which the default mode no longer routes through. **This test was already failing on the marker-free-default commit** before any of the fixes — my original test selection missed it. It now patches the pipeline the route actually uses. - `test_proxy_eager_preload_bind.py` substitutes fake pipelines to control exactly what the preload walks; the eager build injected the real derived router's statuses into an exact-equality assertion. Its shared helper now clears the derived cache, preserving each test's intent without weakening an assertion. Docs unchecked — follow-ups worth doing in the same release: document `config.mode` values in `docs/content/docs/litellm.mdx` and `wiki/proxy.md`; the TS SDK `mode:"ccr"` default; and an operational note that `COMPRESSION_TIMEOUT_SECONDS` defaults to 30 (`helpers.py:687`) while a remote ML endpoint makes one sequential call per unit — on a large payload it trips the executor timeout and the handler fails open, returning `compression_skipped: true` with `tokens_before: 0`, which reads as "nothing to save" rather than "we gave up". Those zeroed counters are misleading and worth a separate fix.
401 lines
15 KiB
Python
401 lines
15 KiB
Python
"""Lossless-first dispatch (intended design).
|
|
|
|
Lossless folds run FIRST for every tool-output block, regardless of the
|
|
``lossless`` flag, and are accepted on a real byte reduction even when the word
|
|
count is flat (the case the word-ratio gate used to reject). In lossless-only
|
|
mode (flag on, no CCR) foldable content folds and non-foldable content is left
|
|
verbatim (no lossy drop). In CCR mode (flag off) a foldable block still keeps
|
|
its byte-exact fold — the lossless floor is never discarded by a later lossy
|
|
stage.
|
|
"""
|
|
|
|
from headroom.transforms.content_router import (
|
|
CompressionStrategy,
|
|
ContentRouter,
|
|
ContentRouterConfig,
|
|
)
|
|
from headroom.transforms.lossless_compaction import search_unheading
|
|
from headroom.transforms.lossless_provider import (
|
|
get_lossless_provider,
|
|
get_lossless_verifier,
|
|
set_lossless_provider,
|
|
)
|
|
|
|
|
|
def _grep_block() -> str:
|
|
# Long, repeated path prefixes → search_heading collapses to --heading form.
|
|
# Word count stays flat/rises while bytes drop a lot (heading adds path words).
|
|
paths = [
|
|
"src/services/wallet/overdraft/automated_overdraft_initiation.py",
|
|
"src/services/wallet/overdraft/capacity_limits.py",
|
|
]
|
|
return (
|
|
"\n".join(
|
|
f"{p}:{ln}: result = compute_overdraft_capacity(business_id, amount)"
|
|
for p in paths
|
|
for ln in range(1, 40)
|
|
)
|
|
+ "\n"
|
|
)
|
|
|
|
|
|
def _code_block() -> str:
|
|
return (
|
|
"\n".join(
|
|
f" def method_{i}(self, arg_{i}):\n return self.reg[{i}] + arg_{i} * {i}"
|
|
for i in range(40)
|
|
)
|
|
+ "\n"
|
|
)
|
|
|
|
|
|
def _compress(content: str, *, lossless: bool):
|
|
router = ContentRouter(ContentRouterConfig(lossless=lossless))
|
|
tr: list[str] = []
|
|
out, was = router._compress_block_content(
|
|
content,
|
|
hash((content, lossless)),
|
|
"",
|
|
1.0,
|
|
1.0,
|
|
None,
|
|
tr,
|
|
{},
|
|
[],
|
|
"tool_result",
|
|
"tool",
|
|
True,
|
|
)
|
|
return out, was, tr
|
|
|
|
|
|
def test_flag_on_search_folds_lossless_byte_exact():
|
|
block = _grep_block()
|
|
out, was, tr = _compress(block, lossless=True)
|
|
assert was is True
|
|
assert tr == ["router:tool_result:lossless_search"]
|
|
assert len(out) < len(block)
|
|
# word count is flat/higher -> the old word-ratio gate would have rejected it
|
|
assert len(out.split()) >= len(block.split())
|
|
# fully recoverable
|
|
assert search_unheading(out) == block
|
|
|
|
|
|
def test_flag_on_search_fold_is_deterministic():
|
|
block = _grep_block()
|
|
out1, _, _ = _compress(block, lossless=True)
|
|
out2, _, _ = _compress(block, lossless=True)
|
|
assert out1 == out2 # pure function of content -> prefix-cache safe
|
|
|
|
|
|
def test_flag_on_leaves_non_foldable_code_verbatim():
|
|
# Lossless-only mode must never emit a lossy / marker-free drop.
|
|
out, was, tr = _compress(_code_block(), lossless=True)
|
|
assert was is False
|
|
assert tr == []
|
|
|
|
|
|
def test_flag_off_still_keeps_lossless_floor_for_foldable():
|
|
block = _grep_block()
|
|
out, was, tr = _compress(block, lossless=False)
|
|
assert was is True
|
|
assert tr == ["router:tool_result:lossless_search"]
|
|
assert search_unheading(out) == block
|
|
|
|
|
|
def test_has_lossless_fold_admits_small_block_below_size_floor():
|
|
# A <500-char search block must be admitted — lossless has NO size floor
|
|
# (the min_chars floor guards the lossy path only).
|
|
router = ContentRouter(ContentRouterConfig(lossless=True))
|
|
small = "\n".join(f"pkg/mod/long_filename.py:{n}:value = {n}" for n in range(1, 8)) + "\n"
|
|
assert len(small) < 500
|
|
assert router._has_lossless_fold(small) is True
|
|
# non-foldable tiny code must NOT be admitted (stays "small")
|
|
assert router._has_lossless_fold("def f():\n return 1\n") is False
|
|
|
|
|
|
def test_registered_provider_competes_on_the_general_path():
|
|
# A registered lossless provider must be consulted for ANY block, not only
|
|
# excluded-tool output — that gate made external folds inert for gateway
|
|
# traffic (/v1/compress), where tool names are the caller's own. The smaller
|
|
# output wins, so a provider can only improve on the built-in folds.
|
|
from headroom.transforms.lossless_provider import set_lossless_provider
|
|
|
|
block = _grep_block()
|
|
baseline, _, _ = _compress(block, lossless=True)
|
|
better = "SHORTER-THAN-ANY-BUILTIN-FOLD\n"
|
|
assert len(better) < len(baseline)
|
|
|
|
try:
|
|
set_lossless_provider(lambda content: (better, "plugin"))
|
|
out, was, tr = _compress(block + "\n", lossless=True) # fresh cache key
|
|
assert was is True
|
|
assert out == better
|
|
assert tr == ["router:tool_result:lossless_plugin"]
|
|
|
|
# A provider that loses to the built-in fold is ignored, not adopted.
|
|
set_lossless_provider(lambda content: (content + "padding" * 100, "plugin"))
|
|
out2, _, tr2 = _compress(block + "\n\n", lossless=True)
|
|
assert tr2 == ["router:tool_result:lossless_search"]
|
|
assert len(out2) < len(block)
|
|
|
|
# A raising provider must not break routing.
|
|
set_lossless_provider(_raise)
|
|
out3, was3, _ = _compress(block + "\n\n\n", lossless=True)
|
|
assert was3 is True
|
|
assert len(out3) < len(block)
|
|
finally:
|
|
set_lossless_provider(None)
|
|
|
|
|
|
def _raise(content: str):
|
|
raise RuntimeError("broken provider")
|
|
|
|
|
|
def test_lossless_mode_non_foldable_is_lossless_noop_not_ratio_too_high():
|
|
# In lossless-only mode, code with no byte-lossless fold is left verbatim.
|
|
# That is NOT a rejected compression, so it must not be bucketed as
|
|
# ratio_too_high (which means "a lossy attempt didn't shrink enough").
|
|
router = ContentRouter(ContentRouterConfig(lossless=True))
|
|
code = "\n".join(f" x{i} = compute_value({i}, offset={i * 3})" for i in range(60)) + "\n"
|
|
rc: dict = {}
|
|
out, was = router._compress_block_content(
|
|
code,
|
|
hash(code),
|
|
"",
|
|
1.0,
|
|
1.0,
|
|
None,
|
|
[],
|
|
rc,
|
|
[],
|
|
"tool_result",
|
|
"tool",
|
|
True,
|
|
)
|
|
assert was is False
|
|
assert rc.get("lossless_noop", 0) >= 1
|
|
assert rc.get("ratio_too_high", 0) == 0
|
|
|
|
|
|
# ── Hostile / third-party provider input ──────────────────────────────────────
|
|
# The provider is arbitrary out-of-tree code called on the request path, and
|
|
# `_lossless_first`'s caller (`TransformPipeline.apply`) re-raises. Nothing a
|
|
# provider returns may fail a request or silently destroy a block.
|
|
|
|
_SHORT = "SHORTER-THAN-ANY-BUILTIN-FOLD\n"
|
|
|
|
_MALFORMED_RESULTS = [
|
|
(_SHORT, "plugin", "extra"), # 3-tuple -> would raise on unpack
|
|
_SHORT, # bare string -> would unpack into 2 chars, or raise
|
|
(_SHORT, 42), # non-str kind
|
|
(42, "plugin"), # non-str candidate
|
|
{"compacted": _SHORT}, # non-tuple entirely
|
|
17, # not even iterable
|
|
]
|
|
|
|
|
|
def test_malformed_provider_result_is_ignored_not_raised():
|
|
block = _grep_block()
|
|
for i, bad in enumerate(_MALFORMED_RESULTS):
|
|
try:
|
|
set_lossless_provider(lambda content, bad=bad: bad)
|
|
# Distinct content per shape so nothing is served from a cache/memo.
|
|
out, was, tr = _compress(block + "\n" * (i + 1), lossless=True)
|
|
finally:
|
|
set_lossless_provider(None)
|
|
# No exception, and the built-in fold is still the answer.
|
|
assert was is True, bad
|
|
assert tr == ["router:tool_result:lossless_search"], bad
|
|
assert len(out) < len(block), bad
|
|
|
|
|
|
def test_empty_provider_result_is_rejected():
|
|
# "" beats every candidate on length, so an unchecked empty result would
|
|
# win and silently delete the block's content.
|
|
block = _grep_block()
|
|
for i, blank in enumerate(("", " ", "\n\t \n")):
|
|
try:
|
|
set_lossless_provider(lambda content, blank=blank: (blank, "plugin"))
|
|
out, was, tr = _compress(block + "x" * (i + 1) + "\n", lossless=True)
|
|
finally:
|
|
set_lossless_provider(None)
|
|
assert was is True, repr(blank)
|
|
assert tr == ["router:tool_result:lossless_search"], repr(blank)
|
|
assert out.strip(), repr(blank)
|
|
|
|
|
|
def test_provider_is_never_offered_diff_content():
|
|
# Diff folding is subtractive with no inverse check and a reflowed hunk
|
|
# breaks `git apply`, so a third-party fold must never see a diff — the
|
|
# same reason the built-in "diff" fold is strategy-gated.
|
|
diff = (
|
|
"diff --git a/x b/x\nindex 1111111..2222222 100644\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n"
|
|
)
|
|
router = ContentRouter(ContentRouterConfig(lossless=True))
|
|
baseline_diff = router._lossless_first(diff, CompressionStrategy.DIFF)
|
|
baseline_pass = router._lossless_first(diff, CompressionStrategy.PASSTHROUGH)
|
|
|
|
seen: list[str] = []
|
|
|
|
def recording(content: str):
|
|
seen.append(content)
|
|
return (_SHORT, "plugin")
|
|
|
|
try:
|
|
set_lossless_provider(recording)
|
|
fresh = ContentRouter(ContentRouterConfig(lossless=True))
|
|
# Both the DIFF strategy and diff-*shaped* content under another
|
|
# strategy must bypass the provider entirely.
|
|
assert fresh._lossless_first(diff, CompressionStrategy.DIFF) == baseline_diff
|
|
assert fresh._lossless_first(diff, CompressionStrategy.PASSTHROUGH) == baseline_pass
|
|
assert seen == []
|
|
finally:
|
|
set_lossless_provider(None)
|
|
|
|
|
|
def test_provider_kind_label_is_sanitized():
|
|
# `kind` reaches transforms_applied and the per-strategy metric/timing keys
|
|
# (Prometheus label values), so an unbounded caller-controlled string is a
|
|
# cardinality bomb. Only ^[a-z0-9_]{1,32}$ survives.
|
|
block = _grep_block()
|
|
# "log\n" is the subtle one: Python's `$` matches before a trailing newline,
|
|
# so a `re.match`-based check would let a newline into a metric label.
|
|
bogus = ["UPPER", "has space", "punct!", "x" * 200, "", "kebab-case", "log\n"]
|
|
for i, kind in enumerate(bogus):
|
|
try:
|
|
set_lossless_provider(lambda content, kind=kind: (_SHORT, kind))
|
|
out, was, tr = _compress(block + "\n" * (i + 1), lossless=True)
|
|
finally:
|
|
set_lossless_provider(None)
|
|
assert was is True, kind
|
|
assert out == _SHORT, kind
|
|
assert tr == ["router:tool_result:lossless_provider"], kind
|
|
|
|
# A clean label is preserved verbatim.
|
|
try:
|
|
set_lossless_provider(lambda content: (_SHORT, "log_fold_2"))
|
|
_out, _was, tr = _compress(block + "\t", lossless=True)
|
|
assert tr == ["router:tool_result:lossless_log_fold_2"]
|
|
finally:
|
|
set_lossless_provider(None)
|
|
|
|
|
|
def test_lossless_mode_verifier_gates_the_provider_candidate():
|
|
# In --lossless mode STAGE 0's output IS the answer: no CCR marker, no
|
|
# retrieval. The built-in folds self-verify; a provider only does if the
|
|
# operator registered a verifier.
|
|
block = _grep_block()
|
|
provider = lambda content: (_SHORT, "plugin") # noqa: E731
|
|
|
|
def _run(verifier, suffix):
|
|
try:
|
|
set_lossless_provider(provider, verifier=verifier)
|
|
return _compress(block + suffix, lossless=True)
|
|
finally:
|
|
set_lossless_provider(None)
|
|
|
|
# No verifier -> documented trust, unchanged behaviour.
|
|
_out, was, tr = _run(None, "\n")
|
|
assert was is True
|
|
assert tr == ["router:tool_result:lossless_plugin"]
|
|
|
|
# Verifier says yes -> adopted.
|
|
out, was, tr = _run(lambda original, compacted: True, "\n\n")
|
|
assert out == _SHORT
|
|
assert tr == ["router:tool_result:lossless_plugin"]
|
|
|
|
# Verifier says no -> rejected, built-in fold stands.
|
|
out, was, tr = _run(lambda original, compacted: False, "\n\n\n")
|
|
assert tr == ["router:tool_result:lossless_search"]
|
|
assert len(out) < len(block)
|
|
|
|
# Verifier raises -> "unverified" -> rejected, never fatal.
|
|
def _boom(original, compacted):
|
|
raise RuntimeError("verifier exploded")
|
|
|
|
out, was, tr = _run(_boom, "\n\n\n\n")
|
|
assert tr == ["router:tool_result:lossless_search"]
|
|
assert len(out) < len(block)
|
|
|
|
|
|
def test_memo_does_not_go_stale_when_the_provider_changes():
|
|
# The STAGE 0 memo caches a value that depends on the registered provider,
|
|
# so its key includes the registration generation. Without that, a provider
|
|
# registered (or cleared) after a block was already folded is ignored for
|
|
# that exact block forever — invisible in production (extensions register at
|
|
# startup) but wrong, and a trap for tests and any hot-reload path.
|
|
from headroom.transforms.content_router import CompressionStrategy
|
|
|
|
router = ContentRouter(ContentRouterConfig(lossless=True))
|
|
block = _grep_block()
|
|
tiny = "TINY\n"
|
|
|
|
try:
|
|
set_lossless_provider(None)
|
|
baseline, baseline_label = router._lossless_first(block, CompressionStrategy.SEARCH)
|
|
assert baseline_label == "lossless_search"
|
|
|
|
# Register AFTER the block was already folded once.
|
|
set_lossless_provider(lambda content: (tiny, "plugin"))
|
|
out, label = router._lossless_first(block, CompressionStrategy.SEARCH)
|
|
assert out == tiny, "provider registered after first fold was ignored (stale memo)"
|
|
assert label == "lossless_plugin"
|
|
|
|
# Clearing it must take effect too.
|
|
set_lossless_provider(None)
|
|
out, label = router._lossless_first(block, CompressionStrategy.SEARCH)
|
|
assert out == baseline, "cleared provider still served from the memo"
|
|
assert label == "lossless_search"
|
|
finally:
|
|
set_lossless_provider(None)
|
|
|
|
|
|
def test_clearing_the_provider_also_clears_the_verifier():
|
|
# A verifier with no provider is dead state that would silently start
|
|
# gating the *next* provider someone registers.
|
|
try:
|
|
set_lossless_provider(lambda content: None, verifier=lambda o, c: True)
|
|
assert get_lossless_verifier() is not None
|
|
set_lossless_provider(None)
|
|
assert get_lossless_provider() is None
|
|
assert get_lossless_verifier() is None
|
|
finally:
|
|
set_lossless_provider(None)
|
|
|
|
|
|
def test_provider_is_called_once_per_block_not_twice():
|
|
# `_has_lossless_fold` (the small-block admission probe) and STAGE 0 both
|
|
# run `_lossless_first` over the same block, under *different* strategies.
|
|
# Memoizing the provider's answer by content collapses that to one call
|
|
# into third-party code.
|
|
calls: list[str] = []
|
|
|
|
def counting(content: str):
|
|
calls.append(content)
|
|
return None
|
|
|
|
small = "\n".join(f"pkg/mod/long_filename.py:{n}:value = {n}" for n in range(1, 8)) + "\n"
|
|
try:
|
|
set_lossless_provider(counting)
|
|
router = ContentRouter(ContentRouterConfig(lossless=True))
|
|
assert router._has_lossless_fold(small) is True
|
|
assert len(calls) == 1
|
|
out, was = router._compress_block_content(
|
|
small,
|
|
hash(small),
|
|
"",
|
|
1.0,
|
|
1.0,
|
|
None,
|
|
[],
|
|
{},
|
|
[],
|
|
"tool_result",
|
|
"tool",
|
|
True,
|
|
)
|
|
assert was is True
|
|
assert len(calls) == 1
|
|
finally:
|
|
set_lossless_provider(None)
|