The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): persist terminal compression activity stamps immediately
wdelarme85a9d1c55a00
diff --git a/agent/activity_tracking.py b/agent/activity_tracking.pyindex f456f9f448c..55da3b59077 100644--- a/agent/activity_tracking.py+++ b/agent/activity_tracking.py@@ -48,24 +48,26 @@ class ActivityTrackingMixin:the exact ``(generation, timestamp)`` it sampled. Also bridges (rate-limited, best-effort) to thekanban heartbeat when this is a dispatcher-spawned worker, and to the durable SessionDB activityprojection. ``provenance`` names special writers (compression); ``force_persist`` bypasses the- SessionDB rate limit. Module-level lock helper, not ``self._liveness_activity_lock()``: doubles bind- only ``_touch_activity`` (tests/agent/test_session_activity_persist.py).+ SessionDB rate limit — as does any terminal compression provenance, which must converge the durable+ row at once (nothing writes after it). Module-level lock helper, not ``self._liveness_activity_lock()``:+ doubles bind only ``_touch_activity`` (tests/agent/test_session_activity_persist.py).Bridge is rate-limited (60s) and best-effort — it never raises into the agent loop. See #31752.See #72016, #72039."""from agent.session_activity import (- bound_activity_description, normalize_activity_provenance,- reset_session_activity_persist_window,+ bound_activity_description, is_terminal_compression_provenance,+ normalize_activity_provenance, reset_session_activity_persist_window,)+ resolved_provenance = normalize_activity_provenance(provenance)with _activity_lock(self):self._turn_liveness_activity_generation = (getattr(self, "_turn_liveness_activity_generation", 0) + 1)self._last_activity_ts = time.time()self._last_activity_desc = bound_activity_description(desc)- self._last_activity_provenance = normalize_activity_provenance(provenance)+ self._last_activity_provenance = resolved_provenance# Real progress invalidates a reserved abort claim; an in-flight watchdog interrupt must abandon# itself at the final mutation edge.self._turn_liveness_abort_claim = None@@ -78,7 +80,11 @@ class ActivityTrackingMixin:heartbeat_current_worker_from_env()# Fold new operator notes into the running turn (OUT-OF-BAND steer).inject_new_comments_from_env(self)- if force_persist:+ if force_persist or is_terminal_compression_provenance(resolved_provenance):+ # A terminal compression stamp must land durably NOW. The heartbeat wrote "context compression+ # in progress" moments ago, so deferring this write to the next 60s window leaves the durable+ # row advertising a compression that has already ended — and no later writer corrects it once+ # the turn is over or the host is gone (the permanently "stuck" chat, #72039 follow-up).reset_session_activity_persist_window(self)self._persist_session_activity_if_due()diff --git a/agent/session_activity.py b/agent/session_activity.pyindex 1ab19ef9784..8ab3ec8b192 100644--- a/agent/session_activity.py+++ b/agent/session_activity.py@@ -14,7 +14,8 @@ ACTIVITY_DESCRIPTION_MAX = 120# Durable SessionDB heartbeat cadence. Contract: MUST stay >= 30s — the SessionDB write path is contended and# this observation-only projection never justifies extra write pressure. A code constant on purpose (no config-# can make it a high-frequency writer); matches the kanban auto-heartbeat. force_persist (terminal stamps) is the only bypass.+# can make it a high-frequency writer); matches the kanban auto-heartbeat. force_persist and terminal+# compression stamps (see TERMINAL_COMPRESSION_PROVENANCES) are the only bypasses.SESSION_ACTIVITY_HEARTBEAT_MIN_INTERVAL_SECONDS = 60.0@@ -30,6 +31,30 @@ class ActivityProvenance(str, Enum):AGENT_COMPRESSION_TURNHOLD = "agent.compression_turnhold"+# Provenances that END the user-visible "compressing" phase: the host's progress timeout, a cooldown/+# backoff block, and the gateway's hygiene turn-hold. Each is written once, at a terminal edge, and must+# reach the durable projection IMMEDIATELY — the heartbeat above wrote "context compression in progress"+# moments earlier, so a rate-limited terminal stamp leaves `sessions.last_activity_description` advertising+# a compression that has already stopped, with no later writer to correct it (the agent may be idle, the+# process gone). That is the permanently "stuck / compressing" chat users see.+#+# Distinct from ``conversation_compression._TERMINAL_COMPRESSION_PROVENANCES``, which answers a different+# question — "may a detached heartbeat still overwrite this stamp?" — and deliberately excludes TURNHOLD,+# because after a turn-hold the worker may still be alive and adoptable.+TERMINAL_COMPRESSION_PROVENANCES = frozenset(+ {+ ActivityProvenance.AGENT_COMPRESSION_TIMEOUT,+ ActivityProvenance.AGENT_COMPRESSION_COOLDOWN,+ ActivityProvenance.AGENT_COMPRESSION_TURNHOLD,+ }+)+++def is_terminal_compression_provenance(provenance: Optional[ActivityProvenance | str]) -> bool:+ """True when this stamp ends a compression phase and must bypass the persist rate limit."""+ return normalize_activity_provenance(provenance) in TERMINAL_COMPRESSION_PROVENANCES++def bound_activity_description(description: Optional[str]) -> str:"""Clamp free-form activity text to the shared description budget."""text = (description or "").strip()diff --git a/tests/agent/test_compression_terminal_activity_persist.py b/tests/agent/test_compression_terminal_activity_persist.pynew file mode 100644index 00000000000..9d3f902ed12--- /dev/null+++ b/tests/agent/test_compression_terminal_activity_persist.py@@ -0,0 +1,170 @@+"""Terminal compression activity stamps must reach the DURABLE activity projection.++Symptom (production, sanitized): a session whose compression attempt was interrupted/stalled kept+``last_activity_description='context compression in progress'`` with+``last_activity_provenance='agent.compression'`` in ``sessions`` forever, while a+``compression_failure_error``/cooldown row proved the attempt had already terminated. Surfaces that+read the durable row (chat lists, session listings, reconnect, stall watchdog) showed a permanently+"stuck / compressing" chat with no turn running.++Mechanism: ``_CompressionActivityHeartbeat`` persists ``context compression in progress`` through the+rate-limited durable heartbeat (``SESSION_ACTIVITY_HEARTBEAT_MIN_INTERVAL_SECONDS``), and every+TERMINAL stamp written by the host / gateway (`compression timed out`, cooldown blocks, hygiene+turn-hold / timeout / abort) calls ``_touch_activity`` WITHOUT ``force_persist``. When the terminal+stamp lands inside the open persist window — the normal case, because the heartbeat just wrote — the+durable row keeps the mid-compression label while in-memory state is already terminal.++``agent/session_activity.py`` already documents the intended contract for that rate limit:+"force_persist (terminal stamps) is the only bypass". These tests pin it.+"""++from __future__ import annotations++import os+import time+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from agent.session_activity import ActivityProvenance+from hermes_state import SessionDB+++def _agent_with_db(db: SessionDB, session_id: str):+ """Real ``AIAgent`` wired to ``db`` and pinned to ``session_id`` (no network, no LLM)."""+ 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.context_compressor = MagicMock()+ return agent+++def _mid_compression_durable_stamp(agent, db: SessionDB, session_id: str) -> None:+ """Drive one heartbeat tick through the real durable path, as a long compression does."""+ from agent.conversation_compression import _CompressionActivityHeartbeat++ heartbeat = _CompressionActivityHeartbeat(agent, interval_seconds=3600.0)+ # Open the persist window so the tick writes through, exactly like a >60s compression.+ agent._session_activity_last_persist_mono = 0.0+ heartbeat._touch("context compression in progress")+ row = db.get_session(session_id)+ assert row["last_activity_description"] == "context compression in progress"+ assert row["last_activity_provenance"] == ActivityProvenance.AGENT_COMPRESSION.value+ # Close the window again: the terminal stamp now lands inside the rate limit (the real race).+ agent._session_activity_last_persist_mono = time.monotonic()+++def session(tmp_path):+ db = SessionDB(db_path=tmp_path / "state.db")+ session_id = "COMPRESSION_TERMINAL_ACTIVITY"+ db.create_session(session_id, source="test")+ agent = _agent_with_db(db, session_id)+ return SimpleNamespace(db=db, session_id=session_id, agent=agent)+++def test_host_timeout_stamp_is_durable_inside_persist_window(session):+ """Host compression timeout must not leave 'in progress' in the durable projection."""+ from agent.compression_facade import _report_compression_timeout++ _mid_compression_durable_stamp(session.agent, session.db, session.session_id)++ _report_compression_timeout(+ session.agent, idle=30.0, waited=30.0, since_progress=30.0, total_ceiling=60.0,+ total_exhausted=False, progress_observed=False,+ )++ row = session.db.get_session(session.session_id)+ assert row["last_activity_description"] != "context compression in progress"+ assert row["last_activity_provenance"] == ActivityProvenance.AGENT_COMPRESSION_TIMEOUT.value+++def test_stall_interrupted_cooldown_stamp_is_durable_inside_persist_window(session):+ """A stall-interrupted attempt that falls back to the cooldown block must clear 'in progress'.++ This is the exact production shape: ``compression_failure_error='…stall_interrupted…'`` plus a+ cooldown timestamp, while the durable activity label still advertised compression in progress.+ """+ _mid_compression_durable_stamp(session.agent, session.db, session.session_id)++ session.agent._warn_context_overflow_blocked("cooldown:42s", 144_323, 128_000)++ row = session.db.get_session(session.session_id)+ assert row["last_activity_description"] != "context compression in progress"+ assert row["last_activity_provenance"] == ActivityProvenance.AGENT_COMPRESSION_COOLDOWN.value+++ "provenance_name, desc",+ [+ ("AGENT_COMPRESSION_TIMEOUT", "session hygiene compression timed out"),+ ("AGENT_COMPRESSION_TURNHOLD", "session hygiene compression turn-hold"),+ ("AGENT_COMPRESSION_COOLDOWN", "session hygiene compression aborted"),+ ],+)+def test_gateway_hygiene_terminal_stamps_are_durable(session, provenance_name, desc):+ """Every gateway-hygiene terminal transition must converge the durable row too."""+ from gateway.run import _stamp_hygiene_compression_provenance++ _mid_compression_durable_stamp(session.agent, session.db, session.session_id)++ _stamp_hygiene_compression_provenance(+ session.agent, desc, getattr(ActivityProvenance, provenance_name), "test stamp failed",+ )++ row = session.db.get_session(session.session_id)+ assert row["last_activity_description"] == desc+ assert row["last_activity_provenance"] == getattr(ActivityProvenance, provenance_name).value+++def test_reconnect_reader_sees_terminal_state_not_in_progress(session):+ """A fresh reader (reconnect / another process) must observe the truthful terminal state."""+ from agent.compression_facade import _report_compression_timeout++ _mid_compression_durable_stamp(session.agent, session.db, session.session_id)+ _report_compression_timeout(+ session.agent, idle=30.0, waited=90.0, since_progress=30.0, total_ceiling=90.0,+ total_exhausted=True, progress_observed=False,+ )++ reconnected = SessionDB(db_path=session.db.db_path)+ row = reconnected.get_session(session.session_id)+ assert row["last_activity_description"] != "context compression in progress"+ assert row["last_activity_provenance"] == ActivityProvenance.AGENT_COMPRESSION_TIMEOUT.value+++def test_orphan_reap_converges_terminated_compression_row(session):+ """Orphan reaping a session left by a dead host must end a row that is no longer 'in progress'."""+ from agent.compression_facade import _report_compression_timeout++ _mid_compression_durable_stamp(session.agent, session.db, session.session_id)+ _report_compression_timeout(+ session.agent, idle=30.0, waited=30.0, since_progress=30.0, total_ceiling=60.0,+ total_exhausted=False, progress_observed=False,+ )+ # Age the row past the sweep window (the host process is gone; nothing will clear labels).+ old = time.time() - 86_400+ session.db._write_sql(+ "UPDATE sessions SET source = 'tui', started_at = ?, last_activity_at = ? WHERE id = ?",+ (old, old, session.session_id),+ )++ reaped = session.db.sweep_orphaned_sessions(+ max_idle_seconds=3600, sources=("tui",), respect_gateway_heartbeats=False,+ )++ assert session.session_id in reaped+ row = session.db.get_session(session.session_id)+ assert row["ended_at"] is not None+ assert row["last_activity_description"] != "context compression in progress"