The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): stop in-place compaction from storing a carried message twice
Sahil Jagtap3fd9be25a17f
diff --git a/hermes_state_coverage.py b/hermes_state_coverage.pyindex 5ab00e78448..f5605b7d682 100644--- a/hermes_state_coverage.py+++ b/hermes_state_coverage.py@@ -9,6 +9,7 @@ from __future__ import annotationsfrom typing import Any, Dict, List, Optional, Set, Tuple+from agent.message_metadata import MESSAGE_UID, message_uid_or_nonefrom hermes_cli.timefmt import coerce_epochfrom hermes_state_common import _placeholdersfrom hermes_state_messages import _parse_tool_calls@@ -17,6 +18,79 @@ from hermes_state_messages import _parse_tool_callsclass SessionCoverageMixin:"""Coverage helpers for SessionDB; relies on SessionMessagesMixin's codec/identity helpers."""+ def _carried_tail_ids(+ self, conn, tail_ids: list[int], compacted_messages: list[dict[str, Any]],+ ) -> dict[int, int]:+ """Rows of *tail_ids* that *compacted_messages* already carry -> ``{row id: index of the carrying dict}``.++ A row above the watermark is normally a concurrent append the summary never saw, so the commit+ clones it after the compacted set. A row the compressor ALSO held (flushed after the watermark+ was read, or left unnamed so coverage fell back to the watermark) is already in the compacted+ set as a carried copy; cloning it too stores the message twice, with a fresh id and timestamp+ each (#137197). A dict names its row by ``_row_id``, by ``message_uid``, by identity plus+ timestamp, or, carrying none of those, by identity alone. Each dict claims at most one row and+ each row is claimed once, so a second row with the same text (another surface's append) keeps+ its clone.+ """+ if not tail_ids or not compacted_messages:+ return {}+ by_row: dict[int, tuple[int, tuple[Any, ...]]] = {}+ by_uid: dict[str, int] = {}+ by_key: dict[tuple[Any, ...], int] = {}+ bare: dict[tuple[Any, ...], list[int]] = {}+ for index, message in enumerate(compacted_messages):+ if not isinstance(message, dict):+ continue+ identity = self._row_identity(+ message.get("role", "unknown"), message.get("content"), message.get("tool_call_id"),+ _parse_tool_calls(message.get("tool_calls")))+ row_id = message.get("_row_id")+ if isinstance(row_id, int) and not isinstance(row_id, bool) and row_id > 0:+ # Authoritative only while the stored identity still matches (a stale stamp names another row).+ by_row.setdefault(row_id, (index, identity))+ else:+ row_id = None+ uid = message_uid_or_none(message)+ if uid is not None:+ by_uid.setdefault(uid, index)+ timestamp = coerce_epoch(message.get("timestamp"), field="message timestamp")+ if timestamp is not None:+ by_key.setdefault((*identity, timestamp), index)+ elif row_id is None and uid is None:+ bare.setdefault(identity, []).append(index)+ carried: dict[int, int] = {}+ claimed: set[int] = set()+ for row in conn.execute(+ f"SELECT id, role, content, tool_call_id, tool_calls, timestamp, {MESSAGE_UID} FROM messages "+ f"WHERE id IN ({_placeholders(tail_ids)}) ORDER BY id", tail_ids,+ ).fetchall():+ identity = self._row_identity(+ row["role"], self._decode_content(row["content"]), row["tool_call_id"],+ _parse_tool_calls(row["tool_calls"]))+ index = None+ if (named := by_row.get(int(row["id"]))) is not None and named[1] == identity:+ index = named[0]+ if index is None and row[MESSAGE_UID]:+ index = by_uid.get(row[MESSAGE_UID])+ if index is None:+ timestamp = coerce_epoch(row["timestamp"], field="message timestamp")+ if timestamp is not None:+ index = by_key.get((*identity, timestamp))+ if index is None and (queue := bare.get(identity)):+ index = queue.pop(0)+ if index is not None and index not in claimed:+ claimed.add(index)+ carried[int(row["id"])] = index+ return carried++ @staticmethod+ def _carried_tail_slots(carried: dict[int, int], compacted_count: int, tail_count: int) -> int:+ """How many of the carried tail's *tail_count* dicts name a row in *carried*: those originals sit+ above the watermark, so the positional rewind below it must take that many fewer rows."""+ if tail_count <= 0:+ return 0+ return sum(1 for index in carried.values() if index >= compacted_count - int(tail_count))+def _resolve_carried_row_ids(self, conn, session_id: str, carried_messages: list[dict[str, Any]],) -> list[int]:diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 614e3262dd7..d89c734fc1c 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -865,9 +865,13 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):covered_set.update(carried_ids)unseen = [row_id for row_id in active_ids if row_id not in covered_set]covered_active = [row_id for row_id in active_ids if row_id in covered_set]+ # An unseen row the compacted set already carries is superseded by that copy, not cloned (#137197).+ carried_unseen = self._carried_tail_ids(conn, unseen, compacted_messages)+ clone_ids = [row_id for row_id in unseen if row_id not in carried_unseen]+ tail_below = tail_count - self._carried_tail_slots(carried_unseen, len(compacted_messages), tail_count)rewind_ids = list(carried_ids)- if tail_count > 0:- rewind_ids += self._tail_originals(covered_active, tail_count, merged_away)+ if tail_below > 0:+ rewind_ids += self._tail_originals(covered_active, tail_below, merged_away)rewind_ids += unseenrewind_ids = list(dict.fromkeys(rewind_ids))if rewind_ids:@@ -882,13 +886,13 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):# the rewound/archived originals above never donate, so this is a no-op for a clean compaction.self._carry_parent_timestamps(conn, session_id, compacted_messages)inserted, tool_calls_total = self._insert_message_rows(conn, session_id, compacted_messages)- if unseen:+ if clone_ids:_ids, unseen_tool_calls = self._tail_rows_after_watermark(conn,- f"SELECT id, tool_calls FROM messages WHERE id IN ({_placeholders(unseen)}) ORDER BY id",- tuple(unseen))- self._clone_message_rows(conn, unseen)- inserted += len(unseen)+ f"SELECT id, tool_calls FROM messages WHERE id IN ({_placeholders(clone_ids)}) ORDER BY id",+ tuple(clone_ids))+ self._clone_message_rows(conn, clone_ids)+ inserted += len(clone_ids)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).@@ -934,6 +938,9 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):platform_message_id, token counts, reasoning sidecars all survive byte-exact, and the FTS triggersindex the clones naturally), and the originals are archived. NOTE: re-sequencing assigns the tailrows fresh ids; consumers that reference durable row ids re-resolve by content (see 3e8ab0610).+ A tail row that *compacted_messages* already carries (the compressor held it, and it was flushed+ above the watermark or left unnamed) is not cloned: the carried copy is its one live row and the+ original takes rewind flags (#137197)."""return self._execute_transcript_write(lambda conn: self._archive_and_compact_on_conn(conn, session_id, compacted_messages, model_config_patch=model_config_patch,@@ -977,20 +984,28 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):conn, session_id, compacted_messages, proved[0], tail_count=tail_count,carried_messages=carried_messages, patched_model_config=patched_model_config, patch=patch,merged_away=proved[1])- tail_ids, tail_tool_calls = ([], 0) if watermark is None else self._tail_rows_after_watermark(- conn, "SELECT id, tool_calls FROM messages WHERE session_id = ? AND active = 1 AND id > ? ORDER BY id",- (session_id, int(watermark)))+ tail_ids: list[int] = [] if watermark is None else [int(row["id"]) for row in conn.execute(+ "SELECT id FROM messages WHERE session_id = ? AND active = 1 AND id > ? ORDER BY id",+ (session_id, int(watermark))).fetchall()]+ # A concurrent-tail row the compacted set already carries is superseded by that copy, not+ # cloned beside it (#137197); its carried dict then has no original below the watermark.+ carried_tail = self._carried_tail_ids(conn, tail_ids, compacted_messages)+ clone_ids = [row_id for row_id in tail_ids if row_id not in carried_tail]+ _ids, tail_tool_calls = ([], 0) if not clone_ids else self._tail_rows_after_watermark(+ conn, f"SELECT id, tool_calls FROM messages WHERE id IN ({_placeholders(clone_ids)}) ORDER BY id",+ tuple(clone_ids))+ tail_below = tail_count - self._carried_tail_slots(carried_tail, len(compacted_messages), tail_count)# Rewind targets sit AT/BELOW the watermark (all the compressor saw); unbounded, a# concurrent append would steal a LIMIT slot.rewind_ids: list[int] = self._resolve_carried_row_ids(conn, session_id, carried_messages or [])- if tail_count > 0:+ if tail_below > 0:bound = watermark is not Nonerewind_ids += [int(row["id"]) for row in conn.execute(f"SELECT id FROM messages WHERE session_id = ? AND active = 1{' AND id <= ?' if bound else ''} ""ORDER BY id DESC LIMIT ?",(session_id, *((int(watermark),) if bound else ()),- int(tail_count) + self._uncounted_merged_rows(compacted_messages[-int(tail_count):]))).fetchall()]+ int(tail_below) + self._uncounted_merged_rows(compacted_messages[-int(tail_count):]))).fetchall()]rewind_ids += tail_idsrewind_ids = list(dict.fromkeys(rewind_ids))if rewind_ids:@@ -1005,9 +1020,9 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):# the rewound/archived originals above never donate, so this is a no-op for a clean compaction.self._carry_parent_timestamps(conn, session_id, compacted_messages)inserted, tool_calls_total = self._insert_message_rows(conn, session_id, compacted_messages)- if tail_ids:- self._clone_message_rows(conn, tail_ids)- inserted += len(tail_ids)+ if clone_ids:+ self._clone_message_rows(conn, clone_ids)+ inserted += len(clone_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).diff --git a/tests/hermes_state/test_compaction_carried_tail_not_cloned.py b/tests/hermes_state/test_compaction_carried_tail_not_cloned.pynew file mode 100644index 00000000000..c2e4a34a7a7--- /dev/null+++ b/tests/hermes_state/test_compaction_carried_tail_not_cloned.py@@ -0,0 +1,109 @@+"""Regression for #137197: a compaction must not store a carried message twice.++A row can be both *held* by the compressor (so the compacted set carries it+verbatim) and *above the commit watermark* (flushed after the watermark was+read, or unnamed by the held dicts so coverage fell back to the watermark).+The carried copy is inserted and the watermark path clones the row again, so+the same message lands twice with fresh ids, and the positional tail rewind+then flags a summarized row as a superseded duplicate instead.+"""++from __future__ import annotations++import sqlite3+from pathlib import Path++import pytest++from hermes_state import SessionDB++SID = "sess1"+SUMMARY_TEXT = "[CONTEXT COMPACTION] summary of the earlier turns"+++def _summary() -> dict:+ """A fresh dict per commit: the insert stamps row id, uid and timestamp onto the dict it stores."""+ return {"role": "user", "content": SUMMARY_TEXT}+++def db(tmp_path: Path):+ handle = SessionDB(tmp_path / "state.db")+ handle.create_session(SID, source="test")+ for i in range(4):+ handle.append_message(SID, role="user" if i % 2 == 0 else "assistant", content=f"old turn {i}")+ try:+ yield handle+ finally:+ handle.close()+++def _rows(db: SessionDB) -> list[dict]:+ conn = sqlite3.connect(db.db_path)+ conn.row_factory = sqlite3.Row+ try:+ return [dict(r) for r in conn.execute(+ "SELECT id, active, compacted, content, message_uid FROM messages WHERE session_id = ? ORDER BY id",+ (SID,)).fetchall()]+ finally:+ conn.close()+++def _copies(db: SessionDB, content: str) -> list[dict]:+ return [r for r in _rows(db) if r["content"] == content]+++class TestCarriedTailAboveWatermark:+ def test_held_row_above_watermark_is_carried_once(self, db: SessionDB) -> None:+ """The carried copy stands for the row; no clone lands beside it, and the+ positional tail rewind leaves the summarized rows summarized."""+ watermark = db.get_active_message_watermark(SID)+ db.append_message(SID, role="user", content="steer during the summary call")+ db.append_message(SID, role="assistant", content="reply during the summary call")+ held = db.get_messages_as_conversation(SID, include_row_ids=True)[-2:]+ assert all(m.get("_row_id") and m.get("message_uid") for m in held)++ count = db.archive_and_compact(SID, [_summary(), *held], watermark=watermark, tail_count=2)++ assert count == 3+ live = db.get_messages_as_conversation(SID)+ assert [m["content"] for m in live] == [+ SUMMARY_TEXT, "steer during the summary call", "reply during the summary call"]+ for content in ("steer during the summary call", "reply during the summary call"):+ copies = _copies(db, content)+ assert len(copies) == 2, f"{content!r}: original + carried copy, no clone"+ assert sorted(r["active"] for r in copies) == [0, 1]+ assert len({r["message_uid"] for r in copies}) == 1+ assert len(db.search_messages(content)) == 1+ # The carried dicts named rows above the watermark, so the tail rewind must not+ # reach below it: every summarized row stays recallable as compacted history.+ for i in range(4):+ (row,) = _copies(db, f"old turn {i}")+ assert (row["active"], row["compacted"]) == (0, 1)++ def test_content_only_carried_copy_is_not_cloned(self, db: SessionDB) -> None:+ """A carried dict with no id, uid or timestamp still names the row by content."""+ watermark = db.get_active_message_watermark(SID)+ db.append_message(SID, role="assistant", content="verbatim carried body")++ db.archive_and_compact(+ SID, [_summary(), {"role": "assistant", "content": "verbatim carried body"}], watermark=watermark)++ copies = _copies(db, "verbatim carried body")+ assert len(copies) == 2+ assert sorted(r["active"] for r in copies) == [0, 1]++ def test_foreign_identical_row_above_watermark_is_still_cloned(self, db: SessionDB) -> None:+ """A row another surface appended keeps its clone even when a held row below the+ watermark carries the same text: the carried dict names its own row, not the newcomer."""+ db.append_message(SID, role="assistant", content="same text twice")+ held = db.get_messages_as_conversation(SID, include_row_ids=True)[-1]+ watermark = db.get_active_message_watermark(SID)+ db.append_message(SID, role="assistant", content="same text twice")++ db.archive_and_compact(SID, [_summary(), held], watermark=watermark, tail_count=1)++ copies = _copies(db, "same text twice")+ assert len(copies) == 4, "held original + its carried copy, foreign original + its clone"+ assert sorted(r["active"] for r in copies) == [0, 0, 1, 1]+ assert len({r["message_uid"] for r in copies if r["active"]}) == 2