mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(kompress): honour toin_read_only in the Kompress CCR store (#4895)
## Description
Fixes #4801
The second TOIN write path of #4474. #4493 gated the router →
`SmartCrusher.crush()` path, but `store_kompress_in_ccr` still recorded
a TOIN observation unconditionally, so a Subscription request
(`CompressionPolicy.toin_read_only=True` — "never writes new pattern
observations from this request") that went through Kompress added an
observation to the shared TOIN store anyway. This change threads the
same per-call gate through the Kompress CCR store, both compressors, and
the router seam.
## 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
- `store_kompress_in_ccr` gains a keyword-only `record_toin: bool =
True`; when `False` the CCR store write still happens (compressed output
stays retrievable, marker unchanged) but the
`get_toin().record_compression(...)` call is skipped.
- `KompressCompressor.compress()` / `compress_batch()` accept and
forward `record_toin` on every internal path (single, batched
reconstruction, sequential fallback); `apply()` derives it from a
`compression_policy` kwarg, the way `SmartCrusher.apply()` and
`CacheAligner` do.
- `RemoteKompressCompressor.compress()` accepts the same keyword
(keeping the drop-in parity contract) and forwards it to the shared
store function.
- `ContentRouter._try_ml_compressor` — the single seam both compressors
are called through — sends `record_toin=False` only when the request's
`_runtime_compression_policy.toin_read_only` is set, mirroring
`_invoke_smart_crusher`; the kwarg is omitted otherwise, so compressors
and test doubles without it keep working and default store calls keep
the exact pre-change 3-argument shape.
- Six regression tests in `tests/test_compression_policy_toin_gate.py`
covering the store function, local `compress()`, `compress_batch()`,
`apply()` under a Subscription policy, the remote client, and router
forwarding.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
$ pytest tests/test_compression_policy_toin_gate.py tests/test_remote_kompress_dropin.py tests/test_ccr_marker_policy.py tests/test_compression_policy.py
58 passed in the combined related run (gate file alone: 8 passed, 8 skipped — skips are the suite's own headroom._core-gated tests, no Rust wheel on this machine)
# Same five runnable new tests against unmodified main: 5 failed (they pass with this change)
$ ruff check headroom/transforms/kompress_compressor.py headroom/transforms/kompress_remote.py headroom/transforms/content_router.py tests/test_compression_policy_toin_gate.py
All checks passed!
$ ruff format --check (same four files)
4 files already formatted
# Issue repro, extended with the new gate (TOIN at a temp file):
store_kompress_in_ccr("word " * 400, "word " * 100, 400) -> TOIN total 0 -> 1 (reported bug; kept as the default for policy-less callers)
store_kompress_in_ccr("word " * 400, "word " * 100, 400, record_toin=False) -> TOIN total 1 -> 1, cache key still returned
store_kompress_in_ccr("word " * 400, "word " * 100, 400) -> TOIN total 1 -> 2
```
Type checking was not run locally (no mypy environment on this machine);
CI runs it.
## Real Behavior Proof
- Environment: Linux, Python 3.12, checkout of `main` at 5023c84e plus
this branch, TOIN pointed at a temporary file, no provider calls.
- Exact command / steps: Ran the issue's function-level repro script
(extended with the new `record_toin` gate), then the pytest and ruff
commands pasted under Testing, then re-ran the five runnable new tests
with the source changes stashed to confirm they fail on unmodified
`main`.
- Observed result: Gated store call leaves the TOIN total unchanged
while still returning a CCR cache key whose entry retrieves
successfully; ungated calls record as before. Related suites: 58 passed.
New tests: fail on `main`, pass with this change.
- Not tested: A live Subscription request through the running proxy
end-to-end (the issue itself was reported and verified at function
level; router forwarding is covered by a stub-compressor test), and the
`_core`-gated router test on this machine (skips without the Rust wheel;
runs in CI).
## Runtime Rollout Safety
- Rollout-managed feature(s): None — this honours the existing F2.2
`CompressionPolicy.toin_read_only` flag; no new flag or channel is
introduced.
- Minimum rollout channel: N/A — no rollout-managed behavior; the gate
only takes effect for requests already classified Subscription with
policy enforcement on.
- Stable/default behavior changed: No for policy-less and PAYG/OAuth
callers (default `record_toin=True` everywhere); Subscription Kompress
traffic stops writing TOIN observations, which is the documented policy
and the bug fix.
- Kill switch / disable path: The existing
`HEADROOM_PROXY_AUTH_MODE_POLICY_ENFORCEMENT` switch already reverts
Subscription requests to the PAYG policy (TOIN writes re-enabled)
without a deploy.
- Unsafe override required: No.
- Qualification impact: None — no change to compression output bytes,
CCR storage, or retrieval markers; only the TOIN learning write is
gated.
- Rollback path: Revert this PR; no data migration (TOIN observations
written before the fix are ordinary pattern data).
## 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)
## Additional Notes
Documentation checklist item is N/A: no user-facing docs describe this
internal write path; the changed functions' docstrings were updated in
place. Direct callers with no policy context keep the previous
write-enabled behaviour, matching the deliberate compatibility decision
of the F2.2 SmartCrusher gate.
---------
Co-authored-by: TEJA P C <pcteja@users.noreply.github.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
TEJA P C
JD Davis
parent
f9627eb462
commit
8da7e17e4e
@@ -5423,6 +5423,14 @@ class ContentRouter(Transform):
|
||||
# don't accept the kwarg are unaffected on the common path.
|
||||
if protected:
|
||||
compress_kwargs["ccr_original"] = content
|
||||
# F2.2: forward the request's TOIN read-only gate per
|
||||
# call, as _invoke_smart_crusher does for crush() —
|
||||
# the compressor is shared across concurrent requests,
|
||||
# and the kwarg is only sent when gating so
|
||||
# compressors without it keep working.
|
||||
_policy = self._runtime_compression_policy
|
||||
if _policy is not None and _policy.toin_read_only:
|
||||
compress_kwargs["record_toin"] = False
|
||||
# One deadline for the whole request, not one per
|
||||
# block. Without this a request with N compressible
|
||||
# blocks gets N full deadlines and can run far past
|
||||
|
||||
@@ -1715,7 +1715,9 @@ def ccr_retrieval_marker(
|
||||
)
|
||||
|
||||
|
||||
def store_kompress_in_ccr(original: str, compressed: str, original_tokens: int) -> str | None:
|
||||
def store_kompress_in_ccr(
|
||||
original: str, compressed: str, original_tokens: int, *, record_toin: bool = True
|
||||
) -> str | None:
|
||||
"""Store an original->compressed mapping in the proxy-local CCR store and
|
||||
return its retrieval hash (or None on any failure).
|
||||
|
||||
@@ -1723,6 +1725,11 @@ def store_kompress_in_ccr(original: str, compressed: str, original_tokens: int)
|
||||
(:mod:`headroom.transforms.kompress_remote`) share one CCR policy. Model-free
|
||||
— touches only the compression store + telemetry, never the ONNX model — so
|
||||
it works in a sandboxed proxy installed without the ``[ml]`` extra.
|
||||
|
||||
``record_toin=False`` still stores in CCR (the compressed output stays
|
||||
retrievable) but skips the TOIN observation for this call. Callers pass
|
||||
it when the request's ``CompressionPolicy`` has ``toin_read_only=True``
|
||||
(Subscription, F2.2), mirroring ``SmartCrusher.crush(record_toin=...)``.
|
||||
"""
|
||||
try:
|
||||
from ..cache.compression_store import get_compression_store
|
||||
@@ -1744,17 +1751,18 @@ def store_kompress_in_ccr(original: str, compressed: str, original_tokens: int)
|
||||
tool_signature_hash=signature.structure_hash,
|
||||
compression_strategy="kompress",
|
||||
)
|
||||
with contextlib.suppress(Exception):
|
||||
from ..telemetry import get_toin
|
||||
if record_toin:
|
||||
with contextlib.suppress(Exception):
|
||||
from ..telemetry import get_toin
|
||||
|
||||
get_toin().record_compression(
|
||||
tool_signature=signature,
|
||||
original_count=original_tokens,
|
||||
compressed_count=compressed_tokens,
|
||||
original_tokens=original_tokens,
|
||||
compressed_tokens=compressed_tokens,
|
||||
strategy="kompress",
|
||||
)
|
||||
get_toin().record_compression(
|
||||
tool_signature=signature,
|
||||
original_count=original_tokens,
|
||||
compressed_count=compressed_tokens,
|
||||
original_tokens=original_tokens,
|
||||
compressed_tokens=compressed_tokens,
|
||||
strategy="kompress",
|
||||
)
|
||||
return cache_key
|
||||
except Exception as e:
|
||||
# Store backends can echo the payload in errors, so no level logs it;
|
||||
@@ -1931,6 +1939,7 @@ class KompressCompressor(Transform):
|
||||
*,
|
||||
allow_download: bool = True,
|
||||
ccr_original: str | None = None,
|
||||
record_toin: bool = True,
|
||||
_deadline_started_at: float | None = None,
|
||||
_time_budget_cap_seconds: float | None = None,
|
||||
) -> KompressResult:
|
||||
@@ -1953,6 +1962,10 @@ class KompressCompressor(Transform):
|
||||
``content`` is a tag-protected placeholder intermediate
|
||||
({{HEADROOM_TAG_N}}); passing the pre-protection original keeps a
|
||||
later full retrieval lossless. Defaults to ``content``.
|
||||
record_toin: When False, the CCR store still records the mapping
|
||||
but no TOIN observation is written for this call. The router
|
||||
passes it when the request policy is ``toin_read_only``
|
||||
(Subscription, F2.2).
|
||||
|
||||
Returns:
|
||||
KompressResult with compressed text.
|
||||
@@ -1994,6 +2007,7 @@ class KompressCompressor(Transform):
|
||||
target_ratio=[target_ratio],
|
||||
batch_size=_batch_size(),
|
||||
ccr_originals=[ccr_original],
|
||||
record_toin=record_toin,
|
||||
_deadline_started_at=t_deadline,
|
||||
_time_budget_cap_seconds=_time_budget_cap_seconds,
|
||||
)
|
||||
@@ -2197,7 +2211,8 @@ class KompressCompressor(Transform):
|
||||
if self.config.enable_ccr:
|
||||
ccr_source = ccr_original if ccr_original is not None else content
|
||||
ccr_source_tokens = len(ccr_source.split())
|
||||
cache_key = self._store_in_ccr(ccr_source, compressed, ccr_source_tokens)
|
||||
gate: dict[str, bool] = {} if record_toin else {"record_toin": False}
|
||||
cache_key = self._store_in_ccr(ccr_source, compressed, ccr_source_tokens, **gate)
|
||||
if cache_key:
|
||||
# Report the source line span so a reader can tell content was
|
||||
# compressed away rather than absent — "items" counts words, which
|
||||
@@ -2292,6 +2307,7 @@ class KompressCompressor(Transform):
|
||||
batch_size: int = 32,
|
||||
*,
|
||||
ccr_originals: list[str | None] | None = None,
|
||||
record_toin: bool = True,
|
||||
_deadline_started_at: float | None = None,
|
||||
_time_budget_cap_seconds: float | None = None,
|
||||
) -> list[KompressResult]:
|
||||
@@ -2402,6 +2418,7 @@ class KompressCompressor(Transform):
|
||||
question=question,
|
||||
target_ratio=r,
|
||||
ccr_original=ccr_source,
|
||||
record_toin=record_toin,
|
||||
_deadline_started_at=t_deadline,
|
||||
_time_budget_cap_seconds=(
|
||||
None if cap_ends_at is None else cap_ends_at - time.monotonic()
|
||||
@@ -2637,7 +2654,8 @@ class KompressCompressor(Transform):
|
||||
if ccr_source is None:
|
||||
ccr_source = content
|
||||
ccr_source_tokens = len(ccr_source.split())
|
||||
cache_key = self._store_in_ccr(ccr_source, compressed, ccr_source_tokens)
|
||||
gate: dict[str, bool] = {} if record_toin else {"record_toin": False}
|
||||
cache_key = self._store_in_ccr(ccr_source, compressed, ccr_source_tokens, **gate)
|
||||
if cache_key:
|
||||
# Report the source line span so a reader can tell content was
|
||||
# compressed away rather than absent — "items" counts words, which
|
||||
@@ -2746,6 +2764,8 @@ class KompressCompressor(Transform):
|
||||
**kwargs: Any,
|
||||
) -> TransformResult:
|
||||
"""Apply Kompress compression to messages (Transform interface)."""
|
||||
policy = kwargs.get("compression_policy")
|
||||
record_toin = not (policy is not None and policy.toin_read_only)
|
||||
tokens_before = sum(tokenizer.count_text(str(m.get("content", ""))) for m in messages)
|
||||
transformed = []
|
||||
transforms_applied = []
|
||||
@@ -2763,7 +2783,7 @@ class KompressCompressor(Transform):
|
||||
# Compress tool outputs and long assistant messages
|
||||
# Model decides how much — no hardcoded ratios
|
||||
if role in ("tool", "assistant"):
|
||||
result = self.compress(content)
|
||||
result = self.compress(content, record_toin=record_toin)
|
||||
if result.compression_ratio < 0.9:
|
||||
transformed.append({**message, "content": result.compressed})
|
||||
transforms_applied.append(f"kompress:{role}:{result.compression_ratio:.2f}")
|
||||
@@ -2781,5 +2801,7 @@ class KompressCompressor(Transform):
|
||||
transforms_applied=transforms_applied or ["kompress:noop"],
|
||||
)
|
||||
|
||||
def _store_in_ccr(self, original: str, compressed: str, original_tokens: int) -> str | None:
|
||||
return store_kompress_in_ccr(original, compressed, original_tokens)
|
||||
def _store_in_ccr(
|
||||
self, original: str, compressed: str, original_tokens: int, *, record_toin: bool = True
|
||||
) -> str | None:
|
||||
return store_kompress_in_ccr(original, compressed, original_tokens, record_toin=record_toin)
|
||||
|
||||
@@ -226,6 +226,7 @@ class RemoteKompressCompressor:
|
||||
*,
|
||||
allow_download: bool = True,
|
||||
ccr_original: str | None = None,
|
||||
record_toin: bool = True,
|
||||
_time_budget_cap_seconds: float | None = None,
|
||||
) -> KompressResult:
|
||||
"""Compress via the remote endpoint.
|
||||
@@ -253,6 +254,9 @@ class RemoteKompressCompressor:
|
||||
which ContentRouter caught with a broad ``except Exception`` and logged
|
||||
as ``Kompress failed: ...``. Compression silently degraded to zero on the
|
||||
whole deployment while the proxy kept reporting success.
|
||||
|
||||
``record_toin`` mirrors the local compressor: False keeps the CCR
|
||||
store write but skips the TOIN observation for this call.
|
||||
"""
|
||||
n_words = len(content.split())
|
||||
# Same floor contract as the in-process compressor: lossy
|
||||
@@ -327,7 +331,8 @@ class RemoteKompressCompressor:
|
||||
ccr_source_tokens = (
|
||||
len(ccr_source.split()) if ccr_original is not None else result.original_tokens
|
||||
)
|
||||
cache_key = store_kompress_in_ccr(ccr_source, compressed, ccr_source_tokens)
|
||||
gate: dict[str, bool] = {} if record_toin else {"record_toin": False}
|
||||
cache_key = store_kompress_in_ccr(ccr_source, compressed, ccr_source_tokens, **gate)
|
||||
if cache_key:
|
||||
# Report the source line span so a reader can tell content was
|
||||
# compressed away rather than absent (#2586).
|
||||
|
||||
@@ -5,7 +5,8 @@ auth mode), TOIN must serve cached recommendations but NEVER write new
|
||||
pattern observations from this request. PAYG / OAuth keep writing so
|
||||
the network effect keeps growing. The gate is read at the
|
||||
``record_compression`` call site in ``smart_crusher.py`` and
|
||||
``content_router.py``.
|
||||
``content_router.py``, and — since #4801 — at the Kompress CCR store
|
||||
(``store_kompress_in_ccr``), the second write path of #4474.
|
||||
|
||||
These tests mirror the structure of
|
||||
``tests/test_smart_crusher_toin_attachment.py`` (the F2.1-era TOIN
|
||||
@@ -339,3 +340,202 @@ def test_smart_crusher_crush_record_toin_false_skips_write(fresh_toin):
|
||||
|
||||
crusher.crush(payload)
|
||||
assert sum(p.total_compressions for p in fresh_toin._patterns.values()) > 0
|
||||
|
||||
|
||||
# ─── Kompress CCR store: record_toin gate (#4801) ────────────────────────
|
||||
|
||||
|
||||
def _toin_total(toin) -> int:
|
||||
return sum(p.total_compressions for p in toin._patterns.values())
|
||||
|
||||
|
||||
def test_kompress_store_record_toin_false_skips_write(fresh_toin):
|
||||
"""``store_kompress_in_ccr(record_toin=False)`` keeps the CCR mapping
|
||||
(the compressed output stays retrievable) but writes no TOIN
|
||||
observation; the default call writes one."""
|
||||
from headroom.cache.compression_store import get_compression_store
|
||||
from headroom.transforms.kompress_compressor import store_kompress_in_ccr
|
||||
|
||||
cache_key = store_kompress_in_ccr("word " * 400, "word " * 100, 400, record_toin=False)
|
||||
assert cache_key is not None
|
||||
assert get_compression_store().retrieve(cache_key) is not None
|
||||
assert _toin_total(fresh_toin) == 0
|
||||
|
||||
cache_key = store_kompress_in_ccr("other " * 400, "other " * 100, 400)
|
||||
assert cache_key is not None
|
||||
assert _toin_total(fresh_toin) == 1
|
||||
|
||||
|
||||
class _FakeEncoding:
|
||||
def __init__(self, word_lists: list[list[str]]):
|
||||
self._word_lists = word_lists
|
||||
self._ids = [[0] * len(w) for w in word_lists]
|
||||
|
||||
def __getitem__(self, key: str):
|
||||
return {"input_ids": self._ids, "attention_mask": self._ids}[key]
|
||||
|
||||
def word_ids(self, batch_index: int = 0) -> list[int]:
|
||||
return list(range(len(self._word_lists[batch_index])))
|
||||
|
||||
|
||||
class _FakeTokenizer:
|
||||
def __call__(self, words, **_kwargs):
|
||||
batch = words if (words and isinstance(words[0], list)) else [words]
|
||||
return _FakeEncoding(batch)
|
||||
|
||||
|
||||
class _FakeModel:
|
||||
def get_keep_mask(self, input_ids, _attention_mask):
|
||||
return [[i < 2 for i in range(len(input_ids[0]))]]
|
||||
|
||||
def get_scores(self, input_ids, _attention_mask):
|
||||
return [[1.0 if i < 2 else 0.0 for i in range(len(row))] for row in input_ids]
|
||||
|
||||
|
||||
def _local_compressor(monkeypatch):
|
||||
from headroom.transforms.kompress_compressor import KompressCompressor
|
||||
|
||||
monkeypatch.setattr(
|
||||
"headroom.transforms.kompress_compressor._load_kompress",
|
||||
lambda *a, **k: (_FakeModel(), _FakeTokenizer(), "onnx"),
|
||||
)
|
||||
return KompressCompressor()
|
||||
|
||||
|
||||
def test_kompress_compressor_record_toin_false_skips_write(fresh_toin, monkeypatch):
|
||||
"""The local compressor forwards the gate to the CCR store: gated
|
||||
compression still returns a retrieval key but records nothing."""
|
||||
compressor = _local_compressor(monkeypatch)
|
||||
content = "line one\nline two\nline three " * 20
|
||||
|
||||
gated = compressor.compress(content, record_toin=False)
|
||||
assert gated.cache_key is not None
|
||||
assert _toin_total(fresh_toin) == 0
|
||||
|
||||
compressor.compress(content)
|
||||
assert _toin_total(fresh_toin) == 1
|
||||
|
||||
|
||||
def test_kompress_compress_batch_record_toin_false_skips_write(fresh_toin, monkeypatch):
|
||||
"""The batch path (which reconstructs and stores separately) honours
|
||||
the gate the same way."""
|
||||
compressor = _local_compressor(monkeypatch)
|
||||
content = "line one\nline two\nline three " * 20
|
||||
|
||||
results = compressor.compress_batch([content], record_toin=False)
|
||||
assert results[0].cache_key is not None
|
||||
assert _toin_total(fresh_toin) == 0
|
||||
|
||||
|
||||
def test_kompress_compress_batch_forced_batched_record_toin_false_skips_write(
|
||||
fresh_toin, monkeypatch
|
||||
):
|
||||
"""Forcing the batched path (no sequential fallback) still honours the
|
||||
gate: its separate CCR store write records nothing when gated."""
|
||||
compressor = _local_compressor(monkeypatch)
|
||||
monkeypatch.setattr(compressor, "_should_use_sequential_fallback", lambda: False)
|
||||
content = "line one\nline two\nline three " * 20
|
||||
|
||||
results = compressor.compress_batch([content], record_toin=False)
|
||||
assert results[0].cache_key is not None
|
||||
assert _toin_total(fresh_toin) == 0
|
||||
|
||||
results = compressor.compress_batch([content])
|
||||
assert results[0].cache_key is not None
|
||||
assert _toin_total(fresh_toin) == 1
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
def __init__(self, payload: dict) -> None:
|
||||
self._payload = payload
|
||||
|
||||
def raise_for_status(self) -> None:
|
||||
return None
|
||||
|
||||
def json(self) -> dict:
|
||||
return self._payload
|
||||
|
||||
|
||||
class _FakeClient:
|
||||
def __init__(self, payload: dict) -> None:
|
||||
self._payload = payload
|
||||
|
||||
def post(self, url, headers=None, json=None): # noqa: A002, ANN001
|
||||
return _FakeResponse(self._payload)
|
||||
|
||||
def close(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def test_remote_kompress_record_toin_false_skips_write(fresh_toin, monkeypatch):
|
||||
"""The remote client shares the store function, so the same gate
|
||||
applies on the hosted-endpoint path."""
|
||||
from headroom.transforms.kompress_remote import RemoteKompressCompressor
|
||||
|
||||
compressor = RemoteKompressCompressor("https://ml.example.invalid")
|
||||
compressor._client = _FakeClient({"compressed": "short", "compression_ratio": 0.2}) # type: ignore[assignment]
|
||||
compressor.config.enable_ccr = True
|
||||
compressor.config.min_input_words = 10
|
||||
content = "real secret block " * 60
|
||||
|
||||
gated = compressor.compress(content, record_toin=False)
|
||||
assert gated.cache_key is not None
|
||||
assert _toin_total(fresh_toin) == 0
|
||||
|
||||
compressor.compress(content)
|
||||
assert _toin_total(fresh_toin) == 1
|
||||
|
||||
|
||||
@_skip_no_core
|
||||
def test_content_router_kompress_path_forwards_toin_gate(monkeypatch):
|
||||
"""The router never calls ``KompressCompressor.apply()``, so it must
|
||||
forward the request's gate per call, as it does for ``crush()``: the
|
||||
kwarg is sent only when the policy is read-only."""
|
||||
from headroom.transforms.content_router import ContentRouter
|
||||
from headroom.transforms.kompress_compressor import KompressResult
|
||||
|
||||
calls: list[dict] = []
|
||||
|
||||
class _Stub:
|
||||
def is_ready(self) -> bool:
|
||||
return True
|
||||
|
||||
def ensure_background_load(self) -> None:
|
||||
return None
|
||||
|
||||
def compress(self, content: str, **kwargs) -> KompressResult:
|
||||
calls.append(kwargs)
|
||||
return KompressResult(
|
||||
compressed="short",
|
||||
original=content,
|
||||
original_tokens=100,
|
||||
compressed_tokens=1,
|
||||
compression_ratio=0.01,
|
||||
)
|
||||
|
||||
router = ContentRouter()
|
||||
monkeypatch.setattr(router, "_get_kompress", lambda: _Stub())
|
||||
content = "plain prose about workers processing batches steadily " * 20
|
||||
|
||||
router._runtime_compression_policy = policy_for_mode(AuthMode.SUBSCRIPTION)
|
||||
router._try_ml_compressor(content, "")
|
||||
assert calls[-1].get("record_toin") is False
|
||||
|
||||
router._runtime_compression_policy = policy_for_mode(AuthMode.PAYG)
|
||||
router._try_ml_compressor(content, "")
|
||||
assert "record_toin" not in calls[-1]
|
||||
|
||||
|
||||
def test_kompress_apply_subscription_policy_skips_write(fresh_toin, monkeypatch):
|
||||
"""Through the Transform interface, a Subscription policy reaches
|
||||
``compress()`` as the gate; no policy keeps the legacy write."""
|
||||
compressor = _local_compressor(monkeypatch)
|
||||
content = "line one\nline two\nline three " * 20
|
||||
messages = [{"role": "tool", "content": content, "tool_call_id": "t1"}]
|
||||
|
||||
policy = policy_for_mode(AuthMode.SUBSCRIPTION)
|
||||
compressor.apply(messages, _tokenizer(), compression_policy=policy)
|
||||
assert _toin_total(fresh_toin) == 0
|
||||
|
||||
compressor.apply(messages, _tokenizer())
|
||||
assert _toin_total(fresh_toin) == 1
|
||||
|
||||
Reference in New Issue
Block a user