Skip to content

The agent that grows with you

fix(agent): keep the durable marker on a storage-equivalent sentinel decode (#125331)

PRATHAMESH75790d6eaf39c5
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 61bd294f252..da540ca5de9 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -695,6 +695,12 @@ def _normalize_sentinel_encoded_content(messages: List[Dict]) -> int:
decoded = _decode_sentinel_content(content)
if decoded is not content:
msg["content"] = decoded
+ # Deliberately keep any `_db_persisted` marker: this decode is representation-only.
+ # `SessionDB._encode_content(decoded)` reproduces the same `\x00json:` scalar already
+ # stored, so the durable row is not stale. Dropping the marker here makes the append-only
+ # flush treat this historical turn as new (user _row_id values are never update targets in
+ # resolve_and_repair_transcript_batch), re-appending a duplicate user turn (review: ehz0ah,
+ # #125331). The merge/prune passes drop the marker only when the durable bytes actually change.
restored += 1
return restored
diff --git a/tests/agent/test_message_sequence_repair.py b/tests/agent/test_message_sequence_repair.py
index 0ef057d1ad8..defb8fbfe9f 100644
--- a/tests/agent/test_message_sequence_repair.py
+++ b/tests/agent/test_message_sequence_repair.py
@@ -1621,3 +1621,84 @@ def test_repair_leaves_corrupted_sentinel_content_untouched():
repair_message_sequence(_bare_agent(), messages)
assert messages[0]["content"] == corrupt
+
+
+def test_repair_decode_of_durable_sentinel_row_does_not_reappend(tmp_path):
+ """ehz0ah #125331 (blocking): decoding a *durable* sentinel row is representation-only —
+ ``SessionDB._encode_content(decoded)`` reproduces the exact ``\\x00json:`` scalar already stored —
+ so the row must KEEP its ``_db_persisted`` marker. Dropping it makes the append-only flush treat
+ the historical user turn as new (user ``_row_id`` values are never update targets in
+ ``resolve_and_repair_transcript_batch``), re-appending a duplicate user turn on the durable
+ transcript. This drives the real repair + ``_persist_session`` flush and asserts the stored row
+ count and role order do not change — a regression the content-only repair tests cannot catch."""
+ import os
+ import json
+ from unittest.mock import patch
+ from hermes_state import SessionDB
+ from agent.agent_runtime_helpers import (
+ repair_message_sequence_with_cursor,
+ _JSON_CONTENT_SENTINEL,
+ )
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ parts = [
+ {"type": "text", "text": "look"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64," + "A" * 2000}},
+ ]
+ # The stored durable scalar is exactly what _encode_content(parts) produces; a resumed row re-enters
+ # the working set as this same string (e.g. after a proactive prune re-inserts history, #124102).
+ encoded = _JSON_CONTENT_SENTINEL + json.dumps(parts)
+
+ db = SessionDB(db_path=tmp_path / "t.db")
+ sid = "20260928_000000_dup"
+ db.create_session(sid, "cli", model="test/model")
+ db.append_message(session_id=sid, role="user", content=encoded)
+ db.append_message(session_id=sid, role="assistant", content="ok")
+
+ def _active_rows():
+ return db._conn.execute(
+ "SELECT role FROM messages WHERE session_id = ? AND active = 1 ORDER BY id",
+ (sid,),
+ ).fetchall()
+
+ before = [r[0] for r in _active_rows()]
+ assert before == ["user", "assistant"]
+
+ with patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}):
+ from run_agent import AIAgent
+
+ agent = AIAgent(
+ api_key="test-key",
+ base_url="https://openrouter.ai/api/v1",
+ model="test/model",
+ quiet_mode=True,
+ session_db=db,
+ session_id=sid,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ agent._session_db_created = True
+ agent._last_flushed_db_idx = 2
+
+ # Live/resumed set: both durable rows carry their persistence markers; the user row arrives as its
+ # stored sentinel scalar.
+ messages = [
+ {"role": "user", "content": encoded, _DB_PERSISTED_MARKER: True},
+ {"role": "assistant", "content": "ok", _DB_PERSISTED_MARKER: True},
+ ]
+
+ repairs = repair_message_sequence_with_cursor(agent, messages)
+
+ # Decode restored the structured content but kept the durable marker (storage-equivalent): a
+ # valid user→assistant sequence needs no alternation repair, so decode adds nothing to the count.
+ assert repairs == 0
+ assert messages[0]["content"] == parts
+ assert messages[0].get(_DB_PERSISTED_MARKER) is True
+
+ # The symptom: run the persist walk twice (turn finalize + close safety-net). The append-only flush
+ # must skip the already-durable user row — no re-INSERT, row count and role order stay put.
+ agent._persist_session(messages, conversation_history=None)
+ agent._persist_session(messages, conversation_history=None)
+
+ after = [r[0] for r in _active_rows()]
+ assert after == ["user", "assistant"], f"flush changed the durable transcript: {before} -> {after}"