Skip to content

The agent that grows with you

fix(agent): bound lease lock tolerance by the row's committed expiry

Tekniumb8788c3cb129
diff --git a/agent/turn_facade_lease.py b/agent/turn_facade_lease.py
index 96be1e6b4b3..3302ad8b868 100644
--- a/agent/turn_facade_lease.py
+++ b/agent/turn_facade_lease.py
@@ -25,6 +25,10 @@ _REASON_LEASE_LOST = "session turn lease lost"
LEASE_TTL_SECONDS = 300.0
LEASE_WAIT_SECONDS = 1800.0
+# SessionDB's default write patience: a renewal waits this long for the write lock, never past the authority.
+_REFRESH_WRITE_PATIENCE_S = 20.0
+# Headroom before expiry for one BEGIN IMMEDIATE blocked in the writer's 1s busy handler, plus jitter.
+_REFRESH_EXPIRY_MARGIN_S = 2.0
class DurableTurnLease:
@@ -35,13 +39,15 @@ class DurableTurnLease:
written only under ``_lock``.
"""
- def __init__(self, agent, db, session_id: str, holder: str) -> None:
+ def __init__(self, agent, db, session_id: str, holder: str, *, expires_at: Optional[float] = None) -> None:
self.agent = agent
self.db = db
self.session_id = session_id # id at admission; release always targets this row
self.holder = holder
- # Wall clock, same as the row's expires_at. A failed refresh must not move it.
- self._authority_deadline = time.time() + LEASE_TTL_SECONDS
+ # Wall clock, same as the row's expires_at, never later than it: the row's committed expiry at
+ # admission, then a timestamp taken BEFORE each successful renewal (the store stamps expiry
+ # before its lock wait). Only a successful renewal moves it.
+ self._authority_deadline = time.time() + LEASE_TTL_SECONDS if expires_at is None else expires_at
self.stop = threading.Event()
self.refresh_interval = float(getattr(agent, "_session_turn_lease_refresh_interval", 60.0))
self._lock = threading.Lock()
@@ -184,6 +190,12 @@ class DurableTurnLease:
if agent._execution_thread_id is not None:
_set_interrupt(False, agent._execution_thread_id)
+ def _stop_on_exhausted_authority(self) -> bool:
+ """State.db stayed locked until no renewal can land before the row expires: stop now."""
+ logger.warning("Session turn lease refresh stayed locked through its lifetime: %s", self._current_session_id())
+ self._interrupt_turn("Session turn lease could not be refreshed; stopping to protect the transcript.")
+ return False
+
def refresh_tick(self):
"""One periodic renewal (every ``refresh_interval`` via the shared scheduler). A real
miss (rowcount 0) or a non-lock error interrupts the turn. A SQLite lock is a missed
@@ -200,11 +212,19 @@ class DurableTurnLease:
a loss."""
if self.stop.is_set():
return False
+ started = time.time()
+ # The whole renewal must finish before the authority runs out: a renewal still waiting on the
+ # write lock past expiry keeps this turn running while a successor reclaims the row. The
+ # margin covers one BEGIN IMMEDIATE that blocks in SQLite's busy handler past the patience.
+ patience = self._authority_deadline - _REFRESH_EXPIRY_MARGIN_S - started
+ if patience <= 0:
+ return self._stop_on_exhausted_authority()
try:
if self.db.refresh_session_turn_lease(
- self._current_session_id(), self.holder, ttl_seconds=LEASE_TTL_SECONDS
+ self._current_session_id(), self.holder, ttl_seconds=LEASE_TTL_SECONDS,
+ patience_s=min(_REFRESH_WRITE_PATIENCE_S, patience),
):
- self._authority_deadline = time.time() + LEASE_TTL_SECONDS
+ self._authority_deadline = started + LEASE_TTL_SECONDS
return None
if self.stop.is_set():
return False
@@ -218,19 +238,10 @@ class DurableTurnLease:
from hermes_state_errors import is_sqlite_lock_error
if is_sqlite_lock_error(exc):
- now = time.time()
- # The scheduler will not try again until one interval from now. If that
- # attempt would meet or pass the row expiry, stop before a successor
- # can claim it.
- if now + self.refresh_interval >= self._authority_deadline:
- logger.warning(
- "Session turn lease refresh stayed locked through its lifetime: %s",
- self._current_session_id(),
- )
- self._interrupt_turn(
- "Session turn lease could not be refreshed; stopping to protect the transcript."
- )
- return False
+ # The scheduler will not try again until one interval from now. If that attempt
+ # could not finish before the row expiry, stop before a successor can claim it.
+ if time.time() + self.refresh_interval + _REFRESH_EXPIRY_MARGIN_S >= self._authority_deadline:
+ return self._stop_on_exhausted_authority()
logger.warning(
"Session turn lease refresh hit a SQLite lock; will retry: %s",
self._current_session_id(),
@@ -254,6 +265,21 @@ class TurnLeaseAdmission:
conversation_history: Optional[List[Dict[str, Any]]] = None
+def _committed_lease_expiry(db, session_id: str, holder: str, floor: float) -> float:
+ """The admitted row's committed ``expires_at``; when unreadable, ``floor + TTL`` (taken before
+ acquisition, so never later than the real expiry). Overstating it lets a successor reclaim the
+ row while this turn still believes it holds the lease."""
+ reader = getattr(db, "session_turn_lease_expires_at", None)
+ if callable(reader):
+ try:
+ committed = reader(session_id, holder)
+ if isinstance(committed, (int, float)):
+ return float(committed)
+ except Exception:
+ logger.debug("Could not read the admitted turn lease expiry; using the pre-acquire floor", exc_info=True)
+ return floor + LEASE_TTL_SECONDS
+
+
def _durable_session_exists(db, session_id: str) -> Optional[bool]:
"""True / False when the row read answered; None when it failed and the state is unknown."""
try:
@@ -315,6 +341,7 @@ def admit_durable_turn_lease(
f"⏳ Still waiting for the other Hermes process on this session ({int(elapsed)}s)..."
)
+ authority_floor = time.time() # every acquisition attempt stamps its expiry after this instant
if not db.acquire_session_turn_lease(
session_id, holder, ttl_seconds=LEASE_TTL_SECONDS, wait_seconds=LEASE_WAIT_SECONDS,
on_wait=_on_wait, on_contended=_on_contended,
@@ -325,7 +352,9 @@ def admit_durable_turn_lease(
# Assign only after admission so the finally cannot release a holder that never owned the
# row; persist paths read the agent attr so a late flush is fenced in the same transaction.
- lease = DurableTurnLease(agent, db, session_id, holder)
+ lease = DurableTurnLease(
+ agent, db, session_id, holder, expires_at=_committed_lease_expiry(db, session_id, holder, authority_floor),
+ )
agent._active_session_turn_lease_holder = holder
agent._active_session_turn_lease_ttl_seconds = LEASE_TTL_SECONDS
try:
diff --git a/hermes_state_compression.py b/hermes_state_compression.py
index dc53551d2f8..becd772da33 100644
--- a/hermes_state_compression.py
+++ b/hermes_state_compression.py
@@ -657,8 +657,22 @@ class SessionCompressionMixin:
last_notice_at = now
time.sleep(min(max(0.01, float(poll_interval_seconds)), remaining))
- def refresh_session_turn_lease(self, session_id: str, holder: str, *, ttl_seconds: float = 300.0) -> bool:
- """Extend a turn lease only while ``holder`` still owns it."""
+ def session_turn_lease_expires_at(self, session_id: str, holder: str) -> Optional[float]:
+ """Committed ``expires_at`` of ``holder``'s turn lease, or None when it does not hold it."""
+ if not session_id or not holder:
+ return None
+ with self._read_ctx() as conn:
+ row = conn.execute(
+ "SELECT expires_at FROM session_turn_leases WHERE conversation_id = ? AND holder = ?",
+ (self._session_turn_lease_key_on_conn(conn, session_id), holder),
+ ).fetchone()
+ return float(row[0]) if row else None
+
+ def refresh_session_turn_lease(
+ self, session_id: str, holder: str, *, ttl_seconds: float = 300.0, patience_s: Optional[float] = None,
+ ) -> bool:
+ """Extend a turn lease only while ``holder`` still owns it. ``expires_at`` is stamped before
+ the write-lock wait, so a caller timestamp taken before this call never exceeds it."""
if not session_id or not holder:
return False
expires_at = time.time() + max(0.1, float(ttl_seconds))
@@ -668,7 +682,7 @@ class SessionCompressionMixin:
"UPDATE session_turn_leases SET expires_at = ? "
"WHERE conversation_id = ? AND holder = ?", (expires_at, conversation_id, holder),
).rowcount > 0
- return bool(self._execute_write(_do))
+ return bool(self._execute_write(_do, patience_s=patience_s))
def release_session_turn_lease(self, session_id: str, holder: str) -> None:
"""Release a turn lease iff ``holder`` still owns it; idempotent."""
diff --git a/tests/agent/test_turn_facade_lease.py b/tests/agent/test_turn_facade_lease.py
index 17997e1893d..29d0846a921 100644
--- a/tests/agent/test_turn_facade_lease.py
+++ b/tests/agent/test_turn_facade_lease.py
@@ -146,78 +146,78 @@ def test_refresh_tick_sqlite_lock_keeps_the_turn():
assert lease.stop.is_set() is False
-def test_repeated_lock_misses_do_not_outlive_the_lease(monkeypatch):
- now = [1000.0]
- monkeypatch.setattr(time, "time", lambda: now[0])
- db = _Db()
-
- def locked(session_id, holder, **kwargs):
- raise sqlite3.OperationalError("database is locked")
-
- db.refresh_session_turn_lease = locked
- lease, calls = _active_lease(db)
- result = None
- for elapsed in (60, 120, 180, 240, 300):
- now[0] = 1000.0 + elapsed
- result = lease.refresh_tick()
- if result is False:
- break
- assert result is False
- assert calls == [
- "Session turn lease could not be refreshed; stopping to protect the transcript."
- ]
- assert now[0] <= 1000.0 + LEASE_TTL_SECONDS
-
-
-def test_one_lock_then_renewal_opens_a_fresh_window(monkeypatch):
- now = [1000.0]
- monkeypatch.setattr(time, "time", lambda: now[0])
- db = _Db()
- locked = {"on": True}
-
- def refresh(session_id, holder, **kwargs):
- if locked["on"]:
- raise sqlite3.OperationalError("database is locked")
- return True
-
- db.refresh_session_turn_lease = refresh
- lease, calls = _active_lease(db)
- now[0] = 1060.0
- assert lease.refresh_tick() is None and calls == []
- locked["on"] = False
- now[0] = 1120.0
- assert lease.refresh_tick() is None and calls == []
- locked["on"] = True
- # Original admission deadline was 1300. The renewal moved it to 1420.
- now[0] = 1300.0
- assert lease.refresh_tick() is None and calls == []
- now[0] = 1360.0
- assert lease.refresh_tick() is False
- assert calls
-
-
-def test_refresh_tick_real_loss_still_interrupts():
- db = _Db()
- db.refresh_session_turn_lease = lambda session_id, holder, **kwargs: False
- lease, calls = _active_lease(db)
-
- assert lease.refresh_tick() is False
- assert calls == ["Session turn lease lost; stopping to protect the transcript."]
-
-
-def test_refresh_tick_non_lock_error_still_interrupts():
- db = _Db()
-
- def broken(session_id, holder, **kwargs):
- raise sqlite3.OperationalError("disk I/O error")
-
- db.refresh_session_turn_lease = broken
- lease, calls = _active_lease(db)
+class _MovingClock:
+ """Wall clock that runs at real speed from a chosen instant, so the store's expiry stamps and
+ the lease's deadline arithmetic see the same time while real lock waits elapse."""
+
+ def __init__(self, at):
+ self._at, self._anchor = at, time.monotonic()
+
+ def time(self):
+ return self._at + (time.monotonic() - self._anchor)
+
+ def set(self, at):
+ self._at, self._anchor = at, time.monotonic()
+
+
+def test_lock_tolerance_never_outlives_the_committed_row_expiry(tmp_path, monkeypatch):
+ """Real SessionDB + a real second-connection write lock. The local deadline never runs past the
+ row's committed expiry (a renewal that waited for the lock), and a renewal blocked near expiry
+ gives up and stops the turn BEFORE the row becomes reclaimable, never after a successor could
+ take it. Control: the lock clearing lets the delayed renewal succeed with no interrupt."""
+ import hermes_state
+ import hermes_state_compression
+ from agent import turn_facade_lease
+
+ clock = _MovingClock(1000.0)
+ fake_time = SimpleNamespace(time=clock.time, monotonic=time.monotonic, sleep=time.sleep)
+ monkeypatch.setattr(turn_facade_lease, "time", fake_time)
+ monkeypatch.setattr(hermes_state_compression, "time", fake_time)
+
+ path = tmp_path / "state.db"
+ db = hermes_state.SessionDB(path)
+ db.create_session("s1", source="test")
+ assert db.try_acquire_session_turn_lease("s1", "h")
+ events = []
+ agent = SimpleNamespace(session_id="s1", interrupt=lambda msg, **kw: events.append((clock.time(), msg)))
+ lease = DurableTurnLease(agent, db, "s1", "h", expires_at=db.session_turn_lease_expires_at("s1", "h"))
+ lease.turn_active = True
- assert lease.refresh_tick() is False
- assert calls == [
+ def row_expiry():
+ return db.session_turn_lease_expires_at("s1", "h")
+
+ def write_lock():
+ conn = sqlite3.connect(path, timeout=0)
+ conn.execute("BEGIN IMMEDIATE")
+ return conn
+
+ # A renewal that waits on the lock still succeeds, and the deadline it adopts is not later than
+ # the expiry the store committed (stamped before the wait).
+ clock.set(1060.0)
+ blocker = write_lock()
+ worker = threading.Thread(target=lease.refresh_tick)
+ worker.start()
+ time.sleep(0.5)
+ blocker.rollback()
+ blocker.close()
+ worker.join(10)
+ assert events == []
+ assert lease._authority_deadline <= row_expiry()
+
+ # Near expiry with the lock held throughout: the renewal must give up and interrupt while the
+ # row is still unexpired, so no successor can reclaim it under a running turn.
+ clock.set(lease._authority_deadline - 3.0)
+ blocker = write_lock()
+ try:
+ assert lease.refresh_tick() is False
+ finally:
+ blocker.rollback()
+ blocker.close()
+ assert [msg for _, msg in events] == [
"Session turn lease could not be refreshed; stopping to protect the transcript."
]
+ assert events[0][0] < row_expiry()
+ db.close()
def test_interrupt_turn_only_while_active():