From 9b3042902e2f8074b0f81ea771d33c842ccbd853 Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Tue, 15 Sep 2026 11:52:34 -0700 Subject: [PATCH] fix: trim hygiene bound salvage to two invariant tests and document the knob MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Salvage follow-up to the cherry-picked #112055 hunk (@Finn763): - tests: fold the landed-commit control into the turn-hold-miss test and drop the two extra end-to-end tests (sub-limit identity is already pinned by the pure contract test) so the fix carries exactly two invariant tests. - gateway/run_turn.py::bound_model_input_without_hygiene: drop the isinstance / limit<=0 defences — the caller always passes the transcript list and a _knob()-validated positive int, so the checks could never fire. - docs: configuration.md now says hygiene_hard_message_limit also bounds the model payload on any turn where hygiene did not land (payload-only, disk untouched, landed summaries adopted as-is). Co-authored-by: Noor-Sol <187156657+Noor-Sol@users.noreply.github.com> Co-authored-by: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> --- gateway/run_turn.py | 2 +- tests/gateway/test_session_hygiene.py | 60 +++++------------------- website/docs/user-guide/configuration.md | 2 + 3 files changed, 15 insertions(+), 49 deletions(-) diff --git a/gateway/run_turn.py b/gateway/run_turn.py index e8d2cbc715..3db8b7a519 100644 --- a/gateway/run_turn.py +++ b/gateway/run_turn.py @@ -93,7 +93,7 @@ def bound_model_input_without_hygiene(history: List[Any], limit: int) -> List[An unaffected. Returns ``history`` unchanged — same object — when nothing needs dropping, so the landed-compression and below-the-limit paths stay byte-identical. """ - if not isinstance(history, list) or not isinstance(limit, int) or limit <= 0 or len(history) <= limit: + if len(history) <= limit: return history head_end = 0 while (head_end < len(history) and isinstance(history[head_end], dict) diff --git a/tests/gateway/test_session_hygiene.py b/tests/gateway/test_session_hygiene.py index cc2d6a6d7f..19d2e6f122 100644 --- a/tests/gateway/test_session_hygiene.py +++ b/tests/gateway/test_session_hygiene.py @@ -1918,7 +1918,8 @@ def test_bound_model_input_without_hygiene_is_deterministic_and_fail_closed(): @pytest.mark.asyncio async def test_hygiene_miss_bounds_the_model_payload(monkeypatch, tmp_path): - """Turn-hold expiry without a landed summary must not feed the model the whole transcript.""" + """Turn-hold expiry without a landed summary must not feed the model the whole transcript + (#111988); a landed commit is still adopted byte-identical.""" worker_started = threading.Event() release_worker = threading.Event() cleanup_done = threading.Event() @@ -1977,53 +1978,16 @@ async def test_hygiene_miss_bounds_the_model_payload(monkeypatch, tmp_path): release_worker.set() await asyncio.wait_for(asyncio.to_thread(cleanup_done.wait), timeout=3) + + # Control: a LANDED hygiene commit is adopted as-is — its 25 summary rows exceed the + # limit, and the bound must not touch them (only the unlanded path is clipped). + db.create_session("sess-landed", "telegram") + runner2, _adapter2, event2 = _make_cooldown_runner( + monkeypatch, tmp_path, _LandedCompressAgent, db, "sess-landed" + ) + runner2.session_store.load_transcript.return_value = _make_bound_probe_transcript() + assert await asyncio.wait_for(runner2._handle_message(event2), timeout=15) == "ok" + assert _turn_payload(runner2) is _LandedCompressAgent.last_compressed finally: release_worker.set() db.close() - - -@pytest.mark.asyncio -async def test_hygiene_landed_payload_is_byte_identical(monkeypatch, tmp_path): - """A landed hygiene commit is adopted as-is — the bound must not touch it.""" - transcript = _make_bound_probe_transcript() - db, runner, _adapter, event = _make_bound_runner( - monkeypatch, tmp_path, _LandedCompressAgent, - "compression:\n" - " enabled: true\n" - f" hygiene_hard_message_limit: {_HARD_LIMIT}\n", - transcript, - ) - try: - assert await asyncio.wait_for(runner._handle_message(event), timeout=15) == "ok" - payload = _turn_payload(runner) - assert payload is _LandedCompressAgent.last_compressed, ( - "a landed hygiene commit must reach the model as the adopted transcript, " - f"unmodified; got {len(payload)} rows" - ) - runner.session_store.rewrite_transcript.assert_called() - finally: - db.close() - - -@pytest.mark.asyncio -async def test_hygiene_not_needed_payload_is_the_loaded_transcript(monkeypatch, tmp_path): - """Below the limit the payload is the very list loaded from disk — zero behaviour change.""" - transcript = _make_bound_probe_transcript(total=_HARD_LIMIT - 1) - db, runner, _adapter, event = _make_bound_runner( - monkeypatch, tmp_path, _LandedCompressAgent, - "compression:\n" - " enabled: true\n" - f" hygiene_hard_message_limit: {_HARD_LIMIT}\n", - transcript, - ) - # A context window wide enough that the token threshold cannot fire either: hygiene is a - # no-op this turn, so the bound must be one too. - monkeypatch.setattr( - "agent.model_metadata.get_model_context_length", lambda *_args, **_kwargs: 1_000_000 - ) - try: - assert await asyncio.wait_for(runner._handle_message(event), timeout=15) == "ok" - payload = _turn_payload(runner) - assert payload is transcript, "a sub-limit transcript must pass through untouched" - finally: - db.close() diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md index a1ce65c984..e17b0c47d5 100644 --- a/website/docs/user-guide/configuration.md +++ b/website/docs/user-guide/configuration.md @@ -990,6 +990,8 @@ Older configs with `compression.summary_model`, `compression.summary_provider`, `hygiene_hard_message_limit` is a gateway-only **pre-compression safety valve**. It exists to break a death spiral: when API calls keep disconnecting on an oversized session, the gateway never receives token-usage data, so the token-based threshold can't fire, so the transcript keeps growing and disconnects get worse. This count-based floor fires on message count alone (always known, regardless of API failures) to force compression and recover the session. Default `5000` — far above any normal session, including large-context (1M+) models doing thousands of short turns, which compress on the token threshold long before this. Raise it further for unusual platforms, lower it to force more aggressive compression. Editing this value on a running gateway takes effect on the next message (see below). +The same limit is also a **fail-closed bound on what the model is sent** whenever hygiene does not land by the time a turn starts — the turn-hold budget expired, the summary timed out or failed, a failure cooldown is active, another compression is still in flight, or compression is disabled. In that case the gateway keeps the leading system/setup rows plus the newest messages, total at most `hygiene_hard_message_limit`, and never starts the kept tail on an orphaned tool result. Only the payload of that one turn is clipped: the transcript on disk is untouched, nothing is deleted, and a summary that lands later is adopted as-is. This is what keeps a week-long DM from feeding the model the full uncompressed history when a compression pass keeps missing. + `hygiene_timeout_seconds` is the gateway's **inactivity budget** for this pre-agent compression pass — not a total wall-clock cap. The compression summary call streams from the model, and each arriving token counts as forward progress: a slow reasoning model that is still generating keeps extending its own deadline, so slow-but-healthy summary models are never cut off mid-generation. Only when the summary model produces **no output** for this many seconds (backend down, hung connection, silent provider) does the gateway warn the user, continue the incoming message without compression, and record a temporary per-session failure cooldown instead of appearing stuck. `hygiene_total_ceiling_seconds` (default `600`) bounds the total wait even while tokens are still moving, so a degenerate trickle stream can't hold a turn hostage indefinitely. It is clamped to at least `hygiene_timeout_seconds`.