Skip to content

The agent that grows with you

refactor: consolidate _db_persisted literal + marker-insensitive no-op check (#92231 follow-up)

Kshitij Kapoor72ae855da517
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 90f3b5e879d..e5dffd458b0 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -104,6 +104,27 @@ COMPACTION_STATUS = (
COMPACTION_DONE_STATUS = "✓ Context compaction complete — continuing turn..."
+def _strip_marker_for_comparison(msgs: Any) -> Any:
+ """Copy ``msgs`` with the ``_db_persisted`` persistence marker removed.
+
+ Used by the no-op progress check: live and loaded dicts carry the marker
+ (loaded rows are stamped at materialization time, #92231) while
+ ``compress()`` output is marker-swept, so a raw ``==`` would misclassify a
+ semantically-identical no-op copy as progress. Non-list inputs and
+ non-dict entries pass through unchanged.
+ """
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ if not isinstance(msgs, list):
+ return msgs
+ return [
+ {k: v for k, v in m.items() if k != _DB_PERSISTED_MARKER}
+ if isinstance(m, dict)
+ else m
+ for m in msgs
+ ]
+
+
def _emit_compaction_done(agent: Any) -> None:
"""Emit the structured terminal edge for a started compaction."""
status_callback = getattr(agent, "status_callback", None)
@@ -3163,8 +3184,15 @@ def compress_context(
# Compare against the pre-dispatch semantic state, not object identity:
# legacy/plugin engines may return an equal copy for a no-op, or mutate
# the live list while returning an unchanged snapshot. Neither case may
- # rotate or rewrite the session.
- if compressed == messages_before_compression:
+ # rotate or rewrite the session. The raw ``==`` leg runs FIRST so a
+ # list subclass returned by an engine keeps its ``__eq__`` semantics
+ # (tests seam on this); the marker-insensitive leg (#92231) then covers
+ # the cold-resume shape where the stamped snapshot differs from the
+ # marker-swept compress() output only by ``_db_persisted``.
+ if compressed == messages_before_compression or (
+ _strip_marker_for_comparison(compressed)
+ == _strip_marker_for_comparison(messages_before_compression)
+ ):
if messages != messages_before_compression:
messages[:] = copy.deepcopy(messages_before_compression)
logger.info(
diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.py
index fbdf19cd91b..e3b20d876e4 100644
--- a/agent/turn_finalizer.py
+++ b/agent/turn_finalizer.py
@@ -26,6 +26,7 @@ import logging
import os
from agent.codex_responses_adapter import _summarize_user_message_for_log
+from agent.context_compressor import _DB_PERSISTED_MARKER
from agent.message_content import flatten_message_text
from agent.message_metadata import append_message, stamp_message_timestamp
from agent.message_sanitization import _sanitize_surrogates
@@ -377,7 +378,7 @@ def finalize_turn(
# re-writes the filled content to the durable store —
# otherwise ``/resume`` reloads ``content=""`` and the bug
# resurfaces cross-session.
- _tail.pop("_db_persisted", None)
+ _tail.pop(_DB_PERSISTED_MARKER, None)
# The bounded flush-scan cursor (run_agent.py) skips the
# identity-matched prefix of its previous snapshot on the
# assumption that no live dict loses the marker in place —
diff --git a/hermes_state.py b/hermes_state.py
index 420c840014f..a2b1f94fe0a 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -37,6 +37,15 @@ from pathlib import Path
from agent.memory_manager import sanitize_context
from agent.session_activity import ActivityProvenance
from agent.message_sanitization import _sanitize_surrogates
+# Intrinsic persistence marker stamped on message dicts that are known-durable
+# (#92231). One shared constant with agent.context_compressor (this module
+# already imports agent.* at module level, and context_compressor is a
+# transitive dependency via hermes_state_common). run_agent keeps its own
+# predating copy — hermes_state cannot import run_agent (circular) — guarded
+# by test_marker_constant_in_sync.
+from agent.context_compressor import (
+ _DB_PERSISTED_MARKER as _DB_PERSISTED_MARKER_KEY,
+)
from agent.skill_commands import (
SKILL_EXCERPT_JOINT,
SKILL_SCAFFOLD_SQL_LIKE,
@@ -776,14 +785,6 @@ def _strip_background_review_harness(
# Matches a bare protocol/tool-name marker such as "[memory]" or "[skill_manage]".
_STALE_TOOL_CALL_MARKER_RE = re.compile(r"^\[[A-Za-z_][A-Za-z0-9_.-]*\]$")
-# Intrinsic persistence marker stamped on message dicts that are known-durable.
-# MUST stay in sync with run_agent._DB_PERSISTED_MARKER and
-# agent.context_compressor._DB_PERSISTED_MARKER (same literal; defined locally
-# because hermes_state must not import run_agent — circular import — and
-# importing the agent layer for one constant inverts the state/agent layering).
-# Drift is guarded by test_marker_constant_in_sync (#92231).
-_DB_PERSISTED_MARKER_KEY = "_db_persisted"
-
def _is_stale_tool_call_marker_message(msg: Dict[str, Any]) -> bool:
"""True when ``msg`` is a persisted assistant turn whose content is a bare
diff --git a/tests/agent/test_load_time_durability_stamp_92231.py b/tests/agent/test_load_time_durability_stamp_92231.py
index 32803071c24..e5f65dd06f1 100644
--- a/tests/agent/test_load_time_durability_stamp_92231.py
+++ b/tests/agent/test_load_time_durability_stamp_92231.py
@@ -58,12 +58,25 @@ def _seed_session(db: SessionDB, sid: str, turns: int = 3) -> None:
def test_marker_constant_in_sync() -> None:
- """hermes_state cannot import run_agent (circular) — literals must match."""
+ """One shared literal across every module that touches the marker.
+
+ ``hermes_state`` and ``agent.turn_finalizer`` import the constant from
+ ``agent.context_compressor`` (single source), so the only genuine drift
+ surface left is ``run_agent``'s predating copy — hermes_state cannot
+ import run_agent (circular), and run_agent's own literal predates the
+ consolidation.
+ """
import agent.context_compressor as cc
+ import agent.turn_finalizer as tf
import run_agent
assert _DB_PERSISTED_MARKER_KEY == run_agent._DB_PERSISTED_MARKER
assert _DB_PERSISTED_MARKER_KEY == cc._DB_PERSISTED_MARKER
+ assert _DB_PERSISTED_MARKER_KEY == tf._DB_PERSISTED_MARKER
+ # The import aliases must be the SAME object as the canonical constant,
+ # not re-defined literals.
+ assert _DB_PERSISTED_MARKER_KEY is cc._DB_PERSISTED_MARKER
+ assert tf._DB_PERSISTED_MARKER is cc._DB_PERSISTED_MARKER
def test_loaded_rows_are_stamped_durable(tmp_path: Path) -> None:
@@ -145,3 +158,40 @@ def test_compaction_copy_strips_stamp_so_child_flush_writes(tmp_path: Path) -> N
# Idempotent thereafter: the flush stamped the copies on write.
agent._flush_messages_to_session_db(compacted)
assert len(db.get_messages("CHILD")) == len(loaded)
+
+
+def test_noop_progress_check_is_marker_insensitive(tmp_path: Path) -> None:
+ """A marker-swept no-op copy must still compare equal to stamped input.
+
+ The commit layer's "no progress" check compares compress() output against
+ a pre-dispatch deepcopy of the live messages. Load-stamping (#92231) puts
+ ``_db_persisted`` on cold-resumed dicts while compress() output is
+ marker-swept — a raw ``==`` would misclassify the semantically-identical
+ no-op as progress and rotate the session for nothing.
+ """
+ from agent.conversation_compression import _strip_marker_for_comparison
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ _seed_session(db, "NOOP", turns=2)
+
+ stamped = db.get_messages_as_conversation("NOOP")
+ assert all(m.get(_DB_PERSISTED_MARKER_KEY) is True for m in stamped)
+ # What a no-op engine hands back after the terminal marker sweep.
+ swept = [
+ {k: v for k, v in m.items() if k != _DB_PERSISTED_MARKER_KEY}
+ for m in stamped
+ ]
+ assert swept != stamped # raw equality is asymmetric — the bug shape
+ assert _strip_marker_for_comparison(swept) == _strip_marker_for_comparison(
+ stamped
+ )
+
+ # Genuine progress must still register as inequality.
+ compacted = swept[:-1]
+ assert _strip_marker_for_comparison(compacted) != _strip_marker_for_comparison(
+ stamped
+ )
+
+ # Defensive passthrough shapes.
+ assert _strip_marker_for_comparison(None) is None
+ assert _strip_marker_for_comparison(["not-a-dict"]) == ["not-a-dict"]