Skip to content

The agent that grows with you

fix(compression): heartbeat honours the quiet-engine contract and the single start line

kshitijk4poorc41525b290a5
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index a82d69bc49a..2450f9d3c2f 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -2315,6 +2315,8 @@ class _CompressionActivityHeartbeat:
self,
agent: Any,
interval_seconds: float | None = None,
+ *,
+ emit_client_status: bool = False,
commit_fence: Optional[CompressionCommitFence] = None,
) -> None:
self._agent = agent
@@ -2331,6 +2333,10 @@ class _CompressionActivityHeartbeat:
if not math.isfinite(interval_seconds):
interval_seconds = 60.0
self._interval_seconds = max(0.1, interval_seconds)
+ # Only a compression that opened a VISIBLE compaction phase (the
+ # routine start status was emitted) keeps it alive with heartbeats;
+ # quiet context engines emit neither (#98371 follow-up).
+ self._emit_client_status = emit_client_status
self._stop = threading.Event()
self._thread = threading.Thread(
target=self._run,
@@ -2343,7 +2349,6 @@ class _CompressionActivityHeartbeat:
# if a prior timeout/cooldown stamp is still on the agent.
self._suppressed = False
self._touch("context compression started", allow_terminal_overwrite=True)
- self._emit_progress_status()
self._thread.start()
return self
@@ -2405,7 +2410,7 @@ class _CompressionActivityHeartbeat:
logger.debug("compression activity heartbeat touch failed", exc_info=True)
def _emit_progress_status(self) -> None:
- """Publish a client-visible ``compacting`` status line.
+ """Re-publish the compacting status so remote transports see progress.
Compression can stream for minutes with no deltas, tool events, or
status lines reaching remote transports. Idle-progress watchdogs on
@@ -2413,22 +2418,23 @@ class _CompressionActivityHeartbeat:
treat the silence as a dead turn and fire ``session.interrupt`` —
killing a healthy compression mid-flight and rolling back its work,
which retriggers on the next prompt and loops forever on sessions
- near the context ceiling. A periodic ``status_callback`` heartbeat
- gives every transport a progress event to re-arm on.
+ near the context ceiling (#98371).
+
+ Routed through ``agent._emit_status`` like every other compaction
+ status: same "lifecycle" key (the TUI gateway re-tags it to
+ ``compacting``; Telegram edits one bubble per key), same chat-platform
+ filter, same CLI print path.
"""
- status_callback = getattr(self._agent, "status_callback", None)
- if not status_callback:
+ if not self._emit_client_status:
+ return
+ emit = getattr(self._agent, "_emit_status", None)
+ if not callable(emit):
return
try:
- # Same "lifecycle" key as every other compaction status: the
- # TUI gateway re-tags it to kind="compacting" via
- # is_compaction_progress_status, and Telegram's per-key
- # send_or_update_status edits the existing bubble instead of
- # appending one per tick.
- status_callback("lifecycle", COMPACTION_HEARTBEAT_STATUS)
+ emit(COMPACTION_HEARTBEAT_STATUS)
except Exception:
logger.debug(
- "status_callback error in compression heartbeat", exc_info=True
+ "status emit error in compression heartbeat", exc_info=True
)
def _run(self) -> None:
@@ -4192,7 +4198,9 @@ def compress_context(
messages_before_compression = copy.deepcopy(messages)
_activity_heartbeat = _CompressionActivityHeartbeat(
- agent, commit_fence=commit_fence
+ agent,
+ commit_fence=commit_fence,
+ emit_client_status=_compaction_status_emitted,
).start()
# Publish forward progress to the commit fence while the summary LLM
# call streams. Async hosts (gateway session hygiene) poll
@@ -5788,7 +5796,9 @@ def _compress_context_via_codex_app_server(
_activity_heartbeat: Optional[_CompressionActivityHeartbeat] = None
try:
- _activity_heartbeat = _CompressionActivityHeartbeat(agent).start()
+ _activity_heartbeat = _CompressionActivityHeartbeat(
+ agent, emit_client_status=True
+ ).start()
result = codex_session.compact_thread()
except BaseException:
if _activity_heartbeat is not None:
diff --git a/tests/agent/test_compression_concurrent_fork.py b/tests/agent/test_compression_concurrent_fork.py
index 2b7ac84c7e6..831f1f95849 100644
--- a/tests/agent/test_compression_concurrent_fork.py
+++ b/tests/agent/test_compression_concurrent_fork.py
@@ -168,14 +168,19 @@ def test_compression_activity_heartbeat_touches_agent_during_long_compress(tmp_p
def test_compression_activity_heartbeat_emits_client_status_events(tmp_path: Path) -> None:
- """The heartbeat must emit ``compacting`` status events, not just DB touches.
+ """The heartbeat must re-emit the compacting status, not just DB touches.
Remote transports (e.g. the Android relay app) run idle-progress turn
watchdogs that ``session.interrupt`` a turn after ~180s with no gateway
events. Compression is silent on the event stream, so without periodic
- ``status_callback`` heartbeats a long compression is killed mid-flight
- and retriggers forever on sessions near the context ceiling.
+ status heartbeats a long compression is killed mid-flight and retriggers
+ forever on sessions near the context ceiling.
"""
+ from agent.conversation_compression import (
+ COMPACTION_HEARTBEAT_STATUS,
+ is_compaction_progress_status,
+ )
+
db = SessionDB(db_path=tmp_path / "state.db")
session_id = "HEARTBEAT_STATUS_TEST"
db.create_session(session_id, source="test")
@@ -203,23 +208,62 @@ def test_compression_activity_heartbeat_emits_client_status_events(tmp_path: Pat
agent._compress_context(messages, "sys", approx_tokens=120_000)
- from agent.conversation_compression import (
- COMPACTION_HEARTBEAT_STATUS,
- is_compaction_progress_status,
- )
-
- heartbeats = [
- (event, message)
- for event, message in status_events
- if message == COMPACTION_HEARTBEAT_STATUS
- ]
- # One emit at heartbeat start plus at least one periodic tick while the
- # summary call blocks.
- assert len(heartbeats) >= 2
+ heartbeats = [e for e in status_events if e[1] == COMPACTION_HEARTBEAT_STATUS]
+ assert heartbeats, "no heartbeat status reached the client"
# Same "lifecycle" key as the other compaction statuses so the TUI gateway
# re-tags it to kind="compacting" and Telegram edits one bubble in place.
assert {event for event, _ in heartbeats} == {"lifecycle"}
assert is_compaction_progress_status(COMPACTION_HEARTBEAT_STATUS)
+ # Exactly one routine start line precedes the first heartbeat; the
+ # heartbeat no longer re-emits a start of its own (adapters without
+ # send_or_update_status would otherwise post two messages).
+ assert status_events[0][1] != COMPACTION_HEARTBEAT_STATUS
+ # Every heartbeat is a periodic tick: none may precede the first
+ # "in progress" DB touch, which is what start() would have produced.
+ first_tick_touch = touch_calls.index("context compression in progress")
+ assert first_tick_touch >= 1 # "started" touch came first
+ assert len(heartbeats) <= touch_calls.count("context compression in progress")
+
+
+def test_compression_heartbeat_is_silent_for_quiet_context_engines(tmp_path: Path) -> None:
+ """A context engine that suppresses the routine start status opens no
+ visible compaction phase; the heartbeat must not open one either (there
+ would be no terminal edge to close it)."""
+ from agent.conversation_compression import COMPACTION_HEARTBEAT_STATUS
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "HEARTBEAT_QUIET_TEST"
+ db.create_session(session_id, source="test")
+
+ agent = _build_agent_with_db(db, session_id)
+ agent._compression_activity_heartbeat_interval = 0.1
+ touch_calls: list[str] = []
+ agent._touch_activity = lambda desc, **_kw: touch_calls.append(desc)
+ status_events: list[tuple[str, str]] = []
+ setattr(
+ agent,
+ "status_callback",
+ lambda event, message: status_events.append((event, message)),
+ )
+
+ def _slow_compress(*_a, **_kw):
+ _wait_for_touch(touch_calls, "context compression in progress")
+ return [
+ {"role": "user", "content": "[CONTEXT COMPACTION] summary"},
+ {"role": "user", "content": "tail"},
+ ]
+
+ agent.context_compressor.compress.side_effect = _slow_compress
+ messages = [{"role": "user", "content": f"m{i}"} for i in range(20)]
+
+ with patch(
+ "agent.conversation_compression.automatic_compaction_status_message",
+ return_value="",
+ ):
+ agent._compress_context(messages, "sys", approx_tokens=120_000)
+
+ assert all(m != COMPACTION_HEARTBEAT_STATUS for _, m in status_events)
+ assert "context compression in progress" in touch_calls # DB touches still ran
def test_lock_contender_preserves_terminal_compaction_lifecycle(tmp_path: Path) -> None: