The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): track commit fences as a registration stack
beardthelion09b72bc6d2f0
diff --git a/agent/compression_facade.py b/agent/compression_facade.pyindex 576b54d194d..e3f1ba7ea0a 100644--- a/agent/compression_facade.py+++ b/agent/compression_facade.py@@ -17,6 +17,21 @@ from agent.session_activity import ActivityProvenancelogger = logging.getLogger("run_agent")+class _CommitFenceRegistration:+ """One ``_compress_context`` attempt's entry on the agent's commit-fence stack.++ The fence slot is a stack, not a save/restore cell: overlapping attempts register in+ order but may complete in any order, so each attempt removes only its own entry and the+ published slot always tracks the newest *live* attempt. The stall-fallback retry swaps+ ``fence`` in place so the slot update stays tied to the owning registration.+ """++ __slots__ = ("fence",)++ def __init__(self, fence) -> None:+ self.fence = fence++def _timeout_fallback_prompt(agent, system_message: str) -> str:"""Cached prompt, else a fresh build, else the raw ``system_message`` (never raises).Resolved lazily by the timeout wrapper: an eager rebuild would raise before compress_context runs when@@ -106,8 +121,8 @@ def _sync_persisted_markers(target_messages, source_messages) -> None:def _run_under_progress_timeout(- agent, run, messages, system_message, *, active_fence, fence_registration_lock, idle_timeout, total_ceiling,- approx_tokens=None,+ agent, run, messages, system_message, *, active_fence, registration, fence_registration_lock,+ idle_timeout, total_ceiling, approx_tokens=None,):"""Run ``run(fence, target_messages=snapshot)`` on the pool under the progress-aware timeout.The pooled worker must NEVER share the caller's live transcript — a late engine after a host timeout could@@ -150,10 +165,14 @@ def _run_under_progress_timeout(def _publish_new_fence():# The stall-fallback retry needs a fence the aborted attempt cannot veto; publish- # it on the slot hard_interrupt() reads. The caller's finally restores its fence.+ # it on the slot hard_interrupt() reads, but only while this attempt still owns the+ # top registration. A later attempt's live fence must not be clobbered.retry_fence = CompressionCommitFence()with fence_registration_lock:- agent._active_compression_commit_fence = retry_fence+ registration.fence = retry_fence+ stack = vars(agent).get("_compression_commit_fence_stack") or ()+ if stack and stack[-1] is registration:+ agent._active_compression_commit_fence = retry_fencereturn retry_fencereturn run_compress_context_with_progress_timeout(@@ -249,11 +268,12 @@ class CompressionFacadeMixin:# entrypoints cannot replace the fence of the attempt currently committing.active_fence = commit_fence or CompressionCommitFence()fence_registration_lock = vars(self).setdefault("_compression_commit_fence_lock", threading.RLock())- with fence_registration_lock:- missing_fence = object()- previous_fence = vars(self).get("_active_compression_commit_fence", missing_fence)- self._active_compression_commit_fence = active_fence+ registration = _CommitFenceRegistration(active_fence)try:+ with fence_registration_lock:+ fence_stack = vars(self).setdefault("_compression_commit_fence_stack", [])+ fence_stack.append(registration)+ self._active_compression_commit_fence = active_fencedef _run(fence=None, target_messages=None, same_turn_fallback_recovery=False):return compress_context(@@ -274,18 +294,30 @@ class CompressionFacadeMixin:else:result = _run_under_progress_timeout(self, _run, messages, system_message,- active_fence=active_fence, fence_registration_lock=fence_registration_lock,+ active_fence=active_fence, registration=registration,+ fence_registration_lock=fence_registration_lock,idle_timeout=idle_timeout, total_ceiling=total_ceiling, approx_tokens=approx_tokens,)_mirror_result_onto_live_lists(self, result, messages, direct_path=direct_path)_rebind_caller_session_context(self)return resultfinally:+ # Remove only THIS attempt's registration. Completion order is not registration+ # order: restoring a saved "previous" fence would resurrect a dead fence over a+ # live newer attempt (and popping the slot outright would delete that attempt's+ # fence mid-run). The slot always tracks the newest live registration.with fence_registration_lock:- if previous_fence is missing_fence:- vars(self).pop("_active_compression_commit_fence", None)+ # Re-read rather than reuse the try-block local: an early exception before+ # the append would otherwise raise NameError here and mask the real failure.+ fence_stack = vars(self).get("_compression_commit_fence_stack") or ()+ for idx in range(len(fence_stack) - 1, -1, -1):+ if fence_stack[idx] is registration:+ del fence_stack[idx]+ break+ if fence_stack:+ self._active_compression_commit_fence = fence_stack[-1].fenceelse:- self._active_compression_commit_fence = previous_fence+ vars(self).pop("_active_compression_commit_fence", None)# Restore whatever the caller had, so a compaction never leaks its tag into the surrounding scope.if token is not None:reset_conversation_context(token)diff --git a/tests/agent/test_compression_commit_fence_race.py b/tests/agent/test_compression_commit_fence_race.pynew file mode 100644index 00000000000..d8fe8440fc0--- /dev/null+++ b/tests/agent/test_compression_commit_fence_race.py@@ -0,0 +1,199 @@+"""Regression: out-of-order completion of overlapping ``_compress_context`` calls+must not corrupt ``_active_compression_commit_fence``.++The fence slot used to be a save/restore cell: attempt B saved previous=A and+published B. When A completed first, its finally popped the slot, deleting B's+live fence mid-attempt (hard_interrupt lost the handle serializing cancel+admission against B's begin_commit). B's finally then republished A's dead+fence, which lingered until the next compression. The slot must instead track+the newest *live* attempt: a registration stack where each attempt removes only+its own entry.+"""++import os+import threading+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import agent.compression_facade as compression_facade+import agent.conversation_compression as conversation_compression+from agent.conversation_compression import CompressionCommitFence+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",+ platform="telegram",+ quiet_mode=True,+ session_db=db,+ session_id=session_id,+ skip_context_files=True,+ skip_memory=True,+ )+ compressor = MagicMock()+ compressor.compression_count = 0+ compressor.last_prompt_tokens = 0+ compressor.last_completion_tokens = 0+ compressor._last_summary_error = None+ compressor._last_compress_aborted = False+ compressor._last_summary_auth_failure = False+ compressor._last_aux_model_failure_model = None+ compressor._last_aux_model_failure_error = None+ agent.context_compressor = compressor+ return agent+++def _overlapping_attempts(agent, messages):+ """Drive two _compress_context attempts whose compress_context calls block on+ release events; returns the controls needed to order their completion."""+ fence_a, fence_b = CompressionCommitFence(), CompressionCommitFence()+ entered_a, entered_b = threading.Event(), threading.Event()+ release_a, release_b = threading.Event(), threading.Event()+ errors = []++ def _fake_compress(_agent, _msgs, _sysmsg, *, commit_fence=None, **_kw):+ if commit_fence is fence_a:+ entered_a.set()+ assert release_a.wait(10), "attempt A never released"+ elif commit_fence is fence_b:+ entered_b.set()+ assert release_b.wait(10), "attempt B never released"+ return [{"role": "user", "content": "x"}], "prompt"++ def _attempt(fence):+ try:+ agent._compress_context(messages, "sys", commit_fence=fence)+ except Exception as exc: # noqa: BLE001 - surfaced via assertion below+ errors.append(exc)++ return fence_a, fence_b, entered_a, entered_b, release_a, release_b, errors, _fake_compress, _attempt+++class TestCommitFenceCompletionOrder:+ def test_earlier_attempt_finishing_first_keeps_newer_live_fence(+ self, tmp_path: Path, monkeypatch+ ):+ db = SessionDB(db_path=tmp_path / "state.db")+ db.create_session("S", source="cli")+ agent = _build_agent(db, "S")+ messages = [{"role": "user", "content": "live question"}]++ (fence_a, fence_b, entered_a, entered_b, release_a, release_b,+ errors, fake, attempt) = _overlapping_attempts(agent, messages)+ monkeypatch.setattr(conversation_compression, "compress_context", fake)++ thread_a = threading.Thread(target=attempt, args=(fence_a,), daemon=True)+ thread_b = threading.Thread(target=attempt, args=(fence_b,), daemon=True)+ thread_a.start()+ assert entered_a.wait(5)+ thread_b.start()+ assert entered_b.wait(5)+ assert vars(agent)["_active_compression_commit_fence"] is fence_b++ # A completes while B is still in its try block: B's fence must survive.+ release_a.set()+ thread_a.join(10)+ assert vars(agent).get("_active_compression_commit_fence") is fence_b++ release_b.set()+ thread_b.join(10)+ assert "_active_compression_commit_fence" not in vars(agent)+ assert not errors++ def test_lifo_completion_restores_outer_fence_while_it_runs(+ self, tmp_path: Path, monkeypatch+ ):+ db = SessionDB(db_path=tmp_path / "state.db")+ db.create_session("S", source="cli")+ agent = _build_agent(db, "S")+ messages = [{"role": "user", "content": "live question"}]++ (fence_a, fence_b, entered_a, entered_b, release_a, release_b,+ errors, fake, attempt) = _overlapping_attempts(agent, messages)+ monkeypatch.setattr(conversation_compression, "compress_context", fake)++ thread_a = threading.Thread(target=attempt, args=(fence_a,), daemon=True)+ thread_b = threading.Thread(target=attempt, args=(fence_b,), daemon=True)+ thread_a.start()+ assert entered_a.wait(5)+ thread_b.start()+ assert entered_b.wait(5)++ # B completes first: A's still-running attempt gets its fence back.+ release_b.set()+ thread_b.join(10)+ assert vars(agent).get("_active_compression_commit_fence") is fence_a++ release_a.set()+ thread_a.join(10)+ assert "_active_compression_commit_fence" not in vars(agent)+ assert not errors+++def _capture_new_fence(monkeypatch):+ """Stub the progress-timeout runner; return the dict that receives its kwargs."""+ captured = {}++ def _stub_runner(**kw):+ captured.update(kw)+ return (["m"], "p")++ monkeypatch.setattr(+ conversation_compression, "run_compress_context_with_progress_timeout", _stub_runner)+ monkeypatch.setattr(+ conversation_compression, "request_exceeds_model_window", lambda *a, **k: False)+ return captured+++class TestStallFallbackFencePublication:+ """``_publish_new_fence`` swaps the owning registration's fence and publishes to the+ slot only while that attempt still holds the top registration."""++ def _drive(self, monkeypatch, agent, registration, fence, lock):+ captured = _capture_new_fence(monkeypatch)+ compression_facade._run_under_progress_timeout(+ agent, lambda *a, **k: (["m"], "p"), [{"role": "user", "content": "x"}], "sys",+ active_fence=fence, registration=registration, fence_registration_lock=lock,+ idle_timeout=1, total_ceiling=2)+ return captured["new_fence"]++ def test_retry_fence_publishes_while_attempt_owns_slot(self, monkeypatch):+ agent = SimpleNamespace()+ lock = threading.RLock()+ fence = CompressionCommitFence()+ registration = compression_facade._CommitFenceRegistration(fence)+ with lock:+ vars(agent)["_compression_commit_fence_stack"] = [registration]+ agent._active_compression_commit_fence = fence++ retry = self._drive(monkeypatch, agent, registration, fence, lock)()++ assert isinstance(retry, CompressionCommitFence)+ assert registration.fence is retry+ assert vars(agent)["_active_compression_commit_fence"] is retry++ def test_retry_fence_does_not_clobber_newer_attempt(self, monkeypatch):+ agent = SimpleNamespace()+ lock = threading.RLock()+ fence = CompressionCommitFence()+ registration = compression_facade._CommitFenceRegistration(fence)+ other_fence = CompressionCommitFence()+ other = compression_facade._CommitFenceRegistration(other_fence)+ with lock:+ vars(agent)["_compression_commit_fence_stack"] = [registration, other]+ agent._active_compression_commit_fence = other_fence++ retry = self._drive(monkeypatch, agent, registration, fence, lock)()++ # The retry still gets its own fresh fence for begin_commit/cancel serialization,+ # but the published slot stays with the newer live attempt.+ assert isinstance(retry, CompressionCommitFence)+ assert registration.fence is retry+ assert vars(agent)["_active_compression_commit_fence"] is other_fence