Skip to content

The agent that grows with you

fix(agent): pop _db_persisted on in-place mutations of stamped live dicts

beardtheliona48b4c7d25d0
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 969c236bfc7..38311a2c963 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -199,6 +199,9 @@ def _prepend_corruption_marker(tool_msg: dict, marker: str) -> None:
except TypeError:
existing = str(existing)
tool_msg["content"] = f"{marker}\n{existing}" if existing else marker
+ # The tool result was rewritten in place; a stamped dict's persisted row is now stale.
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+ tool_msg.pop(_DB_PERSISTED_MARKER, None)
def _find_tool_result(messages: list, start: int, tool_call: dict) -> Optional[dict]:
@@ -240,6 +243,7 @@ def sanitize_tool_call_arguments(
log = logger or logging.getLogger(__name__)
if not isinstance(messages, list):
return 0
+ from agent.context_compressor import _DB_PERSISTED_MARKER
repaired = 0
marker = _ra().AIAgent._TOOL_CALL_ARGUMENTS_CORRUPTION_MARKER
message_index = _cursor_skip_prefix(messages, cursor)
@@ -257,6 +261,7 @@ def sanitize_tool_call_arguments(
arguments = function.get("arguments")
if arguments is None or (isinstance(arguments, str) and not arguments.strip()):
function["arguments"] = "{}"
+ msg.pop(_DB_PERSISTED_MARKER, None)
continue
if not isinstance(arguments, str):
continue
@@ -278,6 +283,9 @@ def sanitize_tool_call_arguments(
function_name, arguments[:_FULL_ARGS_LOG_BOUND],
)
function["arguments"] = "{}"
+ # The persisted row for a stamped dict still holds the corrupted args; pop the
+ # marker so the flush rewrites it (the repaired args are what the wire saw).
+ msg.pop(_DB_PERSISTED_MARKER, None)
existing_tool_msg = _find_tool_result(messages, message_index + 1, tool_call)
if existing_tool_msg is None:
messages.insert(
@@ -371,10 +379,14 @@ def _is_codex_interim(m: Dict) -> bool:
def _merge_assistant_into(prev: Dict, msg: Dict) -> None:
"""Fold a consecutive assistant ``msg`` into ``prev`` (union tool_calls, concat text)."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
prev_calls = list(prev.get("tool_calls") or [])
new_calls = list(msg.get("tool_calls") or [])
+ calls_changed = False
if new_calls:
prev["tool_calls"] = prev_calls + new_calls
+ calls_changed = True
elif prev_calls:
prev["tool_calls"] = prev_calls
else:
@@ -389,6 +401,7 @@ def _merge_assistant_into(prev: Dict, msg: Dict) -> None:
# resume, subagents, cron) and is replayed on the next turn — which is how #58755 kept reproducing
# after the chokepoint fix (#77921). Popping is non-destructive: an empty array carries no
# information.
+ calls_changed = "tool_calls" in prev
prev.pop("tool_calls", None)
# Concatenate plain-text content only; leave multimodal (list) content alone.
prev_content = prev.get("content")
@@ -406,8 +419,10 @@ def _merge_assistant_into(prev: Dict, msg: Dict) -> None:
content_rewritten = new_content != prev_content
# Carry reasoning_content from the later turn only if the earlier lacks it (strict thinking
# providers need one on the merged tool-call turn).
+ reasoning_carried = False
if not prev.get("reasoning_content") and msg.get("reasoning_content"):
prev["reasoning_content"] = msg["reasoning_content"]
+ reasoning_carried = True
# A stale ``api_content`` sidecar overrides ``content`` at API-build time and would replay
# pre-merge bytes; drop it only when content actually changed.
# ``prev`` may carry an ``api_content`` sidecar (the exact bytes previously sent to the API, e.g. a
@@ -424,6 +439,11 @@ def _merge_assistant_into(prev: Dict, msg: Dict) -> None:
# invariant for no reason (wz-heng, #78063 review).
if content_rewritten:
drop_stale_api_content(prev)
+ # The persist marker asserts the whole row is durable (content, tool_calls, reasoning sidecar), so
+ # any merged field stales it; pop it or the flush scan identity-skips the merged dict and the DB
+ # keeps the pre-merge row. The caller recomputes the flush cursor for the surviving sequence.
+ if content_rewritten or calls_changed or reasoning_carried:
+ prev.pop(_DB_PERSISTED_MARKER, None)
def _merge_consecutive_assistants(messages: List[Dict]) -> Tuple[List[Dict], int]:
@@ -494,6 +514,8 @@ def _prune_unanswered_tool_calls(messages: List[Dict]) -> Tuple[List[Dict], int]
"""Pass 2: prune tool_calls not answered in the IMMEDIATELY following tool run (a displaced
result masks the per-call stub pass and strict providers 400). Payload-empty turns are
dropped; codex interims exempt."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
repairs = 0
pruned: List[Dict] = []
for i, msg in enumerate(messages):
@@ -520,13 +542,16 @@ def _prune_unanswered_tool_calls(messages: List[Dict]) -> Tuple[List[Dict], int]
msg["tool_calls"] = kept_calls
else:
msg.pop("tool_calls", None)
+ # tool_calls is part of the persisted row; rewriting it on a stamped dict stales the
+ # marker, so pop it or the flush scan skips the dict and the DB keeps the old calls.
+ msg.pop(_DB_PERSISTED_MARKER, None)
pruned.append(msg)
return pruned, repairs
def _merge_consecutive_users(messages: List[Dict]) -> Tuple[List[Dict], int]:
"""Pass 3: merge consecutive plain-text user messages (no user input lost)."""
- from agent.context_compressor import split_user_originated_turn
+ from agent.context_compressor import _DB_PERSISTED_MARKER, split_user_originated_turn
repairs = 0
merged: List[Dict] = []
@@ -545,11 +570,17 @@ def _merge_consecutive_users(messages: List[Dict]) -> Tuple[List[Dict], int]:
and isinstance(prev.get("content", ""), str) and isinstance(msg.get("content", ""), str)
):
prev_content, new_content = prev.get("content", ""), msg.get("content", "")
- prev["content"] = (
+ merged_content = (
(prev_content + "\n\n" + new_content) if prev_content and new_content else (prev_content or new_content)
)
+ had_api_sidecar = "api_content" in prev
+ prev["content"] = merged_content
# Merged content invalidates the api_content sidecar; drop it so replay cannot use stale bytes.
drop_stale_api_content(prev)
+ # Pop the persist marker only when the durable row actually changed: a merge that
+ # reproduces the persisted bytes (e.g. an empty incoming turn) keeps its stamp.
+ if merged_content != prev_content or had_api_sidecar:
+ prev.pop(_DB_PERSISTED_MARKER, None)
repairs += 1
continue
merged.append(msg)
@@ -587,14 +618,25 @@ def repair_message_sequence_with_cursor(agent, messages: List[Dict]) -> int:
"""Run :func:`repair_message_sequence` and keep ``_last_flushed_db_idx`` consistent. Repair
shrinks the list in place; counting identity-preserved survivors of the flushed prefix gives
the exact new cursor, whereas a ``min()`` clamp would skip unflushed rows (used only without a snapshot)."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
flush_cursor = getattr(agent, "_last_flushed_db_idx", None)
flushed_ids = {id(m) for m in messages[:flush_cursor]} if isinstance(flush_cursor, int) and flush_cursor > 0 else None
+ stamped_ids = {id(m) for m in messages if isinstance(m, dict) and m.get(_DB_PERSISTED_MARKER)}
repairs = repair_message_sequence(agent, messages)
- if repairs > 0 and hasattr(agent, "_last_flushed_db_idx"):
- if flushed_ids is not None:
- agent._last_flushed_db_idx = sum(1 for m in messages if id(m) in flushed_ids)
- else:
- agent._last_flushed_db_idx = min(agent._last_flushed_db_idx, len(messages))
+ if repairs > 0:
+ # A stamped survivor that lost its marker was mutated in place by a merge/prune pass; the
+ # bounded flush scan would skip past it inside the identity-matched prefix, so force a
+ # full re-scan (same contract as the compressor's _flush_scan_cursor_invalidated).
+ if stamped_ids and any(
+ id(m) in stamped_ids and not m.get(_DB_PERSISTED_MARKER) for m in messages
+ ):
+ agent._db_flush_scan_prefix = None
+ if hasattr(agent, "_last_flushed_db_idx"):
+ if flushed_ids is not None:
+ agent._last_flushed_db_idx = sum(1 for m in messages if id(m) in flushed_ids)
+ else:
+ agent._last_flushed_db_idx = min(agent._last_flushed_db_idx, len(messages))
return repairs
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.py
index 5fe2a55e4e8..49b90adce91 100644
--- a/agent/message_sanitization.py
+++ b/agent/message_sanitization.py
@@ -82,10 +82,13 @@ def _sanitize_messages(messages: list, fix: Callable[[str], str], *, deep: bool)
"""Apply ``fix`` to the string fields of every message dict in-place (content / part text,
name, tool_call arguments, non-core top-level str fields). ``deep=True`` adds tool_call ids,
function names, and NESTED non-core fields (``reasoning_details`` from byte-level models)."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
found = False
for msg in messages:
if not isinstance(msg, dict):
continue
+ msg_found = False
content = msg.get("content")
parts = [(p, "text") for p in content if isinstance(p, dict)] if isinstance(content, list) else None
fields = parts if parts is not None else [(msg, "content")]
@@ -96,12 +99,17 @@ def _sanitize_messages(messages: list, fix: Callable[[str], str], *, deep: bool)
fields += [(tc, "id")] if deep and isinstance(tc, dict) else []
fields += ([(fn, "name")] if deep else []) + [(fn, "arguments")] if isinstance(fn, dict) else []
for container, key in fields:
- found |= _fix_str_field(container, key, fix)
+ msg_found |= _fix_str_field(container, key, fix)
for key, value in [kv for kv in msg.items() if kv[0] not in _MESSAGE_CORE_KEYS]:
if isinstance(value, str):
- found |= _fix_str_field(msg, key, fix)
+ msg_found |= _fix_str_field(msg, key, fix)
elif deep and isinstance(value, (dict, list)):
- found |= _sanitize_structure(value, fix)
+ msg_found |= _sanitize_structure(value, fix)
+ if msg_found:
+ # In-place repair of a live dict stales its persisted row; pop the marker so the
+ # flush rewrites it (no-op on api_messages wire copies).
+ msg.pop(_DB_PERSISTED_MARKER, None)
+ found = True
return found
@@ -320,6 +328,7 @@ def _strip_images_from_messages(messages: list) -> bool:
orphans the paired ``tool_call_id`` → HTTP 400); other now-empty messages are dropped.
Rewritten messages lose their ``api_content`` sidecar (it carries the removed images).
"""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
from agent.turn_context import drop_stale_api_content
found = False
@@ -333,8 +342,11 @@ def _strip_images_from_messages(messages: list) -> bool:
found = True
if new_parts:
msg["content"] = new_parts
+ # Rewriting a stamped live dict stales its persisted row; pop the marker.
+ msg.pop(_DB_PERSISTED_MARKER, None)
elif msg.get("role") == "tool" or msg.get("tool_calls"):
msg["content"] = "[image content removed — server does not support images]"
+ msg.pop(_DB_PERSISTED_MARKER, None)
else:
to_delete.append(i)
drop_stale_api_content(msg)
diff --git a/agent/micro_compaction.py b/agent/micro_compaction.py
index a8f17772ea6..34ff76340a4 100644
--- a/agent/micro_compaction.py
+++ b/agent/micro_compaction.py
@@ -395,8 +395,7 @@ class MicroCompactionMixin:
cc = _cc()
return f"{cc.SUMMARY_PREFIX}\n\n{cc.HISTORICAL_TASK_HEADING}\n{summary_text.strip()}\n\n{cc._SUMMARY_END_MARKER}"
- @staticmethod
- def _merge_adjacent_user_turns(result: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ def _merge_adjacent_user_turns(self, result: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Merge consecutive plain-text real user turns left by a supersede. Same ``\\n\\n`` join as
``repair_message_sequence`` pass 2, done here so the marker and cursor are never collateral
damage of the downstream repair. Lists untouched."""
@@ -414,6 +413,12 @@ class MicroCompactionMixin:
if _plain_user(msg) and _plain_user(prev):
prev["content"] = "\n\n".join(c for c in (prev["content"], msg["content"]) if c)
drop_stale_api_content(prev) # merged content invalidates the api_content sidecar
+ # The merge rewrites a live dict that may carry _db_persisted: pop the stamp
+ # and flag the finalizer to invalidate the bounded flush-scan cursor, or the
+ # merged text is identity-skipped and never reaches state.db. Same contract
+ # as the defrag rewrite site above.
+ prev.pop(_cc()._DB_PERSISTED_MARKER, None)
+ self._flush_scan_cursor_invalidated = True
else:
merged.append(msg)
return merged
diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.py
index 5548dffbcc0..f549d6233de 100644
--- a/agent/turn_iteration_prep.py
+++ b/agent/turn_iteration_prep.py
@@ -158,6 +158,9 @@ def prepare_iteration(
messages, logger=request_logger, session_id=agent.session_id, cursor=_sanitize_cursor
)
if repaired_tool_calls > 0:
+ # In-place arg repair may have popped _DB_PERSISTED_MARKER off stamped live dicts;
+ # force a full flush scan so the repaired rows are rewritten.
+ agent._db_flush_scan_prefix = None
request_logger.info(
"Sanitized %s corrupted tool_call arguments before request (session=%s)",
repaired_tool_calls,
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 32324ecd792..2f861765407 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -125,6 +125,10 @@ def _recover_unicode_encode_error(
# Gate the retry on the error type, not on whether anything was found — a new
# transformed field could slip through.
if _surrogates_found or _is_surrogate_error:
+ if _surrogates_found:
+ # In-place rewrites may have popped _DB_PERSISTED_MARKER off stamped live dicts;
+ # force a full flush scan so the repaired rows are rewritten.
+ agent._db_flush_scan_prefix = None
agent._unicode_sanitization_passes += 1
agent._buffer_vprint(
"⚠️ Stripped invalid surrogate characters from messages. Retrying..."
@@ -139,6 +143,8 @@ def _recover_unicode_encode_error(
# Strip all non-ASCII from messages/tool schemas and retry; api_kwargs too so a
# non-ASCII transformed field doesn't survive via _build_api_kwargs cache paths.
_messages_sanitized = _sanitize_messages_non_ascii(messages)
+ if _messages_sanitized:
+ agent._db_flush_scan_prefix = None
if isinstance(api_messages, list):
_sanitize_messages_non_ascii(api_messages)
if isinstance(api_kwargs, dict):
@@ -227,6 +233,8 @@ def recover_before_classification(
if getattr(agent, "_vision_supported", True) and _looks_like_image_content_rejection(_err_body) and _status_ok:
agent._vision_supported = False
_imgs_removed = _strip_images_from_messages(messages)
+ if _imgs_removed:
+ agent._db_flush_scan_prefix = None
if isinstance(api_messages, list):
_strip_images_from_messages(api_messages)
_vlines(
diff --git a/tests/agent/test_message_sequence_repair.py b/tests/agent/test_message_sequence_repair.py
index 32a0ef845a4..9fa97ba8ada 100644
--- a/tests/agent/test_message_sequence_repair.py
+++ b/tests/agent/test_message_sequence_repair.py
@@ -1494,3 +1494,172 @@ def test_sanitize_drops_bridged_result_whose_call_frame_was_pruned():
]
out = sanitize_api_messages(list(messages))
assert [m.get("role") for m in out] == ["user"]
+
+
+# ── persist-marker contract: in-place mutations of stamped live dicts ──────
+#
+# ``_DB_PERSISTED_MARKER`` asserts the whole durable row (content, tool_calls,
+# reasoning sidecars) is already in session.db. Repair passes that mutate a
+# stamped survivor in place must pop it, or the flush scan identity-skips the
+# dict forever and the DB keeps the pre-repair row (silent live/DB divergence
+# on resume) — the same contract the micro-compaction defrag/merge sites honor.
+
+from agent.context_compressor import _DB_PERSISTED_MARKER
+
+
+def test_repair_user_merge_pops_persist_marker_on_stamped_survivor():
+ """Two adjacent stamped user rows (an interrupted turn's flushed prompt plus
+ the next turn's prompt) merge in place; the survivor must lose its marker so
+ the merged text reaches session.db instead of the pre-merge row."""
+ agent = _bare_agent()
+ stamped = {"role": "user", "content": "first", _DB_PERSISTED_MARKER: True}
+ messages = [stamped, {"role": "user", "content": "second"}]
+
+ repairs = AIAgent._repair_message_sequence(agent, messages)
+
+ assert repairs == 1
+ assert len(messages) == 1
+ assert messages[0]["content"] == "first\n\nsecond"
+ assert _DB_PERSISTED_MARKER not in messages[0]
+
+
+def test_repair_user_merge_keeps_marker_when_row_unchanged():
+ """Negative control: merging an empty later turn reproduces the persisted
+ bytes, so the stamp stays and no redundant row is written."""
+ agent = _bare_agent()
+ stamped = {"role": "user", "content": "first", _DB_PERSISTED_MARKER: True}
+ messages = [stamped, {"role": "user", "content": ""}]
+
+ repairs = AIAgent._repair_message_sequence(agent, messages)
+
+ assert repairs == 1
+ assert messages[0]["content"] == "first"
+ assert messages[0][_DB_PERSISTED_MARKER] is True
+
+
+def test_repair_assistant_merge_pops_persist_marker_on_content_rewrite():
+ agent = _bare_agent()
+ stamped = {"role": "assistant", "content": "first reply", _DB_PERSISTED_MARKER: True}
+ messages = [
+ {"role": "user", "content": "Q1"},
+ stamped,
+ {"role": "assistant", "content": "second reply"},
+ ]
+
+ repairs = AIAgent._repair_message_sequence(agent, messages)
+
+ assert repairs == 1
+ assert messages[1]["content"] == "first reply\nsecond reply"
+ assert _DB_PERSISTED_MARKER not in messages[1]
+
+
+def test_repair_assistant_merge_pops_persist_marker_on_tool_calls_union():
+ """The marker asserts the whole row, not just content: a merge that only
+ unions tool_calls still stales the persisted row and must pop it."""
+ agent = _bare_agent()
+ stamped = {
+ "role": "assistant", "content": "answer",
+ "tool_calls": [{"id": "t1", "type": "function",
+ "function": {"name": "f", "arguments": "{}"}}],
+ _DB_PERSISTED_MARKER: True,
+ }
+ messages = [
+ {"role": "user", "content": "Q1"},
+ stamped,
+ {"role": "assistant", "content": None,
+ "tool_calls": [{"id": "t2", "type": "function",
+ "function": {"name": "g", "arguments": "{}"}}]},
+ # Results answer both calls so pass 2 leaves the union intact: the
+ # marker pop is attributable to the merge, not the prune pass.
+ {"role": "tool", "tool_call_id": "t1", "content": "out1"},
+ {"role": "tool", "tool_call_id": "t2", "content": "out2"},
+ {"role": "user", "content": "next"},
+ ]
+
+ repairs = AIAgent._repair_message_sequence(agent, messages)
+
+ assert repairs == 1
+ assert [tc["id"] for tc in messages[1]["tool_calls"]] == ["t1", "t2"]
+ assert messages[1]["content"] == "answer"
+ assert _DB_PERSISTED_MARKER not in messages[1]
+
+
+def test_repair_assistant_merge_keeps_marker_when_nothing_changed():
+ """Negative control: a merge that changes no persisted field keeps the
+ stamp (later turn empty; union reproduces the same tool_calls value)."""
+ agent = _bare_agent()
+ stamped = {
+ "role": "assistant", "content": "answer",
+ _DB_PERSISTED_MARKER: True,
+ }
+ messages = [
+ {"role": "user", "content": "Q1"},
+ stamped,
+ {"role": "assistant", "content": ""},
+ ]
+
+ AIAgent._repair_message_sequence(agent, messages)
+
+ assert messages[1][_DB_PERSISTED_MARKER] is True
+
+
+def test_repair_prune_unanswered_tool_calls_pops_persist_marker():
+ """Pass 2 rewrites ``msg["tool_calls"]`` in place on a stamped assistant
+ row; the marker must go or the DB keeps the unpruned call list."""
+ agent = _bare_agent()
+ stamped = {
+ "role": "assistant", "content": "calling tools",
+ "tool_calls": [
+ {"id": "t1", "type": "function", "function": {"name": "f", "arguments": "{}"}},
+ {"id": "t2", "type": "function", "function": {"name": "g", "arguments": "{}"}},
+ ],
+ _DB_PERSISTED_MARKER: True,
+ }
+ messages = [
+ {"role": "user", "content": "Q1"},
+ stamped,
+ {"role": "tool", "tool_call_id": "t1", "content": "out1"},
+ {"role": "user", "content": "next"},
+ ]
+
+ repairs = AIAgent._repair_message_sequence(agent, messages)
+
+ assert repairs >= 1
+ surviving = next(m for m in messages if m is stamped)
+ assert [tc["id"] for tc in surviving["tool_calls"]] == ["t1"]
+ assert _DB_PERSISTED_MARKER not in surviving
+
+
+def test_repair_cursor_invalidates_scan_prefix_when_stamped_dict_dirtied():
+ """``repair_message_sequence_with_cursor`` must clear the bounded flush-scan
+ snapshot when a repair popped a marker inside it, per the marker contract."""
+ agent = _bare_agent()
+ stamped = {"role": "user", "content": "first", _DB_PERSISTED_MARKER: True}
+ messages = [stamped, {"role": "user", "content": "second"}]
+ agent._last_flushed_db_idx = 2
+ agent._db_flush_scan_prefix = messages[:]
+
+ repairs = repair_message_sequence_with_cursor(agent, messages)
+
+ assert repairs == 1
+ assert _DB_PERSISTED_MARKER not in messages[0]
+ assert agent._db_flush_scan_prefix is None
+
+
+def test_repair_cursor_keeps_scan_prefix_when_no_stamp_dirtied():
+ """Repairs on unstamped dicts must not pay a full re-scan: the prefix
+ snapshot stays valid when no stamped survivor lost its marker."""
+ agent = _bare_agent()
+ messages = [
+ {"role": "user", "content": "first", _DB_PERSISTED_MARKER: True},
+ {"role": "assistant", "content": "a1"},
+ {"role": "assistant", "content": "a2"},
+ ]
+ agent._last_flushed_db_idx = 1
+ prefix = messages[:]
+ agent._db_flush_scan_prefix = prefix
+
+ repairs = repair_message_sequence_with_cursor(agent, messages)
+
+ assert repairs == 1
+ assert agent._db_flush_scan_prefix is prefix
diff --git a/tests/agent/test_micro_compaction.py b/tests/agent/test_micro_compaction.py
index 86ed0ae1cb4..547d686e5ac 100644
--- a/tests/agent/test_micro_compaction.py
+++ b/tests/agent/test_micro_compaction.py
@@ -823,3 +823,63 @@ class TestDefragFlushCursorInvalidation:
"finalize_turn must invalidate the bounded flush-scan cursor "
"when the defrag pop stripped a live marker's stamp"
)
+
+
+class TestMergeAdjacentUserTurnsPersistedMarker:
+ """Third pop site under the _DB_PERSISTED_MARKER contract: a supersede that
+ drops a stale micro marker can leave two persisted plain user dicts adjacent;
+ the merge rewrites the earlier one's content in place, so the stamp must be
+ popped and the flush-scan cursor invalidated or the merged text is
+ identity-skipped and never reaches state.db."""
+
+ def _spliced_merge(self):
+ from agent.context_compressor import (
+ _DB_PERSISTED_MARKER,
+ COMPRESSED_SUMMARY_METADATA_KEY,
+ MICRO_COMPACT_MARKER_KEY,
+ )
+
+ cc = _compressor()
+ cc._micro_compact_rolling_summary = "ROLLING"
+ u1 = {"role": "user", "content": "first", _DB_PERSISTED_MARKER: True}
+ stale_micro = {
+ "role": "assistant",
+ "content": "SUMMARY",
+ COMPRESSED_SUMMARY_METADATA_KEY: True,
+ MICRO_COMPACT_MARKER_KEY: True,
+ _DB_PERSISTED_MARKER: True,
+ }
+ u2 = {"role": "user", "content": "second", _DB_PERSISTED_MARKER: True}
+ exchange = [
+ {"role": "assistant", "content": "answer", _DB_PERSISTED_MARKER: True},
+ {"role": "user", "content": "third", _DB_PERSISTED_MARKER: True},
+ ]
+ messages = [u1, stale_micro, u2, *exchange]
+ # Dropping stale_micro leaves u1/u2 adjacent; the exchange is spliced out.
+ return cc, cc._splice_micro_compact_result(messages, 3, 5, supersede=True)
+
+ def test_merge_pops_persisted_marker_and_raises_flag(self):
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ cc, result = self._spliced_merge()
+
+ merged = [m for m in result if m.get("role") == "user"]
+ assert len(merged) == 1
+ assert merged[0]["content"] == "first\n\nsecond"
+ assert _DB_PERSISTED_MARKER not in merged[0]
+ assert cc._flush_scan_cursor_invalidated is True
+
+ def test_untouched_survivors_keep_their_stamps(self):
+ """Only the rewritten dict loses its stamp; the merge must not strip
+ _db_persisted from messages it did not mutate (the archive would
+ re-insert them as duplicate active rows on failure)."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ _, result = self._spliced_merge()
+
+ markers = _summary_markers(result)
+ assert len(markers) == 1 # the fresh splice marker
+ stale_dropped = [m for m in result if m.get("content") == "SUMMARY"]
+ assert not stale_dropped
+ # The new marker was never persisted; it must not carry a stamp.
+ assert _DB_PERSISTED_MARKER not in markers[0]
diff --git a/tests/agent/test_tool_call_args_sanitizer.py b/tests/agent/test_tool_call_args_sanitizer.py
index 129bb0a827f..f52597249d9 100644
--- a/tests/agent/test_tool_call_args_sanitizer.py
+++ b/tests/agent/test_tool_call_args_sanitizer.py
@@ -158,3 +158,60 @@ def test_non_assistant_messages_ignored():
assert repaired == 0
assert messages == original
+
+
+def test_corrupt_args_repair_pops_persist_marker_on_stamped_dicts():
+ """A resumed session can load stamped rows whose tool_call args are corrupt;
+ repairing them in place must pop the marker or session.db keeps the corrupt
+ bytes while the live transcript holds the repaired ones (divergent resume)."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ stamped_call = _assistant_message(
+ _tool_call(call_id="call_1", arguments="{invalid json")
+ )
+ stamped_call[_DB_PERSISTED_MARKER] = True
+ stamped_result = _tool_message(call_id="call_1", content="ok")
+ stamped_result[_DB_PERSISTED_MARKER] = True
+ messages = [
+ {"role": "user", "content": "hello"},
+ stamped_call,
+ stamped_result,
+ ]
+
+ repaired = AIAgent._sanitize_tool_call_arguments(messages)
+
+ assert repaired == 1
+ assert stamped_call["tool_calls"][0]["function"]["arguments"] == "{}"
+ assert stamped_result["content"].endswith("ok")
+ assert _DB_PERSISTED_MARKER not in stamped_call
+ assert _DB_PERSISTED_MARKER not in stamped_result
+
+
+def test_blank_args_repair_pops_persist_marker():
+ """The blank-args rewrite is also an in-place mutation of the live dict."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ stamped_call = _assistant_message(_tool_call(call_id="call_1", arguments=""))
+ stamped_call[_DB_PERSISTED_MARKER] = True
+ messages = [{"role": "user", "content": "hi"}, stamped_call]
+
+ AIAgent._sanitize_tool_call_arguments(messages)
+
+ assert stamped_call["tool_calls"][0]["function"]["arguments"] == "{}"
+ assert _DB_PERSISTED_MARKER not in stamped_call
+
+
+def test_valid_args_keep_persist_marker():
+ """Control: an untouched stamped dict keeps its stamp."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ stamped_call = _assistant_message(
+ _tool_call(call_id="call_1", arguments='{"path":"/tmp/foo"}')
+ )
+ stamped_call[_DB_PERSISTED_MARKER] = True
+ messages = [{"role": "user", "content": "hi"}, stamped_call]
+
+ repaired = AIAgent._sanitize_tool_call_arguments(messages)
+
+ assert repaired == 0
+ assert stamped_call[_DB_PERSISTED_MARKER] is True
diff --git a/tests/agent/test_unicode_ascii_codec.py b/tests/agent/test_unicode_ascii_codec.py
index a053768f04c..a2130d15ba0 100644
--- a/tests/agent/test_unicode_ascii_codec.py
+++ b/tests/agent/test_unicode_ascii_codec.py
@@ -290,3 +290,32 @@ class TestApiMessagesAndApiKwargsSanitized:
assert _sanitize_messages_non_ascii(messages) is True
assert "\xab" not in messages[1]["reasoning"]
assert "\xbb" not in messages[1]["reasoning"]
+
+
+class TestSanitizeMessagesPersistMarker:
+ """In-place surrogate/non-ASCII repair of a stamped live dict must pop
+ _DB_PERSISTED_MARKER, or the flush scan skips it and session.db keeps the
+ corrupt bytes while the live transcript holds the repaired ones."""
+
+ def test_surrogate_repair_pops_marker(self):
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ msg = {"role": "user", "content": "test \ud800 end", _DB_PERSISTED_MARKER: True}
+ assert _sanitize_messages_surrogates([msg]) is True
+ assert "\ud800" not in msg["content"]
+ assert _DB_PERSISTED_MARKER not in msg
+
+ def test_non_ascii_repair_pops_marker(self):
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ msg = {"role": "user", "content": "café", _DB_PERSISTED_MARKER: True}
+ assert _sanitize_messages_non_ascii([msg]) is True
+ assert msg["content"] != "café"
+ assert _DB_PERSISTED_MARKER not in msg
+
+ def test_unchanged_dict_keeps_marker(self):
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ msg = {"role": "user", "content": "clean ascii", _DB_PERSISTED_MARKER: True}
+ assert _sanitize_messages_non_ascii([msg]) is False
+ assert msg[_DB_PERSISTED_MARKER] is True