Skip to content

The agent that grows with you

fix(compression): a stale prune/micro-compaction generation aborts instead of publishing beside the winner

kshitijk4poor40051c2a13c8
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 617e4fc9848..fbf8ff34222 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -382,6 +382,15 @@ def _strip_persistence_markers(messages: List[Dict[str, Any]]) -> None:
msg.pop(_DB_PERSISTED_MARKER, None)
+class StaleHeldHistory(RuntimeError):
+ """The history a lease-less rewrite holds is no longer the session's live generation.
+
+ Its newest exact row is inactive: another compaction already committed (a ``/compress`` on this or
+ another surface, or an earlier prune/micro pass). Published anyway, the stale rewrite would archive the
+ winner's rows under the lease-less watermark and clone them back as a "concurrent tail" — two summary
+ generations live. Prune and micro-compaction hold no compression lease, so they abort on this instead.
+ """
+
def _archive_watermark_for(session_db: Any, session_id: str, held: List[Dict[str, Any]],
start_watermark: Optional[int] = None) -> Optional[int]:
@@ -395,6 +404,11 @@ def _archive_watermark_for(session_db: Any, session_id: str, held: List[Dict[str
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.
+
+ Raises :class:`StaleHeldHistory` when the newest held exact row is no longer active. The in-place commit
+ falls back to the lease watermark there because its lease rules out an overlapping compaction; prune and
+ micro-compaction hold no lease, so for them that fallback would publish a stale generation beside the one
+ that won.
"""
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)):
@@ -402,7 +416,7 @@ def _archive_watermark_for(session_db: Any, session_id: str, held: List[Dict[str
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)
+ return held_archive_watermark(session_db, session_id, start_watermark, held, stale_raises=True)
def stamp_db_persisted_markers(messages: List[Dict[str, Any]]) -> None:
"""Fulfil the post-commit contract of ``SessionDB.archive_and_compact()``.
@@ -3280,11 +3294,19 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
runway = max(reclaimed, self.proactive_prune_tokens, self.proactive_prune_min_reclaim_tokens)
next_rearm_tokens = after + runway
if session_db and session_id:
+ try:
+ watermark = _archive_watermark_for(session_db, session_id, messages)
+ except StaleHeldHistory:
+ # Another compaction already committed this session's history; a lease-less prune of the
+ # generation this process holds would publish beside the winner. Leave the input alone.
+ logger.info("Proactive tool-result prune skipped: another compaction already committed this session")
+ self._warn_reclamation_no_op("prune:stale_generation", current_tokens, before=before)
+ return messages, 0
try:
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),
+ watermark=watermark,
)
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 410ff5ea9f0..c2f9a3d0dd6 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -3614,6 +3614,7 @@ def _held_watermark(agent: Any, watermark: Optional[int], messages: list, verbat
def held_archive_watermark(
session_db: Any, session_id: str, watermark: Optional[int], messages: list, verbatim_tail: Optional[list] = None,
+ *, stale_raises: bool = False,
) -> Optional[int]:
"""The in-place archive watermark, capped at the newest durable row the compressor was handed.
@@ -3635,10 +3636,15 @@ def held_archive_watermark(
``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.
+
+ *stale_raises*: the newest exact held row being inactive means another compaction already committed.
+ Under the in-place lease that cannot overlap a live compaction, so the lease watermark is returned; a
+ lease-less caller (prune, micro-compaction) passes ``True`` and gets :class:`StaleHeldHistory` instead,
+ because for it the fallback would publish a stale generation beside the winner.
"""
if watermark is None:
return None
- from agent.context_compressor import _DB_PERSISTED_MARKER
+ from agent.context_compressor import _DB_PERSISTED_MARKER, StaleHeldHistory
def _exact_id(m: dict, copied: bool) -> Optional[int]:
rid = m.get("_row_id")
@@ -3652,6 +3658,8 @@ def held_archive_watermark(
if not ids or ids[-1] is None or (newest_held := max(held)) >= watermark:
return watermark
if session_db.get_message_role(session_id, newest_held) is None:
+ if stale_raises:
+ raise StaleHeldHistory(f"held row {newest_held} of session {session_id} is no longer active")
return watermark
return newest_held
diff --git a/agent/micro_compaction.py b/agent/micro_compaction.py
index fe0ffc41851..436097ef3c1 100644
--- a/agent/micro_compaction.py
+++ b/agent/micro_compaction.py
@@ -229,7 +229,7 @@ class MicroCompactionMixin:
# keeps what another surface or a concurrent write added instead of archiving it unseen. A watermark
# the store could not answer for leaves the commit unbounded, so the pass does not run at all.
_held = list(messages)
- _wm_status, _start_watermark = self._micro_start_watermark()
+ _wm_status, _start_watermark = self._micro_start_watermark(_held)
def _telemetry(outcome: str, result: List[Dict[str, Any]], **extra: Any) -> None:
self._emit_micro_compaction_telemetry(
@@ -240,6 +240,9 @@ class MicroCompactionMixin:
if _wm_status == "failed": # an unanswerable watermark would commit an unbounded archive
_telemetry("watermark_unavailable", messages, tokens_after=_tokens_before)
return messages
+ if _wm_status == "stale": # another compaction already committed; this pass holds no lease
+ _telemetry("stale_generation", messages, tokens_after=_tokens_before)
+ return messages
# Defrag rewrites summary text/marker in place (no splice, no cursor move) instead of
# absorbing this turn.
@@ -353,23 +356,31 @@ class MicroCompactionMixin:
except Exception as exc:
logger.debug("failed to emit micro-compaction telemetry: %s", exc)
- def _micro_start_watermark(self) -> "tuple[str, Optional[int]]":
+ def _micro_start_watermark(self, held: List[Dict[str, Any]]) -> "tuple[str, Optional[int]]":
"""``(status, watermark)`` taken before a pass's slow step.
``unsupported`` where the store has no watermark API: the commit keeps today's
archive-everything behaviour, as it always has. ``failed`` when the read itself raised —
that must NOT collapse into the same None, because None means "archive every active row",
which is the very loss this watermark exists to prevent. The pass is skipped instead.
+ ``stale`` when *held* is no longer the session's live generation (another compaction already
+ committed): this pass holds no compression lease, so publishing would leave two generations live.
+ The pass is skipped; the commit re-checks, since a compaction can also land during the summary call.
"""
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 "unsupported", None
try:
- return "ok", watermark_of(session_id)
+ watermark = watermark_of(session_id)
+ _cc()._archive_watermark_for(session_db, session_id, held, watermark)
+ except _cc().StaleHeldHistory as exc:
+ logger.info("micro-compaction: skipping this pass, %s", exc)
+ return "stale", None
except Exception as exc:
logger.info("micro-compaction: watermark read failed, skipping this pass: %s", exc)
return "failed", None
+ return "ok", watermark
def _sync_micro_compact_to_db(
self, compacted_messages: List[Dict[str, Any]], *, held: Optional[List[Dict[str, Any]]] = None,
@@ -399,6 +410,10 @@ class MicroCompactionMixin:
# Shared post-commit stamp site with batch commit and proactive prune.
# See #98450.
_cc().stamp_db_persisted_markers(compacted_messages)
+ except _cc().StaleHeldHistory as exc:
+ # Another compaction committed during the summary call. Nothing is written: the store already
+ # holds the winning generation, and this process's spliced copy is superseded on the next load.
+ logger.info("Micro-compaction commit skipped, %s", exc)
except Exception:
logger.info(
"Micro-compaction DB sync failed — resume will double-load "
diff --git a/tests/agent/test_micro_compaction.py b/tests/agent/test_micro_compaction.py
index 53947e76170..4da798869fe 100644
--- a/tests/agent/test_micro_compaction.py
+++ b/tests/agent/test_micro_compaction.py
@@ -915,3 +915,31 @@ def test_micro_compaction_keeps_a_turn_another_surface_appended_after_load(tmp_p
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
+
+
+def test_micro_compaction_aborts_when_another_compaction_already_committed(tmp_path):
+ """Micro-compaction holds no compression lease. Once another compaction has committed, the history this
+ process holds is a stale generation; committing it would archive the winner's rows and clone them back
+ beside a second summary. The pass must not run and the store must keep exactly the winning generation."""
+ 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
+ winner = [
+ {"role": "assistant", "content": "[winner summary] questions 0-7"},
+ {"role": "user", "content": "[from Telegram] carry on"},
+ ]
+ db.archive_and_compact("s", winner) # another surface's compaction wins the race
+ cc = _compressor()
+ cc._session_db, cc._session_id = db, "s"
+
+ result = cc._micro_compact(messages)
+
+ assert _summary_markers(result) == [] # the pass did not run
+ live = [str(m["content"]) for m in db.get_messages_as_conversation("s")]
+ assert live == [m["content"] for m in winner] # exactly one live generation
diff --git a/tests/agent/test_proactive_prune_restart_safety.py b/tests/agent/test_proactive_prune_restart_safety.py
index 322af041c6c..006465ed822 100644
--- a/tests/agent/test_proactive_prune_restart_safety.py
+++ b/tests/agent/test_proactive_prune_restart_safety.py
@@ -269,3 +269,28 @@ def test_prune_keeps_a_turn_another_surface_appended_after_load(tmp_path: Path)
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
+
+
+def test_prune_aborts_when_another_compaction_already_committed(tmp_path: Path) -> None:
+ """Prune holds no compression lease. When the history it holds is no longer the live generation (a
+ ``/compress`` from another surface already committed), publishing would archive the winner's rows and
+ clone them back beside a second summary generation. It must leave the input and the store alone."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_STALE_GENERATION"
+ 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
+ winner = [
+ {"role": "user", "content": "start"},
+ {"role": "assistant", "content": "[winner summary] the earlier tool loop"},
+ {"role": "user", "content": "[from Telegram] carry on"},
+ ]
+ db.archive_and_compact(session_id, winner) # another surface's compaction wins the race
+
+ result, count = agent.context_compressor.prune_tool_results_only(held, current_tokens=120_000)
+
+ assert result is held and count == 0
+ live = [message["content"] for message in db.get_messages_as_conversation(session_id)]
+ assert live == [message["content"] for message in winner]