The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(compression): keep a fresh prepared candidate without re-planning
kshitijk4poor9c9345bf4577
diff --git a/agent/prepared_compaction.py b/agent/prepared_compaction.pyindex 2d7399099f6..804c42399e2 100644--- a/agent/prepared_compaction.py+++ b/agent/prepared_compaction.py@@ -76,14 +76,16 @@ class _Window:class PreparedSummary(_Window):summary: str # prefixed handoff text, exactly as ``_generate_summary`` returns itbody: str # bare body the next compaction extends iteratively+ prompt_tokens: int = 0 # provider-reported prompt size when the pass was plannedclass _PendingPass:"""The one running pass allowed to publish: its planned window, completion and cancel events, andthe progress and prompt-reading hooks of a compaction waiting on it."""- def __init__(self, window: _Window) -> None:+ def __init__(self, window: _Window, prompt_tokens: int) -> None:self.window = window+ self.prompt_tokens = prompt_tokensself.done = threading.Event()# Set once nothing can use the pass any more; its summary stream is closed (the aux hard-cancel path).self.cancelled = threading.Event()@@ -288,8 +290,8 @@ class PreparedCompaction:or getattr(compressor, "_micro_compact_enabled", False)):return True # another path owns compaction, or history is rewritten every turn- if compressor.awaiting_real_usage_after_compression:- return True+ if compressor.awaiting_real_usage_after_compression or compressor._fallback_compression_streak >= 2:+ return True # no real usage yet, or the summary model is benched after repeated fallbackstokens = compressor.last_prompt_tokensband_floor = int(compressor.threshold_tokens * (1 - PREPARE_BAND_RATIO))if tokens <= 0 or compressor.threshold_tokens <= 0 or tokens < band_floor:@@ -309,6 +311,11 @@ class PreparedCompaction:if self._pending is not None:return Nonecompleted = self._entry+ tokens = compressor.last_prompt_tokens+ if completed is not None and 0 <= tokens - completed.prompt_tokens < MIN_EXTENSION_DELTA_TOKENS:+ # The prompt has barely grown since the candidate's boundary was the cut: keep it without+ # re-planning and re-fingerprinting the transcript before every tool batch.+ return Noneworking, _, start, end = compressor._plan_compaction_window(messages)if start >= end:return None@@ -343,7 +350,7 @@ class PreparedCompaction:if self._pending is not None:_slots.release()return None- token = self._pending = _PendingPass(_Window(start, end, window_fingerprint))+ token = self._pending = _PendingPass(_Window(start, end, window_fingerprint), tokens)from agent.memory_provider import spawn_context_thread# Profile and secret scope ride the contextvars into the pass.@@ -387,7 +394,9 @@ class PreparedCompaction:if token.cancelled.is_set():logger.info("prepared compaction: pass cancelled after %.1fs (superseded)", time.monotonic() - started)elif summary:- entry = PreparedSummary(start, end, window_fingerprint, summary, worker._previous_summary)+ entry = PreparedSummary(+ start, end, window_fingerprint, summary, worker._previous_summary, token.prompt_tokens,+ )logger.info("prepared compaction: pass completed window=%d-%d in %.1fs",start, end, time.monotonic() - started)else:diff --git a/tests/agent/test_prepared_compaction.py b/tests/agent/test_prepared_compaction.pyindex c5e3c3ca34b..8c4cd2832cb 100644--- a/tests/agent/test_prepared_compaction.py+++ b/tests/agent/test_prepared_compaction.py@@ -87,6 +87,10 @@ def _grow(msgs: list, n: int, size: int = 1200, tag: str = "new") -> list:return msgs + _messages(n, size=size, tag=tag)[1:]+# A later prompt that grew by more than the extension threshold since the first pass was planned.+_GROWN_TOKENS = 19500 + pc.MIN_EXTENSION_DELTA_TOKENS++def _agent(cc, tokens: int = 19500):cc.last_prompt_tokens = tokensreturn SimpleNamespace(context_compressor=cc, compression_enabled=True, api_mode="chat_completions")@@ -172,8 +176,9 @@ def test_pass_leaves_live_transcript_and_compressor_untouched():lambda a, cc: setattr(a, "codex_responses_native_compaction", True),lambda a, cc: setattr(cc, "_micro_compact_enabled", True),lambda a, cc: setattr(cc, "_summary_failure_cooldown_until", time.monotonic() + 60),+ lambda a, cc: setattr(cc, "_fallback_compression_streak", 2), # summary model benched], ids=["below-band", "small-trigger-large-window", "awaiting-usage", "disabled", "fork", "app-server", "native",- "micro", "cooldown"])+ "micro", "cooldown", "benched"])def test_gates_start_no_pass(setup):cc = _compressor()agent = _agent(cc)@@ -332,7 +337,7 @@ def test_completed_candidate_splices_while_an_extension_pass_runs():gap = estimate_messages_tokens_rough(grown[first.compress_end:end])assert pc.MIN_EXTENSION_DELTA_TOKENS <= gap <= cc.tail_token_budgetcc.gate = threading.Event()- running = pc.maybe_prepare(_agent(cc), grown, origin="test")+ running = pc.maybe_prepare(_agent(cc, _GROWN_TOKENS), grown, origin="test")assert running is not Nonestarted = time.monotonic()@@ -457,7 +462,7 @@ def test_session_boundary_discards_candidate_and_running_pass(boundary):msgs = _messages(30)_prepare(cc, msgs)cc.gate = threading.Event()- running = pc.maybe_prepare(_agent(cc), _grow(msgs, 14, size=2600), origin="test")+ running = pc.maybe_prepare(_agent(cc, _GROWN_TOKENS), _grow(msgs, 14, size=2600), origin="test")assert running is not Noneif boundary == "reset":cc.on_session_reset()@@ -487,8 +492,9 @@ def test_small_delta_keeps_the_candidate_without_copying_or_taking_a_slot(monkeycc = _compressor()msgs = _messages(30)first = _prepare(cc, msgs)- copies = []+ copies, plans, plan = [], [], cc._plan_compaction_windowmonkeypatch.setattr(pc.copy, "deepcopy", lambda value, *a: copies.append(value) or value)+ monkeypatch.setattr(cc, "_plan_compaction_window", lambda m: plans.append(1) or plan(m))held = [pc._slots.acquire(blocking=False)] # leave exactly one slot freetry:assert pc.maybe_prepare(_agent(cc), _grow(msgs, 4), origin="test") is None@@ -499,6 +505,7 @@ def test_small_delta_keeps_the_candidate_without_copying_or_taking_a_slot(monkeyif ok:pc._slots.release()assert copies == [] and cc.prepared_compaction._entry is first and len(cc.calls) == 1+ assert plans == [], "an unchanged prompt size skips re-planning the window on the turn thread"def test_extension_pass_summarises_only_the_delta_on_top_of_the_previous_body():@@ -506,7 +513,7 @@ def test_extension_pass_summarises_only_the_delta_on_top_of_the_previous_body():msgs = _messages(30)first = _prepare(cc, msgs)grown = _grow(msgs, 14, size=2600)- second = _prepare(cc, grown)+ second = _prepare(cc, grown, _GROWN_TOKENS)call = cc.calls[1]assert call["previous"] == first.bodyassert call["n_turns"] == second.compress_end - first.compress_end@@ -530,14 +537,14 @@ def test_failed_pass_backs_off_without_touching_live_failure_state(tmp_path, moncall = MagicMock(side_effect=RuntimeError("No LLM provider configured"))monkeypatch.setattr(module, "call_llm", call)grown = _grow(msgs, 14, size=2600)- thread = pc.maybe_prepare(_agent(cc), grown, origin="test")+ thread = pc.maybe_prepare(_agent(cc, _GROWN_TOKENS), grown, origin="test")thread.join(5.0)assert call.call_count == 1assert cc.prepared_compaction._entry is first, "a failed extension keeps the previous candidate"assert cc._summary_failure_cooldown_until == 0.0 and cc._last_summary_error is Noneassert db.get_compression_failure_cooldown("S1") is None- assert pc.maybe_prepare(_agent(cc), grown, origin="test") is None, "backs off"+ assert pc.maybe_prepare(_agent(cc, _GROWN_TOKENS), grown, origin="test") is None, "backs off"assert call.call_count == 1