Skip to content

The agent that grows with you

fix(state): ambiguous repaired-row coverage falls back to the watermark again

kshitijk4poor468ade953182
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index b2402a53d4e..12a152f49a2 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -1085,12 +1085,15 @@ class SessionMessagesMixin:
self, conn, session_id: str, covered_ids: Optional[List[int]],
unresolved_held: Optional[List[Dict[str, Any]]], watermark: Optional[int] = None,
) -> Optional[Tuple[List[int], Set[int]]]:
- """``(ids safe to archive as summarized, ids merged into another held dict)``.
-
- Only an absent named-coverage request permits watermark archival. A durable
- dict whose provenance cannot be resolved uniquely contributes no ids; its
- originals stay live, along with every unseen row, rather than expanding
- coverage to a watermark that cannot prove what the compressor held.
+ """``(ids safe to archive as summarized, ids merged into another held dict)``, or None when
+ a durable held row cannot be named.
+
+ An unresolved dict that still carries the persist marker was loaded from the DB.
+ Failing to name it means the watermark path, which archives the rows the compressor
+ saw, including ones whose ids were stripped. A marker-less miss is an unpersisted
+ turn: it names nothing, and it is not a reason to abandon the ids we do have.
+ Several active rows with the same content are ambiguous, so that also abandons,
+ and so does a merged dict whose run cannot be named.
The second set holds only merges the caller could not count: a dict that lists its
own ``_absorbed_row_ids`` is already counted in ``tail_count``.
"""
@@ -1110,7 +1113,7 @@ class SessionMessagesMixin:
# The dict's own row, recorded before a fold rewrote its text, is its own tail slot.
matches = self._matching_retired_ids(conn, session_id, message, watermark)
if len(matches) != 1:
- continue
+ return None
proved.extend(matches)
if not message.get(OWN_ROW):
merged_away.update(matches)
@@ -1124,11 +1127,11 @@ class SessionMessagesMixin:
# resolved first, and a stamped dict that names none is still durable, never an unpersisted turn.
run = self._merged_user_run(conn, session_id, message, watermark)
if message.get(MERGED_DURABLE_ROWS) and not run:
- continue
+ return None
matches = [] if run else self._matching_active_ids(conn, session_id, message)
if len(matches) > 1 or (
message.get(_DB_PERSISTED_MARKER) and len(matches) != 1 and not run):
- continue
+ return None
proved.extend(matches or run)
merged_away.update(set(run[1:]) - set(message.get("_absorbed_row_ids") or ()))
return list(dict.fromkeys(proved)), merged_away
diff --git a/tests/agent/test_in_place_merged_user_rows.py b/tests/agent/test_in_place_merged_user_rows.py
index 1ffb7ca1039..12497a9f451 100644
--- a/tests/agent/test_in_place_merged_user_rows.py
+++ b/tests/agent/test_in_place_merged_user_rows.py
@@ -22,10 +22,15 @@ def _call(call_id):
_UNANSWERED = ("user", "U12x this prompt never got a reply", {})
+_MERGED = "\n\n".join([_UNANSWERED[1], "U13 please continue with the next step"])
+_REPEATED = [("user", "U12x continue", {}), ("assistant", "U12x ok", {})] * 2
+# rows the killed turn left -> the live rows that mention them afterwards
KILLED_TURN_LEFT = {
- "prompt": [_UNANSWERED], # #125564: user;user, the unanswered prompt must not be sent twice
- "tool_call": [_UNANSWERED, _call("call_killed")], # #129123: the dropped tool row is accounted for
- "benign": [], # plain alternating history: compaction is unchanged
+ "prompt": ([_UNANSWERED], [_MERGED]), # #125564: user;user, the unanswered prompt must not be sent twice
+ "tool_call": ([_UNANSWERED, _call("call_killed")], [_MERGED]), # #129123: the dropped tool row is accounted for
+ # Identical durable rows on an id-less reload cannot be named: the watermark path, never a re-clone behind U15.
+ "repeated": (_REPEATED, [c for _, c, _ in _REPEATED]),
+ "benign": ([], []), # plain alternating history: compaction is unchanged
}
@@ -36,7 +41,8 @@ def test_compaction_over_an_unanswered_prompt_keeps_one_copy_of_every_row(sessio
cli = SimpleNamespace(conversation_history=[])
for n in range(1, 13):
_turn(db, agent, cli, surface, n, 5_000)
- for role, content, fields in KILLED_TURN_LEFT[left]:
+ rows, expected = KILLED_TURN_LEFT[left]
+ for role, content, fields in rows:
db.append_message("sid", role, content, **fields)
if surface == "cli": # ACP and the classic CLI restore start from the repaired reload
cli.conversation_history = db.get_messages_as_conversation("sid", repair_alternation=True)
@@ -50,14 +56,12 @@ def test_compaction_over_an_unanswered_prompt_keeps_one_copy_of_every_row(sessio
assert getattr(agent, "_last_compaction_in_place", None) is True
assert {f"A{n}" for n in range(1, 16)} <= _replies_displayed(db)
live = [m["content"] for m in db.get_messages_as_conversation("sid") if isinstance(m.get("content"), str)]
- # The prompts the killed turn left are in exactly one live row, the merged carried copy.
- unanswered = [c for role, c, _ in KILLED_TURN_LEFT[left] if role == "user"]
- merged = "\n\n".join([*unanswered, "U13 please continue with the next step"])
- assert [c for c in live if "U12x" in c or "U12y" in c] == ([merged] if unanswered else [])
+ # The rows the killed turn left are live exactly once (an unanswered prompt only as the merged carried copy).
+ assert [c for c in live if "U12x" in c] == expected
recalled = [row["content"] for row in db._conn.execute(
"SELECT content FROM messages WHERE session_id = 'sid' AND (active = 1 OR compacted = 1)").fetchall()]
carried = live[next(i for i, c in enumerate(live) if "Numbered steps" in c) + 1:]
- assert [recalled.count(content) for content in carried] == [1] * len(carried)
+ assert [recalled.count(content) for content in carried] == [carried.count(content) for content in carried]
# No turn here uses a tool, so a live tool row is the killed turn's, appended behind the running turn.
assert db._conn.execute(
"SELECT COUNT(*) FROM messages WHERE session_id = 'sid' AND active = 1"