Skip to content

The agent that grows with you

fix(sessions): proactive prune rewrites only the changed rows, in place (#124273)

defurniture202520acba037694
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index d8d01fa9dcd..de049abd7d8 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -32,6 +32,7 @@ from agent.auxiliary_client import (
)
from agent.context_engine import ContextEngine, sanitize_memory_context
from agent.context_compressor_prellm import PreLlmSkipMixin
+from agent.context_compressor_prune import ProactivePruneMixin
from agent.context_compressor_summary import SummaryDispatchMixin
from agent.context_compressor_retry import retryable_user_text
from agent.context_compressor_tail import demote_stale_tail_tools, is_demoted_stub, skill_view_names_by_call_id
@@ -2149,7 +2150,8 @@ Describe agent/tool work only as completed actions, state, or historical work.]"
class ContextCompressor(
- SummaryDispatchMixin, PreLlmSkipMixin, CompressionTelemetryMixin, MicroCompactionMixin, ContextEngine,
+ SummaryDispatchMixin, PreLlmSkipMixin, CompressionTelemetryMixin, MicroCompactionMixin,
+ ProactivePruneMixin, ContextEngine,
):
"""Default context engine: prune tool results, protect head/tail, summarize the middle
with an LLM, and iteratively update the previous summary on later compactions."""
@@ -3390,87 +3392,6 @@ class ContextCompressor(
f"{int(self._proactive_prune_rearm_tokens):,}",
)
- def prune_tool_results_only(
- self, messages: list[dict[str, Any]], current_tokens: int | None = None,
- ) -> tuple[list[dict[str, Any]], int]:
- """Deterministic, no-LLM tool-result prune gated on ``proactive_prune_tokens``.
- Protects the tail by message COUNT only. A commit breaks the prompt cache, so it requires
- ``proactive_prune_min_reclaim_tokens`` and a full regrowth runway; otherwise returns the INPUT
- object as ``(messages, 0)``. The rearm gate is measured on message bodies only, so it is
- bypassed (never the reclaim gate) when a provider-billed ``current_tokens`` reading already
- puts the request over ``threshold_tokens`` (#101889); every no-op taken while over threshold
- is logged once per distinct reason.
-
- ``_prune_old_tool_results`` runs all deterministic passes: (1) dedup byte-identical tool results —
- keeps the newest full copy and back-references older exact duplicates ANYWHERE in the list
- (including the protected tail), so no unique content is ever lost; (2) summarize non-tail tool
- results larger than ``min_prune_chars``; (3) truncate oversized tool_call arguments on non-tail
- assistant messages; (3.5) retire image payloads on all but the newest ``_MAX_KEEP_TOOL_IMAGES``
- image-bearing tool results, except a pending round that fits the hard share (#92699). Only pass (2)'s floor is
- raised by ``proactive_prune_min_result_chars``; passes (1) and (3) keep their own fixed floors. The
- recent-tail protection applies to passes (2) and (3); pass (1) is tail-agnostic by design because
- dedup is lossless.
- """
- if self.proactive_prune_tokens <= 0 or (
- current_tokens is not None and current_tokens < self.proactive_prune_tokens
- ):
- return messages, 0
- if len(messages) <= self.protect_last_n + self._protect_head_size(messages) + 1:
- self._warn_reclamation_no_op("prune:tail_only", current_tokens)
- return messages, 0
- before = sum(_estimate_msg_budget_tokens(m) for m in messages)
- # Under-threshold runway skip is ordinary hysteresis (silent); above it the lockout is the bug.
- if before < self._proactive_prune_rearm_tokens and not self._billed_basis_over_threshold(current_tokens):
- return messages, 0
- # Capability gate first: a store without archive_and_compact makes every prune a no-op.
- session_db = getattr(self, "_session_db", None)
- session_id = getattr(self, "_session_id", "")
- if session_db and session_id and not callable(getattr(session_db, "archive_and_compact", None)):
- self._warn_reclamation_no_op("prune:store_cannot_persist", current_tokens)
- return messages, 0
- pruned_msgs, pruned_count = self._prune_old_tool_results(
- messages, protect_tail_count=self.protect_last_n, protect_tail_tokens=None, min_prune_chars=self.proactive_prune_min_result_chars,
- )
- if not pruned_count:
- # No-op contract: return the INPUT object so callers can gate on `result is not input`.
- self._warn_reclamation_no_op("prune:nothing_eligible", current_tokens)
- return messages, 0
- # Prompt-cache hysteresis: commit only when the reclaim is meaningful.
- after = sum(_estimate_msg_budget_tokens(m) for m in pruned_msgs)
- reclaimed = max(0, before - after)
- if reclaimed < self.proactive_prune_min_reclaim_tokens:
- self._warn_reclamation_no_op("prune:reclaim_below_minimum", current_tokens, before=before)
- return messages, 0
- # Require a full trigger-sized regrowth before the next cache-breaking rewrite.
- 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:
- from agent.conversation_compression_archive import coverage_for_commit
- covered_ids, unresolved_held = coverage_for_commit(session_db, session_id, messages)
- 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),
- covered_ids=covered_ids, unresolved_held=unresolved_held,
- )
- 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
- except Exception as exc:
- logger.warning("Proactive tool-result prune DB commit failed; keeping the original transcript: %s", exc)
- return messages, 0
- # Shared post-commit stamp site with the in-place commit and micro-compaction sync.
- # See #98450.
- stamp_db_persisted_markers(pruned_msgs)
- self._proactive_prune_rearm_tokens = next_rearm_tokens
- # Reclamation just ran: let a future lockout warn again.
- self._last_reclaim_block_warn = None
- return pruned_msgs, pruned_count
-
def _compute_summary_budget(self, turns_to_summarize: list[dict[str, Any]]) -> int:
"""Scale the summary token budget with content size and context window."""
content_tokens = estimate_messages_tokens_rough(turns_to_summarize)
diff --git a/agent/context_compressor_prune.py b/agent/context_compressor_prune.py
new file mode 100644
index 00000000000..505f40dc255
--- /dev/null
+++ b/agent/context_compressor_prune.py
@@ -0,0 +1,180 @@
+"""The proactive tool-result prune: deterministic passes plus the in-place row commit (#124102).
+
+Split out of :mod:`agent.context_compressor` (FILE_LINES ratchet): the prune is a self-contained
+reclamation feature. The origin module keeps the ``ContextCompressor`` class; this sibling owns
+``prune_tool_results_only`` and its in-place commit helper. Log name parity with the origin
+module, and every origin-module symbol is read through ``_cc()`` at call time so tests that patch
+``agent.context_compressor.X`` stay effective.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Optional
+
+logger = logging.getLogger("agent.context_compressor")
+
+
+def _cc():
+ """The origin module, resolved lazily: avoids the import cycle and keeps tests that patch
+ ``agent.context_compressor.X`` effective (attributes are read at call time)."""
+ from agent import context_compressor
+ return context_compressor
+
+
+class ProactivePruneMixin:
+ """``ContextCompressor`` mixin: the deterministic, no-LLM tool-result prune and its commit."""
+
+ def prune_tool_results_only(
+ self, messages: list[dict[str, Any]], current_tokens: int | None = None,
+ ) -> tuple[list[dict[str, Any]], int]:
+ """Deterministic, no-LLM tool-result prune gated on ``proactive_prune_tokens``.
+
+ Protects the tail by message COUNT only. A commit breaks the prompt cache, so it requires
+ ``proactive_prune_min_reclaim_tokens`` and a full regrowth runway; otherwise returns the INPUT
+ object as ``(messages, 0)``. The rearm gate is measured on message bodies only, so it is
+ bypassed (never the reclaim gate) when a provider-billed ``current_tokens`` reading already
+ puts the request over ``threshold_tokens`` (#101889); every no-op taken while over threshold
+ is logged once per distinct reason.
+
+ ``_prune_old_tool_results`` runs all deterministic passes: (1) dedup byte-identical tool results —
+ keeps the newest full copy and back-references older exact duplicates ANYWHERE in the list
+ (including the protected tail), so no unique content is ever lost; (2) summarize non-tail tool
+ results larger than ``min_prune_chars``; (3) truncate oversized tool_call arguments on non-tail
+ assistant messages; (3.5) retire image payloads on all but the newest ``_MAX_KEEP_TOOL_IMAGES``
+ image-bearing tool results, except a pending round that fits the hard share (#92699). Only pass (2)'s floor is
+ raised by ``proactive_prune_min_result_chars``; passes (1) and (3) keep their own fixed floors. The
+ recent-tail protection applies to passes (2) and (3); pass (1) is tail-agnostic by design because
+ dedup is lossless.
+ """
+ if self.proactive_prune_tokens <= 0 or (
+ current_tokens is not None and current_tokens < self.proactive_prune_tokens
+ ):
+ return messages, 0
+ if len(messages) <= self.protect_last_n + self._protect_head_size(messages) + 1:
+ self._warn_reclamation_no_op("prune:tail_only", current_tokens)
+ return messages, 0
+ _estimate_msg_budget_tokens = _cc()._estimate_msg_budget_tokens
+ before = sum(_estimate_msg_budget_tokens(m) for m in messages)
+ # Under-threshold runway skip is ordinary hysteresis (silent); above it the lockout is the bug.
+ if before < self._proactive_prune_rearm_tokens and not self._billed_basis_over_threshold(current_tokens):
+ return messages, 0
+ # Capability gate first: a store without archive_and_compact makes every prune a no-op.
+ session_db = getattr(self, "_session_db", None)
+ session_id = getattr(self, "_session_id", "")
+ if session_db and session_id and not callable(getattr(session_db, "archive_and_compact", None)):
+ self._warn_reclamation_no_op("prune:store_cannot_persist", current_tokens)
+ return messages, 0
+ pruned_msgs, pruned_count = self._prune_old_tool_results(
+ messages, protect_tail_count=self.protect_last_n, protect_tail_tokens=None, min_prune_chars=self.proactive_prune_min_result_chars,
+ )
+ if not pruned_count:
+ # No-op contract: return the INPUT object so callers can gate on `result is not input`.
+ self._warn_reclamation_no_op("prune:nothing_eligible", current_tokens)
+ return messages, 0
+ # Prompt-cache hysteresis: commit only when the reclaim is meaningful.
+ after = sum(_estimate_msg_budget_tokens(m) for m in pruned_msgs)
+ reclaimed = max(0, before - after)
+ if reclaimed < self.proactive_prune_min_reclaim_tokens:
+ self._warn_reclamation_no_op("prune:reclaim_below_minimum", current_tokens, before=before)
+ return messages, 0
+ # Require a full trigger-sized regrowth before the next cache-breaking rewrite.
+ runway = max(reclaimed, self.proactive_prune_tokens, self.proactive_prune_min_reclaim_tokens)
+ next_rearm_tokens = after + runway
+ if session_db and session_id:
+ _cc_ = _cc()
+ from hermes_state_errors import HeldRowRewrittenError
+ model_config_patch = {_cc_.PROACTIVE_PRUNE_REARM_MODEL_CONFIG_KEY: next_rearm_tokens}
+ StaleHeldHistory = _cc_.StaleHeldHistory
+ _DB_PERSISTED_MARKER = _cc_._DB_PERSISTED_MARKER
+ rewritten = None
+ try:
+ # Raises StaleHeldHistory when another compaction already won, for both commit paths.
+ watermark = _cc_._archive_watermark_for(session_db, session_id, messages)
+ rewritten = self._rewrite_pruned_rows_in_place(
+ session_db, session_id, messages, pruned_msgs, model_config_patch)
+ if rewritten is None:
+ from agent.conversation_compression_archive import coverage_for_commit
+ covered_ids, unresolved_held = coverage_for_commit(session_db, session_id, messages)
+ session_db.archive_and_compact(
+ session_id, pruned_msgs,
+ model_config_patch=model_config_patch,
+ watermark=watermark,
+ covered_ids=covered_ids, unresolved_held=unresolved_held,
+ held_for_cas=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
+ except HeldRowRewrittenError:
+ # The full writer's in-transaction CAS fence tripped: a held row changed between the
+ # precheck and the commit. Same disposition as StaleHeldHistory — nothing was written.
+ logger.info("Proactive tool-result prune skipped: a held row was rewritten in place before the commit")
+ self._warn_reclamation_no_op("prune:stale_generation", current_tokens, before=before)
+ return messages, 0
+ except Exception as exc: # health: allow BLE001 -- the commit boundary keeps the original transcript on any store failure (#124102)
+ logger.warning("Proactive tool-result prune DB commit failed; keeping the original transcript: %s", exc)
+ return messages, 0
+ # Shared post-commit stamp site with the in-place commit and micro-compaction sync.
+ # See #98450. The in-place rewrite wrote no new rows, so only already-durable messages
+ # carry the marker; unwritten ones reach the DB through the next flush.
+ stamp_db_persisted_markers = _cc_.stamp_db_persisted_markers
+ if rewritten is None:
+ stamp_db_persisted_markers(pruned_msgs)
+ else:
+ stamp_db_persisted_markers([
+ replacement for original, replacement in zip(messages, pruned_msgs)
+ if original.get(_DB_PERSISTED_MARKER)])
+ self._proactive_prune_rearm_tokens = next_rearm_tokens
+ # Reclamation just ran: let a future lockout warn again.
+ self._last_reclaim_block_warn = None
+ return pruned_msgs, pruned_count
+
+ def _rewrite_pruned_rows_in_place(
+ self, session_db: Any, session_id: str, messages: list[dict[str, Any]],
+ pruned_msgs: list[dict[str, Any]], model_config_patch: dict[str, Any],
+ ) -> Optional[int]:
+ """Commit a prune by rewriting only its changed rows (#124102); ``None`` means use the full rewrite.
+
+ A prune edits the content of a few existing messages and never adds, drops or reorders one, so the
+ durable rows it touched can be updated where they are. That needs a store with
+ ``rewrite_pruned_rows`` and unwritten messages only at the end (the next flush appends those in
+ order; one sitting before durable rows would land out of order). A row the store cannot name
+ exactly also falls back: ``archive_and_compact`` handles every shape. A row it *can* name whose
+ stored body changed is not ambiguity but a lost race, and raises ``StaleHeldHistory`` so the
+ caller skips the pass rather than republishing the held generation.
+ """
+ rewrite = getattr(session_db, "rewrite_pruned_rows", None)
+ if not callable(rewrite) or len(messages) != len(pruned_msgs):
+ return None
+ from hermes_state_errors import PruneRowStaleError, PruneRowUnresolvedError
+
+ _DB_PERSISTED_MARKER = _cc()._DB_PERSISTED_MARKER
+ ignored = {_DB_PERSISTED_MARKER, "_row_id"}
+ changes: list[tuple] = []
+ unwritten_seen = False
+ for original, replacement in zip(messages, pruned_msgs):
+ if not isinstance(original, dict) or not isinstance(replacement, dict):
+ return None
+ if not original.get(_DB_PERSISTED_MARKER):
+ unwritten_seen = True
+ continue
+ if unwritten_seen:
+ return None
+ if ({k: v for k, v in original.items() if k not in ignored}
+ != {k: v for k, v in replacement.items() if k not in ignored}):
+ changes.append((original, replacement))
+ try:
+ return rewrite(session_id, changes, model_config_patch=model_config_patch)
+ except PruneRowStaleError as exc:
+ # A named row whose stored body changed is another writer's generation, which is exactly
+ # what StaleHeldHistory exists to catch — the in-place prune preserved the row ids, so
+ # _archive_watermark_for could not see it. Falling back would hand this stale transcript to
+ # archive_and_compact, which archives rows it never compared and republishes the held text
+ # over the newer one. Fail closed; the caller skips the pass.
+ raise _cc().StaleHeldHistory(str(exc)) from exc
+ except PruneRowUnresolvedError as exc:
+ logger.info("Proactive prune: in-place rewrite refused (%s); using the full rewrite", exc)
+ return None
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 81f9ab1bcbd..b265ca006bd 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -43,6 +43,7 @@ from agent.session_activity import ActivityProvenance, normalize_activity_proven
from agent.usage_anchor import set_usage_anchor
from hermes_state_ids import new_session_id as mint_session_id
from hermes_state_pidns import holder_namespace_token
+from agent.conversation_compression_watermark import held_archive_watermark
logger = logging.getLogger(__name__)
@@ -3556,63 +3557,6 @@ def _held_watermark(agent: Any, watermark: Optional[int], messages: list, verbat
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,
- *, stale_raises: bool = False,
-) -> 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`` 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 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.
-
- *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, StaleHeldHistory
-
- 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:
- return watermark
- newest_held = max(held)
- # A lease-less caller checks liveness even when nothing was appended: a commit-time re-check against a
- # watermark read before the slow step never sees newest_held < watermark, yet the winner may have landed.
- if newest_held >= watermark and not stale_raises:
- 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 min(newest_held, watermark)
-
-
_ATTEMPT_TELEMETRY_FIELDS = (
"_last_compression_telemetry", "_active_compression_telemetry", "_compression_telemetry_seed",
)
diff --git a/agent/conversation_compression_watermark.py b/agent/conversation_compression_watermark.py
new file mode 100644
index 00000000000..f1324ba5de5
--- /dev/null
+++ b/agent/conversation_compression_watermark.py
@@ -0,0 +1,89 @@
+"""The held-row watermark cap and its lease-less staleness gate (#124102).
+
+Split out of :mod:`agent.conversation_compression` (FILE_LINES ratchet): the watermark math the
+in-place compaction commit, the proactive prune and micro-compaction share. The origin module
+imports :func:`held_archive_watermark` from here; ``_held_watermark`` (the agent-bound wrapper)
+stays with its only caller in the origin module's commit path.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+
+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.
+
+ 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`` 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 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.
+
+ *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. It also catches the
+ generation change an id/activity check cannot see: an in-place prune rewrites a row's body under its
+ own id, so ``stale_raises`` additionally compares each exact persisted held row against its stored
+ payload (through the store's row-version CAS / loader-lens compare — never raw storage bytes against
+ a loaded view). That comparison runs for every exact persisted held row, so an unstamped trailing
+ message (which caps the watermark through the early return below) cannot suppress it for the durable
+ prefix.
+ """
+ if watermark is None:
+ return None
+ from agent.context_compressor import _DB_PERSISTED_MARKER, StaleHeldHistory
+
+ 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 stale_raises and held:
+ # An IN-PLACE commit (the proactive prune) keeps every row id and activity flag, so the liveness
+ # check below cannot see it. The stored payloads are the only trace: a held row whose active row
+ # now holds something else belongs to a generation this caller never saw, and publishing the held
+ # copy would republish the pre-rewrite text over the winner (#124102). Runs before the
+ # trailing-row early return: an unstamped trailing message may cap the watermark, but it must not
+ # suppress the version check for the durable prefix this caller does hold exactly.
+ rewritten_of = getattr(session_db, "rewritten_held_row_ids", None)
+ if callable(rewritten_of):
+ rewritten = rewritten_of(session_id, [
+ m for m in messages
+ if isinstance(m, dict) and _exact_id(m, False) is not None])
+ if rewritten:
+ raise StaleHeldHistory(
+ f"held row {min(rewritten)} of session {session_id} was rewritten in place")
+ if not ids or ids[-1] is None:
+ return watermark
+ newest_held = max(held)
+ # A lease-less caller checks liveness even when nothing was appended: a commit-time re-check against a
+ # watermark read before the slow step never sees newest_held < watermark, yet the winner may have landed.
+ if newest_held >= watermark and not stale_raises:
+ 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 min(newest_held, watermark)
diff --git a/agent/micro_compaction.py b/agent/micro_compaction.py
index 42cad0c2d82..ae03e83bc37 100644
--- a/agent/micro_compaction.py
+++ b/agent/micro_compaction.py
@@ -416,6 +416,7 @@ class MicroCompactionMixin:
session_db, session_id = getattr(self, "_session_db", None), getattr(self, "_session_id", "")
if not session_db or not session_id:
return True
+ from hermes_state_errors import HeldRowRewrittenError
try:
# Micro-compaction is prefix + marker + suffix, not a contiguous tail. Identify the exact
# byte-identical originals by their persistence marker; the state transaction resolves each
@@ -434,7 +435,8 @@ class MicroCompactionMixin:
covered_ids, unresolved_held = coverage_for_commit(session_db, session_id, held)
session_db.archive_and_compact(
session_id, compacted_messages, carried_messages=carried_messages, watermark=watermark,
- covered_ids=covered_ids, unresolved_held=unresolved_held)
+ covered_ids=covered_ids, unresolved_held=unresolved_held,
+ held_for_cas=held)
# Shared post-commit stamp site with batch commit and proactive prune.
# See #98450.
_cc().stamp_db_persisted_markers(compacted_messages)
@@ -444,6 +446,11 @@ class MicroCompactionMixin:
# and summary); otherwise finalize_turn would append the unmarked summary row beside the winner.
logger.info("Micro-compaction commit skipped, %s", exc)
return False
+ except HeldRowRewrittenError as exc:
+ # The in-transaction CAS fence tripped: a held row changed between the precheck and the
+ # commit. Same disposition as a stale generation — nothing written, the pass is discarded.
+ logger.info("Micro-compaction commit skipped, %s", exc)
+ return False
except Exception:
logger.info(
"Micro-compaction DB sync failed — resume will double-load "
diff --git a/agent/runtime_session_compression.py b/agent/runtime_session_compression.py
index c20bfe61e3e..4f77b9e41b8 100644
--- a/agent/runtime_session_compression.py
+++ b/agent/runtime_session_compression.py
@@ -66,17 +66,25 @@ class RuntimeSessionCompressionMixin:
def archive_and_compact(self, session_id, compacted_messages, model_config_patch=None,
watermark=None, lock_holder=None, tail_count=0, carried_messages=None,
- covered_ids=None, unresolved_held=None):
+ covered_ids=None, unresolved_held=None, held_for_cas=None):
self._session(session_id)
# A carried message names an exact durable original (its _row_id) to rewind rather than
# archive (#118900); the owner resolves identities against its own store. Held-row
# coverage travels the same way: the owner proves it inside the commit transaction.
carried = [dict(m) for m in carried_messages or [] if isinstance(m, dict)]
unresolved = None if unresolved_held is None else [dict(m) for m in unresolved_held if isinstance(m, dict)]
+ # The lease-less staleness fence (#124102): the owner re-verifies the caller's held rows
+ # inside its commit transaction. The projection keeps the closed handoff fields plus the
+ # persistence marker the CAS compare reads; anything else stays worker-local.
+ from hermes_state_runtime import HANDOFF_MESSAGE_FIELDS
+ cas = None if held_for_cas is None else [
+ {k: v for k, v in m.items()
+ if k in HANDOFF_MESSAGE_FIELDS or k == '_db_persisted'}
+ for m in held_for_cas if isinstance(m, dict)]
result = self._apply('compression.archive', dict(messages=_handoff_rows(compacted_messages),
model_config_patch=model_config_patch, watermark=watermark, lock_holder=lock_holder,
tail_count=tail_count, carried_messages=carried, covered_ids=covered_ids,
- unresolved_held=unresolved))
+ unresolved_held=unresolved, held_for_cas=cas))
from agent.runtime_session_store import apply_row_annotations
apply_row_annotations(compacted_messages, result['annotations'])
return result['value']
diff --git a/hermes_state.py b/hermes_state.py
index 761c0cdd9dd..833f4b738f4 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -67,6 +67,8 @@ from hermes_state_dbfile import (
RetiredGenerationCaptureError, capture_retired_wal_generation, refuse_deleted_wal_generation,
)
from hermes_state_messages import SessionMessagesMixin
+from hermes_state_prune_rewrite import SessionPruneRewriteMixin
+from hermes_state_api_content import SessionApiContentMixin
from hermes_state_coverage import SessionCoverageMixin
from hermes_state_rewind import SessionRewindMixin
from hermes_state_wal import (
@@ -462,7 +464,7 @@ class SessionDB(
SessionSessionsMixin, SessionFtsSetupMixin, SessionSearchMixin, SessionSchemaMixin,
SessionPortabilityMixin, SessionTelegramTopicsMixin, SessionCompressionMixin,
SessionGatewayMixin, SessionMaintenanceMixin, SessionUsageMixin, SessionTitlesMixin,
- SessionMessagesMixin, SessionCoverageMixin, SessionRewindMixin, SessionProfileRepairMixin,
+ SessionMessagesMixin, SessionPruneRewriteMixin, SessionApiContentMixin, SessionCoverageMixin, SessionRewindMixin, SessionProfileRepairMixin,
):
"""SQLite-backed session storage with FTS5 search; many reader threads, one writer (WAL)."""
diff --git a/hermes_state_api_content.py b/hermes_state_api_content.py
new file mode 100644
index 00000000000..50cb6ed2369
--- /dev/null
+++ b/hermes_state_api_content.py
@@ -0,0 +1,67 @@
+"""The ``api_content`` sidecar backfill writers for SessionDB (#124102 FILE_LINES split).
+
+Split out of :mod:`hermes_state_messages`: the two row-addressed sidecar UPDATEs the turn prologue
+uses when the current turn's user row was materialized before the sidecar could be composed. Bound
+into ``SessionDB`` via this mixin, so every existing ``session_db.set_message_api_content(...)``
+call site and test patch seam keeps working unchanged.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+class SessionApiContentMixin:
+ """``SessionDB`` mixin: the ``api_content`` sidecar backfills."""
+
+ def set_latest_user_api_content(self, session_id: str, content: Any, api_content: str) -> int:
+ """Backfill the ``api_content`` sidecar onto the newest ACTIVE user row (0/1 rows). Preflight compaction
+ inserts that row BEFORE the sidecar exists and the later persist identity-skips compacted dicts;
+ without this a reload reopens the prompt-cache divergence. ``content`` match guards a racing rewrite.
+
+ POSITIONAL, and only safe when the caller already knows the newest
+ active user row IS the message it stamped. The content match is NOT
+ sufficient on its own: repeated identical user turns ("ok", "y",
+ "continue") make an OLDER row compare equal, so calling this before
+ the current turn's row exists overwrites the previous turn's sidecar
+ with this turn's bytes — durable wrong-bytes replay, a worse cache
+ break than the missing sidecar. When the caller holds the durable row
+ id (``_row_id``, synced onto the live dict by
+ ``sync_flushed_message_markers`` and stamped by
+ :meth:`_insert_message_rows`), use :meth:`set_message_api_content`
+ instead — it addresses the exact row and cannot land on a neighbour.
+ """
+ from hermes_state_messages import _scrub_surrogates
+ return self._write_rowcount(
+ "UPDATE messages SET api_content = ? WHERE id = (SELECT id FROM messages "
+ "WHERE session_id = ? AND role = 'user' AND active = 1 ORDER BY id DESC LIMIT 1"
+ ") AND content IS ?",
+ (_scrub_surrogates(api_content), session_id, self._encode_content(content)))
+
+ def set_message_api_content(
+ self, session_id: str, row_id: int, content: Any, api_content: str
+ ) -> int:
+ """Backfill the ``api_content`` sidecar onto ONE known durable row.
+
+ Row-addressed counterpart to :meth:`set_latest_user_api_content`: the
+ caller passes the ``_row_id`` the write path stamped on the live
+ message dict, so the update cannot drift onto a neighbouring row that
+ merely carries the same text.
+
+ Used by the turn prologue whenever the current turn's user row was
+ already materialized before the sidecar could be composed (in-place
+ preflight compaction, a close/early flush that raced the prologue).
+ The crash persist then marker-skips that message, so this is the only
+ way the stamped bytes reach the store.
+
+ ``active = 1`` and the ``content`` match stay as defensive guards: a
+ row the compaction archived, or one a racing rewrite changed, is left
+ untouched.
+ """
+ from hermes_state_messages import _scrub_surrogates
+ if not session_id or isinstance(row_id, bool) or not isinstance(row_id, int) or row_id <= 0:
+ return 0
+ return self._write_rowcount(
+ "UPDATE messages SET api_content = ? WHERE id = ? AND session_id = ? "
+ "AND role = 'user' AND active = 1 AND content IS ?",
+ (_scrub_surrogates(api_content), row_id, session_id, self._encode_content(content)))
diff --git a/hermes_state_errors.py b/hermes_state_errors.py
index 8ee7a76885e..7019c6c6e16 100644
--- a/hermes_state_errors.py
+++ b/hermes_state_errors.py
@@ -166,6 +166,27 @@ class SessionCompressionInProgressError(CompressionSessionBusyError):
fail fast). Subclassing keeps every existing handler working."""
+class PruneRowUnresolvedError(RuntimeError):
+ """An in-place prune rewrite could not name the exact live row of a changed message. Raised before
+ any write, so the caller commits through ``archive_and_compact`` instead."""
+
+
+class PruneRowStaleError(PruneRowUnresolvedError):
+ """The named live row no longer holds the body the pruner is pruning: another writer already
+ rewrote this generation. Unlike plain ambiguity this must NOT fall back to the full writer —
+ that writer archives rows it never compared and would republish the stale held text over the
+ newer one. Subclassing keeps callers that only know the parent failing closed-enough (they stop
+ the in-place path); the prune caller tells the two apart and skips the pass entirely."""
+
+
+class HeldRowRewrittenError(RuntimeError):
+ """A full-writer commit found one of the held rows it was about to archive already rewritten in
+ place by another writer. Raised INSIDE the commit's write transaction, after the caller's
+ precheck but before any row is archived: a write that lands in that window is exactly the lost
+ race the precheck cannot see (#124102). Callers treat it like ``StaleHeldHistory`` — nothing
+ written, the pass is a no-op and the newer generation keeps the session."""
+
+
class SessionTurnLeaseLostError(RuntimeError):
"""A transcript write presented a turn-lease holder that no longer owns it.
Fail-fast fencing (no ``_execute_write`` retry): a later writer may already
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index 86554d4c46f..0417e17d955 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -899,7 +899,8 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):
lock_holder: Optional[str] = None, tail_count: int = 0,
carried_messages: Optional[list[dict[str, Any]]] = None,
covered_ids: Optional[list[int]] = None,
- unresolved_held: Optional[list[dict[str, Any]]] = None) -> int:
+ unresolved_held: Optional[list[dict[str, Any]]] = None,
+ held_for_cas: Optional[list[dict[str, Any]]] = None) -> int:
"""Non-destructive in-place compaction under ONE session id: soft-archive the active rows (``active=0,
compacted=1``: summarized away, still searchable) and insert *compacted_messages* as fresh active
rows, atomically; returns the new ACTIVE count (= ``message_count``). *watermark* (compression
@@ -915,6 +916,11 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):
They are resolved inside this transaction by row id when present, else by unique durable identity +
timestamp. Those originals and the clones' originals are superseded duplicates and get rewind flags
(``active=0, compacted=0``) so search doesn't return each carried message once per compaction.
+ ``held_for_cas``: the caller's held message dicts for the lease-less staleness gate — re-verified
+ against the live rows INSIDE this transaction (see :meth:`held_row_mismatches`), so a rewrite that
+ lands after the caller's precheck aborts the commit as :class:`HeldRowRewrittenError` before any
+ row is archived (#124102). The lease path leaves it ``None``: its lease rules out an overlapping
+ rewrite, and the turn's own writes are the ones a CAS here would misread.
``model_config_patch`` merges in the same txn (``None`` removes a key).
Concurrent-append safety (#75316): when *watermark* is provided (the value of
@@ -928,7 +934,8 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):
return self._execute_transcript_write(lambda conn: self._archive_and_compact_on_conn(
conn, session_id, compacted_messages, model_config_patch=model_config_patch,
watermark=watermark, lock_holder=lock_holder, tail_count=tail_count,
- carried_messages=carried_messages, covered_ids=covered_ids, unresolved_held=unresolved_held), compacted_messages)
+ carried_messages=carried_messages, covered_ids=covered_ids,
+ unresolved_held=unresolved_held, held_for_cas=held_for_cas), compacted_messages)
def _archive_and_compact_on_conn(
self, conn, session_id: str, compacted_messages: list[dict[str, Any]], *,
@@ -936,7 +943,8 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):
lock_holder: Optional[str] = None, tail_count: int = 0,
carried_messages: Optional[list[dict[str, Any]]] = None,
covered_ids: Optional[list[int]] = None,
- unresolved_held: Optional[list[dict[str, Any]]] = None) -> int:
+ unresolved_held: Optional[list[dict[str, Any]]] = None,
+ held_for_cas: Optional[list[dict[str, Any]]] = None) -> int:
""":meth:`archive_and_compact` on the caller's write transaction (never commits). The owner
and the worker/canonical-mutation verbs share this one body so they cannot drift."""
from hermes_state import SessionCompressionInProgressError
@@ -949,6 +957,16 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):
# on_missing="raise": never commit against a vanished session row (caller keeps the original).
patched_model_config = self._merge_model_config_json(
conn, session_id, model_config_patch, on_missing="raise") if patch else None
+ # The in-transaction half of the lease-less staleness gate (#124102): the caller's
+ # rewritten_held_row_ids precheck runs outside the write lock, so a concurrent in-place
+ # rewrite landing between precheck and BEGIN IMMEDIATE was archived and its stale held
+ # body republished. Re-verify on the connection this commit holds, before any row moves.
+ if held_for_cas:
+ mismatches = getattr(self, "held_row_mismatches", None)
+ if callable(mismatches) and mismatches(conn, session_id, held_for_cas):
+ from hermes_state_errors import HeldRowRewrittenError
+ raise HeldRowRewrittenError(
+ f"a held row of session {session_id} was rewritten in place before the commit")
proved = self._proved_coverage(conn, session_id, covered_ids, unresolved_held, watermark)
if proved is not None:
return self._archive_named_rows(
@@ -1000,56 +1018,6 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):
self._message_columns_cache = [r[1] for r in conn.execute("PRAGMA table_info(messages)").fetchall()]
return self._message_columns_cache
- def set_latest_user_api_content(self, session_id: str, content: Any, api_content: str) -> int:
- """Backfill the ``api_content`` sidecar onto the newest ACTIVE user row (0/1 rows). Preflight compaction
- inserts that row BEFORE the sidecar exists and the later persist identity-skips compacted dicts;
- without this a reload reopens the prompt-cache divergence. ``content`` match guards a racing rewrite.
-
- POSITIONAL, and only safe when the caller already knows the newest
- active user row IS the message it stamped. The content match is NOT
- sufficient on its own: repeated identical user turns ("ok", "y",
- "continue") make an OLDER row compare equal, so calling this before
- the current turn's row exists overwrites the previous turn's sidecar
- with this turn's bytes — durable wrong-bytes replay, a worse cache
- break than the missing sidecar. When the caller holds the durable row
- id (``_row_id``, synced onto the live dict by
- ``sync_flushed_message_markers`` and stamped by
- :meth:`_insert_message_rows`), use :meth:`set_message_api_content`
- instead — it addresses the exact row and cannot land on a neighbour.
- """
- return self._write_rowcount(
- "UPDATE messages SET api_content = ? WHERE id = (SELECT id FROM messages "
- "WHERE session_id = ? AND role = 'user' AND active = 1 ORDER BY id DESC LIMIT 1"
- ") AND content IS ?",
- (_scrub_surrogates(api_content), session_id, self._encode_content(content)))
-
- def set_message_api_content(
- self, session_id: str, row_id: int, content: Any, api_content: str
- ) -> int:
- """Backfill the ``api_content`` sidecar onto ONE known durable row.
-
- Row-addressed counterpart to :meth:`set_latest_user_api_content`: the
- caller passes the ``_row_id`` the write path stamped on the live
- message dict, so the update cannot drift onto a neighbouring row that
- merely carries the same text.
-
- Used by the turn prologue whenever the current turn's user row was
- already materialized before the sidecar could be composed (in-place
- preflight compaction, a close/early flush that raced the prologue).
- The crash persist then marker-skips that message, so this is the only
- way the stamped bytes reach the store.
-
- ``active = 1`` and the ``content`` match stay as defensive guards: a
- row the compaction archived, or one a racing rewrite changed, is left
- untouched.
- """
- if not session_id or isinstance(row_id, bool) or not isinstance(row_id, int) or row_id <= 0:
- return 0
- return self._write_rowcount(
- "UPDATE messages SET api_content = ? WHERE id = ? AND session_id = ? "
- "AND role = 'user' AND active = 1 AND content IS ?",
- (_scrub_surrogates(api_content), row_id, session_id, self._encode_content(content)))
-
def set_user_message_content(self, session_id: str, row_id: int, content: Any) -> int:
"""Rewrite the content of ONE known active user row. Used when a user turn was written at submit
time (before the agent ran) and the turn prologue then rewrote the prompt it persists (@-file
@@ -1202,7 +1170,10 @@ class SessionMessagesMixin(SessionDetachedResultsMixin, SessionTodoResultMixin):
for row in rows:
last_id = row["id"]
identity = self._display_identity(self._display_dedupe_key(row))
- order = first_id.setdefault(identity, last_id)
+ # A row already holding this identity keeps its stored slot (an in-place prune changes a
+ # row's content, not its place); otherwise the slot is the identity's first row.
+ kept = row["display_order"] if row["display_identity"] == identity else None
+ order = first_id.setdefault(identity, last_id if kept is None else kept)
if order != row["display_order"] or identity != row["display_identity"]:
updates.append((order, identity, last_id))
rows.close()
diff --git a/hermes_state_prune_rewrite.py b/hermes_state_prune_rewrite.py
new file mode 100644
index 00000000000..7a5884dc8f2
--- /dev/null
+++ b/hermes_state_prune_rewrite.py
@@ -0,0 +1,267 @@
+"""In-place row-rewrite persistence for the proactive prune (#124102).
+
+Split out of :mod:`hermes_state_messages` (FILE_LINES ratchet): the prune's own commit primitive and
+its lease-less staleness probe. Both are ``SessionMessagesMixin`` methods; this sibling defines a
+``SessionPruneRewriteMixin`` the facade binds into the same MRO slot, so every existing
+``session_db.rewrite_pruned_rows(...)`` / ``rewritten_held_row_ids(...)`` call site and test patch
+seam keeps working unchanged.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+from agent.context_compressor import _DB_PERSISTED_MARKER as _DB_PERSISTED_MARKER_KEY
+from agent.message_metadata import DB_ROW_SNAPSHOT
+from hermes_state_common import _id_chunks, _placeholders
+from hermes_state_messages import _INSERT_MESSAGE_SQL, _parse_tool_calls
+
+# _INSERT_MESSAGE_SQL's columns in bind order, so a row rewrite can diff _message_row_params by name.
+_MESSAGE_ROW_COLUMNS = tuple(
+ column.strip() for column in _INSERT_MESSAGE_SQL.split("(", 1)[1].split(")", 1)[0].split(","))
+# A prune only changes what a message says; who said it, when, and in which row never move.
+_PRUNE_FIXED_COLUMNS = frozenset({"session_id", "role", "tool_call_id", "timestamp", "active", "display_identity"})
+
+
+class SessionPruneRewriteMixin:
+ """``SessionDB`` mixin: the proactive prune's in-place row rewrite and held-row staleness probe."""
+
+ def rewritten_held_row_ids(self, session_id: str, held: list[dict[str, Any]]) -> list[int]:
+ """Ids among *held* message dicts whose ACTIVE row no longer holds the payload the dict holds.
+
+ An in-place commit (the proactive prune's ``rewrite_pruned_rows``) changes what a row says and
+ keeps its id and its ``active`` flag, so an id/activity staleness check cannot see it. A lease-less
+ writer holding the pre-rewrite bodies must not publish them: that archives rows it never compared
+ and republishes the stale text over the newer generation (#124102).
+
+ The comparison is representation-safe, never raw storage against a loaded view. A dict's content
+ passed through the loader lens (``_loaded_view_content`` sanitizes and strips user/assistant
+ strings), so the stored bytes are compared through the same lens; when the dict carries the
+ stored-row CAS digest (``DB_ROW_SNAPSHOT``, see ``agent.transcript_repair``) that wins instead,
+ covering every owned column including assistant ``tool_calls`` arguments. Absent or inactive
+ rows are NOT reported — that is the activity check's job and it has its own fallback rules.
+ Every model-transcript role is compared (user/assistant/tool): the callers gate the FULL
+ writer (``archive_and_compact`` via the prune fallback and micro-compaction), which re-inserts
+ held rows of those roles verbatim — a concurrently rewritten user row (``set_user_message_content``,
+ the repair batch's in-place rewrite) is as much a lost race as a rewritten tool result (#124102).
+ Bookkeeping roles (``session_meta``/``system``) never reach the model-facing list and stay excluded.
+ """
+ return self._read_retrying_ioerr(
+ lambda conn: self.held_row_mismatches(conn, session_id, held))
+
+ def held_row_mismatches(self, conn, session_id: str, held: list[dict[str, Any]]) -> list[int]:
+ """``rewritten_held_row_ids`` against *conn*: the same CAS compare, on a connection the
+ caller already holds (inside a ``BEGIN IMMEDIATE``, the full writer's commit window — a
+ precheck outside that lock misses a write that lands between check and commit, and the
+ full writer would then archive that newer row and republish the stale held text, #124102).
+
+ Chunked like ``stamp_inserted_row_snapshots``: one ``id IN (...)`` per ``_id_chunks`` batch,
+ so a long history stays under SQLite's host-parameter limit instead of failing the pass.
+ Rows without an exact ``_row_id`` but with both the persist marker and a CAS snapshot are
+ resolved by their logical ``message_uid`` (``idx_messages_session_uid``): the unaddressed
+ live-replay loaders stamp exactly that pair, and a rewritten-in-place row is as lost a race
+ there as a row-addressed one (#124102).
+ """
+ from agent.message_metadata import message_uid_or_none
+ from agent.transcript_repair import transcript_row_snapshot
+
+ def _exact_id(message: dict[str, Any]) -> Optional[int]:
+ rid = message.get("_row_id")
+ if isinstance(rid, int) and not isinstance(rid, bool) and rid > 0:
+ return rid
+ return None
+
+ exact = [
+ (message, _exact_id(message))
+ for message in held
+ if isinstance(message, dict) and message.get(_DB_PERSISTED_MARKER_KEY)
+ and message.get("role") in ("user", "assistant", "tool")]
+ by_id = {row_id: message for message, row_id in exact if row_id is not None}
+ # The unaddressed replay shape: snapshot + marker, no _row_id. Only rows the caller can
+ # name with durable identity join the fence; anything else keeps the loader-lens behavior
+ # of the activity check (absence of evidence is not permission to publish, but a dict the
+ # store cannot name at all has always belonged to the caller's fallback rules).
+ by_uid = {}
+ for message, row_id in exact:
+ if row_id is None and isinstance(message.get(DB_ROW_SNAPSHOT), str):
+ uid = message_uid_or_none(message)
+ if uid is not None:
+ by_uid[uid] = message
+ if not session_id or not (by_id or by_uid):
+ return []
+ stored: dict[int, Any] = {}
+ for chunk in _id_chunks(by_id):
+ for row in conn.execute(
+ f"SELECT * FROM messages WHERE session_id = ? AND id IN ({_placeholders(chunk)})",
+ (session_id, *chunk)).fetchall():
+ stored[int(row["id"])] = row
+ by_uid_row: dict[str, Any] = {}
+ for uid, message in by_uid.items():
+ # Newest active row, same rule as the loader's _active_logical_message_row: a logical
+ # message_uid can have several active physical rows (a carried or concurrent compaction
+ # cloning one back beside its archived twin), and the loader stamps the held dict from
+ # the newest. A bare fetchone() could return an older copy whose payload still matches
+ # the held digest — the newest row was rewritten by another writer, and the lease-less
+ # fallback would republish the stale held payload over that newer generation (#124102).
+ row = conn.execute(
+ "SELECT * FROM messages WHERE session_id = ? AND active = 1 AND role = ? AND message_uid = ? "
+ "ORDER BY id DESC LIMIT 1",
+ (session_id, message.get("role"), uid)).fetchone()
+ if row is not None:
+ by_uid_row[uid] = row
+ stored[int(row["id"])] = row
+ mismatches: list[int] = []
+ for message, row_id in exact:
+ row = stored.get(row_id) if row_id is not None else by_uid_row.get(message_uid_or_none(message) or "")
+ if row is None or not int(row["active"] or 0):
+ continue # the activity staleness check owns absent/inactive rows
+ snapshot = message.get(DB_ROW_SNAPSHOT)
+ if isinstance(snapshot, str):
+ if transcript_row_snapshot(row) != snapshot:
+ mismatches.append(int(row["id"]))
+ continue
+ held_identity = self._row_identity(
+ message.get("role", "unknown"), message.get("content"), message.get("tool_call_id"),
+ _parse_tool_calls(message.get("tool_calls")))
+ stored_identity = self._row_identity(
+ row["role"], self._decode_content(row["content"]), row["tool_call_id"],
+ _parse_tool_calls(row["tool_calls"]))
+ if held_identity != stored_identity:
+ mismatches.append(int(row["id"]))
+ return mismatches
+
+ def rewrite_pruned_rows(self, session_id: str, changes: list[tuple[dict[str, Any], dict[str, Any]]], *,
+ model_config_patch: Optional[dict[str, Any]] = None) -> int:
+ """Proactive-prune commit that rewrites only the changed rows, in place (#124102).
+
+ ``archive_and_compact`` is a generation writer: it archives every active row and re-inserts the whole
+ list, which is right for summary compaction (the row set changes) but makes each prune grow the store
+ by the full live transcript although a prune only edits a few rows' content. Each
+ ``(original, replacement)`` in *changes* is a persisted message the prune edited. Its row is named by
+ ``original["_row_id"]``, else by its tool call id (tool results) or tool-call ids (assistant turns),
+ else by the single active row with the same role and stored content. That row gets one archived twin
+ of its pre-prune self (``active=0, compacted=1``: still searchable, like the originals
+ ``archive_and_compact`` keeps), then takes the replacement's changed columns under its own id.
+ Unchanged rows, model order, row ids and concurrently appended rows are untouched; the FTS and
+ display-identity triggers keep both indexes consistent; the counters are unchanged because no row
+ enters or leaves the live set.
+
+ Raises :class:`PruneRowUnresolvedError` before writing anything when a row cannot be named exactly (a
+ merged dict, zero or several matches, an inactive row or a user row), so the caller can commit
+ through ``archive_and_compact``. A named row whose stored payload moved on raises the
+ :class:`PruneRowStaleError` subclass instead: that is another writer's generation, not ambiguity,
+ and the full writer must not be handed the stale transcript. The staleness check is the repo's
+ row-version CAS (``DB_ROW_SNAPSHOT`` / ``transcript_row_snapshot``, see ``agent/transcript_repair``)
+ when the held dict carries the digest — it covers every owned column including assistant
+ ``tool_calls`` arguments — and the representation-safe loader-lens identity compare otherwise
+ (raw storage bytes are never compared against a loaded/normalized view; #124102).
+ Returns the rows rewritten. Each rewritten dict is stamped with its row's new digest, so a second
+ prune of the same transcript compares against what this commit wrote, not what it replaced.
+ """
+ from agent.conversation_compression_archive import ABSORBED_ROW_IDS
+ from agent.message_metadata import DB_ROW_SNAPSHOT
+ from agent.transcript_repair import transcript_row_snapshot
+ from hermes_state_errors import PruneRowStaleError, PruneRowUnresolvedError
+
+ def _call_ids(tool_calls: Any) -> list[Any]:
+ return [call.get("id") if isinstance(call, dict) else None for call in (_parse_tool_calls(tool_calls) or [])]
+
+ def _resolve(conn, original: dict[str, Any]) -> Any:
+ role = original.get("role")
+ if role not in ("assistant", "tool") or original.get(ABSORBED_ROW_IDS):
+ raise PruneRowUnresolvedError(f"a {role} message is not rewritten in place")
+ row_id = original.get("_row_id")
+ if isinstance(row_id, int) and not isinstance(row_id, bool) and row_id > 0:
+ ids = [row_id]
+ elif role == "tool" and original.get("tool_call_id"):
+ ids = [int(row["id"]) for row in conn.execute(
+ "SELECT id FROM messages WHERE session_id = ? AND active = 1 AND role = 'tool' AND tool_call_id = ?",
+ (session_id, original["tool_call_id"])).fetchall()]
+ elif role == "assistant" and _call_ids(original.get("tool_calls")):
+ wanted = _call_ids(original.get("tool_calls"))
+ ids = [int(row["id"]) for row in conn.execute(
+ "SELECT id, tool_calls FROM messages WHERE session_id = ? AND active = 1 AND role = 'assistant' "
+ "AND tool_calls IS NOT NULL", (session_id,)).fetchall() if _call_ids(row["tool_calls"]) == wanted]
+ else:
+ ids = self._matching_active_ids(conn, session_id, original)
+ if len(ids) != 1:
+ raise PruneRowUnresolvedError(f"{len(ids)} live rows match a pruned {role} message")
+ row = conn.execute(
+ "SELECT * FROM messages WHERE id = ? AND session_id = ? AND active = 1", (ids[0], session_id)).fetchone()
+ if row is None or row["role"] != role:
+ raise PruneRowStaleError(f"row {ids[0]} no longer holds the pruned {role} message")
+ snapshot = original.get(DB_ROW_SNAPSHOT)
+ if isinstance(snapshot, str):
+ # The stored-row CAS digest: covers every owned column (tool_calls arguments included), and
+ # is computed from the read-back row, so storage affinity can never fake a mismatch.
+ if transcript_row_snapshot(row) != snapshot:
+ raise PruneRowStaleError(f"row {ids[0]} no longer holds the pruned {role} message")
+ elif (self._row_identity(role, original.get("content"), original.get("tool_call_id"),
+ _parse_tool_calls(original.get("tool_calls")))
+ != self._row_identity(row["role"], self._decode_content(row["content"]),
+ row["tool_call_id"], _parse_tool_calls(row["tool_calls"]))):
+ # No digest (a resumed dict): compare through the loader lens instead, the same
+ # representation both sides of _stamp_kept_live_prefix use.
+ raise PruneRowStaleError(f"row {ids[0]} no longer holds the pruned {role} message")
+ return row
+
+ def _do(conn):
+ patch = model_config_patch is not None
+ patched_model_config = self._merge_model_config_json(
+ conn, session_id, model_config_patch, on_missing="raise") if patch else None
+ updates: list[tuple[int, list[str], list[Any], Any, Any]] = []
+ for original, replacement in changes:
+ row = _resolve(conn, original)
+ role, timestamp = row["role"], row["timestamp"]
+ if replacement.get("role") != role:
+ raise PruneRowUnresolvedError("a prune replacement changed the message role")
+ before = self._message_row_params(session_id, role, original, _parse_tool_calls(
+ original.get("tool_calls")), timestamp, keep_reasoning=role == "assistant")
+ after = self._message_row_params(session_id, role, replacement, _parse_tool_calls(
+ replacement.get("tool_calls")), timestamp, keep_reasoning=role == "assistant")
+ changed = [column for column, old, new in zip(_MESSAGE_ROW_COLUMNS, before, after)
+ if old != new and column not in _PRUNE_FIXED_COLUMNS]
+ if changed:
+ updates.append((int(row["id"]), changed, [
+ value for column, value in zip(_MESSAGE_ROW_COLUMNS, after) if column in changed],
+ row["display_identity"],
+ int(row["display_order"]) if row["display_order"] is not None else int(row["id"]),
+ replacement))
+ twin_columns = ", ".join(c for c in self._message_column_names(conn)
+ if c not in ("id", "active", "compacted", "display_order"))
+ for row_id, columns, values, identity, order, replacement in updates:
+ twin_id = conn.execute(f"INSERT INTO messages ({twin_columns}, active, compacted) "
+ f"SELECT {twin_columns}, 0, 1 FROM messages WHERE id = ?", (row_id,)).lastrowid
+ # The content UPDATE fires the identity trigger, which nulls the slot of the live row and of
+ # every visible row sharing its old identity: the twin and any earlier generation's copies.
+ peers = conn.execute(
+ "SELECT id, display_order FROM messages WHERE session_id = ? AND id <> ? "
+ "AND display_identity = ? AND (active = 1 OR compacted = 1)",
+ (session_id, row_id, identity)).fetchall() if identity is not None else [(twin_id, order)]
+ conn.execute(f"UPDATE messages SET {', '.join(f'{column} = ?' for column in columns)} WHERE id = ?",
+ [*values, row_id])
+ # The superseded bodies keep their identity and slot. The live row takes the identity of what it
+ # now stores, so a later compaction's copy of it joins the same slot, and keeps the slot.
+ # The page shows one row per display_order, preferring the live one: the stub, in place.
+ conn.executemany("UPDATE messages SET display_identity = ?, display_order = ? WHERE id = ?",
+ [(identity, order if peer_order is None else peer_order, peer_id)
+ for peer_id, peer_order in peers])
+ live = conn.execute(
+ "SELECT role, content, timestamp, tool_call_id, tool_calls, tool_name, display_kind, "
+ "display_metadata FROM messages WHERE id = ?", (row_id,)).fetchone()
+ conn.execute("UPDATE messages SET display_identity = ?, display_order = ? WHERE id = ?",
+ (self._display_identity(self._display_dedupe_key(live)), order, row_id))
+ # Stamp the replacement with the stored row's new CAS digest (read back, not the bind values):
+ # a second prune of this transcript must compare against what this commit wrote, not what it
+ # replaced, or it would false-stale against its own output (#124102).
+ final_row = conn.execute(
+ "SELECT * FROM messages WHERE id = ?", (row_id,)).fetchone()
+ replacement[DB_ROW_SNAPSHOT] = transcript_row_snapshot(final_row)
+ if patch:
+ conn.execute("UPDATE sessions SET model_config = ? WHERE id = ?", (patched_model_config, session_id))
+ return len(updates)
+ self._ensure_display_order(session_id) # every row holds its stored slot before one is carried over
+ # _execute_transcript_write restores each dict's row state (id/digest/timestamp) on rollback, so a
+ # failed or retried commit never leaves the replacements stamped with an uncommitted digest.
+ return self._execute_transcript_write(
+ _do, [replacement for _, replacement in changes])
diff --git a/hermes_state_worker_compression.py b/hermes_state_worker_compression.py
index a7ac9747952..5b301db727e 100644
--- a/hermes_state_worker_compression.py
+++ b/hermes_state_worker_compression.py
@@ -205,13 +205,13 @@ def worker_history(db, conn, sid, payload):
-def archive_on_connection(db, conn, session_id: str, compacted_messages: list[dict[str, Any]], model_config_patch: Optional[dict[str, Any]]=None, watermark: Optional[int]=None, lock_holder: Optional[str]=None, tail_count: int=0, carried_messages: Optional[list[dict[str, Any]]]=None, covered_ids: Optional[list[int]]=None, unresolved_held: Optional[list[dict[str, Any]]]=None):
+def archive_on_connection(db, conn, session_id: str, compacted_messages: list[dict[str, Any]], model_config_patch: Optional[dict[str, Any]]=None, watermark: Optional[int]=None, lock_holder: Optional[str]=None, tail_count: int=0, carried_messages: Optional[list[dict[str, Any]]]=None, covered_ids: Optional[list[int]]=None, unresolved_held: Optional[list[dict[str, Any]]]=None, held_for_cas: Optional[list[dict[str, Any]]]=None):
# The owner's in-place compaction body, on this receipt's connection: one implementation, so
# main's coverage/merge/timestamp/display-order fixes reach worker and mutation verbs too.
return db._archive_and_compact_on_conn(conn, session_id, compacted_messages,
model_config_patch=model_config_patch, watermark=watermark, lock_holder=lock_holder,
tail_count=tail_count, carried_messages=carried_messages, covered_ids=covered_ids,
- unresolved_held=unresolved_held)
+ unresolved_held=unresolved_held, held_for_cas=held_for_cas)
def publish_on_connection(db, conn, *, parent_session_id: str, child_session_id: str, source: str, messages: list[dict[str, Any]], model: str | None=None, model_config: dict[str, Any] | None=None, system_prompt: str | None=None, cwd: str | None=None, profile_name: str | None=None, compression_lock_holder: str | None=None, require_compression_lease: bool=True, require_lease_refresh: bool=False, lease_ttl_seconds: float=300.0, watermark: Optional[int]=None, watermark_ceiling: Optional[int]=None):
# The owner's rotation body (lease, closure, child row, timestamps, tail clone, local target,
@@ -251,7 +251,7 @@ def _watermarks(payload):
def worker_archive(db, conn, sid, payload):
from hermes_state_worker_context import SIDECAR_KEYS
_fields(payload, ('messages', 'model_config_patch', 'watermark', 'lock_holder', 'tail_count'),
- optional=('carried_messages', 'covered_ids', 'unresolved_held'))
+ optional=('carried_messages', 'covered_ids', 'unresolved_held', 'held_for_cas'))
_handoff_messages(conn, sid, payload['messages'])
carried = payload.get('carried_messages') or []
if not isinstance(carried, list) or any(not isinstance(m, dict) for m in carried):
@@ -264,6 +264,12 @@ def worker_archive(db, conn, sid, payload):
if unresolved is not None and (not isinstance(unresolved, list)
or any(not isinstance(m, dict) for m in unresolved)):
raise RuntimeStoreError('invalid_params')
+ # The lease-less CAS fence (#124102): dicts projected to the closed handoff fields plus the
+ # persistence marker the owner's compare reads; validated like the other held-row payloads.
+ cas = payload.get('held_for_cas')
+ if cas is not None and (not isinstance(cas, list)
+ or any(not isinstance(m, dict) for m in cas)):
+ raise RuntimeStoreError('invalid_params')
_watermarks(payload)
# Micro-compaction and proactive prune archive in place without a lease, like the owner path.
if payload['lock_holder'] is not None:
@@ -275,7 +281,7 @@ def worker_archive(db, conn, sid, payload):
raise RuntimeStoreError('invalid_params')
value = archive_on_connection(db, conn, sid, payload['messages'], model_config_patch=patch,
watermark=payload['watermark'], lock_holder=payload['lock_holder'], tail_count=payload['tail_count'],
- carried_messages=carried, covered_ids=covered, unresolved_held=unresolved)
+ carried_messages=carried, covered_ids=covered, unresolved_held=unresolved, held_for_cas=cas)
from hermes_state_runtime import row_annotations
return {'value': value, 'annotations': row_annotations(payload['messages'])}
diff --git a/tests/agent/test_micro_compaction.py b/tests/agent/test_micro_compaction.py
index a62d3a05e6c..f8a828daa34 100644
--- a/tests/agent/test_micro_compaction.py
+++ b/tests/agent/test_micro_compaction.py
@@ -953,3 +953,199 @@ def test_a_stale_generation_aborts_leaving_the_winner_the_only_live_version(tmp_
assert cc._micro_compact_rolling_summary == summary # the stale summary is not carried into the next pass
live = [m["content"] for m in db.get_messages_as_conversation("s")]
assert live == [m["content"] for m in winner] # exactly one live generation
+
+
[email protected]("mode", ["prune", "micro"])
+def test_a_generation_rewritten_in_place_aborts_a_lease_less_pass(tmp_path, mode):
+ """An in-place prune keeps every row id and activity flag, so the id/activity staleness check is
+ blind to it. A second lease-less surface still holding the pre-prune bodies must abort anyway:
+ publishing them archives rows it never compared and republishes the pruned-away text over the
+ winner, undoing the prune (#124102)."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ db, cc, held = _held_session(tmp_path, mode)
+ # Another surface commits a prune in place: same ids, same activity, different bodies.
+ rewritten = [m for m in db.get_resume_conversations("s")[0] if m.get("role") == "tool"][:1] or [
+ m for m in db.get_resume_conversations("s")[0] if m.get("role") == "assistant"][:1]
+ assert rewritten, "fixture has no rewritable row"
+ original = dict(rewritten[0])
+ db.rewrite_pruned_rows("s", [(original, {**original, "content": "[pruned by the other surface]"})])
+ before = [m["content"] for m in db.get_messages_as_conversation("s")]
+
+ result = _run_pass(cc, mode, held)
+ for msg in result: # finalize_turn's persist flush appends every unpersisted dict
+ if not msg.get(_DB_PERSISTED_MARKER):
+ db.append_message("s", msg["role"], msg.get("content"))
+
+ assert result is held
+ assert [m["content"] for m in db.get_messages_as_conversation("s")] == before
+
+
[email protected]("mode", ["prune", "micro"])
+def test_a_freshly_resumed_unchanged_history_is_not_a_stale_generation(tmp_path, mode):
+ """The held history's user/assistant strings load sanitized and stripped; that lens is not a rewrite.
+
+ The pre-repair guard compared raw stored bytes against the loaded view, so an unchanged padded row read
+ back as stale and silently disabled both lease-less passes (#124102). Through the loader lens the same
+ unchanged history must still be reclaimed."""
+ db, cc, held = _held_session(tmp_path, mode)
+ # Pad a durable user row; the resume projection loads it stripped.
+ db._execute_write(lambda conn: conn.execute(
+ "UPDATE messages SET content = ' padded start \n' WHERE session_id = 's' AND role = 'user'"))
+ held = db.get_resume_conversations("s")[0]
+
+ result = _run_pass(cc, mode, held)
+
+ assert result is not held # the pass ran and committed: no false stale
+ live = [m["content"] for m in db.get_messages_as_conversation("s")]
+ assert "padded start" in " ".join(str(c) for c in live)
+
+
[email protected]("mode", ["prune", "micro"])
+def test_an_unstamped_trailing_row_does_not_suppress_the_stale_check(tmp_path, mode):
+ """An exact persisted prefix plus an unstamped trailing message is the live-turn shape. The trailing
+ row may cap the watermark, but the durable prefix the caller holds exactly must still be compared —
+ a rewritten prefix aborts the pass instead of republishing the pre-rewrite text (#124102)."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ db, cc, held = _held_session(tmp_path, mode)
+ rewritten = [m for m in db.get_resume_conversations("s")[0] if m.get("role") == "tool"][:1] or [
+ m for m in db.get_resume_conversations("s")[0] if m.get("role") == "assistant"][:1]
+ assert rewritten, "fixture has no rewritable row"
+ original = dict(rewritten[0])
+ db.rewrite_pruned_rows("s", [(original, {**original, "content": "[pruned by the other surface]"})])
+ held = held + [{"role": "user", "content": "live turn not yet flushed"}]
+ before = [m["content"] for m in db.get_messages_as_conversation("s")]
+
+ result = _run_pass(cc, mode, held)
+ for msg in result: # finalize_turn's persist flush appends every unpersisted dict
+ if not msg.get(_DB_PERSISTED_MARKER):
+ db.append_message("s", msg["role"], msg.get("content"))
+
+ assert result is held
+ # The pass is a no-op on the durable prefix; the trailing row this process authored still flushes once.
+ live = [m["content"] for m in db.get_messages_as_conversation("s")]
+ assert live == before + ["live turn not yet flushed"]
+
+
+def test_a_stale_generation_held_without_row_ids_aborts_the_micro_compact(tmp_path):
+ """The unaddressed live-replay projection (ACP restore, OpenAI session continuation:
+ ``get_messages_as_conversation`` without ``include_row_ids=True``) is the lease-less shape with
+ no ``_row_id``. It loads with the persist marker, durable identity and the stored-row CAS digest,
+ so the fence must still name its rows by ``message_uid``: after another surface pruned in place,
+ micro-compaction from that stale held history must be a no-op — the pruned stubs stay the only
+ live generation and the pre-prune bodies are not republished (#124102)."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ db, cc, _held = _held_session(tmp_path, "micro")
+ held = db.get_messages_as_conversation("s", repair_alternation=True)
+ from agent.message_metadata import DB_ROW_SNAPSHOT
+ assert held and not any(m.get("_row_id") for m in held)
+ assert all(m.get(_DB_PERSISTED_MARKER) and isinstance(m.get(DB_ROW_SNAPSHOT), str) for m in held)
+ # Another surface commits a prune in place: same ids, same activity, different bodies.
+ # Rewrite an assistant row in place (micro sessions hold plain user/assistant turns, no tool rows).
+ original = next(m for m in db.get_resume_conversations("s")[0]
+ if m.get("role") == "assistant" and m.get("content"))
+ db.rewrite_pruned_rows("s", [(dict(original), {**original, "content": "[pruned by the other surface]"})])
+ before = [m["content"] for m in db.get_messages_as_conversation("s")]
+
+ result = cc._micro_compact(held)
+ for msg in result: # finalize_turn's persist flush appends every unpersisted dict
+ if not msg.get(_DB_PERSISTED_MARKER):
+ db.append_message("s", msg["role"], msg.get("content"))
+
+ assert result is held
+ assert [m["content"] for m in db.get_messages_as_conversation("s")] == before
+
+
+def _uid_rows(db, uid: str):
+ """Every active physical row currently sharing *uid*, oldest first (a carried or concurrent
+ compaction can clone a row back beside its archived twin, so one logical message_uid may have
+ several live rows; the loader's ``_active_logical_message_row`` always stamps the newest)."""
+ return db._execute_write(lambda conn: conn.execute(
+ "SELECT id, content FROM messages WHERE session_id = ? AND active = 1 AND message_uid = ? ORDER BY id",
+ ("s", uid)).fetchall())
+
+
+def test_the_uid_fence_cas_against_the_newest_active_copy(tmp_path):
+ """A held id-less dict is resolved by its logical ``message_uid``, and one uid can name several
+ active physical rows. The fence must CAS against the NEWEST active copy — the row the loader
+ would have stamped the held digest from — never whichever row the uid index returns first: a
+ bare ``fetchone()`` that lands on an older unchanged duplicate clears the held digest as
+ current while another writer rewrote the newest, and the lease-less fallback then republishes
+ the stale held payload over that newer generation (#124102)."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ db, cc, _held = _held_session(tmp_path, "micro")
+ held = db.get_messages_as_conversation("s", repair_alternation=True)
+ assert held and not any(m.get("_row_id") for m in held)
+ target = next(m for m in held if m.get("role") == "assistant" and m.get("content"))
+ uid = target["message_uid"]
+
+ # Another surface's carried compaction clones the row back beside its twin: two active rows,
+ # same uid, same payload. The clone is the newest (AUTOINCREMENT id).
+ newest = _uid_rows(db, uid)[-1]
+ db._execute_write(lambda conn: conn.execute(
+ "INSERT INTO messages (session_id, role, content, tool_call_id, tool_calls, tool_name, "
+ "effect_disposition, timestamp, token_count, finish_reason, reasoning, reasoning_content, "
+ "reasoning_details, codex_reasoning_items, codex_message_items, platform_message_id, observed, "
+ "_compressed_summary, active, api_content, display_kind, display_metadata, message_uid, "
+ "absorbed_message_uids, tool_call_uids, tool_call_uid) "
+ "SELECT session_id, role, content, tool_call_id, tool_calls, tool_name, effect_disposition, "
+ "timestamp, token_count, finish_reason, reasoning, reasoning_content, reasoning_details, "
+ "codex_reasoning_items, codex_message_items, platform_message_id, observed, _compressed_summary, "
+ "active, api_content, display_kind, display_metadata, message_uid, absorbed_message_uids, "
+ "tool_call_uids, tool_call_uid FROM messages WHERE id = ?", (newest["id"],)))
+ original_id, clone_id = (row["id"] for row in _uid_rows(db, uid))
+ assert clone_id > original_id and len(_uid_rows(db, uid)) == 2
+
+ # Then that surface prunes the NEWEST copy in place (the row-addressed projection materializes
+ # both active rows; its dict for the clone is the one its own pass rewrote). The older duplicate
+ # still holds the payload the held dict was stamped from.
+ resume = db.get_messages_as_conversation("s", include_row_ids=True, repair_alternation=False)
+ original = next(m for m in resume if m.get("message_uid") == uid and m["_row_id"] == clone_id)
+ db.rewrite_pruned_rows("s", [(dict(original), {**original, "content": "[pruned by the other surface]"})])
+
+ # The fence names the newest row: the held digest is stale even though an older duplicate
+ # still matches it, so publishing the held generation must be refused.
+ assert db.rewritten_held_row_ids("s", held) == [clone_id]
+ before = [m["content"] for m in db.get_messages_as_conversation("s")]
+ result = cc._micro_compact(held)
+ for msg in result: # finalize_turn's persist flush appends every unpersisted dict
+ if not msg.get(_DB_PERSISTED_MARKER):
+ db.append_message("s", msg["role"], msg.get("content"))
+ assert result is held
+ assert [m["content"] for m in db.get_messages_as_conversation("s")] == before
+
+
+def test_the_uid_fence_lets_a_held_digest_stay_current_when_only_an_older_duplicate_moved(tmp_path):
+ """The newest-active rule cuts both ways: when the newest active copy still holds the payload
+ the held digest was stamped from, the held generation is the live winner even if an older
+ duplicate of the same uid was rewritten. The fence must report no mismatch there — resolving
+ whichever row the uid index happens to return first would false-abort a current generation
+ and refuse a legitimate compaction pass (#124102)."""
+ db, _cc, _held = _held_session(tmp_path, "micro")
+ held = db.get_messages_as_conversation("s", repair_alternation=True)
+ target = next(m for m in held if m.get("role") == "assistant" and m.get("content"))
+ uid = target["message_uid"]
+
+ newest = _uid_rows(db, uid)[-1]
+ db._execute_write(lambda conn: conn.execute(
+ "INSERT INTO messages (session_id, role, content, tool_call_id, tool_calls, tool_name, "
+ "effect_disposition, timestamp, token_count, finish_reason, reasoning, reasoning_content, "
+ "reasoning_details, codex_reasoning_items, codex_message_items, platform_message_id, observed, "
+ "_compressed_summary, active, api_content, display_kind, display_metadata, message_uid, "
+ "absorbed_message_uids, tool_call_uids, tool_call_uid) "
+ "SELECT session_id, role, content, tool_call_id, tool_calls, tool_name, effect_disposition, "
+ "timestamp, token_count, finish_reason, reasoning, reasoning_content, reasoning_details, "
+ "codex_reasoning_items, codex_message_items, platform_message_id, observed, _compressed_summary, "
+ "active, api_content, display_kind, display_metadata, message_uid, absorbed_message_uids, "
+ "tool_call_uids, tool_call_uid FROM messages WHERE id = ?", (newest["id"],)))
+ original_id, _clone_id = (row["id"] for row in _uid_rows(db, uid))
+
+ # Only the OLDER duplicate is rewritten in place; the newest (the one the loader stamps and the
+ # fence must compare against) still holds the held payload.
+ db._execute_write(lambda conn: conn.execute(
+ "UPDATE messages SET content = ? WHERE id = ?", ("[edited in place by another writer]", original_id)))
+
+ assert db.rewritten_held_row_ids("s", held) == []
diff --git a/tests/agent/test_proactive_prune_restart_safety.py b/tests/agent/test_proactive_prune_restart_safety.py
index 6ece43eb996..e24505ec94b 100644
--- a/tests/agent/test_proactive_prune_restart_safety.py
+++ b/tests/agent/test_proactive_prune_restart_safety.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import contextlib
import json
import os
from pathlib import Path
@@ -151,7 +152,8 @@ def test_fresh_agent_rearms_after_durable_history_regrowth_once(tmp_path: Path)
assert third_count == 0
assert restarted.context_compressor._proactive_prune_rearm_tokens == second_runway
-def test_prune_persistence_failure_is_a_noop(tmp_path: Path) -> None:
[email protected]("writer", ["rewrite_pruned_rows", "archive_and_compact"])
+def test_prune_persistence_failure_is_a_noop(tmp_path: Path, writer: str) -> None:
db = SessionDB(db_path=tmp_path / "state.db")
session_id = "PRUNE_PERSISTENCE_FAILURE"
db.create_session(session_id, source="telegram")
@@ -161,8 +163,10 @@ def test_prune_persistence_failure_is_a_noop(tmp_path: Path) -> None:
messages = db.get_messages_as_conversation(session_id)
original_contents = [message["content"] for message in messages]
- with patch.object(
- db, "archive_and_compact", side_effect=RuntimeError("disk full"),
+ # The full rewrite runs when the store has no in-place writer.
+ in_place = patch.object(db, "rewrite_pruned_rows", None) if writer == "archive_and_compact" else contextlib.nullcontext()
+ with in_place, patch.object(
+ db, writer, side_effect=RuntimeError("disk full"),
):
result, count = agent.context_compressor.prune_tool_results_only(
messages, current_tokens=120_000,
@@ -231,3 +235,409 @@ def test_patch_session_model_config_merge_and_delete(tmp_path: Path) -> None:
# Missing rows and empty patches are no-ops, never errors.
db.patch_session_model_config("NO_SUCH_SESSION", {"x": 1})
db.patch_session_model_config(session_id, {})
+
+
+def _rows(db: SessionDB, session_id: str) -> list[tuple]:
+ return db._conn.execute(
+ "SELECT id, role, content, active, compacted FROM messages WHERE session_id = ? ORDER BY id",
+ (session_id,),
+ ).fetchall()
+
+
+def test_in_place_prune_grows_by_changed_rows_only(tmp_path: Path) -> None:
+ """#124102: N messages with K demoted leave exactly N + K rows, and every live row keeps its id."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_IN_PLACE_GROWTH"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ before_rows = _rows(db, session_id)
+ messages = db.get_messages_as_conversation(session_id)
+
+ pruned, count = agent.context_compressor.prune_tool_results_only(messages, current_tokens=120_000)
+
+ changed = [i for i, (old, new) in enumerate(zip(messages, pruned)) if old["content"] != new["content"]]
+ assert count >= 1 and changed
+ after_rows = _rows(db, session_id)
+ live = [row for row in after_rows if row[3] == 1]
+ twins = [row for row in after_rows if row[3] == 0]
+ assert len(after_rows) == len(before_rows) + len(changed)
+ assert [row[0] for row in live] == [row[0] for row in before_rows]
+ assert sorted(row[2] for row in twins) == sorted(before_rows[i][2] for i in changed)
+ assert all(row[4] == 1 for row in twins) # the demoted full bodies stay searchable
+ assert [m["content"] for m in db.get_messages_as_conversation(session_id)] == [m["content"] for m in pruned]
+ assert all(m.get("_db_persisted") for m in pruned)
+ # The twin keeps the live row's display slot: the transcript page shows one row per message, in place.
+ assert len(db.get_messages(session_id, include_compacted=True)) == len(pruned)
+
+
+def _page(db: SessionDB, session_id: str) -> list:
+ return [m["content"] for m in db.get_messages(session_id, include_compacted=True)]
+
+
[email protected]("shape", ["first-generation", "carried", "carried-legacy-slots"])
+def test_in_place_prune_display_survives_later_compaction_and_backfill(tmp_path: Path, shape: str) -> None:
+ """The transcript page shows each message once, in its own slot, as the stub and never the archived
+ full body: right after the prune, after a later full compaction, and after a later display backfill."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_IN_PLACE_DISPLAY"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ if shape != "first-generation": # every message already has an archived copy in its display slot
+ db.archive_and_compact(session_id, db.get_messages_as_conversation(session_id))
+ if shape == "carried-legacy-slots": # rows written before the display index existed
+ db._conn.execute("UPDATE messages SET display_order = NULL, display_identity = NULL WHERE session_id = ?",
+ (session_id,))
+ db._conn.commit()
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ pruned, count = agent.context_compressor.prune_tool_results_only(
+ db.get_messages_as_conversation(session_id), current_tokens=120_000)
+ assert count >= 1
+ # The prune leaves every visible row its slot, so no whole-session backfill follows it.
+ assert db._conn.execute(
+ "SELECT COUNT(*) FROM messages WHERE session_id = ? AND (active = 1 OR compacted = 1) "
+ "AND (display_order IS NULL OR display_identity IS NULL)", (session_id,)).fetchone()[0] == 0
+ expected = [m["content"] for m in pruned]
+ assert _page(db, session_id) == expected
+
+ db.archive_and_compact(session_id, db.get_messages_as_conversation(session_id))
+ assert _page(db, session_id) == expected
+
+ # A later content rewrite elsewhere (the turn prologue's) re-derives the session's display slots.
+ db.append_messages_batch(session_id, [{"role": "user", "content": "@notes.md"}])
+ row_id = db._conn.execute("SELECT MAX(id) FROM messages WHERE session_id = ?", (session_id,)).fetchone()[0]
+ assert db.set_user_message_content(session_id, row_id, "expanded notes") == 1
+ assert _page(db, session_id) == expected + ["expanded notes"]
+
+
+def test_in_place_prune_twice_keeps_one_search_hit_per_unchanged_turn(tmp_path: Path) -> None:
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_IN_PLACE_SEARCH"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ compressor = agent.context_compressor
+ _, first_count = compressor.prune_tool_results_only(
+ db.get_messages_as_conversation(session_id), current_tokens=120_000)
+ assert first_count >= 1
+ grown = []
+ for index in range(8, 16):
+ call_id = f"call_{index}"
+ grown += [_assistant_call(call_id), _tool_result(call_id, chr(65 + index % 26) * 24_000)]
+ db.append_messages_batch(session_id, grown)
+ rows_before_second = len(_rows(db, session_id))
+
+ _, second_count = compressor.prune_tool_results_only(
+ db.get_messages_as_conversation(session_id), current_tokens=1_000_000)
+
+ assert second_count >= 1
+ assert len(_rows(db, session_id)) - rows_before_second == second_count
+ hits = [hit for hit in db.search_messages("start") if hit.get("session_id") == session_id]
+ assert len(hits) == 1
+
+
+def test_in_place_prune_skips_when_another_writer_changed_the_stored_body(tmp_path: Path) -> None:
+ """A stored body that moved on belongs to a newer generation: the prune must not commit at all.
+
+ The in-place rewrite keeps row ids, so the held-history watermark cannot see the race; only the
+ stored-body mismatch can. Falling back to the full writer here archives rows it never compared and
+ republishes the stale held text over the newer one (#124102).
+ """
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_IN_PLACE_STALE"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ messages = db.get_messages_as_conversation(session_id)
+ # Another surface rewrites the row this agent still holds the pre-edit body of.
+ db._conn.execute(
+ "UPDATE messages SET content = 'edited elsewhere' WHERE session_id = ? AND tool_call_id = 'call_0'",
+ (session_id,))
+ db._conn.commit()
+ rows_before = _rows(db, session_id)
+
+ with patch.object(db, "archive_and_compact", wraps=db.archive_and_compact) as full_rewrite:
+ result, count = agent.context_compressor.prune_tool_results_only(messages, current_tokens=120_000)
+
+ assert (result, count) == (messages, 0)
+ assert full_rewrite.call_count == 0
+ assert _rows(db, session_id) == rows_before
+ live = [message["content"] for message in db.get_messages_as_conversation(session_id)]
+ assert live.count("edited elsewhere") == 1
+
+
+def test_in_place_prune_falls_back_to_full_rewrite_when_a_row_cannot_be_named(tmp_path: Path) -> None:
+ """Genuine ambiguity over *current* content still commits through the full writer."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_IN_PLACE_UNRESOLVED"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ messages = db.get_messages_as_conversation(session_id)
+ # Two live rows now carry call_0's current body, so no single row can be named.
+ columns = ", ".join(
+ name for name in (row[1] for row in db._conn.execute("PRAGMA table_info(messages)"))
+ if name not in ("id", "display_order"))
+ db._conn.execute(
+ f"INSERT INTO messages ({columns}) SELECT {columns} FROM messages "
+ "WHERE session_id = ? AND tool_call_id = 'call_0' AND active = 1", (session_id,))
+ db._conn.commit()
+
+ with patch.object(db, "archive_and_compact", wraps=db.archive_and_compact) as full_rewrite:
+ pruned, count = agent.context_compressor.prune_tool_results_only(messages, current_tokens=120_000)
+
+ assert count >= 1
+ assert full_rewrite.call_count == 1
+ assert [m["content"] for m in db.get_messages_as_conversation(session_id)] == [
+ m["content"] for m in pruned]
+
+
+def test_in_place_prune_leaves_unwritten_suffix_to_the_flush(tmp_path: Path) -> None:
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_IN_PLACE_SUFFIX"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ messages = db.get_messages_as_conversation(session_id) + [{"role": "user", "content": "new turn"}]
+
+ pruned, count = agent.context_compressor.prune_tool_results_only(messages, current_tokens=120_000)
+
+ assert count >= 1
+ assert not pruned[-1].get("_db_persisted")
+ assert "new turn" not in [m["content"] for m in db.get_messages_as_conversation(session_id)]
+ agent._flush_messages_to_session_db(pruned)
+ durable = [m["content"] for m in db.get_messages_as_conversation(session_id)]
+ assert durable == [m["content"] for m in pruned]
+ assert durable.count("new turn") == 1
+
+
+def test_rewrite_pruned_rows_refuses_user_rows(tmp_path: Path) -> None:
+ from hermes_state_errors import PruneRowUnresolvedError
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_IN_PLACE_USER"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ messages = db.get_messages_as_conversation(session_id)
+ rows_before = _rows(db, session_id)
+
+ with pytest.raises(PruneRowUnresolvedError):
+ db.rewrite_pruned_rows(session_id, [(messages[0], {**messages[0], "content": "rewritten"})])
+ assert _rows(db, session_id) == rows_before
+
+
+def test_a_stale_generation_with_an_unstamped_trailing_row_still_aborts(tmp_path: Path) -> None:
+ """The stale check must run for the durable prefix an unstamped trailing row cannot suppress.
+
+ A lease-less writer can hold an exact persisted prefix plus a trailing message with no stamps (a live
+ turn this process authored and has not flushed yet). The early return that caps the watermark for that
+ trailing row must not also skip the version check for the rows the caller does hold exactly (#124102).
+ """
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_STALE_PREFIX"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ messages = db.get_messages_as_conversation(session_id) + [{"role": "user", "content": "live turn"}]
+ db._conn.execute(
+ "UPDATE messages SET content = 'edited elsewhere' WHERE session_id = ? AND tool_call_id = 'call_0'",
+ (session_id,))
+ db._conn.commit()
+ rows_before = _rows(db, session_id)
+
+ with patch.object(db, "archive_and_compact", wraps=db.archive_and_compact) as full_rewrite:
+ result, count = agent.context_compressor.prune_tool_results_only(messages, current_tokens=120_000)
+
+ assert (result, count) == (messages, 0)
+ assert full_rewrite.call_count == 0
+ assert _rows(db, session_id) == rows_before
+ live = [message["content"] for message in db.get_messages_as_conversation(session_id)]
+ assert live.count("edited elsewhere") == 1
+
+
+def _history_with_padded_text() -> list[dict]:
+ """A history whose user/assistant rows carry surrounding whitespace, the resume projection's lens."""
+ messages: list[dict] = [{"role": "user", "content": " start \n"}]
+ for index in range(8):
+ call_id = f"call_{index}"
+ messages.append(_assistant_call(call_id))
+ content = chr(65 + index) * 24_000 if index < 3 else "ok"
+ messages.append(_tool_result(call_id, content))
+ messages.append({"role": "assistant", "content": " done \n"})
+ messages.append({"role": "user", "content": "wrap up"})
+ return messages
+
+
[email protected]("loader", ["plain", "resume"], ids=["reload", "resume_projection"])
+def test_a_freshly_resumed_unchanged_transcript_is_not_stale(tmp_path: Path, loader: str) -> None:
+ """The loader lens (sanitize + strip on user/assistant strings) is not a rewrite (#124102).
+
+ Stored user/assistant content with surrounding whitespace loads stripped; the pre-repair head compared
+ raw storage bytes against that loaded view and falsely reported every such unchanged row as rewritten,
+ silently disabling the prune. Through the lens it must pass, and the prune must still reclaim.
+ """
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_NOT_STALE_WHITESPACE"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history_with_padded_text())
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ if loader == "resume":
+ messages = db.get_resume_conversations(session_id)[0]
+ else:
+ messages = db.get_messages_as_conversation(session_id, include_row_ids=True)
+
+ assert db.rewritten_held_row_ids(session_id, messages) == []
+
+ with patch.object(db, "archive_and_compact", wraps=db.archive_and_compact) as full_rewrite:
+ result, count = agent.context_compressor.prune_tool_results_only(messages, current_tokens=120_000)
+
+ assert (result, count) != (messages, 0)
+ assert full_rewrite.call_count == 0 # committed in place, not through the generation writer
+
+
+def test_an_assistant_tool_calls_rewrite_is_stale_with_and_without_a_snapshot(tmp_path: Path) -> None:
+ """The old guard compared ids and tool content only; changed ``tool_calls`` arguments slipped through.
+
+ A named assistant row whose stored call arguments moved on is a lost race. It must fail closed in the
+ row-local writer through the loader-lens identity compare (which covers the arguments), and equally
+ through the lease-less gate — aborting the whole prune, not just the row (#124102).
+ """
+ from hermes_state_errors import PruneRowStaleError
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_STALE_TOOL_CALLS"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ messages = db.get_messages_as_conversation(session_id, include_row_ids=True)
+ held_assistant = next(m for m in messages if m.get("role") == "assistant" and m.get("tool_calls"))
+ # Another writer changes the stored arguments of that row; the content (empty) is untouched.
+ db._conn.execute(
+ "UPDATE messages SET tool_calls = ? WHERE session_id = ? AND id = ?",
+ (json.dumps([{**held_assistant["tool_calls"][0],
+ "function": {**held_assistant["tool_calls"][0]["function"],
+ "arguments": '{"cmd":"winner"}'}}]), session_id,
+ held_assistant["_row_id"]))
+ db._conn.commit()
+
+ # The row-local writer names the row exactly and fails closed through the lens compare.
+ stale = dict(held_assistant)
+ with pytest.raises(PruneRowStaleError):
+ db.rewrite_pruned_rows(session_id, [(stale, {**stale, "content": "pruned stub"})])
+ # The lease-less gate sees the same race: the prune must be a true no-op.
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ rows_before = _rows(db, session_id)
+ with patch.object(db, "archive_and_compact", wraps=db.archive_and_compact) as full_rewrite:
+ result, count = agent.context_compressor.prune_tool_results_only(messages, current_tokens=120_000)
+ assert (result, count) == (messages, 0)
+ assert full_rewrite.call_count == 0
+ assert _rows(db, session_id) == rows_before
+
+
+def test_a_concurrent_user_edit_stays_active_when_the_prune_falls_back(tmp_path: Path) -> None:
+ """The fallback full writer republishes every held row, user rows included.
+
+ A lease-less prune can hold an unwritten message BEFORE later durable rows, which sends the commit
+ down the archive_and_compact fallback. Its staleness gate must then cover the USER rows the fallback
+ re-inserts verbatim, not just the tool/assistant rows the in-place writer edits: a user row another
+ view rewrote in place (``set_user_message_content``) is the same lost race. Republishing the held
+ pre-edit body would leave the newer edit with zero active copies (#124102).
+ """
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_STALE_USER_EDIT_FALLBACK"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ messages = db.get_messages_as_conversation(session_id, include_row_ids=True)
+ user_row = next(m for m in messages if m.get("role") == "user")
+ # Another SessionDB view rewrites that durable user row in place (a newer user edit).
+ assert db.set_user_message_content(session_id, user_row["_row_id"], "edited by the user elsewhere") == 1
+ # One unwritten live-turn message placed BEFORE later durable rows forces the fallback branch:
+ # _rewrite_pruned_rows_in_place refuses (row order would break) and returns None.
+ splice = next(i for i, m in enumerate(messages)
+ if m.get("_row_id") and m["_row_id"] > user_row["_row_id"])
+ held = messages[:splice] + [{"role": "user", "content": "live turn not yet flushed"}] + messages[splice:]
+ rows_before = _rows(db, session_id)
+
+ with patch.object(db, "archive_and_compact", wraps=db.archive_and_compact) as full_rewrite:
+ result, count = agent.context_compressor.prune_tool_results_only(held, current_tokens=120_000)
+
+ assert (result, count) == (held, 0) # a true no-op: the stale generation is never published
+ assert full_rewrite.call_count == 0
+ assert _rows(db, session_id) == rows_before
+ live = [message["content"] for message in db.get_messages_as_conversation(session_id)]
+ assert live.count("edited by the user elsewhere") == 1 # the newer edit keeps its active copy
+ assert "start" not in live # the stale pre-edit body is not republished
+
+
+def test_the_fallback_still_commits_when_no_held_row_was_rewritten(tmp_path: Path) -> None:
+ """Widening the stale check to user rows must not disable the fallback itself: with no concurrent
+ rewrite, the same interleaved-unwritten shape still commits through archive_and_compact (#124102)."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_FALLBACK_CLEAN_COMMIT"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ messages = db.get_messages_as_conversation(session_id, include_row_ids=True)
+ first_user = next(i for i, m in enumerate(messages) if m.get("role") == "user")
+ splice = next(i for i, m in enumerate(messages) if i > first_user and m.get("_row_id"))
+ held = messages[:splice] + [{"role": "user", "content": "live turn not yet flushed"}] + messages[splice:]
+
+ with patch.object(db, "archive_and_compact", wraps=db.archive_and_compact) as full_rewrite:
+ result, count = agent.context_compressor.prune_tool_results_only(held, current_tokens=120_000)
+
+ assert (result, count) != (held, 0)
+ assert full_rewrite.call_count == 1
+ live = [message["content"] for message in db.get_messages_as_conversation(session_id)]
+ assert live.count("start") == 1 # the held user row is republished exactly once
+ assert live.count("live turn not yet flushed") == 1
+
+
+def test_a_user_edit_landing_after_the_precheck_stays_active_in_the_commit(tmp_path: Path) -> None:
+ """The lease-less stale gate runs OUTSIDE the full writer's write transaction.
+
+ A second SessionDB connection that rewrites a covered user row AFTER the precheck but BEFORE the
+ commit's ``BEGIN IMMEDIATE`` was invisible to it: ``archive_and_compact`` archived the newer row
+ and republished the stale held text, leaving the newer edit with zero active copies (#124102).
+ The commit must re-verify the held rows against the live store inside its own transaction and
+ abort as a no-op when one moved — the held row is never published and the edit keeps its row.
+ """
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "PRUNE_CAS_COMMIT_WINDOW"
+ db.create_session(session_id, source="telegram")
+ db.append_messages_batch(session_id, _history())
+ agent = _build_agent(db, session_id)
+ _configure_pruning(agent)
+ messages = db.get_messages_as_conversation(session_id, include_row_ids=True)
+ user_row = next(m for m in messages if m.get("role") == "user")
+ splice = next(i for i, m in enumerate(messages)
+ if m.get("_row_id") and m["_row_id"] > user_row["_row_id"])
+ held = messages[:splice] + [{"role": "user", "content": "live turn not yet flushed"}] + messages[splice:]
+
+ other = SessionDB(db_path=tmp_path / "state.db")
+ original = db.archive_and_compact
+
+ def _edit_then_commit(*args, **kwargs):
+ # The call boundary is after the caller's precheck and before BEGIN IMMEDIATE: a second
+ # connection can take the write lock first and rewrite the covered user row in place.
+ assert other.set_user_message_content(session_id, user_row["_row_id"], "edited inside the window") == 1
+ return original(*args, **kwargs)
+
+ with patch.object(db, "archive_and_compact", side_effect=_edit_then_commit):
+ result, count = agent.context_compressor.prune_tool_results_only(held, current_tokens=120_000)
+
+ assert (result, count) == (held, 0) # the commit aborted inside its transaction: a true no-op
+ live = [message["content"] for message in db.get_messages_as_conversation(session_id)]
+ assert live.count("edited inside the window") == 1 # the newer edit keeps its single active row
+ assert "start" not in live # the stale pre-edit body was never republished
+ other.close()