The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): keep row-addressed resume off the replay digest path
kshitijk4poord037aba45055
diff --git a/agent/transcript_repair.py b/agent/transcript_repair.pyindex 96e9af02c07..23632fae00d 100644--- a/agent/transcript_repair.py+++ b/agent/transcript_repair.py@@ -171,8 +171,8 @@ def resolve_and_repair_transcript_batch((encode_content_fn(msg.get("content")), target_id, session_id, target_row["content"]),).rowcount > 0else:- # Legacy dict (no digest: a resumed or cloned dict) over a non-blank assistant row: another writer- # already filled it. Adopt its content only, never the whole row: the live tool_calls /+ # Legacy dict (no digest: a row-addressed resume, a clone, or a repair_alternation=False+ # projection) over a non-blank assistant row: another writer already filled it. Adopt its content only, never the whole row: the live tool_calls /# reasoning* / codex_* fields may be sanitizer-fixed while the durable JSON still holds the raw# escaped surrogate, and live-only fields must survive.if role == "assistant":diff --git a/hermes_state.py b/hermes_state.pyindex 948b909c1fd..a086aae23b2 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -1605,7 +1605,9 @@ class SessionDB(#: Reactions live inside ``display_metadata`` so they survive row rewrites.REACTIONS_METADATA_KEY = "reactions"# Columns every conversation projection decodes; ``active`` rides along so a display read- # can split compaction-archived rows without a second query.+ # can split compaction-archived rows without a second query. Contract: must include every+ # ``agent.transcript_repair._OWNED_COLUMNS`` column, because replay stamps+ # ``transcript_row_snapshot(row)`` from these rows (token_count is hashed there, not decoded)._CONVERSATION_ROW_COLUMNS = ("id, role, content, tool_call_id, tool_calls, tool_name, effect_disposition, ""finish_reason, reasoning, reasoning_content, reasoning_details, "diff --git a/hermes_state_common.py b/hermes_state_common.pyindex a09137a9d82..fe8d93248b0 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -715,6 +715,9 @@ BEGINEND;CREATE INDEX IF NOT EXISTS idx_messages_active_nullON messages(active) WHERE active IS NULL;+-- Logical-identity recovery (agent.transcript_repair._active_logical_message_row) runs inside the write lock.+CREATE INDEX IF NOT EXISTS idx_messages_session_uid+ ON messages(session_id, message_uid) WHERE active = 1;CREATE INDEX IF NOT EXISTS idx_sessions_session_keyON sessions(session_key, started_at DESC);CREATE INDEX IF NOT EXISTS idx_sessions_gateway_peerdiff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 7d8470cf368..fc3bcd88dc3 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -1650,17 +1650,18 @@ class SessionMessagesMixin:include_summary_markers: bool = False) -> List[Dict[str, Any]]:"""Decode fetched rows (ordered by id, pre-filtered) into OpenAI format, stable key order. Every dict isstamped ``_DB_PERSISTED_MARKER_KEY`` (born durable) so an identity-losing handoff never re-appends the- transcript on flush. Live-replay projections also carry the stored-row CAS digest: if a later rewrite+ transcript on flush. Unaddressed live-replay projections also carry the stored-row CAS digest: if a later rewriteloses its physical ``_row_id``, logical ``message_uid`` can recover the row without guessing bymutable payload while the digest still fences a concurrent winner. ``_row_id`` is opt-in (gatewayreactions); reasoning restored on assistant rows only; ``api_content`` VERBATIM (no sanitize/strip)so replay keeps the provider prompt cache byte-stable."""from hermes_state import _strip_background_review_harness, _strip_stale_tool_call_markers- row_snapshot = None- if repair_alternation:- # Runtime import avoids the transcript_repair -> hermes_state_messages module cycle.- from agent.transcript_repair import transcript_row_snapshot- row_snapshot = transcript_row_snapshot+ # Runtime import avoids the transcript_repair -> hermes_state_messages module cycle.+ from agent.transcript_repair import transcript_row_snapshot+ # Only the unaddressed live replay gets the digest: row-addressed loaders (include_row_ids) keep the+ # legacy resumed-dict path, whose rewrite never re-writes columns the projection does not decode+ # (a CAS-match rewrite of a resumed row would otherwise null token_count).+ stamp_snapshot = repair_alternation and not include_row_idsmessages = []exact_user_clones: Dict[Tuple[Any, str], Dict[str, Any]] = {}tool_uid_index: Dict[str, str] = {} # pairing-id variant -> uid, from the assistant rows indexed so far@@ -1672,8 +1673,8 @@ class SessionMessagesMixin:# Underscore-prefixed like ``_row_id``: transports strip it before the wire; compression's# assembly copies strip it so rotated child handoffs still flush (_fresh_compaction_message_copy).msg = {"role": row["role"], "content": content, _DB_PERSISTED_MARKER_KEY: True}- if row_snapshot is not None:- msg[DB_ROW_SNAPSHOT] = row_snapshot(row)+ if stamp_snapshot:+ msg[DB_ROW_SNAPSHOT] = transcript_row_snapshot(row)# Born durable (#92231): this dict is materialized FROM a durable row, so stamp the persistence# marker at the source instead of relying on every restore caller to thread the loaded list back# through a flush as ``conversation_history=`` — any identity-losing handoff (compression'sdiff --git a/tests/hermes_state/test_unaddressed_rewrite_identity.py b/tests/hermes_state/test_unaddressed_rewrite_identity.pyindex 5cfb772944d..8114d1299ea 100644--- a/tests/hermes_state/test_unaddressed_rewrite_identity.py+++ b/tests/hermes_state/test_unaddressed_rewrite_identity.py@@ -11,7 +11,7 @@ from __future__ import annotationsimport pytestfrom agent.context_compressor import _DB_PERSISTED_MARKER-from agent.message_metadata import DB_ROW_SNAPSHOT+from agent.message_metadata import DB_ROW_SNAPSHOT, MESSAGE_UIDfrom hermes_state import SessionDB@@ -28,26 +28,28 @@ def _active_rows(store, sid):return [dict(row)for row in store._conn.execute(- "SELECT id, role, content, timestamp, message_uid, tool_calls "+ "SELECT id, role, content, timestamp, token_count, message_uid, tool_calls ""FROM messages WHERE session_id = ? AND active = 1 ORDER BY id",(sid,),).fetchall()]-def test_unaddressed_mutated_replay_rewrites_its_original_row(db):[email protected]("include_row_ids", [False, True], ids=["unaddressed", "row-addressed"])+def test_unaddressed_mutated_replay_rewrites_its_original_row(db, include_row_ids):sid = "mutated-replay"db.create_session(sid, "desktop")- original = {"role": "assistant", "content": "before repair", "timestamp": 1000.0}+ original = {"role": "assistant", "content": "before repair", "timestamp": 1000.0, "token_count": 42}assert db.append_messages_batch(sid, [original]) == 1before = _active_rows(db, sid)# Live replay without physical row ids is a supported shape (gateway/ACP and identity-losing# handoffs). It still carries logical identity and, for a writable replay, the CAS version.- restored = db.get_messages_as_conversation(sid, repair_alternation=True)- assert "_row_id" not in restored[0]- assert restored[0]["message_uid"] == before[0]["message_uid"]- assert isinstance(restored[0].get(DB_ROW_SNAPSHOT), str)+ # Row-addressed resume loaders keep the legacy (no-digest) path: the projection never decodes+ # token_count, so a digest-matched rewrite of a resumed row would null it.+ restored = db.get_messages_as_conversation(sid, repair_alternation=True, include_row_ids=include_row_ids)+ assert restored[0][MESSAGE_UID] == before[0]["message_uid"]+ assert (DB_ROW_SNAPSHOT in restored[0]) is not include_row_ids# Real rewrite sites change the payload BEFORE clearing the persisted marker.restored[0]["content"] = "after repair"@@ -58,20 +60,21 @@ def test_unaddressed_mutated_replay_rewrites_its_original_row(db):assert len(after) == 1assert after[0]["id"] == before[0]["id"]assert after[0]["message_uid"] == before[0]["message_uid"]- assert after[0]["content"] == "after repair"+ if include_row_ids:+ assert after[0]["token_count"] == 42+ else:+ assert after[0]["content"] == "after repair"def test_fresh_identical_message_is_never_adopted_by_payload(db):- """Content and timestamps are not identity: two real occurrences may be byte-identical."""+ """Content, timestamps and even a copied message_uid are not proof: only uid + CAS snapshot is."""sid = "identical-twins"db.create_session(sid, "desktop")first = {"role": "user", "content": "same", "timestamp": 3000.0}- second = {"role": "user", "content": "same", "timestamp": 3000.0}-assert db.append_messages_batch(sid, [first]) == 1- assert DB_ROW_SNAPSHOT not in second and "message_uid" not in second+ first_uid = _active_rows(db, sid)[0]["message_uid"]++ second = {"role": "user", "content": "same", "timestamp": 3000.0, MESSAGE_UID: first_uid}assert db.append_messages_batch(sid, [second]) == 1- rows = _active_rows(db, sid)- assert len(rows) == 2- assert rows[0]["message_uid"] != rows[1]["message_uid"]+ assert len(_active_rows(db, sid)) == 2