Skip to content

The agent that grows with you

fix(persistence): preserve transcript row identity safely

Nagisa-300002b8c4a65510
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.py
index 294937fbc91..79e1ab370a5 100644
--- a/agent/message_sanitization.py
+++ b/agent/message_sanitization.py
@@ -23,7 +23,8 @@ logger = logging.getLogger(__name__)
_SURROGATE_RE = re.compile(r'[\ud800-\udfff]')
# Keys handled explicitly by _sanitize_messages; every OTHER key is swept generically.
-_MESSAGE_CORE_KEYS = frozenset({"content", "name", "tool_calls", "role"})
+# The durable snapshot is an immutable compare-and-swap version, not message payload.
+_MESSAGE_CORE_KEYS = frozenset({"content", "name", "tool_calls", "role", "_db_row_snapshot"})
def _sanitize_surrogates(text: str) -> str:
diff --git a/agent/session_persistence.py b/agent/session_persistence.py
index 1c5c04a5c0b..e7a356caee7 100644
--- a/agent/session_persistence.py
+++ b/agent/session_persistence.py
@@ -23,7 +23,7 @@ from agent.memory_manager import sanitize_context
from agent.tool_dispatch_helpers import _is_multimodal_tool_result, _multimodal_text_summary
from agent.trajectory import save_trajectory as _save_trajectory_to_file
-from agent.transcript_repair import sync_flushed_message_markers
+from agent.transcript_repair import _DB_ROW_SNAPSHOT, sync_flushed_message_markers
logger = logging.getLogger("run_agent") # origin module's name: log records / caplog filters unchanged
@@ -210,17 +210,23 @@ def _db_flush_row(agent, msg: Dict, is_current_turn_user: bool) -> Dict[str, Any
api_content = content
# Key order is the divert-JSONL wire order (divert_session_transcript_jsonl).
row = {
- "role": role, "content": _durable_content(content), "tool_name": msg.get("tool_name"),
+ "role": role, "content": _durable_content(content),
+ "tool_name": msg.get("tool_name") or (msg.get("name") if role == "tool" else None),
"tool_calls": msg["tool_calls"] if isinstance(msg.get("tool_calls"), list) else None,
- "tool_call_id": msg.get("tool_call_id"), "finish_reason": msg.get("finish_reason"),
+ "tool_call_id": msg.get("tool_call_id"), "effect_disposition": msg.get("effect_disposition"),
+ "token_count": msg.get("token_count"), "finish_reason": msg.get("finish_reason"),
**{k: msg.get(k) for k in _ROW_REASONING_KEYS},
"_compressed_summary": bool(msg.get(COMPRESSED_SUMMARY_METADATA_KEY)),
"timestamp": timestamp, "api_content": api_content,
"display_kind": _summary_display_kind(msg), "display_metadata": msg.get("display_metadata"),
- "platform_message_id": msg.get("platform_message_id"), # load-bearing for restart drain-window recovery dedup
+ # Load-bearing for restart drain-window recovery dedup.
+ "platform_message_id": msg.get("platform_message_id") or msg.get("message_id"),
+ "observed": bool(msg.get("observed")),
}
if isinstance(msg.get("_row_id"), int):
row["_row_id"] = msg["_row_id"]
+ if isinstance(msg.get(_DB_ROW_SNAPSHOT), dict):
+ row[_DB_ROW_SNAPSHOT] = dict(msg[_DB_ROW_SNAPSHOT])
return row
diff --git a/agent/transcript_repair.py b/agent/transcript_repair.py
index 8f0d0141ef4..aa90002a8fd 100644
--- a/agent/transcript_repair.py
+++ b/agent/transcript_repair.py
@@ -5,11 +5,35 @@ clone lookup) and sync markers after commit."""
from __future__ import annotations
import sqlite3
-from typing import Any, Callable, Dict, List
+from typing import Any, Callable, Dict, List, Mapping
from agent.context_compressor import _DB_PERSISTED_MARKER
+_DB_ROW_SNAPSHOT = "_db_row_snapshot"
+_CANONICAL_ROW = "_canonical_row"
+_REPAIR_COLUMNS = (
+ "content", "tool_call_id", "tool_calls", "tool_name", "effect_disposition", "token_count",
+ "finish_reason", "reasoning", "reasoning_content", "reasoning_details", "codex_reasoning_items",
+ "codex_message_items", "platform_message_id", "observed", "_compressed_summary", "api_content",
+ "display_kind", "display_metadata",
+)
+_SYNC_FIELDS = (
+ "role", "content", "tool_call_id", "tool_calls", "tool_name", "effect_disposition", "token_count",
+ "finish_reason", "reasoning", "reasoning_content", "reasoning_details", "codex_reasoning_items",
+ "codex_message_items", "message_id", "platform_message_id", "observed",
+ "_compressed_summary", "api_content", "display_kind", "display_metadata",
+)
+
+
+def transcript_row_snapshot(row: Mapping[str, Any]) -> Optional[Dict[str, Any]]:
+ """Serialized durable values used as the CAS version, or ``None`` for a partial SELECT."""
+ keys = set(row.keys()) if hasattr(row, "keys") else set(row)
+ if not set(_REPAIR_COLUMNS) <= keys:
+ return None
+ return {column: row[column] for column in _REPAIR_COLUMNS}
+
+
def is_content_blank(content: Any) -> bool:
"""True when decoded message content is None, whitespace-only, or has no visible text parts."""
if content is None:
@@ -27,77 +51,177 @@ def resolve_and_repair_transcript_batch(
messages: List[Dict[str, Any]],
encode_content_fn: Callable[[Any], Any],
decode_content_fn: Callable[[Any], Any],
+ serialize_message_fn: Callable[[Dict[str, Any], float], Mapping[str, Any]],
+ decode_row_fn: Callable[[Mapping[str, Any]], Dict[str, Any]],
) -> List[Dict[str, Any]]:
- """Partition a message batch within an active write transaction. A message carrying an existing
- integer ``_row_id`` targets that same-role SQLite row, or the active clone a watermark compaction made
- of it. Sanitizer rewrites update non-assistant and inactive rows in place without changing archive/rewind
- state. An active blank assistant row is filled, while an active non-blank assistant row (concurrent
- winner) has its canonical content adopted without overwrite. Returns rows that need fresh inserts."""
+ """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.
+ """
inserted_rows: List[Dict[str, Any]] = []
for msg in messages:
existing_row_id = msg.get("_row_id") if isinstance(msg, dict) else None
- target_row = None
role = msg.get("role", "unknown") if isinstance(msg, dict) else "unknown"
+ target_row = None
if isinstance(existing_row_id, int):
target_row = _active_message_row(conn, session_id, existing_row_id, role)
if target_row is None:
inserted_rows.append(msg)
continue
+
target_id = int(target_row["id"])
- decoded = decode_content_fn(target_row["content"])
msg["_row_id"] = target_id
- if int(target_row["active"] or 0) == 0 or role != "assistant":
- # Sanitizers mutate every transcript role. Preserve the addressed durable identity (or active
- # compaction clone) so rewound/compacted user and tool rows cannot be appended as duplicates.
- # Updating content alone leaves active/compacted/display identity state untouched.
- conn.execute(
- "UPDATE messages SET content = ? WHERE id = ? AND session_id = ?",
- (encode_content_fn(msg.get("content")), target_id, session_id),
- )
- elif is_content_blank(decoded):
+ serialized = serialize_message_fn(msg, float(target_row["timestamp"]))
+ expected = msg.get(_DB_ROW_SNAPSHOT)
+ has_snapshot = isinstance(expected, dict) and all(column in expected for column in _REPAIR_COLUMNS)
+ repaired = _compare_and_swap_row(conn, session_id, target_row, serialized, expected) if has_snapshot else False
+ if not has_snapshot and role == "assistant" and is_content_blank(decode_content_fn(target_row["content"])):
+ # Blank assistant rows are the pre-existing interrupted-stream repair path. Keep its narrow
+ # content-only CAS for live dicts that predate durable row snapshots.
conn.execute(
- "UPDATE messages SET content = ? "
- "WHERE id = ? AND session_id = ? AND active = 1",
- (encode_content_fn(msg.get("content")), target_id, session_id),
+ "UPDATE messages SET content = ? WHERE id = ? AND session_id = ? AND content IS ?",
+ (encode_content_fn(msg.get("content")), target_id, session_id, target_row["content"]),
)
- else:
- msg["_canonical_content"] = decoded # concurrent winner: adopt, don't overwrite
+
+ final_row = conn.execute(
+ "SELECT * FROM messages WHERE id = ? AND session_id = ?", (target_id, session_id)
+ ).fetchone()
+ msg["timestamp"] = final_row["timestamp"]
+ msg[_DB_ROW_SNAPSHOT] = transcript_row_snapshot(final_row)
+ msg[_CANONICAL_ROW] = decode_row_fn(final_row)
return inserted_rows
+def _compare_and_swap_row(
+ conn: sqlite3.Connection,
+ session_id: str,
+ target_row: Mapping[str, Any],
+ serialized: Mapping[str, Any],
+ expected: Mapping[str, Any],
+) -> bool:
+ """Rewrite one durable payload only while it still equals the live dict's last committed snapshot."""
+ old_identity = target_row["display_identity"]
+ old_peer_ids = [
+ int(row["id"])
+ for row in conn.execute(
+ "SELECT id FROM messages WHERE session_id = ? AND id != ? "
+ "AND (active = 1 OR compacted = 1) AND display_identity IS ?",
+ (session_id, target_row["id"], old_identity),
+ ).fetchall()
+ ] if old_identity is not None else []
+
+ assignments = ", ".join(f"{column} = ?" for column in _REPAIR_COLUMNS)
+ predicates = " AND ".join(f"{column} IS ?" for column in _REPAIR_COLUMNS)
+ params = [serialized[column] for column in _REPAIR_COLUMNS]
+ params += [int(target_row["id"]), session_id]
+ params += [expected[column] for column in _REPAIR_COLUMNS]
+ cur = conn.execute(
+ f"UPDATE messages SET {assignments} WHERE id = ? AND session_id = ? AND {predicates}", params,
+ )
+ if cur.rowcount != 1:
+ return False
+ _restore_display_index(conn, session_id, target_row, serialized, old_identity, old_peer_ids)
+ return True
+
+
+def _restore_display_index(
+ conn: sqlite3.Connection,
+ session_id: str,
+ target_row: Mapping[str, Any],
+ serialized: Mapping[str, Any],
+ old_identity: Any,
+ old_peer_ids: List[int],
+) -> None:
+ """Restore display identities/orders invalidated by the payload-update trigger."""
+ if old_peer_ids:
+ placeholders = ", ".join("?" for _ in old_peer_ids)
+ old_order = min(old_peer_ids)
+ conn.execute(
+ f"UPDATE messages SET display_identity = ?, display_order = ? "
+ f"WHERE session_id = ? AND id IN ({placeholders})",
+ (old_identity, old_order, session_id, *old_peer_ids),
+ )
+
+ target_id = int(target_row["id"])
+ new_identity = serialized["display_identity"]
+ visible = bool(target_row["active"] or target_row["compacted"])
+ if not visible:
+ conn.execute(
+ "UPDATE messages SET display_identity = ?, display_order = ? WHERE id = ? AND session_id = ?",
+ (new_identity, target_id, target_id, session_id),
+ )
+ return
+
+ peers = conn.execute(
+ "SELECT id, display_order FROM messages WHERE session_id = ? AND id != ? "
+ "AND (active = 1 OR compacted = 1) AND display_identity IS ?",
+ (session_id, target_id, new_identity),
+ ).fetchall()
+ new_order = min(
+ [target_id]
+ + [int(peer["display_order"] if peer["display_order"] is not None else peer["id"]) for peer in peers]
+ )
+ conn.execute(
+ "UPDATE messages SET display_identity = ?, display_order = ? WHERE id = ? AND session_id = ?",
+ (new_identity, new_order, target_id, session_id),
+ )
+ if peers:
+ conn.executemany(
+ "UPDATE messages SET display_order = ? WHERE id = ? AND session_id = ?",
+ [(new_order, int(peer["id"]), session_id) for peer in peers],
+ )
+
+
def _active_message_row(conn: sqlite3.Connection, session_id: str, row_id: int, role: str):
"""The same-role active clone for ``row_id``, or the addressed inactive row when no clone exists."""
row = conn.execute(
- "SELECT id, role, active, timestamp, content FROM messages "
- "WHERE id = ? AND session_id = ?",
- (row_id, session_id),
+ "SELECT * FROM messages WHERE id = ? AND session_id = ?", (row_id, session_id)
).fetchone()
if row is None or row["role"] != role:
return None
if int(row["active"] or 0) == 1:
return row
- # Watermark compaction soft-archived the concurrent tail and cloned it. Prefer that live identity;
- # otherwise keep the addressed inactive row so a later sanitizer pass cannot append it as new.
- clone = conn.execute(
- "SELECT id, role, active, timestamp, content FROM messages "
- "WHERE session_id = ? AND active = 1 AND role = ? "
- "AND timestamp IS ? AND id != ? "
- "ORDER BY id DESC LIMIT 1",
- (session_id, role, row["timestamp"], row["id"]),
- ).fetchone()
- return clone if clone is not None else row
+ # Watermark compaction copies the complete durable row payload and display identity byte-for-byte.
+ # Timestamp alone is not an identity: externally supplied event timestamps may collide across unrelated
+ # messages. Legacy rows without an indexed identity cannot be resolved safely, so retain the addressed row.
+ if row["display_identity"] is None:
+ return row
+ payload_predicates = " AND ".join(f"{column} IS ?" for column in _REPAIR_COLUMNS)
+ clones = conn.execute(
+ "SELECT * FROM messages WHERE session_id = ? AND active = 1 AND role = ? "
+ "AND display_identity IS ? AND timestamp IS ? AND id != ? AND "
+ f"{payload_predicates} ORDER BY id DESC LIMIT 2",
+ (
+ session_id,
+ role,
+ row["display_identity"],
+ row["timestamp"],
+ row["id"],
+ *(row[column] for column in _REPAIR_COLUMNS),
+ ),
+ ).fetchall()
+ return clones[0] if len(clones) == 1 else row
def sync_flushed_message_markers(batch_msgs: List[Dict[str, Any]], batch_rows: List[Dict[str, Any]]) -> None:
- """Stamp _DB_PERSISTED_MARKER and sync canonical durable fields onto live dicts after commit."""
+ """Stamp persistence markers and sync canonical durable fields onto live dicts after commit."""
for written, row in zip(batch_msgs, batch_rows):
written[_DB_PERSISTED_MARKER] = True
if isinstance(row.get("_row_id"), int):
written["_row_id"] = row["_row_id"]
if isinstance(row.get("timestamp"), (int, float)):
written["timestamp"] = row["timestamp"]
- if "_canonical_content" in row:
- written["content"] = row["_canonical_content"]
+ if isinstance(row.get(_DB_ROW_SNAPSHOT), dict):
+ written[_DB_ROW_SNAPSHOT] = dict(row[_DB_ROW_SNAPSHOT])
+ canonical = row.get(_CANONICAL_ROW)
+ if isinstance(canonical, dict):
+ for key in _SYNC_FIELDS:
+ if key in canonical and canonical[key] is not None:
+ written[key] = canonical[key]
+ elif key not in ("role", "content"):
+ written.pop(key, None)
# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index 0bf7a6844a5..22dd95337dd 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -32,9 +32,10 @@ _INSERT_MESSAGE_SQL = """INSERT INTO messages (session_id, role, content, tool_c
# Every column this module knows how to read: the ones it writes plus the three SQLite/compaction
# owns. `_row_to_message_dict` drops raw bytes ONLY outside this set — a schema column keeps its
# key (and its typed decoder) even when a row holds a BLOB, so no reader ever loses msg["content"].
-_MESSAGE_SCHEMA_KEYS = frozenset(
+_MESSAGE_WRITE_COLUMNS = tuple(
re.findall(r"\w+", _INSERT_MESSAGE_SQL.split("(", 1)[1].split(")", 1)[0])
-) | {"id", "compacted", "display_order"}
+)
+_MESSAGE_SCHEMA_KEYS = frozenset(_MESSAGE_WRITE_COLUMNS) | {"id", "compacted", "display_order"}
_BUMP_GENERATION_SQL = """
INSERT INTO conversation_generations (source, session_key, generation)
VALUES (?, ?, 1)
@@ -285,6 +286,62 @@ class SessionMessagesMixin:
_str_or_none(msg.get("api_content")), _str_or_none(msg.get("display_kind")),
display_metadata, self._display_identity(self._display_dedupe_key(identity_row)))
+ def _serialized_message_row(
+ self, session_id: str, msg: Dict[str, Any], message_timestamp: float
+ ) -> Dict[str, Any]:
+ """Serialize one live message with the exact durable shape used by INSERT."""
+ role = msg.get("role", "unknown")
+ params = self._message_row_params(
+ session_id,
+ role,
+ msg,
+ _parse_tool_calls(msg.get("tool_calls")),
+ message_timestamp,
+ keep_reasoning=role == "assistant",
+ )
+ return dict(zip(_MESSAGE_WRITE_COLUMNS, params))
+
+ def _decoded_repair_row(self, row) -> Dict[str, Any]:
+ """Decode one durable row without replay dedupe, alternation repair, or content stripping."""
+ msg: Dict[str, Any] = {
+ "role": row["role"],
+ "content": self._decode_content(row["content"]),
+ }
+ for column in ("tool_call_id", "tool_name", "effect_disposition", "token_count", "finish_reason"):
+ if row[column] is not None:
+ msg[column] = row[column]
+ if row["tool_calls"]:
+ msg["tool_calls"] = _json_or(
+ row["tool_calls"], [], "Failed to deserialize repaired tool_calls, falling back to []"
+ )
+ if row["platform_message_id"] is not None:
+ msg["message_id"] = row["platform_message_id"]
+ msg["platform_message_id"] = row["platform_message_id"]
+ if row["role"] == "tool" and row["tool_name"] is not None:
+ msg["name"] = row["tool_name"]
+ if row["observed"]:
+ msg["observed"] = True
+ if row["_compressed_summary"]:
+ msg["_compressed_summary"] = True
+ if row["api_content"] is not None:
+ msg["api_content"] = row["api_content"]
+ if row["display_kind"] is not None:
+ msg["display_kind"] = row["display_kind"]
+ if row["display_metadata"] is not None:
+ metadata = self._decode_display_metadata(row["display_metadata"])
+ if metadata is not None:
+ msg["display_metadata"] = metadata
+ if row["role"] == "assistant":
+ for column in ("reasoning", "reasoning_content"):
+ if row[column] is not None:
+ msg[column] = row[column]
+ for column in ("reasoning_details", "codex_reasoning_items", "codex_message_items"):
+ if row[column]:
+ msg[column] = _json_or(
+ row[column], None, f"Failed to deserialize repaired {column}, falling back to None"
+ )
+ return msg
+
@staticmethod
def _bump_session_counters(conn, session_id: str, inserted: int, tool_calls: int, *, unit: bool) -> None:
"""Bump sessions.* counters after an insert; *unit* bakes the ``+ 1`` literal into the SQL."""
@@ -378,8 +435,17 @@ class SessionMessagesMixin:
self._check_transcript_write_guards(conn, session_id, compression_lock_holder,
turn_lease_holder=turn_lease_holder, turn_lease_ttl_seconds=turn_lease_ttl_seconds)
from agent.transcript_repair import resolve_and_repair_transcript_batch
- inserted_rows = resolve_and_repair_transcript_batch(conn, session_id, messages,
- encode_content_fn=self._encode_content, decode_content_fn=self._decode_content)
+ inserted_rows = resolve_and_repair_transcript_batch(
+ conn,
+ session_id,
+ messages,
+ encode_content_fn=self._encode_content,
+ decode_content_fn=self._decode_content,
+ serialize_message_fn=lambda msg, timestamp: self._serialized_message_row(
+ session_id, msg, timestamp
+ ),
+ decode_row_fn=self._decoded_repair_row,
+ )
inserted, tool_calls_total = self._insert_message_rows(conn, session_id, inserted_rows)
self._bump_session_counters(conn, session_id, inserted, tool_calls_total, unit=False)
return inserted
@@ -591,14 +657,16 @@ class SessionMessagesMixin:
Never touches sessions.* counters (callers reconcile differently); reasoning kept for assistant rows.
A caller that re-archives some rows afterwards passes ``prune_checkpoints=False`` and prunes once they
are archived again (:meth:`_prune_shadowed_checkpoints`)."""
+ from agent.transcript_repair import _DB_ROW_SNAPSHOT, transcript_row_snapshot
+
now_ts = time.time()
inserted = tool_calls_total = 0
for msg in messages:
role = msg.get("role", "unknown")
tool_calls = _parse_tool_calls(msg.get("tool_calls"))
message_timestamp = _coerce_timestamp(msg.get("timestamp"), now_ts)
- cur = conn.execute(_INSERT_MESSAGE_SQL, self._message_row_params(
- session_id, role, msg, tool_calls, message_timestamp, keep_reasoning=role == "assistant"))
+ serialized = self._serialized_message_row(session_id, msg, message_timestamp)
+ cur = conn.execute(_INSERT_MESSAGE_SQL, tuple(serialized[column] for column in _MESSAGE_WRITE_COLUMNS))
# Keep the caller's live row aligned with the durable identity. Rows created without an explicit
# timestamp (notably mid-turn steers) may be carried through several compaction generations; if
# the generated timestamp exists only in SQLite, every copy receives a new identity and renders
@@ -606,6 +674,7 @@ class SessionMessagesMixin:
msg["timestamp"] = message_timestamp
if cur.lastrowid is not None:
msg["_row_id"] = cur.lastrowid
+ msg[_DB_ROW_SNAPSHOT] = transcript_row_snapshot(serialized)
inserted += 1
tool_calls_total += _tool_calls_count(tool_calls)
now_ts = max(now_ts, message_timestamp) + 1e-6
@@ -1430,7 +1499,11 @@ class SessionMessagesMixin:
# durable-snapshot adoption, incremental persists with no history arg) would otherwise re-append
# the ENTIRE transcript on flush.
if include_row_ids and row["id"] is not None:
+ from agent.transcript_repair import _DB_ROW_SNAPSHOT, transcript_row_snapshot
+
msg["_row_id"] = row["id"]
+ if (snapshot := transcript_row_snapshot(row)) is not None:
+ msg[_DB_ROW_SNAPSHOT] = snapshot
msg.update((col, row[col]) for col in ("api_content", "display_kind") if row[col])
if row["display_metadata"] and (decoded := self._decode_display_metadata(row["display_metadata"])) is not None:
msg["display_metadata"] = decoded
diff --git a/tests/agent/test_tool_call_incremental_persistence.py b/tests/agent/test_tool_call_incremental_persistence.py
index 5c838fe9fd0..eceb237ce06 100644
--- a/tests/agent/test_tool_call_incremental_persistence.py
+++ b/tests/agent/test_tool_call_incremental_persistence.py
@@ -995,6 +995,98 @@ def test_flush_atomic_mixed_repair_and_append_rollback_on_failure(tmp_path, monk
assert (durable[-1].get("content") or "") == ""
+def test_flush_stale_active_user_adopts_concurrent_winner(tmp_path):
+ """A stale non-assistant live dict must not replace a newer durable row."""
+ agent = _make_agent()
+ db_path = tmp_path / "state.db"
+ session_id = "sess-stale-active-user"
+ db = _attach_real_session_db(agent, db_path, session_id)
+ messages = [{"role": "user", "content": "initial"}]
+ agent._flush_messages_to_session_db(messages)
+ row_id = messages[0]["_row_id"]
+
+ db._execute_write(
+ lambda conn: conn.execute(
+ "UPDATE messages SET content = ? WHERE id = ?",
+ (db._encode_content("newer durable content"), row_id),
+ )
+ )
+ messages[0]["content"] = "stale sanitizer copy"
+ messages[0].pop("_db_persisted", None)
+ agent._db_flush_scan_prefix = None
+
+ assert agent._flush_messages_to_session_db(messages) is True
+
+ row = next(item for item in db.get_messages(session_id, include_inactive=True) if item["id"] == row_id)
+ assert row["content"] == "newer durable content"
+ assert messages[0]["content"] == "newer durable content"
+ assert messages[0]["_row_id"] == row_id
+ assert messages[0]["_db_persisted"] is True
+
+
+def test_flush_inactive_row_does_not_select_same_timestamp_collision(tmp_path):
+ """An unrelated active row with the same role/timestamp is not a compaction clone."""
+ agent = _make_agent()
+ db_path = tmp_path / "state.db"
+ session_id = "sess-inactive-timestamp-collision"
+ db = _attach_real_session_db(agent, db_path, session_id)
+ messages = [{"role": "user", "content": "original", "timestamp": 1_700_000_000.0}]
+ agent._flush_messages_to_session_db(messages)
+ original_id = messages[0]["_row_id"]
+
+ db._execute_write(
+ lambda conn: conn.execute(
+ "UPDATE messages SET active = 0, compacted = 0 WHERE id = ?",
+ (original_id,),
+ )
+ )
+ collision_id = db.append_message(
+ session_id, "user", "unrelated active row", timestamp=messages[0]["timestamp"]
+ )
+ messages[0]["content"] = "repaired original"
+ messages[0].pop("_db_persisted", None)
+ agent._db_flush_scan_prefix = None
+
+ assert agent._flush_messages_to_session_db(messages) is True
+
+ rows = {row["id"]: row for row in db.get_messages(session_id, include_inactive=True)}
+ assert rows[original_id]["content"] == "repaired original"
+ assert rows[original_id]["active"] in (0, False)
+ assert rows[collision_id]["content"] == "unrelated active row"
+ assert rows[collision_id]["active"] in (1, True)
+ assert messages[0]["_row_id"] == original_id
+
+
+def test_flush_ascii_repair_persists_structured_tool_fields(tmp_path):
+ """Repair writes every durable field changed by the sanitizer before marking the dict durable."""
+ from agent.message_sanitization import _sanitize_messages_non_ascii
+
+ agent = _make_agent()
+ db_path = tmp_path / "state.db"
+ session_id = "sess-structured-ascii-repair"
+ db = _attach_real_session_db(agent, db_path, session_id)
+ messages = [
+ {
+ "role": "tool",
+ "content": "résult",
+ "tool_call_id": "call-café",
+ "name": "términal",
+ }
+ ]
+ agent._flush_messages_to_session_db(messages)
+ row_id = messages[0]["_row_id"]
+
+ assert _sanitize_messages_non_ascii(messages) is True
+ agent._db_flush_scan_prefix = None
+ assert agent._flush_messages_to_session_db(messages) is True
+
+ row = next(item for item in db.get_messages(session_id, include_inactive=True) if item["id"] == row_id)
+ assert row["content"] == "rsult"
+ assert row["tool_call_id"] == "call-caf"
+ assert row["tool_name"] == "trminal"
+ assert messages[0]["_db_persisted"] is True
+
+
def test_flush_concurrent_nonblank_winner_adopts_canonical_content(tmp_path):
"""A concurrent non-blank winner must be adopted without overwrite and synced to live dict."""
agent = _make_agent()