Skip to content

The agent that grows with you

fix(sessions): revive uncontested expired turn leases

fangliquanflq19b120439201
diff --git a/hermes_state.py b/hermes_state.py
index 0317af448f6..f4a7b75bd85 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -8268,6 +8268,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
session_id: str,
compression_lock_holder: Optional[str],
turn_lease_holder: Optional[str] = None,
+ turn_lease_ttl_seconds: float = 300.0,
) -> None:
"""Transcript-append admission checks, run INSIDE the write txn.
@@ -8295,15 +8296,26 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
"WHERE conversation_id = ?",
(conversation_id,),
).fetchone()
- if (
- lease is None
- or lease["holder"] != turn_lease_holder
- or float(lease["expires_at"]) <= time.time()
- ):
+ if lease is None or lease["holder"] != turn_lease_holder:
raise SessionTurnLeaseLostError(
f"Session turn lease lost; refusing transcript write "
f"for {session_id!r}"
)
+ now = time.time()
+ if float(lease["expires_at"]) <= now:
+ # Expiry makes the row reclaimable; it does not prove that a
+ # takeover occurred. BEGIN IMMEDIATE serializes this renewal
+ # with acquisition, so a still-matching owner can recover from
+ # a starved refresher without weakening the foreign-holder fence.
+ conn.execute(
+ "UPDATE session_turn_leases SET expires_at = ? "
+ "WHERE conversation_id = ? AND holder = ?",
+ (
+ now + max(0.1, float(turn_lease_ttl_seconds)),
+ conversation_id,
+ turn_lease_holder,
+ ),
+ )
session = conn.execute(
"SELECT ended_at, end_reason FROM sessions WHERE id = ?",
(session_id,),
@@ -8384,6 +8396,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
display_metadata: Optional[Dict[str, Any]] = None,
compression_lock_holder: Optional[str] = None,
turn_lease_holder: Optional[str] = None,
+ turn_lease_ttl_seconds: float = 300.0,
) -> int:
"""
Append a message to a session. Returns the message row ID.
@@ -8446,6 +8459,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
session_id,
compression_lock_holder,
turn_lease_holder=turn_lease_holder,
+ turn_lease_ttl_seconds=turn_lease_ttl_seconds,
)
cursor = conn.execute(
"""INSERT INTO messages (session_id, role, content, tool_call_id,
@@ -8509,6 +8523,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
compression_lock_holder: Optional[str] = None,
turn_lease_holder: Optional[str] = None,
chunk_rows: Optional[int] = None,
+ turn_lease_ttl_seconds: float = 300.0,
) -> int:
"""Append multiple messages atomically in ONE write transaction.
@@ -8548,6 +8563,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
messages[start:start + chunk_rows],
compression_lock_holder=compression_lock_holder,
turn_lease_holder=turn_lease_holder,
+ turn_lease_ttl_seconds=turn_lease_ttl_seconds,
)
return inserted_total
@@ -8557,6 +8573,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
session_id,
compression_lock_holder,
turn_lease_holder=turn_lease_holder,
+ turn_lease_ttl_seconds=turn_lease_ttl_seconds,
)
inserted, tool_calls_total = self._insert_message_rows(
conn, session_id, messages
diff --git a/run_agent.py b/run_agent.py
index dd4b189bd1a..f62ea6a360d 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -2293,6 +2293,10 @@ class AIAgent:
turn_lease_holder=getattr(
self, "_active_session_turn_lease_holder", None
),
+ turn_lease_ttl_seconds=getattr(
+ self, "_active_session_turn_lease_ttl_seconds", 300.0
+ )
+ or 300.0,
)
for _written in _batch_msgs:
_written[_DB_PERSISTED_MARKER] = True
@@ -8228,6 +8232,7 @@ class AIAgent:
# the same SQLite write transaction as the transcript insert.
durable_turn_lease = _durable_holder
self._active_session_turn_lease_holder = _durable_holder
+ self._active_session_turn_lease_ttl_seconds = _lease_ttl
if _lease_waited:
self._emit_status(
"Session is free; loading the latest transcript..."
@@ -8254,6 +8259,12 @@ class AIAgent:
)
def _refresh_durable_turn_lease() -> None:
+ def _interrupt_turn(message: str) -> None:
+ try:
+ self.interrupt(message, hard_cancel=True)
+ except Exception:
+ self._interrupt_requested = True
+
while not durable_turn_lease_stop.wait(_lease_refresh_interval):
try:
if not _turn_db.refresh_session_turn_lease(
@@ -8270,21 +8281,24 @@ class AIAgent:
"Lost session turn lease while turn is active: %s",
getattr(self, "session_id", None) or session_id,
)
- try:
- self.interrupt(
- "Session turn lease lost; stopping to "
- "protect the transcript.",
- hard_cancel=True,
- )
- except Exception:
- self._interrupt_requested = True
+ _interrupt_turn(
+ "Session turn lease lost; stopping to protect "
+ "the transcript."
+ )
return
except Exception:
+ if durable_turn_lease_stop.is_set():
+ return
logger.warning(
"Failed to refresh session turn lease: %s",
getattr(self, "session_id", None) or session_id,
exc_info=True,
)
+ _interrupt_turn(
+ "Session turn lease could not be refreshed; "
+ "stopping to protect the transcript."
+ )
+ return
durable_turn_lease_thread = threading.Thread(
target=_refresh_durable_turn_lease,
@@ -8415,6 +8429,7 @@ class AIAgent:
== durable_turn_lease
):
self._active_session_turn_lease_holder = None
+ self._active_session_turn_lease_ttl_seconds = None
# Always clear mid-turn labels when the turn exits — including
# interrupted early returns that skip finalize_turn. Keep ts.
try:
diff --git a/tests/run_agent/test_cross_process_turn_lease.py b/tests/run_agent/test_cross_process_turn_lease.py
index 267ca8eb619..feb37ad84f8 100644
--- a/tests/run_agent/test_cross_process_turn_lease.py
+++ b/tests/run_agent/test_cross_process_turn_lease.py
@@ -339,6 +339,51 @@ def test_run_conversation_interrupts_when_lease_refresh_lost(monkeypatch):
assert "lease lost" in str(interrupt_calls[0][0]).lower()
+def test_run_conversation_interrupts_when_lease_refresh_errors(monkeypatch):
+ db = _DB()
+ agent = _agent_with_db(db)
+ agent._session_turn_lease_refresh_interval = 0.01
+ interrupt_calls = []
+
+ def track_interrupt(message=None, hard_cancel=False):
+ interrupt_calls.append((message, hard_cancel))
+ agent._interrupt_requested = True
+
+ agent.interrupt = track_interrupt
+
+ def refresh_error(session_id, holder, **kwargs):
+ raise OSError("database unavailable")
+
+ db.refresh_session_turn_lease = refresh_error
+
+ def fake_run(_agent, _message, _system, history, *_args, **_kwargs):
+ deadline = time.monotonic() + 2.0
+ while time.monotonic() < deadline:
+ if getattr(_agent, "_interrupt_requested", False):
+ return {
+ "final_response": "",
+ "messages": history,
+ "api_calls": 0,
+ "completed": False,
+ "interrupted": True,
+ }
+ time.sleep(0.01)
+ raise AssertionError("refresh error did not interrupt the turn")
+
+ monkeypatch.setattr("agent.conversation_loop.run_conversation", fake_run)
+
+ result = AIAgent.run_conversation(
+ agent,
+ "new message",
+ conversation_history=[{"role": "user", "content": "seed"}],
+ )
+
+ assert result.get("interrupted") is True
+ assert interrupt_calls
+ assert interrupt_calls[0][1] is True
+ assert "could not be refreshed" in str(interrupt_calls[0][0]).lower()
+
+
def test_late_refresh_miss_after_release_does_not_interrupt(monkeypatch):
db = _DB()
agent = _agent_with_db(db)
diff --git a/tests/state/test_session_turn_lease.py b/tests/state/test_session_turn_lease.py
index 07f043e264e..8020eaa0dc5 100644
--- a/tests/state/test_session_turn_lease.py
+++ b/tests/state/test_session_turn_lease.py
@@ -490,21 +490,29 @@ def test_turn_lease_fences_stale_transcript_flush_after_reclaim(tmp_path):
db.release_session_turn_lease("shared", next_holder)
-def test_turn_lease_fences_flush_when_row_is_absent_or_expired(tmp_path):
+def test_turn_lease_revives_expired_row_still_owned_by_writer(tmp_path):
db = SessionDB(tmp_path / "state.db")
db.create_session("shared", source="test")
holder = f"pid={os.getpid()}:turn=owner"
assert db.try_acquire_session_turn_lease("shared", holder, ttl_seconds=0.05)
time.sleep(0.12)
- with pytest.raises(SessionTurnLeaseLostError, match="turn lease lost"):
- db.append_messages_batch(
- "shared",
- [{"role": "assistant", "content": "after ttl"}],
- turn_lease_holder=holder,
- )
+ assert db.append_messages_batch(
+ "shared",
+ [{"role": "assistant", "content": "after ttl"}],
+ turn_lease_holder=holder,
+ turn_lease_ttl_seconds=0.2,
+ ) == 1
+ assert not db.try_acquire_session_turn_lease(
+ "shared", f"pid={os.getpid()}:turn=contender", ttl_seconds=5
+ )
+
+
+def test_turn_lease_fences_flush_when_row_is_absent(tmp_path):
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("shared", source="test")
+ holder = f"pid={os.getpid()}:turn=owner"
- db.release_session_turn_lease("shared", holder)
with pytest.raises(SessionTurnLeaseLostError, match="turn lease lost"):
db.append_messages_batch(
"shared",