The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): reconcile explicit hard-cancel (main d15b638a88) with pooled fence rework
Teknium15267a1d2d7f
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex a6fce9bf434..756b93ecc49 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -536,7 +536,12 @@ class CompressionCommitFence:def begin_commit(self, cancel_event: Any = None) -> bool:"""Atomically admit commit unless a hard cancellation already won."""self._lock.acquire()- if self._cancelled or self._admission_revoked:+ if (+ self._cancelled+ or self._admission_revoked+ or (cancel_event is not None and bool(cancel_event.is_set()))+ ):+ self._cancelled = Trueself._lock.release()return Falseself._commit_started = True@@ -781,6 +786,7 @@ def run_compress_context_with_progress_timeout(total_ceiling_seconds: float,on_timeout: Optional[Callable[[float, float, float], None]] = None,on_commit_overrun: Optional[Callable[[float, float], None]] = None,+ fence: Optional[CompressionCommitFence] = None,) -> Tuple[list, str]:"""Run ``worker(fence)`` under a sync progress-aware timeout.@@ -823,7 +829,7 @@ def run_compress_context_with_progress_timeout(return system_prompt_fallback()return system_prompt_fallback- fence = CompressionCommitFence()+ fence = fence if fence is not None else CompressionCommitFence()ceiling = max(float(total_ceiling_seconds), float(idle_timeout_seconds))idle = float(idle_timeout_seconds)# Sync mirror of gateway session-hygiene's run_in_executor(None, ...) +@@ -2761,6 +2767,10 @@ def compress_context()except Exception:pass+ # Incoming-message interrupts and active-turn redirects must not tear an+ # atomic summary in half (#23975). Explicit stop surfaces set a separate+ # Event atomically; never infer cause from the racy message fields.+ _hard_cancel_event = getattr(agent, "_hard_interrupt_requested", None)try:# F6: never start expensive summary work for an already-cancelled# fence (a stale queued job admitted after host departure).@@ -2772,14 +2782,72 @@ def compress_context()compressed = messageselse:- with aux_progress_hook(_progress_hook):+ with aux_progress_hook(_progress_hook), aux_interrupt_protection(+ cancel_event=_hard_cancel_event+ ):compressed = compress_fn(messages, **compress_kwargs)+ # Freeze a hard stop that arrived after the final provider+ # attempt unwound but before this transaction can rotate+ # session state.+ if (+ _hard_cancel_event is not None+ and _hard_cancel_event.is_set()+ ):+ raise AuxiliaryExplicitCancellation()finally:if commit_fence is not None:try:agent.context_compressor._compression_cancelled_check = Noneexcept Exception:pass+ except AuxiliaryExplicitCancellation:+ try:+ _restore_compressor_attempt_state(+ agent.context_compressor,+ _compressor_attempt_snapshot,+ durable_cooldown_authoritative=_durable_cooldown_authoritative,+ durable_cooldown_state=_durable_cooldown_state,+ )+ except BaseException as _rollback_exc:+ # Compensation failure must surface, but it must not strand the+ # session lease or retain an in-memory transcript mutation.+ if (+ messages_before_compression is not None+ and messages != messages_before_compression+ ):+ messages[:] = copy.deepcopy(messages_before_compression)+ if _activity_heartbeat is not None:+ _activity_heartbeat.stop("context compression rollback failed")+ _activity_heartbeat = None+ _release_lock()+ _emit_compression_attempt_telemetry(+ agent,+ started_at=_attempt_started_at,+ commit_status="aborted",+ split_status="aborted",+ failure_class=f"rollback:{type(_rollback_exc).__name__}",+ )+ raise+ if (+ messages_before_compression is not None+ and messages != messages_before_compression+ ):+ messages[:] = copy.deepcopy(messages_before_compression)+ if _activity_heartbeat is not None:+ _activity_heartbeat.stop("context compression cancelled")+ _activity_heartbeat = None+ _release_lock()+ _emit_compression_attempt_telemetry(+ agent,+ started_at=_attempt_started_at,+ commit_status="aborted",+ split_status="aborted",+ failure_class="explicit_interrupt",+ )+ _existing_sp = getattr(agent, "_cached_system_prompt", None)+ if not _existing_sp:+ _existing_sp = agent._build_system_prompt(system_message)+ return messages, _existing_spexcept BaseException as _compress_exc:# ANY exception after lock acquisition — memory hook, capability# inspection, engine lookup, or compress() — must release the lock sodiff --git a/run_agent.py b/run_agent.pyindex c8282f7a02c..eee84344ef2 100644--- a/run_agent.py+++ b/run_agent.py@@ -7094,6 +7094,7 @@ class AIAgent:``force=False``."""from agent.conversation_compression import (+ CompressionCommitFence,compress_context,resolve_context_compression_timeouts,run_compress_context_with_progress_timeout,@@ -7122,6 +7123,22 @@ class AIAgent:root = self._conversation_root_id()if root:token = set_conversation_context(root)+ # Every AIAgent compression has a fence, including ordinary in-turn and+ # manual paths. hard_interrupt() uses this exact instance to serialize+ # cancel admission against begin_commit().+ active_fence = commit_fence or CompressionCommitFence()+ # A single agent can receive overlapping automatic/manual entrypoints.+ # Serialize fence publication so a waiter cannot replace the fence of+ # the attempt currently generating/committing a summary.+ 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_fencetry:def _run(fence=None, target_messages=None):return compress_context(@@ -7140,11 +7157,11 @@ class AIAgent:# Callers that already own a progress-aware wait (gateway session# hygiene) pass commit_fence and must not be double-wrapped.if commit_fence is not None:- return _run(commit_fence)+ return _run(active_fence)idle_timeout, total_ceiling = resolve_context_compression_timeouts()if idle_timeout <= 0:- return _run(None)+ return _run(active_fence)def _snapshot_worker(fence=None):# #76354 review F3: the pooled worker must NEVER share the@@ -7259,6 +7276,7 @@ class AIAgent:total_ceiling_seconds=total_ceiling,on_timeout=_on_timeout,on_commit_overrun=_on_commit_overrun,+ fence=active_fence,)# compress_context ran on a daemon pool worker thread; the session# id rotation updated hermes_logging._session_context (a@@ -7288,6 +7306,11 @@ class AIAgent:)return resultfinally:+ with fence_registration_lock:+ if previous_fence is missing_fence:+ vars(self).pop("_active_compression_commit_fence", None)+ else:+ self._active_compression_commit_fence = previous_fence# Restore whatever the caller had, so a compaction never leaks its# tag into the surrounding scope.if token is not None:diff --git a/tests/agent/test_compression_concurrent_fork.py b/tests/agent/test_compression_concurrent_fork.pyindex 772cb3d56cf..9cc18dee1ef 100644--- a/tests/agent/test_compression_concurrent_fork.py+++ b/tests/agent/test_compression_concurrent_fork.py@@ -1240,10 +1240,14 @@ def test_hard_interrupt_aborts_compression_and_unblocks_session_writes(tmp_path:messages = [{"role": "user", "content": f"m{i}"} for i in range(20)]original_messages = copy.deepcopy(messages)- def _cancelled_compress(*_args, **_kwargs):+ def _cancelled_compress(current, *_args, **_kwargs):agent._hard_interrupt_requested.set()assert aux._aux_interrupt_cancel_requested() is True- messages[0]["content"] = "must be rolled back"+ # F3 isolation: the engine only ever sees the pooled snapshot, so an+ # in-place mutation lands on ``current`` (the worker's copy), never on+ # the caller's live list. The rollback contract is that the RETURNED+ # transcript equals the pre-compression one.+ current[0]["content"] = "must be rolled back"raise aux.AuxiliaryExplicitCancellation()agent.context_compressor.compress.side_effect = _cancelled_compress