Skip to content

The agent that grows with you

fix(compression): a here-N tail copy vouches for its row id only when its source is unchanged

kshitijk4poor4d5899868a5e
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 02e60f7fdf5..209907df7b5 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -3611,39 +3611,42 @@ def _held_watermark(agent: Any, watermark: Optional[int], messages: list, verbat
"""The in-place archive watermark, capped at the newest durable row the compressor was handed.
The lease watermark is the newest row in state.db, but a surface compacts the history it holds, and that
- can be older: a Desktop/TUI or CLI /compress, or a long-lived CLI, does not hold turns another surface
- appended to the same session since. Archived under the watermark, those rows would leave every surface's
+ can be older: a Desktop/TUI or CLI ``/compress`` does not hold turns another surface appended to the same
+ session since it loaded. Archived under the watermark, those rows would leave every surface's
history and search, and the summary never saw them. Above the cap they take the concurrent-append path
instead (cloned after the compacted set).
- Only while the held history is a live prefix of the session: its LAST row names its ``_row_id`` (a
- trailing row of unknown provenance may be durable under the lease watermark without any stamp, e.g. the
- TUI model-switch marker appended to history and written with a bare ``append_message``; capped below it,
- the clone would land beside its own carried copy), and that row is still active (after another surface
- compacted, the held rows are archived and every live row would be cloned beside the new summary).
+ Only while the held history is a live prefix of the session: its LAST row names an exact ``_row_id``, and
+ that row is still active (after another surface compacted, the held rows are archived and every live row
+ would be cloned beside the new summary). An id is exact while its dict is unchanged since it was loaded: a
+ dict loaded from the DB is born carrying both the id and the persist marker, and a pass that rewrote its
+ content drops the marker and keeps the id (the user/assistant merges in ``repair_message_sequence``, or a
+ context engine that rewrites in place). Such a row absorbed later durable rows whose ids are gone from the
+ held set, so its id no longer names what the summary covered: capped there, those rows would be cloned
+ live beside a summary that already contains them. A trailing row of unknown provenance may be durable
+ under the lease watermark without any stamp (the TUI model-switch marker, written with a bare
+ ``append_message``); capped below it, the clone would land beside its own carried copy. A ``here N`` tail
+ is marker-swept copies, so ``compress_now`` keeps a copy's id only when its source still carried the
+ marker; their ids are trusted as given.
"""
if watermark is None:
return None
from agent.context_compressor import _DB_PERSISTED_MARKER
- rows = [*messages, *(verbatim_tail or ())]
- held = [m.get("_row_id") for m in rows if isinstance(m, dict)]
- held = [rid for rid in held if isinstance(rid, int) and not isinstance(rid, bool) and rid > 0]
- newest = next((m for m in reversed(rows) if isinstance(m, dict)), None)
- if newest is None or newest.get("_row_id") not in held or max(held) >= watermark:
- return watermark
- # ...and, when it is a summarized row, that it still matches its durable row. A dict loaded from
- # the DB is born carrying both the id and the persist marker; a pass that rewrote its content drops
- # the marker and keeps the id (the user/assistant merges in `repair_message_sequence`, or a context
- # engine that rewrites in place). Such a row absorbed later durable rows whose ids are gone from
- # `held`, so `max(held)` no longer names what the summary covered: capped there, those rows would be
- # cloned live beside a summary that already contains them. A `here N` tail is exempt: it is copied
- # verbatim (without the marker), so its ids are exact and, being newest, they lift the cap above
- # anything a merged row earlier in `messages` absorbed.
- if not any(isinstance(m, dict) for m in (verbatim_tail or ())) and not newest.get(_DB_PERSISTED_MARKER):
+
+ def _exact_id(m: dict, copied: bool) -> Optional[int]:
+ rid = m.get("_row_id")
+ if not isinstance(rid, int) or isinstance(rid, bool) or rid <= 0:
+ return None
+ return rid if copied or m.get(_DB_PERSISTED_MARKER) else None
+
+ ids = [_exact_id(m, False) for m in messages if isinstance(m, dict)]
+ ids += [_exact_id(m, True) for m in (verbatim_tail or ()) if isinstance(m, dict)]
+ held = [rid for rid in ids if rid is not None]
+ if not ids or ids[-1] is None or (newest_held := max(held)) >= watermark:
return watermark
- if agent._session_db.get_message_role(agent.session_id, max(held)) is None:
+ if agent._session_db.get_message_role(agent.session_id, newest_held) is None:
return watermark
- return max(held)
+ return newest_held
def _commit_compaction(
diff --git a/agent/conversation_compression_manual.py b/agent/conversation_compression_manual.py
index 16215b44c72..329a79d0763 100644
--- a/agent/conversation_compression_manual.py
+++ b/agent/conversation_compression_manual.py
@@ -105,8 +105,15 @@ def compress_now(
if skip_without_window and callable(has_content) and has_content(head) is False:
return CompressResult("nothing_to_do", before, before, before_tokens, before_tokens, request)
# An in-place commit archives every durable row under the lease watermark, the kept tail's included, so
- # it must store the tail again itself. It gets copies because the insert writes row ids onto them.
- tail_rows = [_fresh_compaction_message_copy(m) for m in tail]
+ # it must store the tail again itself. It gets copies because the insert writes row ids onto them. A copy
+ # keeps its source's row id only while the source is unchanged since it was loaded (marker present): a
+ # resume merge rewrote the row and dropped the marker, and its id no longer bounds what the row holds.
+ tail_rows = []
+ for m in tail:
+ row = _fresh_compaction_message_copy(m)
+ if not m.get(_DB_PERSISTED_MARKER):
+ row.pop("_row_id", None)
+ tail_rows.append(row)
try:
compressed, _ = agent._compress_context(
head, system_message, approx_tokens=before_tokens, focus_topic=request.focus_topic, force=True,
diff --git a/tests/agent/test_conversation_compression_manual.py b/tests/agent/test_conversation_compression_manual.py
index 3e81880cf4a..e96a54eec42 100644
--- a/tests/agent/test_conversation_compression_manual.py
+++ b/tests/agent/test_conversation_compression_manual.py
@@ -269,18 +269,20 @@ def test_in_place_compress_never_leaves_two_live_copies_of_a_row(session_db, sta
assert len(contents) == len(set(contents))
-def test_in_place_compress_never_clones_a_row_a_merge_already_carried(session_db):
[email protected]("raw", ["", "here 2"])
+def test_in_place_compress_never_clones_a_row_a_merge_already_carried(session_db, raw):
"""Resume repair merges consecutive user rows into the first one's dict: that dict keeps its row id, drops the
persisted marker, and the later row's id leaves the held history. Stopping the archive at the newest held id
would then leave the later row above the stop, cloned as a concurrent append beside the merged row that
- already carries its content. Two strings, so the exact-duplicate check above cannot see it."""
+ already carries its content. Two strings, so the exact-duplicate check above cannot see it. With ``here 2``
+ the merged row is the newest row of the verbatim tail, whose marker-swept copy must not vouch for its id."""
agent, _ = _stored_agent(session_db, _exchanges(10))
session_db.append_message("sid", "user", "first half of a split prompt")
session_db.append_message("sid", "user", "second half 9931")
held = session_db.get_resume_conversations("sid")[0] # the resume path merges the two user rows
assert "second half 9931" in held[-1]["content"] and held[-1]["content"] != "second half 9931"
- assert _compress(agent, held, "").status == "compressed"
+ assert _compress(agent, held, raw).status == "compressed"
contents = [m["content"] for m in session_db.get_messages_as_conversation("sid")]
assert sum("second half 9931" in c for c in contents) == 1