The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): rotation heals stale automatic ended_at stamps instead of wedging (#88197)
Tekniumc0667439ec08
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 11337d3b33c..bdb8bd4eabe 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -4682,13 +4682,27 @@ def compress_context(# before. Deliberately NOT extended to the compression lease:# a lease is re-acquirable, so a transient miss here would# abort a rotation that would otherwise have committed.+ #+ # AUTOMATIC stamps (tui_shutdown, ws_disconnect, orphan+ # reap, idle/LRU evict — is_automatic_end_reason) do NOT+ # trip this guard: publish_compression_child treats them+ # as stale-by-construction and clears them in its own+ # transaction (#88197 Bug 1), so aborting here would keep+ # rotation wedged on exactly the stamp the publish can+ # heal. Only deliberate boundaries (compression,+ # session_reset, explicit close) abort before the flush._parent_row_reader = getattr(agent._session_db, "get_session", None)_parent_already_ended = Falseif callable(_parent_row_reader):try:+ from hermes_state_common import is_automatic_end_reason+_parent_row = _parent_row_reader(old_session_id) or {}_parent_already_ended = (_parent_row.get("ended_at") is not None+ and not is_automatic_end_reason(+ _parent_row.get("end_reason")+ ))except Exception:# Fail OPEN: an unreadable row must not turn a cheapdiff --git a/hermes_state.py b/hermes_state.pyindex a6e8ab3645d..c50aeccada6 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -67,6 +67,7 @@ from hermes_state_common import ( # noqa: F401 (re-exported for back-compat)_PREVIEW_RAW_SELECT,_RECOVERABLE_END_REASONS,_RECOVERABLE_END_REASONS_SQL,+ is_automatic_end_reason,_RESET_END_REASONS,_RESET_END_REASONS_SQL,_ephemeral_child_sql,@@ -7211,7 +7212,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)f"Compression lease lost before publication: {parent_session_id}")parent = conn.execute(- """SELECT ended_at, cwd, git_branch, git_repo_root,+ """SELECT ended_at, end_reason, cwd, git_branch, git_repo_root,user_id, session_key, chat_id, chat_type,thread_id, display_name, origin_json, profile_nameFROM sessions WHERE id = ?""",@@ -7220,7 +7221,30 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)if parent is None:raise RuntimeError(f"Compression parent not found: {parent_session_id}")if parent["ended_at"] is not None:- raise RuntimeError(f"Compression parent already ended: {parent_session_id}")+ # A parent stamped ended by AUTOMATIC cleanup (tui_shutdown,+ # ws_disconnect, orphan reap, idle/LRU evict) while a live+ # agent is publishing its rotation is stale by construction —+ # this writer holds the compression lease and is actively+ # continuing the conversation the stamp claims is over.+ # Left in place it wedges rotation forever: every attempt+ # aborts here, nothing clears the stamp, and each attempt's+ # pre-publish flush re-grows the parent until the provider+ # rejects the request (#88197: 303 unique messages → 2,611+ # rows → HTTP 400). Clear it in this same transaction and+ # proceed; the closure UPDATE below re-stamps the parent with+ # its true boundary (end_reason='compression'). Deliberate+ # boundaries (compression, session_reset, explicit close)+ # still fail closed — those mean another path owns lineage.+ if is_automatic_end_reason(parent["end_reason"]):+ conn.execute(+ "UPDATE sessions SET ended_at = NULL, end_reason = NULL "+ "WHERE id = ?",+ (parent_session_id,),+ )+ else:+ raise RuntimeError(+ f"Compression parent already ended: {parent_session_id}"+ )if not messages:raise RuntimeError("Compression child handoff must not be empty")system_prompt_hash = self._store_system_prompt(conn, system_prompt)diff --git a/hermes_state_common.py b/hermes_state_common.pyindex c726d0790fd..d7f70bcf544 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -224,6 +224,32 @@ _RECOVERABLE_END_REASONS = ()_RECOVERABLE_END_REASONS_SQL = ", ".join(f"'{reason}'" for reason in _RECOVERABLE_END_REASONS)+# End reasons written by AUTOMATIC infrastructure cleanup (server shutdown,+# orphan reapers, idle/LRU eviction) rather than by a deliberate conversation+# boundary (compression, session_reset, session_switch, explicit user close).+# An automatic stamp records "some runtime went away", NOT "this conversation+# ended" — so a writer that can prove the conversation is still live (e.g. an+# active compression rotation holding the lease, #88197) may treat the stamp+# as stale and clear it. Superset of the recoverable set: those are already+# resumable accidents; the extra TUI reasons are the same accident class but+# were historically only known to tui_gateway's _AUTOMATIC_SESSION_END_REASONS.+_AUTOMATIC_END_REASONS = frozenset(_RECOVERABLE_END_REASONS) | {+ "tui_shutdown",+ "ws_disconnect",+ "idle_timeout",+ "lru_evict",+}+++def is_automatic_end_reason(reason) -> bool:+ """True when *reason* is an automatic-cleanup end stamp (see above).++ Single owner of the "accidental vs deliberate end" predicate — every+ compression-liveness site must call this instead of re-implementing the+ reason taxonomy (#88197, never-patch-predicates).+ """+ return isinstance(reason, str) and reason in _AUTOMATIC_END_REASONS+def _legacy_reset_child_sql(alias: str, reasons_sql: str) -> str:"""Pre-marker reset-continuation heuristic.diff --git a/tests/agent/test_compression_rotation_state.py b/tests/agent/test_compression_rotation_state.pyindex 50d54d7a2df..4bbd4dfed7d 100644--- a/tests/agent/test_compression_rotation_state.py+++ b/tests/agent/test_compression_rotation_state.py@@ -1969,19 +1969,48 @@ class TestAbortedRotationDoesNotGrowParent:def _durable_len(db: SessionDB, session_id: str) -> int:return len(db.get_messages_as_conversation(session_id))- def test_ended_parent_aborts_before_the_prepublish_flush(self, tmp_path: Path):+ def test_automatic_stamp_no_longer_wedges_rotation(self, tmp_path: Path):+ """Flipped by the #88197 wedge fix: an AUTOMATIC stamp+ (``tui_shutdown`` — is_automatic_end_reason) is stale by construction+ for a live rotating writer, so publish now clears it in-transaction+ and the rotation COMMITS instead of aborting forever. The abort+ contract below moves to deliberate boundaries."""db = SessionDB(db_path=tmp_path / "state.db")- parent = "PARENT_ENDED_NO_GROWTH"+ parent = "PARENT_AUTOMATIC_STAMP_HEALS"db.create_session(parent, source="cli")agent = _build_agent_with_db(db, parent)# The lie at the heart of #88197: the row says ended, the agent is live.- # ``tui_shutdown`` is not a lineage boundary -- nothing forked off this- # session -- so durable writes to it are still permitted, which is- # exactly why the flush lands and the publish still refuses.db.end_session(parent, "tui_shutdown")assert db.get_session(parent)["ended_at"] is not None+ returned, _sp = agent._compress_context(_msgs(), "sys", approx_tokens=120_000)++ # Rotation went through — no abort loop, no repeated flush growth.+ assert agent.session_id != parent+ parent_row = db.get_session(parent)+ assert parent_row["end_reason"] == "compression", (+ "parent must close with its TRUE boundary, not the stale stamp"+ )+ child_row = db.get_session(agent.session_id)+ assert child_row is not None+ assert child_row["parent_session_id"] == parent++ def test_deliberately_ended_parent_aborts_before_the_prepublish_flush(+ self, tmp_path: Path+ ):+ db = SessionDB(db_path=tmp_path / "state.db")+ parent = "PARENT_ENDED_NO_GROWTH"+ db.create_session(parent, source="cli")+ agent = _build_agent_with_db(db, parent)++ # A DELIBERATE boundary (another path owns lineage): the guard must+ # still refuse BEFORE the #47202 flush so aborted attempts cannot+ # grow the parent (#88411's contract, now scoped to non-automatic+ # reasons — automatic stamps rotate through, see the test above).+ db.end_session(parent, "session_reset")+ assert db.get_session(parent)["ended_at"] is not None+before = self._durable_len(db, parent)# Three consecutive auto-compactions, as the reported incident saw.diff --git a/tests/hermes_state/test_88197_automatic_ended_stamp.py b/tests/hermes_state/test_88197_automatic_ended_stamp.pynew file mode 100644index 00000000000..d75a8b55796--- /dev/null+++ b/tests/hermes_state/test_88197_automatic_ended_stamp.py@@ -0,0 +1,172 @@+"""Regression tests for #88197 — a dirty automatic ``ended_at`` stamp on a+live compression parent must not wedge rotation.++TUI server shutdown (``_shutdown_sessions``) stamps ``ended_at`` /+``end_reason='tui_shutdown'`` on every session in its memory, including+sessions whose agent process keeps running (dist auto-reload, second TUI+instance). Nothing on the attach path clears it, so every subsequent rotation+aborted at ``publish_compression_child``'s liveness check — silently and+forever (#88197: 7 aborted attempts, 88% duplicate rows, HTTP 400; the+amplification half was fixed by #88411, the wedge half is covered here).++Contract under test: automatic-cleanup stamps (``is_automatic_end_reason``)+are stale-by-construction for a writer that holds the compression lease —+``publish_compression_child`` clears them in its own transaction and+proceeds; deliberate boundaries (``compression``, ``session_reset``,+explicit close) still fail closed.+"""++from __future__ import annotations++import os+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest++from hermes_state import SessionDB+from hermes_state_common import is_automatic_end_reason+++def db(tmp_path: Path):+ handle = SessionDB(db_path=tmp_path / "state.db")+ try:+ yield handle+ finally:+ handle.close()+++def _publish(db: SessionDB, parent: str, child: str) -> None:+ db.publish_compression_child(+ parent_session_id=parent,+ child_session_id=child,+ source="tui",+ messages=[{"role": "user", "content": "[CONTEXT COMPACTION] summary"}],+ require_compression_lease=False,+ )+++class TestAutomaticEndReasonPredicate:+ def test_taxonomy(self) -> None:+ for reason in (+ "tui_shutdown",+ "ws_disconnect",+ "idle_timeout",+ "lru_evict",+ "ws_orphan_reap",+ "agent_close",+ "startup_orphan_reap",+ "superseded_by_resume",+ ):+ assert is_automatic_end_reason(reason), reason+ for reason in (+ "compression",+ "session_reset",+ "session_switch",+ "tui_close",+ None,+ "",+ ):+ assert not is_automatic_end_reason(reason), reason+++class TestPublishHealsAutomaticStamp:+ @pytest.mark.parametrize(+ "reason", ["tui_shutdown", "ws_disconnect", "ws_orphan_reap", "idle_timeout"]+ )+ def test_rotation_publishes_through_automatic_stamp(+ self, db: SessionDB, reason: str+ ) -> None:+ parent = f"P_{reason}"+ db.create_session(parent, source="tui")+ db.append_message(parent, "user", content="hello")+ db.end_session(parent, reason) # the dirty stamp+ assert db.get_session(parent)["ended_at"] is not None++ _publish(db, parent, f"C_{reason}")++ parent_row = db.get_session(parent)+ # Parent closed with its TRUE boundary, not the stale stamp.+ assert parent_row["end_reason"] == "compression"+ assert parent_row["ended_at"] is not None+ child_row = db.get_session(f"C_{reason}")+ assert child_row is not None+ assert child_row["parent_session_id"] == parent++ @pytest.mark.parametrize("reason", ["compression", "session_reset", "tui_close"])+ def test_deliberate_boundary_still_fails_closed(+ self, db: SessionDB, reason: str+ ) -> None:+ parent = f"P_{reason}"+ db.create_session(parent, source="tui")+ db.end_session(parent, reason)+ with pytest.raises(RuntimeError, match="already ended"):+ _publish(db, parent, f"C_{reason}")+ # No child row leaked from the refused publish.+ assert db.get_session(f"C_{reason}") is None++ def test_live_parent_unaffected(self, db: SessionDB) -> None:+ db.create_session("P_live", source="tui")+ _publish(db, "P_live", "C_live")+ assert db.get_session("P_live")["end_reason"] == "compression"+ assert db.get_session("C_live") is not None+++class TestRotationEndToEnd:+ def _build_agent(self, 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="tui",+ quiet_mode=True,+ session_db=db,+ session_id=session_id,+ skip_context_files=True,+ skip_memory=True,+ )+ compressor = MagicMock()+ compressor.compress.return_value = [+ {"role": "user", "content": "[CONTEXT COMPACTION] summary"},+ {"role": "user", "content": "tail"},+ ]+ compressor.compression_count = 1+ 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+ agent.compression_in_place = False # rotation path+ return agent++ def test_dirty_tui_shutdown_stamp_does_not_wedge_rotation(+ self, db: SessionDB+ ) -> None:+ """#88197 end-to-end: TUI shutdown stamps the live session, then+ auto-compaction rotates anyway instead of aborting forever."""+ parent = "PARENT_88197_E2E"+ db.create_session(parent, source="tui")+ agent = self._build_agent(db, parent)++ # Simulate the old TUI server exit stamping the still-live session.+ db.end_session(parent, "tui_shutdown")++ msgs = [{"role": "user", "content": f"m{i}"} for i in range(20)]+ agent._compress_context(list(msgs), "sys", approx_tokens=120_000)++ assert agent.session_id != parent, (+ "rotation aborted on the stale tui_shutdown stamp — "+ "the #88197 wedge is back"+ )+ parent_row = db.get_session(parent)+ assert parent_row["end_reason"] == "compression"+ child_row = db.get_session(agent.session_id)+ assert child_row is not None+ assert child_row["parent_session_id"] == parent