Skip to content

The agent that grows with you

fix(agent): a tool-row rewrite commits only while this process owns the turn

Teknium9182739a2922
diff --git a/agent/session_persistence.py b/agent/session_persistence.py
index 6cdb926b954..88d3979fda9 100644
--- a/agent/session_persistence.py
+++ b/agent/session_persistence.py
@@ -276,11 +276,14 @@ def sync_rewritten_tool_rows(agent, batch: list[dict], contents_before: list[Any
return 0
rows = [(_db_flush_row(agent, {**msg, "content": before}, False), _db_flush_row(agent, msg, False))
for msg, before in changed]
- from hermes_state_errors import PruneRowUnresolvedError
+ from hermes_state_errors import PruneRowUnresolvedError, SessionTurnLeaseLostError
try:
with _persist_lock(agent):
- written = rewrite(session_id, rows)
- except PruneRowUnresolvedError as exc: # PruneRowStaleError included: another writer owns the row now
+ written = rewrite(
+ session_id, rows, turn_lease_holder=getattr(agent, "_active_session_turn_lease_holder", None),
+ turn_lease_ttl_seconds=getattr(agent, "_active_session_turn_lease_ttl_seconds", 300.0) or 300.0,
+ )
+ except (PruneRowUnresolvedError, SessionTurnLeaseLostError) as exc: # another writer owns the row or turn
logger.info("Tool-result rewrite not persisted; the stored row keeps the full body: %s", exc)
return 0
except Exception as exc: # health: allow BLE001 -- a store failure must not fail the turn; the row keeps its body
diff --git a/hermes_state_prune_rewrite.py b/hermes_state_prune_rewrite.py
index 7a5884dc8f2..2d9ae397dd8 100644
--- a/hermes_state_prune_rewrite.py
+++ b/hermes_state_prune_rewrite.py
@@ -131,7 +131,8 @@ class SessionPruneRewriteMixin:
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:
+ model_config_patch: Optional[dict[str, Any]] = None, turn_lease_holder: Optional[str] = None,
+ turn_lease_ttl_seconds: float = 300.0) -> 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
@@ -155,6 +156,8 @@ class SessionPruneRewriteMixin:
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).
+ ``turn_lease_holder`` (a writer inside a turn) refuses with :class:`SessionTurnLeaseLostError`, before
+ writing anything, when another process owns the session's turn lease, as ``append_message`` does.
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.
"""
@@ -206,6 +209,10 @@ class SessionPruneRewriteMixin:
return row
def _do(conn):
+ if turn_lease_holder:
+ # A writer inside a turn commits only while it still owns the turn, like its appends.
+ self._check_transcript_write_guards(conn, session_id, None, turn_lease_holder=turn_lease_holder,
+ turn_lease_ttl_seconds=turn_lease_ttl_seconds)
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
diff --git a/tests/agent/test_turn_budget_durable_rows.py b/tests/agent/test_turn_budget_durable_rows.py
index 2ccd457a06d..555c0e5749a 100644
--- a/tests/agent/test_turn_budget_durable_rows.py
+++ b/tests/agent/test_turn_budget_durable_rows.py
@@ -115,3 +115,25 @@ def test_spilled_full_body_stays_searchable_and_next_flush_appends_once(agent_an
assert agent._flush_messages_to_session_db(messages) is True
replay = db.get_messages_as_conversation(agent.session_id, repair_alternation=True)
assert [m["role"] for m in replay] == ["user", "assistant", "tool", "tool", "assistant"]
+
+
+
+def test_a_process_that_lost_the_turn_lease_leaves_the_rows_alone(agent_and_db):
+ agent, db = agent_and_db
+ assert db.try_acquire_session_turn_lease(agent.session_id, "process-a", ttl_seconds=60)
+ agent._active_session_turn_lease_holder = "process-a"
+ rewrite = db.rewrite_pruned_rows
+
+ def taken_over_first(*args, **kwargs):
+ # Another process takes the turn after A flushed the full rows and before A's rewrite commits.
+ db.release_session_turn_lease(agent.session_id, "process-a")
+ assert db.try_acquire_session_turn_lease(agent.session_id, "process-b", ttl_seconds=60)
+ return rewrite(*args, **kwargs)
+
+ db.rewrite_pruned_rows = taken_over_first
+ calls = [_tc("web_search", '{"query":"a"}', "l-large-1"), _tc("web_search", '{"query":"b"}', "l-large-2")]
+ _run_batch(agent, calls)
+
+ stored = [m["content"] for m in db.get_messages_as_conversation(agent.session_id) if m.get("role") == "tool"]
+ assert stored and all(_LARGE in body and PERSISTED_OUTPUT_TAG not in body for body in stored), (
+ "a rewrite under another process's lease must not land")