The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): a row the repair drops is named, not a reason to fall back to the watermark
unsupportedpastelsda88c23c0209
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex f5575b001f6..1d01264b85a 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -467,7 +467,7 @@ def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any], *,text survives). An empty incoming turn still merges; stamping an empty list would change a message thatabsorbed nothing. A dropped id that equals the survivor's own live id (the display-marker merge adoptsthe plain row's id, #94486) is not an absorbed row: the survivor IS that row."""- from agent.conversation_compression_archive import UNNAMED_DURABLE_ROWS+ from agent.conversation_compression_archive import OWN_ROW, RETIRED_DURABLE_ROWS, UNNAMED_DURABLE_ROWSown_id = survivor.get("_row_id")ids = []@@ -485,6 +485,10 @@ def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any], *,# The rows the retired dict counted are behind the survivor now.if dropped.get(UNNAMED_DURABLE_ROWS):survivor[UNNAMED_DURABLE_ROWS] = int(survivor.get(UNNAMED_DURABLE_ROWS) or 0) + int(dropped[UNNAMED_DURABLE_ROWS])+ # Its own row is behind the survivor now too.+ if dropped.get(RETIRED_DURABLE_ROWS):+ survivor.setdefault(RETIRED_DURABLE_ROWS, []).extend(+ {k: v for k, v in row.items() if k != OWN_ROW} for row in dropped[RETIRED_DURABLE_ROWS])# The uid witness claims the dropped dict's TEXT lives on in the survivor: only a fold earns it. A# superseded row (``folded=False``) is retired like any absorbed row but its content is discarded.if folded:@@ -494,15 +498,30 @@ def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any], *,def _count_unnamed_row(survivor: Dict[str, Any], retired: Dict[str, Any]) -> None:"""On a reload without row ids nothing names *retired*'s durable row once the repair takes the dictout of the list, so *survivor* counts it. A dict that counts rows was loaded too: a merge may have- popped its marker since. Call before the merge rewrites the survivor."""+ popped its marker since. Call before the merge rewrites the survivor: *retired*'s own fields are+ recorded so the commit can name its row."""from agent.context_compressor import _DB_PERSISTED_MARKER- from agent.conversation_compression_archive import UNNAMED_DURABLE_ROWS+ from agent.conversation_compression_archive import (+ RETIRED_DURABLE_ROWS, UNNAMED_DURABLE_ROWS, retired_row_payload)def loaded(message: Dict[str, Any]) -> bool:return bool(message.get(_DB_PERSISTED_MARKER) or message.get(UNNAMED_DURABLE_ROWS))if loaded(survivor) and loaded(retired) and not isinstance(retired.get("_row_id"), int):survivor[UNNAMED_DURABLE_ROWS] = int(survivor.get(UNNAMED_DURABLE_ROWS) or 0) + 1+ survivor.setdefault(RETIRED_DURABLE_ROWS, []).append(retired_row_payload(retired))+++def _remember_own_row(survivor: Dict[str, Any]) -> None:+ """An assistant fold rewrites *survivor*'s text, so on a reload without row ids its own row no longer+ matches it by content. Record its loaded fields first, once."""+ from agent.context_compressor import _DB_PERSISTED_MARKER+ from agent.conversation_compression_archive import OWN_ROW, RETIRED_DURABLE_ROWS, retired_row_payload++ recorded = survivor.get(RETIRED_DURABLE_ROWS) or ()+ if (survivor.get(_DB_PERSISTED_MARKER) and not isinstance(survivor.get("_row_id"), int)+ and not any(isinstance(row, dict) and row.get(OWN_ROW) for row in recorded)):+ survivor.setdefault(RETIRED_DURABLE_ROWS, []).append({**retired_row_payload(survivor), OWN_ROW: True})def _retire_dropped_row(kept: List[Dict], dropped: Dict[str, Any], leading: List[Dict]) -> None:@@ -541,6 +560,7 @@ def _merge_consecutive_assistants(messages: List[Dict]) -> Tuple[List[Dict], intcollapsed[-1] = msgelse:_count_unnamed_row(prev, msg)+ _remember_own_row(prev)_remember_absorbed_row(prev, msg, folded=_merge_assistant_into(prev, msg))repairs += 1continuediff --git a/agent/conversation_compression_archive.py b/agent/conversation_compression_archive.pyindex 02dd535773f..0360baea457 100644--- a/agent/conversation_compression_archive.py+++ b/agent/conversation_compression_archive.py@@ -18,6 +18,25 @@ MERGED_DURABLE_ROWS = "_merged_durable_rows"# run: rows the repair dropped behind it (a tool call with no result, a result with no call) or# folded into an assistant turn. The caller was handed them, and nothing else names them.UNNAMED_DURABLE_ROWS = "_unnamed_durable_rows"+# What names those rows at commit: role, content and tool-call ids of each, one per counted row.+# The commit matches each to one active row, so the rest of the held history keeps exact coverage.+RETIRED_DURABLE_ROWS = "_retired_durable_rows"+# Tags an entry of RETIRED_DURABLE_ROWS once coverage_for_commit hands it to the commit as unresolved.+RETIRED_ROW = "_retired_row"+# Marks the entry for the dict's own row: an assistant fold rewrote its text, so content no longer names it.+# It stands in the dict's own tail slot and is not one of the counted rows behind it.+OWN_ROW = "_own_row"+++def retired_row_payload(message: Dict[str, Any]) -> Dict[str, Any]:+ """The fields the commit matches a retired id-less row by."""+ payload: Dict[str, Any] = {"role": message.get("role"), "content": message.get("content")}+ if message.get("tool_call_id"):+ payload["tool_call_id"] = message["tool_call_id"]+ calls = [call.get("id") for call in message.get("tool_calls") or () if isinstance(call, dict)]+ if calls:+ payload["tool_call_ids"] = calls+ return payloaddef _positive_id(value: Any) -> Optional[int]:@@ -87,9 +106,12 @@ def coverage_for_commit(``None`` when the newest exact held row is already inactive (another compactionwon: archiving only the held ids would clone the winner), when nothing held- is a durable row, or when a held dict counts rows no id names: naming the rest- would clone those behind the running turn. A trailing unpersisted turn+ is a durable row, or when a held dict counts more rows than it can name: naming+ the rest would clone those behind the running turn. A trailing unpersisted turndoes not take this branch: the rows above it stay unnamed and are cloned.+ The rows a dict names in ``RETIRED_DURABLE_ROWS`` join the unresolved set, so a+ dropped row does not throw away the coverage of everything else: the watermark+ would also archive rows another surface appended that the compressor never saw."""from agent.context_compressor import _DB_PERSISTED_MARKER@@ -98,8 +120,13 @@ def coverage_for_commit(if newest is not None and callable(role_of) and role_of(session_id, newest) is None:return None, Nonecovered, unresolved = held_archive_coverage(messages, verbatim_tail)- if any(message.get(UNNAMED_DURABLE_ROWS) for message in unresolved):- return None, None+ retired: List[Dict[str, Any]] = []+ for message in unresolved:+ named = [row for row in message.get(RETIRED_DURABLE_ROWS) or () if isinstance(row, dict)]+ if int(message.get(UNNAMED_DURABLE_ROWS) or 0) > sum(1 for row in named if not row.get(OWN_ROW)):+ return None, None+ retired.extend({**row, _DB_PERSISTED_MARKER: True, RETIRED_ROW: True} for row in named)+ unresolved = [*unresolved, *retired]marked = [message for message in unresolvedif isinstance(message, dict) and message.get(_DB_PERSISTED_MARKER)diff --git a/agent/message_metadata.py b/agent/message_metadata.pyindex 7eb8cf12ec9..dac5e52238c 100644--- a/agent/message_metadata.py+++ b/agent/message_metadata.py@@ -7,7 +7,7 @@ from time import time as wall_timefrom uuid import uuid4from typing import Any, List, Mapping, MutableMapping, Optional, TypeVar-from agent.conversation_compression_archive import MERGED_DURABLE_ROWS, UNNAMED_DURABLE_ROWS+from agent.conversation_compression_archive import MERGED_DURABLE_ROWS, RETIRED_DURABLE_ROWS, UNNAMED_DURABLE_ROWS# These fields describe Hermes' durable record and timeline display, not@@ -46,7 +46,7 @@ PERSISTENCE_ONLY_MESSAGE_FIELDS = frozenset({"timestamp", "display_kind", "display_metadata", "_row_id", "_submit_row_session_id",MERGED_TURN_PREFIX, MESSAGE_UID, ABSORBED_MESSAGE_UIDS, TOOL_CALL_UIDS, TOOL_CALL_UID,# The alternation repair's row counts: an in-place compaction reads them off the live dict.- MERGED_DURABLE_ROWS, UNNAMED_DURABLE_ROWS}+ MERGED_DURABLE_ROWS, UNNAMED_DURABLE_ROWS, RETIRED_DURABLE_ROWS}) | REPAIR_BOOKKEEPING_FIELDSdiff --git a/gateway/run.py b/gateway/run.pyindex a7500e57028..743e9a285e1 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -1158,8 +1158,8 @@ def _build_replay_entry(entry["_db_persisted"] = True# A merged user dict lost that stamp; this one is what ties it to its durable rows at compaction.# The other counts the rows the repair dropped behind a dict or folded into an assistant turn,- # which this view cannot name either.- for stamp in ("_merged_durable_rows", "_unnamed_durable_rows"):+ # which this view cannot name either; the last names them for the commit.+ for stamp in ("_merged_durable_rows", "_unnamed_durable_rows", "_retired_durable_rows"):if msg.get(stamp):entry[stamp] = msg[stamp]return entrydiff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 81be5fed97a..a1ea2aad578 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -994,6 +994,36 @@ class SessionMessagesMixin:"SELECT id FROM messages WHERE session_id = ? AND active = 1 AND role = ? AND content = ?",(session_id, message.get("role"), stored)).fetchall()]+ def _matching_retired_ids(+ self, conn, session_id: str, retired: Dict[str, Any], watermark: Optional[int] = None,+ ) -> List[int]:+ """Active rows equal to a row the alternation repair retired without an id.++ Matched on role, loaded-view content (an empty assistant stores ``None`` or ``""``), tool_call_id+ and the ids of its tool calls. Only rows at or below *watermark*: the repair ran on a load taken+ before the snapshot, so a later equal row is another surface's append.+ """+ role = str(retired.get("role") or "")+ bound = watermark is not None+ rows = conn.execute(+ "SELECT id, content, tool_call_id, tool_calls FROM messages WHERE session_id = ? AND active = 1 "+ f"AND role = ?{' AND id <= ?' if bound else ''} ORDER BY id",+ (session_id, role, *((int(watermark),) if bound else ()))).fetchall()+ want_calls = list(retired.get("tool_call_ids") or ())+ matches = []+ for row in rows:+ content = self._loaded_view_content(role, self._decode_content(row["content"]))+ if (content or None) != (retired.get("content") or None):+ continue+ if (row["tool_call_id"] or None) != (retired.get("tool_call_id") or None):+ continue+ calls = _parse_tool_calls(row["tool_calls"]) or []+ ids = [call.get("id") for call in calls if isinstance(call, dict)] if isinstance(calls, list) else []+ if ids != want_calls:+ continue+ matches.append(int(row["id"]))+ return matches+def _merged_user_run(self, conn, session_id: str, message: Dict[str, Any], watermark: Optional[int] = None,) -> Optional[List[int]]:@@ -1056,13 +1086,23 @@ class SessionMessagesMixin:if covered_ids is None:return Nonefrom agent.context_compressor import _DB_PERSISTED_MARKER- from agent.conversation_compression_archive import MERGED_DURABLE_ROWS+ from agent.conversation_compression_archive import MERGED_DURABLE_ROWS, OWN_ROW, RETIRED_ROWproved = [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+ if message.get(RETIRED_ROW):+ # A row the repair dropped behind another held dict: that dict stands for it in the tail.+ # The dict's own row, recorded before a fold rewrote its text, is its own tail slot.+ matches = self._matching_retired_ids(conn, session_id, message, watermark)+ if len(matches) != 1:+ return None+ proved.extend(matches)+ if not message.get(OWN_ROW):+ merged_away.update(matches)+ continue# 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.diff --git a/tests/hermes_state/test_dropped_row_unseen_gap.py b/tests/hermes_state/test_dropped_row_unseen_gap.pynew file mode 100644index 00000000000..9bdfd1657ac--- /dev/null+++ b/tests/hermes_state/test_dropped_row_unseen_gap.py@@ -0,0 +1,74 @@+"""A row the alternation repair drops is named at commit, so the rest of the held history keeps exact coverage.++Falling back to the watermark instead archives rows another surface appended below it, which the+compressor never saw: they leave the model's history without being in the summary.+"""++from types import SimpleNamespace++import pytest++from agent.agent_runtime_helpers import repair_message_sequence+from agent.conversation_compression_archive import coverage_for_commit+from hermes_state import SessionDB+from tests.agent.test_in_place_preflight_rewind import _turn, session # noqa: F401++_CALL = {"tool_calls": [{"id": "call_killed", "type": "function",+ "function": {"name": "terminal", "arguments": "{}"}}]}+DROPPED = {+ "tool_result": [("tool", "ORPHAN_RESULT", {"tool_call_id": "call_killed"})],+ "tool_call": [("assistant", "", _CALL)],+ "two_replies": [("assistant", "A2b a second reply", {})],+}++[email protected]("row_ids", [False, True])[email protected]("left", list(DROPPED))+def test_an_unseen_gap_survives_a_dropped_row(tmp_path, left, row_ids):+ db = SessionDB(tmp_path / "state.db")+ try:+ db.create_session("sid", source="test")+ db.append_message("sid", "user", "U1")+ db.append_message("sid", "assistant", "A1")+ held = db.get_messages_as_conversation("sid", include_row_ids=row_ids)+ # Another surface writes after this process loaded its prefix; its live list never loads the gap.+ db.append_message("sid", "user", "UNSEEN_USER")+ db.append_message("sid", "assistant", "UNSEEN_REPLY")+ db.append_message("sid", "user", "U2")+ db.append_message("sid", "assistant", "A2")+ for role, content, fields in DROPPED[left]:+ db.append_message("sid", role, content, **fields)+ db.append_message("sid", "user", "U3")+ db.append_message("sid", "assistant", "A3")+ held.extend(db.get_messages_as_conversation("sid", include_row_ids=row_ids)[4:])+ repair_message_sequence(None, held)+ covered, unresolved = coverage_for_commit(db, "sid", held)++ db.archive_and_compact(+ "sid", [{"role": "user", "content": "summary of the held rows"}],+ watermark=db.get_active_message_watermark("sid"), covered_ids=covered, unresolved_held=unresolved)++ live = db.get_messages("sid")+ assert [row["content"] for row in live] == ["summary of the held rows", "UNSEEN_USER", "UNSEEN_REPLY"]+ assert not any(row["tool_calls"] or row["role"] == "tool" for row in live)+ finally:+ db.close()+++def test_the_named_rows_stay_off_the_request_copy(session):+ from agent.conversation_compression_archive import RETIRED_DURABLE_ROWS+ from agent.turn_context import build_api_messages+ from tests.agent.test_in_place_merged_user_rows import KILLED_TURN_LEFT++ db, agent = session+ _turn(db, agent, SimpleNamespace(conversation_history=[]), "cli", 1, 5_000)+ for role, content, fields in KILLED_TURN_LEFT["two_prompts_tool_call"]:+ db.append_message("sid", role, content, **fields)+ history = db.get_messages_as_conversation("sid", repair_alternation=True)+ assert RETIRED_DURABLE_ROWS in history[-1]++ request, _ = build_api_messages(+ agent, history, current_turn_user_idx=len(history) - 1,+ ext_prefetch_cache="", plugin_user_context="", moa_config=None, active_system_prompt="")++ assert not any(RETIRED_DURABLE_ROWS in message for message in request)