Skip to content

The agent that grows with you

fix(state): re-fold split display generations at compaction commit

finn7633d7058fc8303
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index 72a223a3041..cb80b4f0f7d 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -815,6 +815,9 @@ class SessionMessagesMixin:
self._clone_message_rows(conn, unseen)
inserted += len(unseen)
tool_calls_total += unseen_tool_calls
+ # A carried copy whose stored identity was computed differently lands in its own
+ # display_order group and would project twice; re-fold before publishing (#122167).
+ self._reconcile_display_orders(conn, session_id)
conn.execute(
f"{_SET_COUNTERS_SQL}{', model_config = ?' if patch else ''} WHERE id = ?",
(inserted, tool_calls_total, *((patched_model_config,) if patch else ()), session_id))
@@ -894,6 +897,9 @@ class SessionMessagesMixin:
self._clone_message_rows(conn, tail_ids)
inserted += len(tail_ids)
tool_calls_total += tail_tool_calls
+ # A carried copy whose stored identity was computed differently lands in its own
+ # display_order group and would project twice; re-fold before publishing (#122167).
+ self._reconcile_display_orders(conn, session_id)
conn.execute(f"{_SET_COUNTERS_SQL}{', model_config = ?' if patch else ''} WHERE id = ?",
(inserted, tool_calls_total, *((patched_model_config,) if patch else ()), session_id))
return inserted
@@ -1018,6 +1024,39 @@ class SessionMessagesMixin:
# copy in a newer generation has a higher id than messages emitted after the original.
return [seen[key] for key in sorted(seen, key=first_id.__getitem__)]
+ def _reconcile_display_orders(self, conn, session_id: str) -> None:
+ """Re-fold split display generations by the recomputed display key.
+
+ A compaction generation that computed the display identity differently (or cloned
+ without inheriting it) leaves one logical message in two ``display_order`` groups,
+ and ``GROUP BY display_order`` then projects it twice (#122167). Folding by the same
+ recomputed key :meth:`_dedupe_display_generations` uses keeps every display projection
+ on one definition of a logical message; the live copy wins its group via the read
+ path's ``ORDER BY candidate.active DESC, candidate.id DESC``. Writes only on drift."""
+ first_id: Dict[bytes, int] = {}
+ last_id = 0
+ while True:
+ rows = conn.execute(
+ "SELECT id, role, content, timestamp, tool_call_id, tool_calls, tool_name, "
+ "display_kind, display_metadata, display_order, display_identity "
+ "FROM messages INDEXED BY idx_messages_session_id "
+ "WHERE session_id = ? AND id > ? AND (active = 1 OR compacted = 1) "
+ "ORDER BY id LIMIT 1000",
+ (session_id, last_id))
+ batch_start = last_id
+ updates = []
+ for row in rows:
+ last_id = row["id"]
+ identity = self._display_identity(self._display_dedupe_key(row))
+ order = first_id.setdefault(identity, last_id)
+ if order != row["display_order"] or identity != row["display_identity"]:
+ updates.append((order, identity, last_id))
+ rows.close()
+ if last_id == batch_start:
+ break
+ conn.executemany(
+ "UPDATE messages SET display_order = ?, display_identity = ? WHERE id = ?", updates)
+
def _ensure_display_order(self, session_id: str) -> bool:
"""Backfill one legacy session once, preserving the pre-index display identity exactly."""
with self._read_ctx() as conn:
@@ -1033,29 +1072,7 @@ class SessionMessagesMixin:
missing = conn.execute(_DISPLAY_INDEX_MISSING_SQL, (session_id,)).fetchone()
if missing is None:
return True
- first_id: Dict[bytes, int] = {}
- last_id = 0
- while True:
- rows = conn.execute(
- "SELECT id, role, content, timestamp, tool_call_id, tool_calls, tool_name, "
- "display_kind, display_metadata, display_order, display_identity "
- "FROM messages INDEXED BY idx_messages_session_id "
- "WHERE session_id = ? AND id > ? AND (active = 1 OR compacted = 1) "
- "ORDER BY id LIMIT 1000",
- (session_id, last_id))
- batch_start = last_id
- updates = []
- for row in rows:
- last_id = row["id"]
- identity = self._display_identity(self._display_dedupe_key(row))
- order = first_id.setdefault(identity, last_id)
- if order != row["display_order"] or identity != row["display_identity"]:
- updates.append((order, identity, last_id))
- rows.close()
- if last_id == batch_start:
- break
- conn.executemany(
- "UPDATE messages SET display_order = ?, display_identity = ? WHERE id = ?", updates)
+ self._reconcile_display_orders(conn, session_id)
return True
return bool(self._execute_write(_do))
diff --git a/tests/hermes_state/test_display_split_heal.py b/tests/hermes_state/test_display_split_heal.py
new file mode 100644
index 00000000000..bd0d5ff80e4
--- /dev/null
+++ b/tests/hermes_state/test_display_split_heal.py
@@ -0,0 +1,103 @@
+"""A split display generation must still project as one message (issue #122167).
+
+Symptom B: after a compaction tail move, the server-side display projection
+(``get_messages(include_compacted=True)``, the ``GROUP BY display_order`` path
+in ``_display_rows_from_conn``) hands the renderer the same assistant reply
+twice. The reporter's measurement on the real function: both rowids inside the
+returned list, ``display_order == own id`` on each side, only
+active/compacted/display_order/display_identity differing.
+
+This test rebuilds that measured end-state (compaction carry + a skewed stored
+identity/order on the copy, as left behind by a generation that computed the
+identity differently), drives one more compaction, and asserts the behavior
+contract: one logical message, one projection entry. The heal lives on the
+compaction write path (not the read path) so paged display reads stay bounded
+in the size of the page, not the transcript.
+"""
+
+from hermes_state import SessionDB
+
+
+def _carry_and_split(db, sid, reply_text):
+ ts = 1727000000.0
+ db.create_session(sid, source="desktop")
+ db.append_message(sid, "user", "q", timestamp=ts)
+ db.append_message(sid, "assistant", reply_text, timestamp=ts + 1)
+ live = db.get_messages_as_conversation(sid)
+ db.archive_and_compact(
+ sid, [{"role": "user", "content": "[summary]"}] + live[-2:], tail_count=2)
+
+ def _split(conn):
+ copy_id = conn.execute(
+ "SELECT MAX(id) FROM messages WHERE session_id = ? AND active = 1 AND role = 'assistant'",
+ (sid,)).fetchone()[0]
+ # A generation that computed the identity differently leaves the copy
+ # in its own display_order group: order == own id, foreign identity.
+ conn.execute(
+ "UPDATE messages SET display_order = id, display_identity = zeroblob(32) "
+ "WHERE id = ?", (copy_id,))
+ # ...while the carried original was archived (still display-visible)
+ # instead of rewound — the issue's measured end-state: both rowids
+ # display-visible, one logical message in two display_order groups.
+ conn.execute(
+ "UPDATE messages SET compacted = 1 WHERE session_id = ? AND role = 'assistant' "
+ "AND active = 0 AND id <> ?", (sid, copy_id))
+ return copy_id
+
+ return db._execute_write(_split)
+
+
+def _compact_again(db, sid, reply_text):
+ """One more ordinary compaction; its commit re-folds any split generation.
+
+ ``tail_count=0`` archives (not rewinds) the skewed copy, so it stays
+ display-visible: the exact shape that used to project twice."""
+ live = db.get_messages_as_conversation(sid)
+ tail = [m for m in live if m["role"] == "assistant" and m["content"] == reply_text][-1:]
+ db.archive_and_compact(
+ sid, [{"role": "user", "content": "[summary 2]"}] + tail, tail_count=0)
+
+
+def _reply_count(db, sid, reply_text):
+ rows = db.get_messages(sid, include_compacted=True)
+ return sum(1 for m in rows if m["role"] == "assistant" and m["content"] == reply_text)
+
+
+class TestSplitDisplayGenerationProjectsOnce:
+ def test_text_reply_projects_once(self, tmp_path):
+ from pathlib import Path
+ db = SessionDB(Path(tmp_path) / "state.db")
+ _carry_and_split(db, "chat", "same reply")
+ assert _reply_count(db, "chat", "same reply") == 2
+ _compact_again(db, "chat", "same reply")
+
+ assert _reply_count(db, "chat", "same reply") == 1
+ # The desktop pages this path (limit/offset/latest): paged reads fold too.
+ for rows in (db.get_messages("chat", include_compacted=True, latest=True, limit=10),
+ db.get_messages("chat", include_compacted=True, limit=10, offset=0)):
+ assert sum(1 for m in rows if m["role"] == "assistant"
+ and m["content"] == "same reply") == 1
+
+ def test_empty_reply_projects_once(self, tmp_path):
+ from pathlib import Path
+ db = SessionDB(Path(tmp_path) / "state.db")
+ _carry_and_split(db, "chat", "")
+ assert _reply_count(db, "chat", "") == 2
+ _compact_again(db, "chat", "")
+
+ assert _reply_count(db, "chat", "") == 1
+
+ def test_heal_is_durable_not_per_read(self, tmp_path):
+ """After the healing compaction, the rows share one group on disk."""
+ from pathlib import Path
+ db = SessionDB(Path(tmp_path) / "state.db")
+ _carry_and_split(db, "chat", "same reply")
+ _compact_again(db, "chat", "same reply")
+ assert _reply_count(db, "chat", "same reply") == 1
+
+ orders = db._read_all(
+ "SELECT DISTINCT display_order FROM messages WHERE session_id = ? "
+ "AND role = 'assistant' AND content = ? AND (active = 1 OR compacted = 1)",
+ ("chat", db._encode_content("same reply")))
+
+ assert len(orders) == 1