Skip to content

The agent that grows with you

fix(state): recover unaddressed rewrites by logical identity

JoaoMarcos44be20a423ba8b
diff --git a/agent/transcript_repair.py b/agent/transcript_repair.py
index e8e0d740541..96e9af02c07 100644
--- a/agent/transcript_repair.py
+++ b/agent/transcript_repair.py
@@ -88,6 +88,25 @@ def is_content_blank(content: Any) -> bool:
return False
+def _active_logical_message_row(
+ conn: sqlite3.Connection, session_id: str, role: str, message_uid: Any,
+) -> Mapping[str, Any] | None:
+ """Newest active physical row for one durable logical message.
+
+ A ``message_uid`` names a logical message, not a physical row: compaction/copy paths deliberately
+ keep it while re-issuing row ids. The later active row is the current version. Callers use this only
+ when the live dict also carries a stored-row snapshot, so a fresh message that merely resembles an
+ older one can never be adopted here.
+ """
+ if not isinstance(message_uid, str) or not message_uid:
+ return None
+ return conn.execute(
+ "SELECT * FROM messages WHERE session_id = ? AND active = 1 AND role = ? AND message_uid = ? "
+ "ORDER BY id DESC LIMIT 1",
+ (session_id, role, message_uid),
+ ).fetchone()
+
+
def resolve_and_repair_transcript_batch(
conn: sqlite3.Connection,
session_id: str,
@@ -99,17 +118,24 @@ def resolve_and_repair_transcript_batch(
) -> List[Dict[str, Any]]:
"""Resolve row-addressed rewrites without appending duplicates or replacing concurrent winners.
- A durable row snapshot is a compare-and-swap version for sanitizer rewrites. Watermark-compaction clones
- are matched by their copied payload identity, not timestamp alone. Legacy blank assistant rows retain the
- narrow interrupted-stream content repair. Returns only rows that need fresh inserts.
+ A durable row snapshot is a compare-and-swap version for sanitizer rewrites. When a live replay loses
+ its physical ``_row_id``, the pair (logical ``message_uid``, stored-row snapshot) recovers the newest
+ active generation without matching mutable payload. Watermark-compaction clones are matched by their
+ copied payload identity, not timestamp alone. Legacy blank assistant rows retain the narrow interrupted-
+ stream content repair. Returns only rows that need fresh inserts.
"""
inserted_rows: List[Dict[str, Any]] = []
for msg in messages:
existing_row_id = msg.get("_row_id") if isinstance(msg, dict) else None
role = msg.get("role", "unknown") if isinstance(msg, dict) else "unknown"
+ expected = msg.get(DB_ROW_SNAPSHOT) if isinstance(msg, dict) else None
target_row = None
if isinstance(existing_row_id, int):
target_row = _active_message_row(conn, session_id, existing_row_id, role)
+ elif isinstance(expected, str):
+ # Logical identity + the CAS version prove this dict came from durable replay. A new message
+ # has neither proof, even when role/content/timestamp happen to equal an older message exactly.
+ target_row = _active_logical_message_row(conn, session_id, role, msg.get(MESSAGE_UID))
if target_row is None:
inserted_rows.append(msg)
continue
@@ -117,7 +143,6 @@ def resolve_and_repair_transcript_batch(
target_id = int(target_row["id"])
msg["_row_id"] = target_id
_fill_missing_tool_call_uids(target_row, msg) # a dict that lost its uids must not rewrite them away
- expected = msg.get(DB_ROW_SNAPSHOT)
canonical = None
adopt = wrote = False
if isinstance(expected, str):
diff --git a/hermes_state.py b/hermes_state.py
index dca255c379c..948b909c1fd 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1610,7 +1610,7 @@ class SessionDB(
"id, role, content, tool_call_id, tool_calls, tool_name, effect_disposition, "
"finish_reason, reasoning, reasoning_content, reasoning_details, "
"codex_reasoning_items, codex_message_items, platform_message_id, observed, "
- "_compressed_summary, timestamp, active, api_content, display_kind, display_metadata, message_uid, "
+ "_compressed_summary, timestamp, token_count, active, api_content, display_kind, display_metadata, message_uid, "
"absorbed_message_uids, tool_call_uids, tool_call_uid"
)
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index c0df36136ae..7d8470cf368 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -1650,9 +1650,17 @@ 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 is
stamped ``_DB_PERSISTED_MARKER_KEY`` (born durable) so an identity-losing handoff never re-appends the
- transcript on flush. ``_row_id`` is opt-in (gateway reactions); reasoning restored on assistant rows
- only; ``api_content`` VERBATIM (no sanitize/strip) so replay keeps the provider prompt cache byte-stable."""
+ transcript on flush. Live-replay projections also carry the stored-row CAS digest: if a later rewrite
+ loses its physical ``_row_id``, logical ``message_uid`` can recover the row without guessing by
+ mutable payload while the digest still fences a concurrent winner. ``_row_id`` is opt-in (gateway
+ reactions); 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
messages = []
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
@@ -1664,6 +1672,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)
# 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's
diff --git a/tests/hermes_state/test_unaddressed_rewrite_identity.py b/tests/hermes_state/test_unaddressed_rewrite_identity.py
new file mode 100644
index 00000000000..e9afa46dbf1
--- /dev/null
+++ b/tests/hermes_state/test_unaddressed_rewrite_identity.py
@@ -0,0 +1,162 @@
+"""Durable logical-message identity for unaddressed live-replay rewrites (#129065).
+
+A live replay may intentionally omit the physical SQLite row id. If that dict is edited in
+place, the write path must update the logical message it came from without guessing from its
+now-mutated payload. The durable message_uid identifies the logical message and the stored-row
+snapshot remains the compare-and-swap proof for the version we actually loaded.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from agent.context_compressor import _DB_PERSISTED_MARKER
+from agent.message_metadata import DB_ROW_SNAPSHOT
+from hermes_state import SessionDB
+
+
+def db(tmp_path):
+ store = SessionDB(tmp_path / "state.db")
+ try:
+ yield store
+ finally:
+ store.close()
+
+
+def _active_rows(store, sid):
+ return [
+ dict(row)
+ for row in store._conn.execute(
+ "SELECT id, role, content, timestamp, 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):
+ sid = "mutated-replay"
+ db.create_session(sid, "desktop")
+ original = {"role": "assistant", "content": "before repair", "timestamp": 1000.0}
+ assert db.append_messages_batch(sid, [original]) == 1
+ before = _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)
+
+ # Real rewrite sites change the payload BEFORE clearing the persisted marker.
+ restored[0]["content"] = "after repair"
+ restored[0].pop(_DB_PERSISTED_MARKER, None)
+
+ assert db.append_messages_batch(sid, restored) == 0
+ after = _active_rows(db, sid)
+ assert len(after) == 1
+ assert after[0]["id"] == before[0]["id"]
+ assert after[0]["message_uid"] == before[0]["message_uid"]
+ assert after[0]["content"] == "after repair"
+
+
+def test_unaddressed_tool_call_repair_does_not_append_a_clone(db):
+ sid = "tool-repair"
+ db.create_session(sid, "desktop")
+ original = {
+ "role": "assistant",
+ "content": "calling tool",
+ "timestamp": 2000.0,
+ "tool_calls": [{
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "demo", "arguments": '{"broken":'},
+ }],
+ }
+ assert db.append_messages_batch(sid, [original]) == 1
+ before = _active_rows(db, sid)
+
+ restored = db.get_messages_as_conversation(sid, repair_alternation=True)
+ restored[0]["tool_calls"][0]["function"]["arguments"] = "{}"
+ restored[0].pop(_DB_PERSISTED_MARKER, None)
+
+ assert db.append_messages_batch(sid, restored) == 0
+ after = _active_rows(db, sid)
+ assert len(after) == 1 and after[0]["id"] == before[0]["id"]
+ calls = json.loads(after[0]["tool_calls"])
+ assert calls[0]["function"]["arguments"] == "{}"
+
+
+def test_fresh_identical_message_is_never_adopted_by_payload(db):
+ """Content and timestamps are not identity: two real occurrences may be byte-identical."""
+ 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
+ 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"]
+
+
+def test_message_uid_without_snapshot_does_not_authorize_adoption(db):
+ """Logical identity alone can span physical generations; the CAS proof is required."""
+ sid = "uid-copy"
+ db.create_session(sid, "desktop")
+ first = {"role": "assistant", "content": "generation one", "timestamp": 3500.0}
+ assert db.append_messages_batch(sid, [first]) == 1
+
+ copied_generation = {
+ "role": "assistant",
+ "content": "generation two",
+ "timestamp": 3501.0,
+ "message_uid": first["message_uid"],
+ }
+ assert DB_ROW_SNAPSHOT not in copied_generation and "_row_id" not in copied_generation
+ assert db.append_messages_batch(sid, [copied_generation]) == 1
+
+ rows = _active_rows(db, sid)
+ assert len(rows) == 2
+ assert rows[0]["message_uid"] == rows[1]["message_uid"] == first["message_uid"]
+
+
+def test_unaddressed_replay_respects_a_concurrent_winner(db):
+ sid = "concurrent-winner"
+ db.create_session(sid, "desktop")
+ original = {"role": "assistant", "content": "base", "timestamp": 4000.0}
+ db.append_messages_batch(sid, [original])
+ row_id = _active_rows(db, sid)[0]["id"]
+
+ stale = db.get_messages_as_conversation(sid, repair_alternation=True)[0]
+ assert isinstance(stale.get(DB_ROW_SNAPSHOT), str)
+
+ # Simulate another writer changing the durable payload after this replay was loaded.
+ db._conn.execute(
+ "UPDATE messages SET content = ? WHERE id = ?",
+ (db._encode_content("foreign winner"), row_id),
+ )
+ db._conn.commit()
+
+ stale["content"] = "stale local edit"
+ stale.pop(_DB_PERSISTED_MARKER, None)
+ assert db.append_messages_batch(sid, [stale]) == 0
+
+ rows = _active_rows(db, sid)
+ assert len(rows) == 1
+ assert rows[0]["id"] == row_id
+ assert rows[0]["content"] == "foreign winner"
+
+
+def test_plain_read_shape_does_not_expose_internal_cas_digest(db):
+ sid = "plain-read"
+ db.create_session(sid, "desktop")
+ db.append_message(sid, "user", "hello")
+ plain = db.get_messages_as_conversation(sid)
+ assert plain and DB_ROW_SNAPSHOT not in plain[0]