The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): a merged user dict resolves its rows before its text is compared
John Paul Soliva49486411d514
diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex f08228a26bf..4de69acb889 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -1042,28 +1042,51 @@ class SessionMessagesMixin:Failing to name it means the watermark path, which archives the rows the compressorsaw, including ones whose ids were stripped. A marker-less miss is an unpersistedturn: it names nothing, and it is not a reason to abandon the ids we do have.- Several active rows with the same content are ambiguous, so that also abandons.+ Several active rows with the same content are ambiguous, so that also abandons,+ and so does a merged dict whose run cannot be named.The second set holds only merges the caller could not count: a dict that lists itsown ``_absorbed_row_ids`` is already counted in ``tail_count``."""if covered_ids is None:return Nonefrom agent.context_compressor import _DB_PERSISTED_MARKER+ from agent.conversation_compression_archive import MERGED_DURABLE_ROWSproved = [int(row_id) for row_id in covered_ids if isinstance(row_id, int) and row_id > 0]merged_away: Set[int] = set()for message in unresolved_held or ():if not isinstance(message, dict):continue- matches = self._matching_active_ids(conn, session_id, message)- run = [] if matches else self._merged_user_run(conn, session_id, message)- if run is None or len(matches) > 1 or (+ # The stamp is provenance and text is not: a surface may have re-rendered the dict since the+ # repair (gateway timestamps), and a later row can equal the merged text. So the run is+ # resolved first, and a stamped dict that names none is still durable, never an unpersisted turn.+ run = self._merged_user_run(conn, session_id, message)+ if message.get(MERGED_DURABLE_ROWS) and not run:+ return None+ matches = [] if run else self._matching_active_ids(conn, session_id, message)+ if len(matches) > 1 or (message.get(_DB_PERSISTED_MARKER) and len(matches) != 1 and not run):return Noneproved.extend(matches or run)merged_away.update(set(run[1:]) - set(message.get("_absorbed_row_ids") or ()))return list(dict.fromkeys(proved)), merged_away+ @staticmethod+ def _uncounted_merged_rows(tail: List[Dict[str, Any]]) -> int:+ """Durable rows behind the carried *tail* beyond one per dict, for the positional rewind.++ The watermark path cannot name a merged dict's run, so it widens by the stamp. A dict that+ lists ``_absorbed_row_ids`` is already counted in ``tail_count``, and one that holds a+ ``_row_id`` was written back as a single row by an earlier compaction.+ """+ from agent.conversation_compression_archive import MERGED_DURABLE_ROWS++ return sum(+ message[MERGED_DURABLE_ROWS] - 1 for message in tail+ if isinstance(message, dict) and type(message.get(MERGED_DURABLE_ROWS)) is int+ and message[MERGED_DURABLE_ROWS] > 1 and not message.get("_absorbed_row_ids")+ and not isinstance(message.get("_row_id"), int))+@staticmethoddef _tail_originals(covered_active: List[int], tail_count: int, merged_away: Set[int]) -> List[int]:"""Newest rows behind *tail_count* carried dicts; a dict that merged rows stands for each of them."""@@ -1186,7 +1209,8 @@ class SessionMessagesMixin:rewind_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))).fetchall()]+ (session_id, *((int(watermark),) if bound else ()),+ int(tail_count) + self._uncounted_merged_rows(compacted_messages[-int(tail_count):]))).fetchall()]rewind_ids += tail_idsrewind_ids = list(dict.fromkeys(rewind_ids))if rewind_ids:diff --git a/tests/hermes_state/test_archive_merged_user_rows.py b/tests/hermes_state/test_archive_merged_user_rows.pyindex e634b77d6b1..692dc15389a 100644--- a/tests/hermes_state/test_archive_merged_user_rows.py+++ b/tests/hermes_state/test_archive_merged_user_rows.py@@ -23,3 +23,49 @@ def test_unpersisted_prompt_leaves_rows_appended_after_the_snapshot_live(tmp_patassert [row["content"] for row in db.get_messages("sid")] == ["summary", "ok", prompt["content"], "same first paragraph", "same second paragraph"]db.close()+++def _unanswered_pair(tmp_path, *after):+ db = SessionDB(tmp_path / "state.db")+ db.create_session("sid", source="test")+ for role, content in (("user", "first prompt"), ("user", "second prompt"), *after):+ db.append_message("sid", role, content)+ return db, db.get_active_message_watermark("sid")+++def _live(db):+ return [row["content"] for row in db.get_messages("sid")]+++def test_carried_merged_prompt_rendered_with_a_timestamp_keeps_one_copy_of_each_row(tmp_path):+ from gateway.run import _build_gateway_agent_history++ db, watermark = _unanswered_pair(tmp_path)+ restored = db.get_messages_as_conversation("sid", repair_alternation=True)+ held, _ = _build_gateway_agent_history(restored, inject_timestamps=True)+ assert held[0]["content"] != restored[0]["content"] # the render is what hides the rows++ db.archive_and_compact(+ "sid", [{"role": "assistant", "content": "summary"}, held[0]], watermark=watermark, tail_count=1,+ covered_ids=[], unresolved_held=held)++ assert _live(db) == ["summary", held[0]["content"]]+ recalled = " ".join(row["content"] for row in db._conn.execute(+ "SELECT content FROM messages WHERE session_id = 'sid' AND (active = 1 OR compacted = 1)").fetchall())+ assert (recalled.count("first prompt"), recalled.count("second prompt")) == (1, 1)+ db.close()+++def test_merged_prompt_names_its_pair_not_a_later_row_with_the_merged_text(tmp_path):+ db, watermark = _unanswered_pair(tmp_path, ("assistant", "A1"))+ held = db.get_messages_as_conversation("sid", repair_alternation=True)+ for message in held:+ message.pop("_row_id", None)+ message.pop("_absorbed_row_ids", None)+ db.append_message("sid", "user", held[0]["content"])++ db.archive_and_compact(+ "sid", [{"role": "user", "content": "summary"}], watermark=watermark, covered_ids=[], unresolved_held=held)++ assert _live(db) == ["summary", "first prompt\n\nsecond prompt"]+ db.close()