From 4c76ec81a97df299e7db493489185d55d3f292d4 Mon Sep 17 00:00:00 2001 From: kshitijk4poor Date: Sat, 22 Aug 2026 15:38:16 +0530 Subject: [PATCH] fix(compression): restore the prune runway when a would-grow refusal keeps the transcript MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit compress()'s successful tail zeroes _proactive_prune_rearm_tokens in memory — correct for a committed compaction, whose boundary already broke the prompt-cache prefix. But compress_context's anti-growth guard can then REFUSE the result and keep the original transcript, whose cached prefix is intact. The refusal returned with the in-memory runway still at 0 while the durable model_config copy kept the old value, so: - the next eligible iteration's proactive prune fired without the regrowth interval #79640 introduced — an immediate, unthrottled cache-breaking rewrite (#91830's bug class), and - memory and disk disagreed until a restart silently re-armed the throttle from the stale durable row. The refusal branch now restores the runway from the attempt snapshot — the same targeted restore the rotation-failure rollback already performs. Sibling non-commit branches audited: aborted (returns before the tail zero), no-progress (tail zero only runs after a real boundary rewrite, which no-progress by definition lacks), empty-transcript (built-in tail never returns []), fence-denied (full snapshot restore already covers the runway), in-place DB failure (in-memory transcript keeps the compacted form, so the zeroed runway is consistent with it). Fixes the reachable half of the structural asymmetry flagged in #91830. --- agent/conversation_compression.py | 19 +++++ tests/agent/test_would_grow_refusal_runway.py | 82 +++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 tests/agent/test_would_grow_refusal_runway.py diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py index a2b2643bf3..3d4b220d4d 100644 --- a/agent/conversation_compression.py +++ b/agent/conversation_compression.py @@ -3460,6 +3460,25 @@ def compress_context( "could not record rejected-compaction strike", exc_info=True, ) + # Restore ONLY the prune runway (same rationale as the + # rotation-failure rollback below): compress()'s successful + # tail already zeroed _proactive_prune_rearm_tokens in + # memory, but this refusal keeps the ORIGINAL transcript — + # whose cached prefix is intact. Leaving the runway at 0 + # disarms the #79640 throttle, so the very next iteration's + # proactive prune rewrites history and breaks the prompt + # cache without the required regrowth interval (#91830). + # The durable copy was never cleared (that clear only rides + # the archive_and_compact / child-row commit that never + # ran), so restoring the snapshot re-aligns memory with + # disk. When compress() aborted before its tail, snapshot + # and current value are identical and this is a no-op. + if "_proactive_prune_rearm_tokens" in _compressor_attempt_snapshot: + agent.context_compressor._proactive_prune_rearm_tokens = ( + _compressor_attempt_snapshot[ + "_proactive_prune_rearm_tokens" + ] + ) _release_lock() return messages, _existing_sp diff --git a/tests/agent/test_would_grow_refusal_runway.py b/tests/agent/test_would_grow_refusal_runway.py new file mode 100644 index 0000000000..480577f42f --- /dev/null +++ b/tests/agent/test_would_grow_refusal_runway.py @@ -0,0 +1,82 @@ +"""Regression: a would-grow refusal must not disarm the proactive-prune runway. + +#91830 follow-up. ``ContextCompressor.compress()`` zeroes +``_proactive_prune_rearm_tokens`` on its successful tail — correct for a +COMMITTED compaction (the boundary already broke the prompt-cache prefix, so +the throttle restarts from the new baseline). But ``compress_context``'s +anti-growth guard can then REFUSE the result and keep the original +transcript, whose cached prefix is intact. Before the fix, that refusal +returned with the in-memory runway still at 0 while the durable +``model_config`` copy kept the old value: + +- the very next eligible iteration's proactive prune fired without the + regrowth interval #79640 introduced — an immediate, unthrottled + cache-breaking rewrite of history that was still byte-identical to what + the provider had cached, and +- memory and disk disagreed until the next restart silently re-armed the + throttle from the stale durable row. + +The refusal branch now restores the runway from the attempt snapshot, the +same targeted restore the rotation-failure rollback already performed. +""" + +from __future__ import annotations + +import os +from pathlib import Path +from unittest.mock import patch + +from hermes_state import SessionDB + + +def _build_agent(db: SessionDB, session_id: str): + with patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}): + from run_agent import AIAgent + + agent = AIAgent( + api_key="test-key", + base_url="https://openrouter.ai/api/v1", + model="test/model", + quiet_mode=True, + session_db=db, + session_id=session_id, + skip_context_files=True, + skip_memory=True, + ) + # Skip the one-time aux-model feasibility probe (may hit the network). + agent._compression_feasibility_checked = True + return agent + + +def test_would_grow_refusal_restores_prune_runway(tmp_path: Path) -> None: + db = SessionDB(db_path=tmp_path / "state.db") + session_id = "WOULD_GROW_RUNWAY" + db.create_session(session_id, source="test") + + agent = _build_agent(db, session_id) + compressor = agent.context_compressor + armed_runway = 250_000 + compressor._proactive_prune_rearm_tokens = armed_runway + + messages = [{"role": "user", "content": f"m{i} " + "x" * 200} for i in range(10)] + + def _growing_compress(msgs, **_kw): + # Mirror the real compress() tail: it zeroes the in-memory runway + # before returning — then return a transcript LARGER than the input + # so the caller's anti-growth guard refuses the commit. + compressor._proactive_prune_rearm_tokens = 0 + return list(msgs) + [ + {"role": "assistant", "content": "GROWN " * 20_000}, + ] + + with patch.object(type(compressor), "compress", side_effect=_growing_compress): + returned, _sp = agent._compress_context(messages, "sys", approx_tokens=120_000) + + # Refusal contract: original transcript kept, refusal flagged. + assert returned == messages + assert compressor._last_compress_refused_would_grow is True + # The runway must survive the refusal — memory re-aligned with the + # (never-cleared) durable copy, keeping the #79640 throttle armed. + assert compressor._proactive_prune_rearm_tokens == armed_runway + # And the compression lock must not leak. + assert db.get_compression_lock_holder(session_id) is None