The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): the repair counts every durable row it retires without an id
John Paul Soliva63c34ec4420f
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex b51364a0469..78cfd614e5f 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 DROPPED_DURABLE_ROWS+ from agent.conversation_compression_archive import UNNAMED_DURABLE_ROWSown_id = survivor.get("_row_id")ids = []@@ -482,28 +482,37 @@ def _remember_absorbed_row(survivor: Dict[str, Any], dropped: Dict[str, Any], *,for row_id in ids:if row_id not in absorbed:absorbed.append(row_id)- # Rows the repair dropped behind the retired dict are behind the survivor now.- if dropped.get(DROPPED_DURABLE_ROWS):- survivor[DROPPED_DURABLE_ROWS] = int(survivor.get(DROPPED_DURABLE_ROWS) or 0) + int(dropped[DROPPED_DURABLE_ROWS])+ # 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])# 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:record_absorbed_message(survivor, dropped)+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 dict+ out 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."""+ from agent.context_compressor import _DB_PERSISTED_MARKER+ from agent.conversation_compression_archive import UNNAMED_DURABLE_ROWS++ 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++def _retire_dropped_row(kept: List[Dict], dropped: Dict[str, Any]) -> None:"""A durable row the repair drops was still handed to the caller, so the survivor before it standsfor it. Left unnamed, an in-place compaction takes it for a row another surface appended and- re-sequences it behind the running turn. A reload without row ids can only count it."""- from agent.context_compressor import _DB_PERSISTED_MARKER- from agent.conversation_compression_archive import DROPPED_DURABLE_ROWS-+ re-sequences it behind the running turn."""prev = kept[-1] if kept and isinstance(kept[-1], dict) else None- if prev is None or not dropped.get(_DB_PERSISTED_MARKER):- return- _remember_absorbed_row(prev, dropped, folded=False)- if not isinstance(dropped.get("_row_id"), int):- prev[DROPPED_DURABLE_ROWS] = int(prev.get(DROPPED_DURABLE_ROWS) or 0) + 1+ if prev is not None:+ _count_unnamed_row(prev, dropped)+ _remember_absorbed_row(prev, dropped, folded=False)def _merge_consecutive_assistants(messages: List[Dict]) -> Tuple[List[Dict], int]:@@ -519,9 +528,11 @@ def _merge_consecutive_assistants(messages: List[Dict]) -> Tuple[List[Dict], int):# A provisional verification candidate is superseded, not unioned.if prev.get("finish_reason") in {"verification_required", "verify_hook_continue"}:+ _count_unnamed_row(msg, prev)_remember_absorbed_row(msg, prev, folded=False)collapsed[-1] = msgelse:+ _count_unnamed_row(prev, msg)_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 d849ca9c4cc..02dd535773f 100644--- a/agent/conversation_compression_archive.py+++ b/agent/conversation_compression_archive.py@@ -14,9 +14,10 @@ ABSORBED_ROW_IDS = "_absorbed_row_ids"# How many durable rows an alternation repair folded into one user dict. A reload without row ids# has no other way to tell that dict from a prompt that was never persisted.MERGED_DURABLE_ROWS = "_merged_durable_rows"-# How many durable rows the repair dropped behind a dict on a reload without row ids (a tool call-# with no result, a result with no call). The caller was handed them, and nothing else names them.-DROPPED_DURABLE_ROWS = "_dropped_durable_rows"+# How many more durable rows a dict stands for on a reload without row ids, besides a merged user+# 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"def _positive_id(value: Any) -> Optional[int]:@@ -86,8 +87,8 @@ 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 row the repair dropped has no id: naming the rest- would clone that one behind the running turn. A trailing unpersisted turn+ 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 turndoes not take this branch: the rows above it stay unnamed and are cloned."""from agent.context_compressor import _DB_PERSISTED_MARKER@@ -97,7 +98,7 @@ 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(DROPPED_DURABLE_ROWS) for message in unresolved):+ if any(message.get(UNNAMED_DURABLE_ROWS) for message in unresolved):return None, Nonemarked = [message for message in unresolveddiff --git a/gateway/run.py b/gateway/run.pyindex 0c0b190bb62..a7500e57028 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -1157,8 +1157,9 @@ def _build_replay_entry(if msg.get("_db_persisted"):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, which this view cannot name either.- for stamp in ("_merged_durable_rows", "_dropped_durable_rows"):+ # 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"):if msg.get(stamp):entry[stamp] = msg[stamp]return entrydiff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex d0f32a185a5..81be5fed97a 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -1083,16 +1083,16 @@ class SessionMessagesMixin:The watermark path cannot name a merged dict's run, so it widens by the stamp, less therows the dict lists in ``_absorbed_row_ids``: those are already counted in ``tail_count``.- Rows the repair dropped behind a dict on a reload without ids are in neither, so their- count is added. A dict that holds a ``_row_id`` was written back as a single row by an- earlier compaction.+ Rows the repair dropped behind a dict, or folded into an assistant turn, on a reload+ without ids are in neither, so their count is added. A dict that holds a ``_row_id`` was+ written back as a single row by an earlier compaction."""- from agent.conversation_compression_archive import DROPPED_DURABLE_ROWS, MERGED_DURABLE_ROWS+ from agent.conversation_compression_archive import MERGED_DURABLE_ROWS, UNNAMED_DURABLE_ROWSdef behind(message: Dict[str, Any]) -> int:- merged, dropped = message.get(MERGED_DURABLE_ROWS), message.get(DROPPED_DURABLE_ROWS)- unnamed = merged - 1 - len(message.get("_absorbed_row_ids") or ()) if type(merged) is int else 0- return max(0, unnamed) + (dropped if type(dropped) is int else 0)+ merged, unnamed = message.get(MERGED_DURABLE_ROWS), message.get(UNNAMED_DURABLE_ROWS)+ unlisted = merged - 1 - len(message.get("_absorbed_row_ids") or ()) if type(merged) is int else 0+ return max(0, unlisted) + (unnamed if type(unnamed) is int else 0)return sum(behind(message) for message in taildiff --git a/tests/agent/test_in_place_merged_user_rows.py b/tests/agent/test_in_place_merged_user_rows.pyindex fc1302f48e2..3ba5e7e5d28 100644--- a/tests/agent/test_in_place_merged_user_rows.py+++ b/tests/agent/test_in_place_merged_user_rows.py@@ -3,7 +3,8 @@A crash between turn start and the reply leaves a durable ``user;user`` pair. The alternation repairhands the compressor one dict for both rows, so the commit has to account for two originals behind it.A turn killed later leaves a tool call with no result, or a result the repair cannot pair. The repair-drops those rows, and they are still behind the dict before them.+drops those rows, and they are still behind the dict before them. Two assistant rows in a row are+folded into one turn the same way."""from types import SimpleNamespace@@ -12,18 +13,24 @@ import pytestfrom tests.agent.test_in_place_preflight_rewind import _replies_displayed, _turn, session # noqa: F401++def _call(call_id):+ return ("assistant", "", {"tool_calls": [+ {"id": call_id, "type": "function", "function": {"name": "terminal", "arguments": "{}"}}]})++_UNANSWERED = ("user", "U12x this prompt never got a reply", {})_RETRIED = ("user", "U12y the same request again", {})-_CALL = ("assistant", "", {"tool_calls": [- {"id": "call_killed", "type": "function", "function": {"name": "terminal", "arguments": "{}"}}]})_RESULT = ("tool", "partial output", {"tool_call_id": "call_killed"})KILLED_TURN_LEFT = {"prompt": [_UNANSWERED],"two_prompts": [_UNANSWERED, _RETRIED],- "tool_call": [_UNANSWERED, _CALL],+ "tool_call": [_UNANSWERED, _call("call_killed")],"tool_result": [_UNANSWERED, _RESULT],- "two_prompts_tool_call": [_UNANSWERED, _RETRIED, _CALL],+ "two_prompts_tool_call": [_UNANSWERED, _RETRIED, _call("call_killed")],+ "two_tool_calls": [_UNANSWERED, _call("call_killed"), _call("call_killed_again")],"result_after_a_reply": [_RESULT],+ "two_replies": [("assistant", "A12b a second reply to the same prompt", {})],}@@ -60,3 +67,4 @@ def test_compaction_over_an_unanswered_prompt_keeps_one_copy_of_every_row(sessioassert db._conn.execute("SELECT COUNT(*) FROM messages WHERE session_id = 'sid' AND active = 1"" AND (role = 'tool' OR tool_calls IS NOT NULL)").fetchone()[0] == 0+ assert [c.split(" ")[0] for c in live[-2:]] == ["U15", "A15"]