Skip to content

The agent that grows with you

fix(tui_gateway): re-resolve the queued row across an in-place compaction (#123675)

Brooklyn Nicholson0a6eaab83ca9
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index bb4406f4775..ea9f333d8b1 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -1236,6 +1236,26 @@ class SessionMessagesMixin:
"UPDATE messages SET active = 0 WHERE id = ? AND session_id = ?",
(row_id, session_id))
+ def resolve_active_row_id(self, session_id: str, row_id: int) -> Optional[int]:
+ """The active row that still carries *row_id*'s message: *row_id* itself while active, else the one
+ row an in-place compaction re-sequenced it into (``_clone_message_rows`` copies role, content and
+ timestamp byte-exact to a higher id). ``None`` when neither exists or the clone is ambiguous.
+ A caller holding a row id across a compaction (the queued-prompt envelope) re-resolves it here
+ before deactivating or rewriting the row (#123675)."""
+ if not session_id or isinstance(row_id, bool) or not isinstance(row_id, int) or row_id <= 0:
+ return None
+ origin = self._read_one("SELECT active FROM messages WHERE id = ? AND session_id = ?", (row_id, session_id))
+ if origin is None:
+ return None
+ if origin[0]:
+ return row_id
+ clones = self._read_all(
+ "SELECT c.id FROM messages c JOIN messages o ON o.id = ? "
+ "WHERE c.session_id = ? AND c.active = 1 AND c.id > o.id AND c.role = o.role "
+ "AND c.content IS o.content AND c.timestamp = o.timestamp",
+ (row_id, session_id))
+ return int(clones[0][0]) if len(clones) == 1 else None
+
def deactivate_messages_by_display_kind(self, session_id: str, display_kind: str) -> int:
"""Deactivate every live row of one ``display_kind`` (idempotent; returns the affected row count).
The durable counterpart to the in-memory strip a self-replacing pivot performs: the in-memory path
diff --git a/tests/tui_gateway/test_queued_prompt_persistence.py b/tests/tui_gateway/test_queued_prompt_persistence.py
index d9ca27041e6..c8bb60ac445 100644
--- a/tests/tui_gateway/test_queued_prompt_persistence.py
+++ b/tests/tui_gateway/test_queued_prompt_persistence.py
@@ -234,3 +234,66 @@ def test_partial_drain_never_puts_a_later_prompt_before_an_earlier_one(monkeypat
finally:
server._sessions.pop(sid, None)
db.close()
+
+
+def _compact_in_place_while_queued(db, key):
+ """The live turn compacts in place: it holds its own rows, never the queued prompt's accept-time
+ row, so the commit re-sequences that row to a new id after the compacted set."""
+ held = [r["_row_id"] for r in db.get_messages_as_conversation(key, include_row_ids=True)
+ if "QUEUED-MARKER" not in str(r["content"])]
+ db.archive_and_compact(key, [{"role": "user", "content": "[CONTEXT COMPACTION] summary of turn A"},
+ {"role": "assistant", "content": "ok, continuing"}],
+ covered_ids=held, unresolved_held=[])
+
+
+def test_drain_after_in_place_compaction_leaves_one_active_queued_row(monkeypatch, tmp_path):
+ """The envelope kept the accept-time id after the compaction re-sequenced the row, so the drain
+ deactivated the (already inactive) original and the clone stayed live: the queued prompt was
+ active twice, once before reply A, which then replayed as the answer to it."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ session = server._sessions[sid]
+ try:
+ server._ensure_session_db_row(session)
+ db.append_message(key, "user", content="prompt A")
+ _busy(session)
+ server._handle_busy_submit("r1", sid, session, "queued text QUEUED-MARKER", "ws-1",
+ queued=True, display_kind=None)
+ _compact_in_place_while_queued(db, key)
+ db.append_message(key, "assistant", content="reply A")
+ with session["history_lock"]:
+ session["running"] = False
+ server._clear_inflight_turn(session)
+ monkeypatch.setattr(server, "_run_prompt_submit",
+ lambda rid, s, sess, text, **kw: _run_turn(sess, db, key, text, "reply B"))
+ assert server._drain_queued_prompt("r2", sid, session) is True
+
+ rows = [(r["role"], r["content"]) for r in _active_rows(db, key)]
+ assert [c for _r, c in rows].count("queued text QUEUED-MARKER") == 1
+ # The queued prompt follows reply A (the repaired projection may fold the summary ack into it).
+ assert rows[-2:] == [("user", "queued text QUEUED-MARKER"), ("assistant", "reply B")]
+ assert rows[-3][0] == "assistant" and rows[-3][1].endswith("reply A")
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
+def test_merge_after_in_place_compaction_updates_the_live_queued_row(monkeypatch, tmp_path):
+ """A text-only arrival after the compaction merged into the envelope, but the row update used the
+ stale id, matched no active row, and the live clone kept only the first fragment."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ session = server._sessions[sid]
+ try:
+ server._ensure_session_db_row(session)
+ db.append_message(key, "user", content="prompt A")
+ _busy(session)
+ server._handle_busy_submit("r1", sid, session, "first QUEUED-MARKER", "ws-1", queued=True, display_kind=None)
+ _compact_in_place_while_queued(db, key)
+ server._handle_busy_submit("r2", sid, session, "second", "ws-1", queued=True, display_kind=None)
+
+ queued = [r["content"] for r in _active_rows(db, key) if "QUEUED-MARKER" in str(r["content"])]
+ assert queued == ["first QUEUED-MARKER\n\nsecond"]
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.py
index 541f77d86ed..a3bdedf7a4b 100644
--- a/tui_gateway/session_auto_continue.py
+++ b/tui_gateway/session_auto_continue.py
@@ -314,13 +314,24 @@ def _persist_queued_user_row(session: dict, envelope: dict, display_kind: str |
return
try:
# The staged dict records the session its row was written under; a rotated-away
- # ``session_key`` misses that row's session_id and the merge update no-ops.
- db.set_user_message_content(
- _submit_row_owner_key(staged, session), staged["_row_id"], envelope["text"])
+ # ``session_key`` misses that row's session_id and the merge update no-ops. An
+ # in-place compaction of the live turn may also have re-sequenced the row to a
+ # new id (the original was deactivated and cloned): follow it or the update
+ # no-ops against the dead original (#123675).
+ key = _submit_row_owner_key(staged, session)
+ live_id = db.resolve_active_row_id(key, staged["_row_id"])
+ updated = live_id is not None and bool(
+ db.set_user_message_content(key, live_id, envelope["text"]))
except Exception:
logger.debug("queued-prompt row merge update failed", exc_info=True)
return
- staged["content"] = envelope["text"]
+ if not updated:
+ # No live row carries the prompt any more (compaction re-sequenced it away):
+ # drop the staged row so the drained turn writes its own, rather than letting
+ # the envelope claim a durable row that no longer exists.
+ envelope.pop("_submit_user_row", None)
+ return
+ staged["_row_id"], staged["content"] = live_id, envelope["text"]
return
# ``display_metadata`` marker: ``reopen_session`` retires still-marked rows after a restart
# discarded the in-memory queue (#125577); the drain's replacement row is unmarked.
@@ -369,8 +380,14 @@ def _replace_queued_user_row_for_turn(session: dict, queued: dict, is_dispatchin
try:
# The accept-time dict records the session its row was written under; a rotated-away
# ``session_key`` would miss it and leave that row ACTIVE beside its replacement in the
- # continuation — the [uA, uB, aA] shape this function exists to prevent.
- db.deactivate_message(_submit_row_owner_key(early, session), early["_row_id"])
+ # continuation — the [uA, uB, aA] shape this function exists to prevent. An in-place
+ # compaction of the live turn may also have re-sequenced the row to a new id: deactivate
+ # the row that is live NOW, or the clone stays active beside its replacement and the
+ # queued prompt is active twice after the drain (#123675).
+ key = _submit_row_owner_key(early, session)
+ live_id = db.resolve_active_row_id(key, early["_row_id"])
+ if live_id is not None:
+ db.deactivate_message(key, live_id)
except Exception:
# Both rows briefly active merges in projection but never loses the message; deleting or
# losing text would be worse.