The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): retire never-drained queue rows on the read-only mount paths too (#128508, #125577)
Brooklyn Nicholson653667e4300d
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.pyindex 7e137ea3ecf..08517135a18 100644--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@ -496,24 +496,39 @@ class SessionSessionsMixin:self._bump_conversation_generation(conn, session_id, reason)return changed+ @staticmethod+ def _retire_undrained_queue_rows_conn(conn, session_id: str) -> int:+ """The still-marked == never-drained accept-row UPDATE (#125577), on a caller's connection."""+ return conn.execute(+ "UPDATE messages SET active = 0 "+ "WHERE session_id = ? AND role = 'user' AND active = 1 "+ f"AND COALESCE({_sql_json_extract('display_metadata', '$.' + QUEUED_PROMPT_METADATA_KEY)}, 0) = 1",+ (session_id,),+ ).rowcount++ def retire_undrained_queue_rows(self, session_id: str) -> int:+ """Deactivate busy-queue accept rows that never drained (#125577): a restart discarded the+ in-memory queue, so nothing re-placed/deactivated the row written at accept time and+ alternation repair would glue the never-run prompt into the previous turn's user message.+ The drain's replacement row carries no marker, so still-marked == never drained; a+ dispatched-then-interrupted turn's row is never marked (its discard is handled in-process,+ #123532). Deactivated, never deleted — the row stays as history.++ Split out of :meth:`reopen_session` so the read-only mount paths (#85303: resume,+ lazy watch, hydration) can retire stale accept rows WITHOUT clearing ``ended_at`` —+ after a restart the marked row would otherwise stay active and visible on every+ mount until the next send. Idempotent; returns the number of rows retired.+ """+ return self._execute_write(+ lambda conn: self._retire_undrained_queue_rows_conn(conn, session_id))+def reopen_session(self, session_id: str) -> None:"""Clear ended_at/end_reason so a session can be resumed; first freeze markerless legacy resetchildren, skipping explicit fork/delegate provenance and children that predate the parent itself.The guard compares against the parent's started_at, not its current ended_at: a parent that wasreopened and re-ended later still owns reset children from its earlier boundaries."""def _do(conn):- # Retire busy-queue accept rows that never drained (#125577): a restart discarded the- # in-memory queue, so nothing re-placed/deactivated the row written at accept time and- # alternation repair would glue the never-run prompt into the previous turn's user- # message. The drain's replacement row carries no marker, so still-marked == never- # drained; a dispatched-then-interrupted turn's row is never marked (its discard is- # handled in-process, #123532). Deactivated, never deleted — the row stays as history.- conn.execute(- "UPDATE messages SET active = 0 "- f"WHERE session_id = ? AND role = 'user' AND active = 1 "- f"AND COALESCE({_sql_json_extract('display_metadata', '$.' + QUEUED_PROMPT_METADATA_KEY)}, 0) = 1",- (session_id,),- )+ self._retire_undrained_queue_rows_conn(conn, session_id)conn.execute("UPDATE sessions AS child SET model_config = json_set(""COALESCE(child.model_config, '{}'), '$._reset_from', child.parent_session_id) "diff --git a/tests/tui_gateway/test_queued_prompt_restart_retire.py b/tests/tui_gateway/test_queued_prompt_restart_retire.pyindex fa57cb3ae08..8afb1be4874 100644--- a/tests/tui_gateway/test_queued_prompt_restart_retire.py+++ b/tests/tui_gateway/test_queued_prompt_restart_retire.py@@ -17,6 +17,7 @@ def _desktop_session(monkeypatch, db):monkeypatch.setattr(server, "_get_db", lambda: db)monkeypatch.setattr(server, "_schedule_agent_build", lambda _sid: None)monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)+ monkeypatch.setattr(server, "_schedule_agent_build", lambda _sid: None)monkeypatch.setattr(server, "_register_session_cwd", lambda _session: None)resp = server.handle_request({"id": "c", "method": "session.create", "params": {"cols": 96, "source": "desktop"}})assert "result" in resp, resp@@ -142,3 +143,66 @@ def test_restart_between_drains_retires_only_the_later_prompt(monkeypatch, tmp_pfinally:server._sessions.pop(sid, None)db.close()+++def test_readonly_resume_after_restart_retires_marked_row_without_reopen(+ monkeypatch, tmp_path):+ """RED on the #128508 head: with the reopen gone from the mount paths, a restart + bare+ resume (no submit) left the still-marked accept row ACTIVE — it stayed glued into the+ previous turn's user message by alternation repair until the next send. The mount must+ stay read-only for the session row (ended_at keeps, #85303) while retiring the residue.+ """+ import pytest++ db = SessionDB(db_path=tmp_path / "state.db")+ sid, key = _desktop_session(monkeypatch, db)+ try:+ _accept_busy_prompt_a_concludes(db, sid, key)+ # The restart: the queue is gone and no live in-memory session survives (the queue,+ # running flag and inflight turn all lived in it); the row is FINALIZED and carries+ # a never-drained accept row.+ with server._sessions[sid]["history_lock"]:+ server._sessions[sid]["running"] = False+ server._clear_inflight_turn(server._sessions[sid])+ server._sessions.pop(sid, None)+ db.end_session(key, "agent_close")+ assert db.get_session(key)["ended_at"] is not None++ home = tmp_path / "home"+ home.mkdir(exist_ok=True)+ monkeypatch.setattr("hermes_state_registry.acquire", lambda db_path=None, **kwargs: db)+ monkeypatch.setattr(server, "_profile_home", lambda p: home if p else None)+ monkeypatch.setattr(server, "_profile_configured_cwd", lambda _: str(tmp_path))+ monkeypatch.setattr(server, "_default_session_cwd", lambda: str(tmp_path))+ monkeypatch.setattr(server, "_get_db", lambda: db)+ monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)+ monkeypatch.setattr(server, "_maybe_schedule_auto_continue", lambda *args: None)+ monkeypatch.setattr(server, "_start_agent_build", lambda *args: None)+ for defer_history in (False, True): # cold read + deferred hydration paths+ monkeypatch.setattr(server, "_schedule_agent_build", lambda *args: None)+ response = server.handle_request({"id": "resume", "method": "session.resume", "params": {+ "session_id": key, "source": "desktop", "defer_history": defer_history}})+ assert response is not None and "error" not in response, response+ resumed_sid = response["result"]["session_id"]+ try:+ if defer_history: # the hydration thread owns the retire on this path+ assert server._sessions[resumed_sid]["resume_history_ready"].wait(5)+ # Read-only mount kept (#85303): the row stays finalized.+ row = db.get_session(key)+ assert row["ended_at"] is not None, "resume must not reopen the finalized row (#85303)"+ assert row["end_reason"] == "agent_close"+ # But the never-drained accept row is retired (#125577): the repaired projection+ # no longer absorbs the queued prompt into turn A's user message.+ repaired = db.get_messages_as_conversation(key, repair_alternation=True,+ include_row_ids=True)+ assert [(r["role"], r["content"]) for r in repaired] == [+ ("user", "prompt A"), ("assistant", "reply A")]+ raw = db.get_messages(key, include_inactive=True)+ assert [(r["role"], r["active"]) for r in raw] == [+ ("user", 1), ("user", 0), ("assistant", 1)]+ finally:+ server._sessions.pop(resumed_sid, None)+ finally:+ server._sessions.pop(sid, None)+ db.close()diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex b5371c7b11b..ebb85810fbc 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -696,7 +696,15 @@ class _Resume:Read-only mount: an ended row stays ended — resume must not clear ``ended_at``/``end_reason``with no new activity, or the DB-derived liveness paints a finalized session live the moment- it is opened (#85303). The first real turn (``prompt.submit``) reopens it."""+ it is opened (#85303). The first real turn (``prompt.submit``) reopens it. Still read-only+ for the session row, but NOT for stale queue residue: the restart that made this resume+ necessary also discarded the busy-queue, so retire never-drained accept rows (#125577)+ # here — with #128508 the reopen no longer runs on this path and the marked row would stay+ active and visible until the next send. Best-effort like the resume guard: a handle+ without the method (duck-typed doubles) skips the cleanup, a real error still fails."""+ retire = getattr(self.db, "retire_undrained_queue_rows", None)+ if callable(retire):+ retire(self.target)if self.omit_messages:return self.child_history(repair=True), []return self.db.get_resume_conversations(self.target)@@ -912,6 +920,12 @@ def _resume_lazy(ctx: _Resume) -> dict:sid, source, cwd = ctx.mint(prompts=False)try:# Read-only mount (#85303): an ended row stays ended; the first real turn reopens it.+ # But a restart discarded the busy-queue — retire never-drained accept rows (#125577)+ # or the marked row stays active and visible until the next send. Best-effort like+ # the resume guard: a handle without the method (duck-typed doubles) skips it.+ retire = getattr(ctx.db, "retire_undrained_queue_rows", None)+ if callable(retire):+ retire(ctx.target)# repair_alternation heals a durable ``user;user`` once here.history = ctx.child_history(repair=True)except Exception as e:diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 22fce15c3ba..2ec14e29524 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2976,7 +2976,13 @@ def _schedule_resume_hydration(sid: str, stored_id: str, db, *, close_db: bool =return_emit("session.resume_progress", sid, {"phase": "history", "status": "loading"})# Read-only mount (#85303): hydration is a read; an ended row stays ended —- # the first real turn (prompt.submit) reopens it.+ # the first real turn (prompt.submit) reopens it. But a restart discarded the+ # busy-queue, so retire never-drained accept rows (#125577) before the read —+ # with #128508 the reopen (and its retire) no longer runs on this path.+ # Best-effort like the resume guard: a handle without the method skips it.+ retire = getattr(db, "retire_undrained_queue_rows", None)+ if callable(retire):+ retire(stored_id)raw_history, display_history, prefix = _load_resume_transcript(db, stored_id, model_history_only=model_history_only)# Display keeps the full transcript; the model-fed history uses the