Skip to content

The agent that grows with you

fix(agent): silence detached compression heartbeat after host timeout

fangliquanflq61e722261ce1
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index d28b54bebfc..ad96ef0d6d6 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -55,7 +55,9 @@ logger = logging.getLogger(__name__)
# Terminal compression outcomes published by host/hygiene timeout or cooldown
# writers. Detached heartbeat workers must not clobber these back to
-# agent.compression after cancel (otherwise timeout is unobservable).
+# agent.compression after cancel (otherwise timeout is unobservable). Observing
+# a terminal stamp (or a cancelled commit fence) also latches the heartbeat
+# silent so a later UNKNOWN rewrite cannot re-arm a zombie worker.
_TERMINAL_COMPRESSION_PROVENANCES = frozenset(
{
ActivityProvenance.AGENT_COMPRESSION_TIMEOUT,
@@ -499,6 +501,11 @@ class CompressionCommitFence:
"""Leave a commit boundary entered by :meth:`begin_commit`."""
self._lock.release()
+ @property
+ def is_cancelled(self) -> bool:
+ """True after cancellation won before the commit boundary."""
+ return self._cancelled
+
# Defaults for the in-agent (non-hygiene) progress-aware compress_context wrap.
# Mirror hermes_cli.config.DEFAULT_CONFIG["compression"] keys of the same name.
@@ -981,8 +988,17 @@ def _supported_compression_kwargs(
class _CompressionActivityHeartbeat:
"""Refresh the agent inactivity tracker while compression blocks in an aux call."""
- def __init__(self, agent: Any, interval_seconds: float | None = None) -> None:
+ def __init__(
+ self,
+ agent: Any,
+ interval_seconds: float | None = None,
+ commit_fence: Optional[CompressionCommitFence] = None,
+ ) -> None:
self._agent = agent
+ self._commit_fence = commit_fence
+ # Latched once host cancel/timeout wins or a terminal stamp is observed,
+ # so a later UNKNOWN rewrite cannot re-arm a detached zombie heartbeat.
+ self._suppressed = False
if interval_seconds is None:
interval_seconds = getattr(agent, "_compression_activity_heartbeat_interval", 60.0)
try:
@@ -1002,6 +1018,7 @@ class _CompressionActivityHeartbeat:
def start(self) -> "_CompressionActivityHeartbeat":
# A new compression episode always republishes agent.compression even
# if a prior timeout/cooldown stamp is still on the agent.
+ self._suppressed = False
self._touch("context compression started", allow_terminal_overwrite=True)
self._thread.start()
return self
@@ -1010,24 +1027,49 @@ class _CompressionActivityHeartbeat:
self._stop.set()
if self._thread.is_alive() and threading.current_thread() is not self._thread:
self._thread.join(timeout=1.0)
+ # Host timeout already owns the terminal stamp; a detached worker's
+ # late stop must not republish agent.compression / "completed".
+ if self._should_suppress():
+ return
self._touch(desc)
+ def _fence_cancelled(self) -> bool:
+ fence = self._commit_fence
+ return fence is not None and fence.is_cancelled
+
+ def _should_suppress(self) -> bool:
+ if self._suppressed:
+ return True
+ if self._fence_cancelled():
+ self._suppressed = True
+ return True
+ return False
+
def _touch(self, desc: str, *, allow_terminal_overwrite: bool = False) -> None:
try:
if not allow_terminal_overwrite:
+ if self._should_suppress():
+ return
current = normalize_activity_provenance(
getattr(self._agent, "_last_activity_provenance", None)
)
if current in _TERMINAL_COMPRESSION_PROVENANCES:
+ self._suppressed = True
return
touch = getattr(self._agent, "_touch_activity", None)
if callable(touch):
+ # Re-check after reading provenance: host may cancel/stamp
+ # TIMEOUT between the earlier guard and the write.
+ if not allow_terminal_overwrite and self._should_suppress():
+ return
touch(desc, provenance=ActivityProvenance.AGENT_COMPRESSION)
except Exception:
logger.debug("compression activity heartbeat touch failed", exc_info=True)
def _run(self) -> None:
while not self._stop.wait(self._interval_seconds):
+ if self._should_suppress():
+ return
self._touch("context compression in progress")
@@ -2232,7 +2274,9 @@ def compress_context(
)
messages_before_compression = copy.deepcopy(messages)
- _activity_heartbeat = _CompressionActivityHeartbeat(agent).start()
+ _activity_heartbeat = _CompressionActivityHeartbeat(
+ agent, commit_fence=commit_fence
+ ).start()
# Publish forward progress to the commit fence while the summary LLM
# call streams. Async hosts (gateway session hygiene) poll
# ``commit_fence.seconds_since_progress()`` to extend their deadline
diff --git a/tests/agent/test_compression_concurrent_fork.py b/tests/agent/test_compression_concurrent_fork.py
index 99942475b71..1b789b7d207 100644
--- a/tests/agent/test_compression_concurrent_fork.py
+++ b/tests/agent/test_compression_concurrent_fork.py
@@ -364,6 +364,79 @@ def test_compression_heartbeat_start_republishes_after_terminal_provenance() ->
assert agent._last_activity_provenance is ActivityProvenance.AGENT_COMPRESSION
+def test_compression_heartbeat_does_not_rearm_after_unknown_provenance() -> None:
+ """After a terminal stamp, UNKNOWN must not re-arm a detached heartbeat."""
+ from types import SimpleNamespace
+
+ from agent.conversation_compression import _CompressionActivityHeartbeat
+ from agent.session_activity import ActivityProvenance
+
+ agent = SimpleNamespace(
+ _last_activity_provenance=ActivityProvenance.AGENT_COMPRESSION_TIMEOUT,
+ _last_activity_desc="context compression timed out",
+ touches=[],
+ )
+
+ def _touch(desc, *, provenance=None):
+ agent.touches.append((desc, provenance))
+ agent._last_activity_provenance = provenance
+ agent._last_activity_desc = desc
+
+ agent._touch_activity = _touch
+
+ hb = _CompressionActivityHeartbeat(agent, interval_seconds=60.0)
+ # First tick observes TIMEOUT and latches silent.
+ hb._touch("context compression in progress")
+ assert hb._suppressed is True
+ # Turn continues / ends and clears labels to UNKNOWN — must stay silent.
+ agent._last_activity_provenance = ActivityProvenance.UNKNOWN
+ agent._last_activity_desc = "calling model"
+ hb._touch("context compression in progress")
+ hb.stop("context compression completed")
+
+ assert agent.touches == []
+ assert agent._last_activity_provenance is ActivityProvenance.UNKNOWN
+ assert agent._last_activity_desc == "calling model"
+
+
+def test_compression_heartbeat_stops_when_commit_fence_cancelled() -> None:
+ """Host fence cancel must silence detached heartbeat refresh and late stop."""
+ from types import SimpleNamespace
+
+ from agent.conversation_compression import (
+ CompressionCommitFence,
+ _CompressionActivityHeartbeat,
+ )
+ from agent.session_activity import ActivityProvenance
+
+ agent = SimpleNamespace(
+ _last_activity_provenance=ActivityProvenance.AGENT_COMPRESSION,
+ _last_activity_desc="context compression started",
+ touches=[],
+ )
+
+ def _touch(desc, *, provenance=None):
+ agent.touches.append((desc, provenance))
+ agent._last_activity_provenance = provenance
+ agent._last_activity_desc = desc
+
+ agent._touch_activity = _touch
+
+ fence = CompressionCommitFence()
+ assert fence.cancel_before_commit() is True
+
+ hb = _CompressionActivityHeartbeat(
+ agent, interval_seconds=60.0, commit_fence=fence
+ )
+ hb._touch("context compression in progress")
+ hb.stop("context compression completed")
+
+ assert agent.touches == []
+ assert hb._suppressed is True
+ assert agent._last_activity_provenance is ActivityProvenance.AGENT_COMPRESSION
+ assert agent._last_activity_desc == "context compression started"
+
+
def test_concurrent_compression_does_not_fork_session(tmp_path: Path) -> None:
"""Two AIAgents that share a session_id MUST NOT both rotate it.