Skip to content

The agent that grows with you

fix(compression): an in-place compaction never archives turns the compacting surface did not hold

John Paul Soliva302899581704
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 45511e49144..1e85ee1cde5 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -3607,6 +3607,35 @@ class _CommitOutcome:
made_progress: bool = False
+def _held_watermark(agent: Any, watermark: Optional[int], messages: list, verbatim_tail: Optional[list]) -> Optional[int]:
+ """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
+ 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 newest durable row names its ``_row_id``
+ (one held without it could sit above the cap and be cloned 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).
+ """
+ if watermark is None:
+ return None
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+ rows = [*((m, False) for m in messages), *((m, True) for m in 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, kept in reversed(rows) if isinstance(m, dict)
+ and (kept or "_row_id" in m or m.get(_DB_PERSISTED_MARKER))), None)
+ if newest is None or newest.get("_row_id") not in held or max(held) >= watermark:
+ return watermark
+ if agent._session_db.get_message_role(agent.session_id, max(held)) is None:
+ return watermark
+ return max(held)
+
+
def _commit_compaction(
agent: Any, messages: list, compressed: list, *, in_place: bool, lease: _CompressionLease,
new_system_prompt: str, system_message: str, compressed_user_turn_outcome: str,
@@ -3673,8 +3702,8 @@ def _commit_compaction(
tail_count += len(verbatim_tail)
agent._session_db.archive_and_compact(
agent.session_id, persisted, model_config_patch={PROACTIVE_PRUNE_REARM_MODEL_CONFIG_KEY: None},
- watermark=lease.watermark, lock_holder=lease.holder, tail_count=tail_count,
- carried_messages=carried_messages,
+ watermark=_held_watermark(agent, lease.watermark, messages, verbatim_tail),
+ lock_holder=lease.holder, tail_count=tail_count, carried_messages=carried_messages,
)
compressed = persisted
split_status = "in_place_committed"
diff --git a/tests/agent/test_conversation_compression_manual.py b/tests/agent/test_conversation_compression_manual.py
index 18083023057..c55e6c65ab4 100644
--- a/tests/agent/test_conversation_compression_manual.py
+++ b/tests/agent/test_conversation_compression_manual.py
@@ -130,9 +130,10 @@ def _exchanges(n, *, unanswered=()):
return history
-def _stored_agent(db, history):
+def _stored_agent(db, history, *, create=True):
"""A real AIAgent (default in-place mode) over ``history`` as stored rows, loaded back like the gateway does."""
- db.create_session("sid", "telegram", model="test/model")
+ if create:
+ db.create_session("sid", "telegram", model="test/model")
for message in history:
db.append_message("sid", message["role"], message["content"])
with patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}):
@@ -144,12 +145,15 @@ def _stored_agent(db, history):
def _compress_here(agent, history, keep):
+ return _compress(agent, history, f"here {keep}")
+
+
+def _compress(agent, history, raw):
response = MagicMock()
response.choices = [MagicMock()]
response.choices[0].message.content = "## Goal\nNumbered fruit questions.\n## Progress\nEarly ones answered."
with patch("agent.context_compressor.call_llm", lambda **_kw: response):
- return compress_now(agent, history, parse_compress_args(f"here {keep}"), system_message="",
- skip_without_window=True)
+ return compress_now(agent, history, parse_compress_args(raw), system_message="", skip_without_window=True)
def _flags(db, content):
@@ -208,3 +212,52 @@ def test_in_place_here_n_folds_the_seam_once(session_db):
assert _live(durable) == _live(result.after_messages)
assert f"{history[-5]['content']}\n\n{history[-4]['content']}" in [m["content"] for m in durable]
assert _live(durable[-3:]) == _live(history[-3:])
+
+
+FOREIGN_TURN = [("user", "[from Telegram] the vault code is 7741"), ("assistant", "Noted: the vault code is 7741.")]
+
+
[email protected]("raw", ["", "here 2"])
+def test_in_place_compress_keeps_turns_the_caller_never_held(session_db, raw):
+ """A surface compacts the history it holds (Desktop/TUI and CLI /compress), and another surface may have
+ appended turns to the same session since. The archive runs under state.db's newest row, so unless it stops at
+ the caller's newest row it takes those turns away unseen: the summarizer never read them, and they leave every
+ surface's history and search."""
+ agent, _ = _stored_agent(session_db, _exchanges(10))
+ held = session_db.get_resume_conversations("sid")[0] # what a resume restores: row ids included
+ for role, content in FOREIGN_TURN:
+ session_db.append_message("sid", role, content)
+
+ assert _compress(agent, held, raw).status == "compressed"
+
+ durable = session_db.get_messages_as_conversation("sid")
+ assert _live(durable[-2:]) == FOREIGN_TURN
+ assert len({m["content"] for m in durable}) == len(durable) # kept (`here 2`) and carried rows once each
+ model_history, display_history = session_db.get_resume_conversations("sid")
+ for _role, content in FOREIGN_TURN:
+ assert [m["content"] for m in model_history].count(content) == 1
+ assert [m["content"] for m in display_history].count(content) == 1
+ assert session_db.search_messages("vault 7741")
+
+
[email protected]("stale", ["compacted elsewhere", "newest rows without ids"])
+def test_in_place_compress_never_leaves_two_live_copies_of_a_row(session_db, stale):
+ """Stopping the archive at the caller's newest row is only exact while the held history is a live prefix of the
+ session. After another surface compacted it, every live row is newer than the held (now archived) ones; and a
+ durable row held without its row id may sit above the stop. Either way the rows above it would be cloned beside
+ their own copies in the new transcript."""
+ agent, _ = _stored_agent(session_db, _exchanges(10))
+ held = session_db.get_resume_conversations("sid")[0]
+ if stale == "compacted elsewhere":
+ other, _ = _stored_agent(session_db, [], create=False)
+ assert _compress(other, session_db.get_messages_as_conversation("sid"), "").status == "compressed"
+ else:
+ for message in held[-2:]:
+ message.pop("_row_id")
+ for role, content in FOREIGN_TURN:
+ session_db.append_message("sid", role, content)
+
+ assert _compress(agent, held, "").status == "compressed"
+
+ contents = [m["content"] for m in session_db.get_messages_as_conversation("sid")]
+ assert len(contents) == len(set(contents))