The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): key candidate supersession on working attempts, not entry claims
kokhlob5108bb1614b
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex a02c322d90e..a99d805340f 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -234,6 +234,35 @@ def _compressor_attempt_is_current(compressor: Any, generation: int) -> bool:return int(getattr(compressor, "_compression_attempt_generation", 0) or 0) == generation+def _mark_compressor_working_attempt(compressor: Any, generation: int) -> None:+ """Publish the generation of the attempt that is ACTUALLY running summary work.++ The entry claim is taken before the breaker gates and the per-session lock, so no-op+ entries (lock sit-outs, transient gates) bump ``_compression_attempt_generation``+ without doing any work. Candidate supersession must key on this separate marker,+ published only when the summary dispatch begins, or those no-op claims discard a+ completed candidate and compression livelocks. Slotted/frozen compressors that+ cannot hold the attribute keep the entry-generation check as a conservative fallback.+ """+ with _COMPRESSOR_ATTEMPT_LOCK:+ with contextlib.suppress(Exception):+ compressor._compression_working_attempt_generation = generation+++def _working_attempt_is_current(compressor: Any, generation: Any) -> bool:+ """True when *generation* is still the last attempt that began summary work.++ Without a published marker (attribute-less compressor, or the attempt never reached+ dispatch) supersession falls back to the entry-generation ownership check."""+ if not generation:+ return True+ with _COMPRESSOR_ATTEMPT_LOCK:+ marker = getattr(compressor, "_compression_working_attempt_generation", None)+ if marker is None:+ return int(getattr(compressor, "_compression_attempt_generation", 0) or 0) == generation+ return int(marker) == int(generation)++def _install_compression_cancelled_check(compressor: Any, check: Any, generation: int) -> None:"""Install the F4 cancellation consult, stamped with its owner attempt."""with _COMPRESSOR_ATTEMPT_LOCK:@@ -2689,6 +2718,10 @@ def _run_summary_dispatch(_install_compression_cancelled_check(agent.context_compressor, lambda: commit_fence.is_cancelled, attempt_generation)+ # From here this attempt is doing real summary work: publish it as the working+ # attempt so later no-op entry claims (lock sit-outs on other paths) cannot+ # supersede the candidate this run produces.+ _mark_compressor_working_attempt(agent.context_compressor, attempt_generation)def _compression_cancel_requested() -> bool:return bool(@@ -3213,13 +3246,20 @@ def _candidate_rejected()return True- # A newer attempt claiming this compressor supersedes us; discard the late- # candidate. Fence poison alone misses a successor that minted its own fence.- if not _compressor_attempt_is_current(agent.context_compressor, attempt_generation):+ # A newer WORKING attempt supersedes us; discard the late candidate. No-op+ # entry claims (sit-outs that never ran a summary) do not: keying on them+ # discards a completed candidate and livelocks compression. Without a+ # published working marker, fence poison alone misses a successor that+ # minted its own fence — fall back to the entry-generation check.+ if not _working_attempt_is_current(agent.context_compressor, attempt_generation):+ _working_gen = getattr(+ agent.context_compressor, "_compression_working_attempt_generation", None+ )logger.warning("Discarding late compression candidate: attempt generation "- "%s was superseded by a newer attempt (current: %s) (session=%s).", attempt_generation,- getattr(agent.context_compressor, "_compression_attempt_generation", None),+ "%s was superseded by a newer working attempt (current working: %s) (session=%s).",+ attempt_generation,+ _working_gen,agent.session_id or "none",)_restore_messages_snapshot(messages, messages_before_compression)diff --git a/tests/agent/test_compression_attempt_lifecycle.py b/tests/agent/test_compression_attempt_lifecycle.pyindex 15a24db7eb6..0d0f454415d 100644--- a/tests/agent/test_compression_attempt_lifecycle.py+++ b/tests/agent/test_compression_attempt_lifecycle.py@@ -32,6 +32,7 @@ from agent.auxiliary_client import AuxiliaryExplicitCancellationfrom agent.conversation_compression import (CompressionCommitFence,_claim_compressor_attempt,+ _mark_compressor_working_attempt,compress_context,compression_blocked_transiently,run_compress_context_with_progress_timeout,@@ -236,8 +237,10 @@ class TestSupersessionDiscardsLateResults:def compress_and_get_superseded(messages, **_kwargs):# While this attempt's summary was in flight, a NEWER attempt- # claimed the compressor (what a retry/fallback does).- _claim_compressor_attempt(agent.context_compressor)+ # claimed the compressor AND began its own summary work (what a+ # retry/fallback reaching dispatch does).+ newer = _claim_compressor_attempt(agent.context_compressor)+ _mark_compressor_working_attempt(agent.context_compressor, newer)return [{"role": "assistant", "content": "stale summary"}]agent.context_compressor.compress = compress_and_get_supersededdiff --git a/tests/agent/test_compression_supersession_split.py b/tests/agent/test_compression_supersession_split.pynew file mode 100644index 00000000000..e8f9eb1d641--- /dev/null+++ b/tests/agent/test_compression_supersession_split.py@@ -0,0 +1,110 @@+"""Candidate supersession must key on working attempts, not entry claims.++Regression for the compression livelock: ``_begin_compression_attempt()``+claims the monotonic generation on entry — before the breaker gates and the+per-session lock — so every early no-op return (lock sit-outs, transient+gates) has already bumped the shared counter without doing any work. The+commit-side gate then discarded a *completed* summary as "superseded" by+those no-op claims: nothing committed, the session stayed over threshold and+re-triggered compression every turn.+"""++import copy+from pathlib import Path+from unittest.mock import patch++import os++from agent.conversation_compression import (+ _claim_compressor_attempt,+ _mark_compressor_working_attempt,+ compress_context,+)+from hermes_state import SessionDB+++def _build_agent(tmp_path: Path, session_id: str):+ db = SessionDB(db_path=tmp_path / "state.db")+ db.create_session(session_id, source="cli")+ 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,+ )+ agent._compression_feasibility_checked = True+ agent.compression_in_place = True+ agent._cached_system_prompt = "sys"+ agent.context_compressor.threshold_tokens = 1_000+ return db, agent+++def _messages():+ return [{"role": "user", "content": f"m{i}"} for i in range(20)]+++class TestSupersessionKeysOnWorkingAttempts:+ def test_noop_claims_do_not_discard_a_completed_summary(self, tmp_path: Path):+ """Lock sit-outs claim the entry generation without doing work; the+ attempt that actually ran the summary must still commit. Sabotage:+ removing the working-attempt split regresses this to the livelock+ (candidate discarded, input returned unchanged)."""+ db, agent = _build_agent(tmp_path, "LIVELOCK")+ live = _messages()+ original = copy.deepcopy(live)+ summary = [+ {"role": "user", "content": "m0"},+ {"role": "assistant", "content": "summary"},+ ]++ def compress_while_sitouts_claim(messages, **_kwargs):+ # Sit-outs while this summary is in flight: each claims the entry+ # generation and returns without touching a provider (what+ # _sit_out_lock_contention / transient gates do on other paths).+ for _ in range(5):+ _claim_compressor_attempt(agent.context_compressor)+ return summary++ agent.context_compressor.compress = compress_while_sitouts_claim+ out, _prompt = compress_context(agent, live, "sys", approx_tokens=500_000)+ assert out == summary, (+ "a completed summary was discarded as superseded by no-op entry "+ "claims — the compression livelock (#112482)"+ )+ assert live != original or out is not live+ assert db.get_compression_lock_holder("LIVELOCK") is None++ def test_genuinely_newer_working_attempt_still_discards_late_candidate(+ self, tmp_path: Path+ ):+ """A newer attempt that began its own summary work (stall-fallback+ overlap) still supersedes: the late candidate is discarded, never+ committed over newer state."""+ db, agent = _build_agent(tmp_path, "WORKING_SUPERSEDE")+ live = _messages()+ original = copy.deepcopy(live)++ def compress_and_get_superseded(messages, **_kwargs):+ # While this attempt's summary was in flight, a NEWER attempt+ # claimed the compressor AND began its own summary work (what a+ # retry/fallback does when it reaches dispatch).+ newer = _claim_compressor_attempt(agent.context_compressor)+ _mark_compressor_working_attempt(agent.context_compressor, newer)+ return [{"role": "assistant", "content": "stale summary"}]++ agent.context_compressor.compress = compress_and_get_superseded+ out, _prompt = compress_context(agent, live, "sys", approx_tokens=500_000)+ assert out == original, (+ "late candidate from an attempt superseded by a newer WORKING "+ "attempt must be discarded, never committed over newer state"+ )+ assert live == original+ assert db.get_compression_lock_holder("WORKING_SUPERSEDE") is None+ db.append_message("WORKING_SUPERSEDE", "assistant", "still writable")