Skip to content

The agent that grows with you

fix(state): make a rewind truncation recoverable instead of a hard DELETE (#82756)

joaomarcos60645f8a536c
diff --git a/hermes_state.py b/hermes_state.py
index 844ea1d8d30..d60d39afd57 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -7974,6 +7974,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
session_id: str,
messages: List[Dict[str, Any]],
active_only: bool = False,
+ archive_dropped: bool = False,
) -> None:
"""Atomically replace the stored messages for a session.
@@ -7994,6 +7995,20 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
full-history rewrite doesn't wipe the rows the agent deliberately
archived. ``message_count``/``tool_call_count`` then track the live set,
matching :meth:`archive_and_compact`.
+
+ Pass ``archive_dropped=True`` to SOFT-archive the live rows instead of
+ DELETEing them: the replaced turns stay on disk with ``active = 0``,
+ ``compacted = 0`` — the same "the user took it back" marking
+ :meth:`rewind_to_message` applies — and stay readable via
+ :meth:`get_messages` with ``include_inactive=True``. This is the mode a
+ rewind/edit/regenerate must use: those flows overwrite a transcript the
+ user may not have meant to drop, and a plain DELETE also evicts the rows
+ from the FTS index, leaving nothing to recover from (#82756). It implies
+ active-only handling — already-archived rows are never touched — so
+ ``active_only`` is redundant with it. The rewritten set is inserted as
+ fresh active rows exactly as in the destructive path, so the live view
+ is identical either way; only the durability of the dropped turns
+ differs.
"""
active_clause = " AND active = 1" if active_only else ""
@@ -8009,10 +8024,21 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
and session["end_reason"] == "compression"
):
raise CompressionSessionClosedError(session_id)
- conn.execute(
- f"DELETE FROM messages WHERE session_id = ?{active_clause}",
- (session_id,),
- )
+ if archive_dropped:
+ # Content-preserving UPDATE: the rows keep their FTS entries
+ # (the messages_fts triggers index on INSERT / drop on DELETE
+ # and don't key on active), so the replaced turns stay both
+ # readable and searchable-by-id after the rewrite.
+ conn.execute(
+ "UPDATE messages SET active = 0 "
+ "WHERE session_id = ? AND active = 1",
+ (session_id,),
+ )
+ else:
+ conn.execute(
+ f"DELETE FROM messages WHERE session_id = ?{active_clause}",
+ (session_id,),
+ )
conn.execute(
"UPDATE sessions SET message_count = 0, tool_call_count = 0 WHERE id = ?",
(session_id,),
diff --git a/tests/hermes_state/test_replace_messages_archive_siblings.py b/tests/hermes_state/test_replace_messages_archive_siblings.py
index 039d4c34f82..a2decc87907 100644
--- a/tests/hermes_state/test_replace_messages_archive_siblings.py
+++ b/tests/hermes_state/test_replace_messages_archive_siblings.py
@@ -157,3 +157,104 @@ class TestTuiPromptTruncationPreservesArchives:
if m.get("role") in ("user", "assistant")
]
assert [m["content"] for m in live] == ["kept head"]
+
+
+class TestArchiveDroppedIsRecoverable:
+ """`active_only=True` protects rows archived EARLIER; it still DELETEs the
+ live ones it replaces.
+
+ That is the last write standing between a mis-aimed rewind and permanent
+ loss, and all three reported incidents (#70516, #80763, #82756) ended
+ there with an empty WAL, no `active=0` rows and an FTS entry dropped in
+ sync. `archive_dropped=True` keeps the replaced turns on disk under the
+ same "the user took it back" marking `rewind_to_message` uses.
+ """
+
+ def test_dropped_turns_survive_as_inactive_rows(self, state_db):
+ sid = "archive-dropped"
+ state_db.create_session(sid, "test")
+ state_db.append_messages_batch(
+ sid,
+ [
+ {"role": "user", "content": "first"},
+ {"role": "assistant", "content": "first reply"},
+ {"role": "user", "content": "second"},
+ {"role": "assistant", "content": "second reply"},
+ ],
+ )
+
+ state_db.replace_messages(
+ sid,
+ [
+ {"role": "user", "content": "first"},
+ {"role": "assistant", "content": "first reply"},
+ ],
+ active_only=True,
+ archive_dropped=True,
+ )
+
+ # The live transcript is exactly what a destructive replace would leave.
+ live = [
+ m for m in state_db.get_messages_as_conversation(sid)
+ if m.get("role") in ("user", "assistant")
+ ]
+ assert [m["content"] for m in live] == ["first", "first reply"]
+
+ # …but the dropped turns are still readable instead of gone.
+ recovered = [
+ m["content"]
+ for m in state_db.get_messages(sid, include_inactive=True)
+ if not m["active"]
+ ]
+ assert "second" in recovered
+ assert "second reply" in recovered
+
+ def test_archived_rows_use_rewind_marking_not_compaction(self, state_db):
+ """compacted=0 keeps abandoned turns out of session search results.
+
+ `archive_and_compact` marks its rows compacted=1 precisely so they stay
+ discoverable; a rewound turn is one the user took back, so it must
+ carry the `rewind_to_message` marking instead.
+ """
+ sid = "archive-marking"
+ state_db.create_session(sid, "test")
+ state_db.append_messages_batch(
+ sid,
+ [
+ {"role": "user", "content": "keep"},
+ {"role": "assistant", "content": "drop me"},
+ ],
+ )
+
+ state_db.replace_messages(
+ sid,
+ [{"role": "user", "content": "keep"}],
+ active_only=True,
+ archive_dropped=True,
+ )
+
+ archived = [
+ m for m in state_db.get_messages(sid, include_inactive=True)
+ if not m["active"]
+ ]
+ assert archived, "the replaced rows must still be on disk"
+ assert all(not m.get("compacted") for m in archived)
+
+ def test_default_stays_destructive(self, state_db):
+ """The other three callers must be untouched by the new parameter."""
+ sid = "archive-default"
+ state_db.create_session(sid, "test")
+ state_db.append_messages_batch(
+ sid,
+ [
+ {"role": "user", "content": "gone"},
+ {"role": "assistant", "content": "also gone"},
+ ],
+ )
+
+ state_db.replace_messages(sid, [{"role": "user", "content": "fresh"}])
+
+ assert not [
+ m for m in state_db.get_messages(sid, include_inactive=True)
+ if not m["active"]
+ ]
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index 8bb8188be63..5ec9a0d1429 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -4352,7 +4352,7 @@ def test_prompt_submit_rejects_negative_truncate_ordinal(monkeypatch):
replaced = []
class _FakeDB:
- def replace_messages(self, key, messages, active_only=False):
+ def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
replaced.append((key, list(messages)))
history = [
@@ -4406,7 +4406,7 @@ def test_prompt_submit_refuses_unconfirmed_nonempty_truncation(monkeypatch):
replaced = []
class _FakeDB:
- def replace_messages(self, key, messages):
+ def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
replaced.append((key, list(messages)))
history = [
@@ -4469,7 +4469,7 @@ def test_prompt_submit_refuses_empty_truncation_without_confirm(monkeypatch):
replaced = []
class _FakeDB:
- def replace_messages(self, key, messages, active_only=False):
+ def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
replaced.append((key, list(messages)))
history = [
@@ -4556,7 +4556,7 @@ def test_prompt_submit_empty_truncation_allowed_with_confirm(monkeypatch):
self._target()
class _FakeDB:
- def replace_messages(self, key, messages, active_only=False):
+ def replace_messages(self, key, messages, active_only=False, archive_dropped=False):
replaced.append((key, list(messages)))
history = [
@@ -9535,7 +9535,7 @@ def test_prompt_submit_can_truncate_before_user_ordinal(monkeypatch):
def __init__(self):
self.replaced = []
- def replace_messages(self, session_id, messages, active_only=False):
+ def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
self.replaced.append((session_id, list(messages)))
stub_db = _StubDb()
@@ -9592,7 +9592,7 @@ def test_prompt_submit_refuses_turn_when_truncate_persist_fails(monkeypatch):
server._sessions["trunc-fail-sid"] = sess
class _FailDb:
- def replace_messages(self, session_id, messages, active_only=False):
+ def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
raise OSError("disk full")
monkeypatch.setattr(server, "_get_db", lambda: _FailDb())
@@ -9684,7 +9684,7 @@ def test_prompt_submit_truncate_ordinal_skips_display_kind_rows(monkeypatch):
def __init__(self):
self.replaced = []
- def replace_messages(self, session_id, messages, active_only=False):
+ def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
self.replaced.append((session_id, list(messages)))
stub_db = _StubDb()
@@ -16762,7 +16762,7 @@ def test_personality_marker_does_not_shift_truncate_ordinal(monkeypatch):
def __init__(self):
self.replaced = []
- def replace_messages(self, session_id, messages, active_only=False):
+ def replace_messages(self, session_id, messages, active_only=False, archive_dropped=False):
self.replaced.append((session_id, list(messages)))
session = _session(
@@ -16836,3 +16836,82 @@ def test_personality_marker_does_not_shift_truncate_ordinal(monkeypatch):
finally:
server._sessions.pop("personality-ordinal-sid", None)
+
+def test_prompt_submit_truncation_archives_instead_of_deleting(monkeypatch):
+ """The rewind write must be recoverable, not a hard DELETE.
+
+ #70516 / #80763 / #82756 all ended at this one call, and all three were
+ unrecoverable for the same reason: `replace_messages` DELETEs the rows and
+ the FTS entry goes with them. Guarding the *aim* of a rewind still leaves
+ every other way of aiming it wrong terminal, so the write itself has to
+ stop destroying. The storage-layer contract this relies on is pinned in
+ tests/hermes_state/test_replace_messages_archive_siblings.py.
+ """
+
+ captured = {}
+
+ class _Agent:
+ def run_conversation(self, prompt, conversation_history=None, stream_callback=None, **_kwargs):
+ return {
+ "final_response": "reply",
+ "messages": [
+ *(conversation_history or []),
+ {"role": "user", "content": prompt},
+ {"role": "assistant", "content": "reply"},
+ ],
+ }
+
+ class _ImmediateThread:
+ def __init__(self, target=None, daemon=None):
+ self._target = target
+
+ def start(self):
+ self._target()
+
+ class _StubDb:
+ def replace_messages(
+ self, session_id, messages, active_only=False, archive_dropped=False
+ ):
+ captured["active_only"] = active_only
+ captured["archive_dropped"] = archive_dropped
+
+ server._sessions["archive-trunc-sid"] = _session(
+ agent=_Agent(),
+ history=[
+ {"role": "user", "content": "first"},
+ {"role": "assistant", "content": "first reply"},
+ {"role": "user", "content": "second"},
+ {"role": "assistant", "content": "second reply"},
+ ],
+ )
+
+ try:
+ monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)
+ monkeypatch.setattr(server, "_session_info", lambda *a, **k: {})
+ monkeypatch.setattr(server, "_emit", lambda *a: None)
+ monkeypatch.setattr(server, "_get_usage", lambda _a: {})
+ monkeypatch.setattr(server, "render_message", lambda _t, _c: "")
+ monkeypatch.setattr(server, "_get_db", lambda: _StubDb())
+
+ resp = server.handle_request(
+ {
+ "id": "1",
+ "method": "prompt.submit",
+ "params": {
+ "session_id": "archive-trunc-sid",
+ "text": "second, reworded",
+ "truncate_before_user_ordinal": 1,
+ "confirm_truncate": True,
+ },
+ }
+ )
+
+ assert resp.get("result"), f"got error: {resp.get('error')}"
+ assert captured.get("archive_dropped") is True, (
+ "a rewind must soft-archive the turns it drops, not DELETE them"
+ )
+ # #80216: still must not touch rows archived by an earlier compaction.
+ assert captured.get("active_only") is True
+ finally:
+ server._sessions.pop("archive-trunc-sid", None)
+
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index f76e2f65b23..9cede691413 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -257,8 +257,18 @@ def _(rid, params: dict) -> dict:
# class #80216 fixed for /retry. On an uncompacted session
# all rows are active=1, so this is behaviorally identical
# to the full replace.
+ # archive_dropped: a rewind overwrites turns the user may
+ # not have meant to drop, and this write is the last step
+ # before they are gone — three reported incidents ended
+ # here with nothing to restore from (#70516, #80763,
+ # #82756). Soft-archiving keeps them on disk (active=0) and
+ # in the FTS index, so a mis-aimed cut is recoverable
+ # instead of terminal. The live transcript is unchanged.
db.replace_messages(
- session["session_key"], truncated, active_only=True
+ session["session_key"],
+ truncated,
+ active_only=True,
+ archive_dropped=True,
)
except Exception as exc:
logger.error(