Skip to content

The agent that grows with you

fix(compression): proactive prune and micro-compaction keep turns another surface appended

John Paul Soliva3f7e0fd072e8
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 17c64cf3000..617e4fc9848 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -382,6 +382,28 @@ def _strip_persistence_markers(messages: List[Dict[str, Any]]) -> None:
msg.pop(_DB_PERSISTED_MARKER, None)
+
+def _archive_watermark_for(session_db: Any, session_id: str, held: List[Dict[str, Any]],
+ start_watermark: Optional[int] = None) -> Optional[int]:
+ """The archive watermark for a commit that rewrites the history this process holds.
+
+ Without one, ``archive_and_compact`` archives every active row, including turns another surface appended
+ to the same session since this process loaded it (a Desktop session continued from Telegram) and rows
+ that arrived while the commit was being built. Those never reached this process, so they would be marked
+ summarized away with no summary holding them: still displayed and searchable, but gone from the model's
+ history. Capping at the newest row the process held sends them down the
+ concurrent-append path instead (cloned after the new set), the same rule the in-place compaction commit
+ applies. *start_watermark* is the store's watermark from before any slow step; it defaults to now.
+ A store without the watermark API keeps today's archive-everything commit.
+ """
+ watermark_of = getattr(session_db, "get_active_message_watermark", None)
+ if not callable(watermark_of) or not callable(getattr(session_db, "get_message_role", None)):
+ return None
+ if start_watermark is None:
+ start_watermark = watermark_of(session_id)
+ from agent.conversation_compression import held_archive_watermark
+ return held_archive_watermark(session_db, session_id, start_watermark, held)
+
def stamp_db_persisted_markers(messages: List[Dict[str, Any]]) -> None:
"""Fulfil the post-commit contract of ``SessionDB.archive_and_compact()``.
Single stamp site for all callers. Call ONLY after the commit succeeded, on the dict instances the
@@ -3262,6 +3284,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
session_db.archive_and_compact(
session_id, pruned_msgs,
model_config_patch={PROACTIVE_PRUNE_REARM_MODEL_CONFIG_KEY: next_rearm_tokens},
+ watermark=_archive_watermark_for(session_db, session_id, messages),
)
except Exception as exc:
logger.warning("Proactive tool-result prune DB commit failed; keeping the original transcript: %s", exc)
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 209907df7b5..410ff5ea9f0 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -3608,6 +3608,13 @@ class _CommitOutcome:
def _held_watermark(agent: Any, watermark: Optional[int], messages: list, verbatim_tail: Optional[list]) -> Optional[int]:
+ """The in-place commit's cap; see :func:`held_archive_watermark`."""
+ return held_archive_watermark(agent._session_db, agent.session_id, watermark, messages, verbatim_tail)
+
+
+def held_archive_watermark(
+ session_db: Any, session_id: str, watermark: Optional[int], messages: list, verbatim_tail: Optional[list] = None,
+) -> 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
@@ -3644,7 +3651,7 @@ def _held_watermark(agent: Any, watermark: Optional[int], messages: list, verbat
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, newest_held) is None:
+ if session_db.get_message_role(session_id, newest_held) is None:
return watermark
return newest_held
diff --git a/agent/micro_compaction.py b/agent/micro_compaction.py
index 718162ec5f3..328f723f550 100644
--- a/agent/micro_compaction.py
+++ b/agent/micro_compaction.py
@@ -225,6 +225,9 @@ class MicroCompactionMixin:
# Telemetry baseline; taken only once an exchange exists so no-op turns don't pay.
_started_at = time.monotonic()
_tokens_before = estimate_messages_tokens_rough(messages)
+ # The history this pass rewrites, and the store's watermark, before the slow summary call: the commit
+ # keeps what another surface or a concurrent write added instead of archiving it unseen.
+ _held, _start_watermark = list(messages), self._micro_start_watermark()
def _telemetry(outcome: str, result: List[Dict[str, Any]], **extra: Any) -> None:
self._emit_micro_compaction_telemetry(
@@ -237,7 +240,7 @@ class MicroCompactionMixin:
if self._needs_defrag():
defragged = self._defrag_rolling_summary(messages)
if defragged:
- self._sync_micro_compact_to_db(messages)
+ self._sync_micro_compact_to_db(messages, held=_held, start_watermark=_start_watermark)
self._reset_micro_failure_tracking()
outcome = "defrag" if defragged else "defrag_failed"
_telemetry(outcome, messages, tokens_after=estimate_messages_tokens_rough(messages))
@@ -260,7 +263,7 @@ class MicroCompactionMixin:
result = self._splice_micro_compact_result(messages, exchange_start, exchange_end, supersede=_cumulative)
self._micro_compact_cursor = self._cursor_after_splice(result, exchange_start + 1)
- self._sync_micro_compact_to_db(result)
+ self._sync_micro_compact_to_db(result, held=_held, start_watermark=_start_watermark)
_telemetry(
"absorbed", result, tokens_after=estimate_messages_tokens_rough(result), exchange_tokens=_exchange_tokens,
)
@@ -344,7 +347,21 @@ class MicroCompactionMixin:
except Exception as exc:
logger.debug("failed to emit micro-compaction telemetry: %s", exc)
- def _sync_micro_compact_to_db(self, compacted_messages: List[Dict[str, Any]]) -> None:
+ def _micro_start_watermark(self) -> Optional[int]:
+ """The store's active watermark before a pass's slow step, or None where the store has none."""
+ session_db, session_id = getattr(self, "_session_db", None), getattr(self, "_session_id", "")
+ watermark_of = getattr(session_db, "get_active_message_watermark", None)
+ if not session_id or not callable(watermark_of):
+ return None
+ try:
+ return watermark_of(session_id)
+ except Exception:
+ return None
+
+ def _sync_micro_compact_to_db(
+ self, compacted_messages: List[Dict[str, Any]], *, held: Optional[List[Dict[str, Any]]] = None,
+ start_watermark: Optional[int] = None,
+ ) -> None:
"""Persist the micro-compacted set to the session DB atomically and stamp rows persisted.
Without this the old exchange rows stay ``active=1`` and a resume double-loads both the
summary and the originals."""
@@ -361,8 +378,11 @@ class MicroCompactionMixin:
message for message in compacted_messages
if isinstance(message, dict) and message.get(_cc()._DB_PERSISTED_MARKER)
]
+ watermark = None
+ if held is not None and start_watermark is not None:
+ watermark = _cc()._archive_watermark_for(session_db, session_id, held, start_watermark)
session_db.archive_and_compact(
- session_id, compacted_messages, carried_messages=carried_messages)
+ session_id, compacted_messages, carried_messages=carried_messages, watermark=watermark)
# Shared post-commit stamp site with batch commit and proactive prune.
# See #98450.
_cc().stamp_db_persisted_markers(compacted_messages)
diff --git a/tests/agent/test_micro_compaction.py b/tests/agent/test_micro_compaction.py
index ce001a4c30d..8be28b49443 100644
--- a/tests/agent/test_micro_compaction.py
+++ b/tests/agent/test_micro_compaction.py
@@ -859,3 +859,29 @@ def test_superseding_marker_never_shows_a_user_input_twice_in_display_history(tm
finally:
legacy.close()
db.close()
+
+
+def test_micro_compaction_keeps_a_turn_another_surface_appended_after_load(tmp_path):
+ """The micro-compaction commit rewrites the history this process holds. A turn another surface appended to
+ the same session since then was archived with the rest (no watermark), as summarized away though the rolling
+ summary never saw it. The display and search still show it, but the model never sees it again."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session("s", source="cli")
+ messages = _conversation(exchanges=8)
+ for msg in messages:
+ msg["_row_id"] = db.append_message("s", role=msg["role"], content=msg["content"])
+ msg[_DB_PERSISTED_MARKER] = True
+ foreign = "[from Telegram] the vault code is 7741"
+ db.append_message("s", "user", foreign)
+ cc = _compressor()
+ cc._session_db, cc._session_id = db, "s"
+
+ result = cc._micro_compact(messages)
+
+ assert len(_summary_markers(result)) == 1 # a pass ran
+ live = [str(m["content"]) for m in db.get_messages_as_conversation("s")]
+ assert live[-1] == foreign
+ assert sum(foreign in content for content in live) == 1
diff --git a/tests/agent/test_proactive_prune_restart_safety.py b/tests/agent/test_proactive_prune_restart_safety.py
index 0ae91779ff1..322af041c6c 100644
--- a/tests/agent/test_proactive_prune_restart_safety.py
+++ b/tests/agent/test_proactive_prune_restart_safety.py
@@ -246,3 +246,26 @@ def test_patch_session_model_config_merge_and_delete(tmp_path: Path) -> None:
db.patch_session_model_config(session_id, {})
+
+
+def test_prune_keeps_a_turn_another_surface_appended_after_load(tmp_path: Path) -> None:
+ """The prune commit rewrites the history this process holds. Another surface may have appended to the same
+ session since it was loaded (a Desktop session continued from Telegram); with no watermark the commit
+ archived that turn with the rest, as summarized away though no summary holds it. The display and search
+ still show it, but the model never sees it again."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_FOREIGN_TURN"
+ db.create_session(session_id, source="cli")
+ db.append_messages_batch(session_id, _history())
+ agent = _build_agent(db, session_id, platform="cli")
+ _configure_pruning(agent)
+ held = db.get_resume_conversations(session_id)[0] # what a resume restores: row ids included
+ foreign = "[from Telegram] the vault code is 7741"
+ db.append_message(session_id, "user", foreign)
+
+ _pruned, count = agent.context_compressor.prune_tool_results_only(held, current_tokens=120_000)
+
+ assert count >= 1
+ live = [message["content"] for message in db.get_messages_as_conversation(session_id)]
+ assert live[-1] == foreign
+ assert sum(foreign in content for content in live) == 1