Skip to content

The agent that grows with you

fix(state): a busy state.db is not a turn-lease wait

kshitijk4poor73f7fc2ca54c
diff --git a/agent/turn_facade_lease.py b/agent/turn_facade_lease.py
index b0f13e308cb..2f1b14bf397 100644
--- a/agent/turn_facade_lease.py
+++ b/agent/turn_facade_lease.py
@@ -260,11 +260,18 @@ def admit_durable_turn_lease(
holder = (
f"pid={os.getpid()}:turn={relay_turn_id}:platform={task_context['platform'] or 'unknown'}"
)
- waited = False
+ reload_needed = announced = False
+
+ def _on_contended() -> None:
+ # A busy state.db, not a known holder: say nothing, but still reload after admission,
+ # since the busy writer may have been the previous holder's final flush (one that fits
+ # inside the write patience never gets here, before or after this signal existed).
+ nonlocal reload_needed
+ reload_needed = True
def _on_wait(elapsed: float) -> None:
- nonlocal waited
- waited = True
+ nonlocal reload_needed, announced
+ reload_needed = announced = True
agent._emit_status(
"⏳ Another Hermes process is using this session; "
"waiting for it to finish before starting your turn..."
@@ -274,7 +281,8 @@ def admit_durable_turn_lease(
if not db.acquire_session_turn_lease(
session_id, holder, ttl_seconds=LEASE_TTL_SECONDS, wait_seconds=LEASE_WAIT_SECONDS,
- on_wait=_on_wait, should_abort=lambda: getattr(agent, "_interrupt_requested", False),
+ on_wait=_on_wait, on_contended=_on_contended,
+ should_abort=lambda: getattr(agent, "_interrupt_requested", False),
):
admission.early_result = _lease_not_acquired_result(agent, session_id, conversation_history)
return admission
@@ -297,8 +305,9 @@ def admit_durable_turn_lease(
# row is written, and reloading an absent row would erase that seed. An unknown row still
# reads the transcript after a wait and adopts it only if it returns rows; that read
# raising ends the turn.
- if waited and durable is not False:
- agent._emit_status("Session is free; loading the latest transcript...")
+ if reload_needed and durable is not False:
+ if announced:
+ agent._emit_status("Session is free; loading the latest transcript...")
# The holder may have compressed/rotated the session while we waited: reload only
# AFTER admission; an immediate acquisition skips this (needless prompt-cache miss).
latest_session_id = db.resolve_resume_session_id(session_id)
diff --git a/hermes_state_compression.py b/hermes_state_compression.py
index c09196cc58b..aa1be22bb03 100644
--- a/hermes_state_compression.py
+++ b/hermes_state_compression.py
@@ -576,12 +576,17 @@ class SessionCompressionMixin:
self, session_id: str, holder: str, *, ttl_seconds: float = 300.0,
wait_seconds: float = 1800.0, poll_interval_seconds: float = 1.0, on_wait=None,
wait_notice_interval_seconds: float = 15.0, should_abort=None, acquire_patience_s: float = 0.5,
+ on_contended=None,
) -> bool:
"""Wait for a cross-process turn lease without holding a SQLite lock. ``on_wait(elapsed)`` is
- best-effort: called when the first attempt fails and about every ``wait_notice_interval_seconds``
- after. ``should_abort()`` True (e.g. ``/stop``) returns False at once."""
+ best-effort: called when another holder has the lease and about every
+ ``wait_notice_interval_seconds`` after. A busy database is not a holder: the attempt is
+ retried at once with a longer write patience, and ``on_contended()`` is called instead,
+ since the busy writer may be the holder's last flush. ``should_abort()`` True (e.g.
+ ``/stop``) returns False at once."""
from hermes_state import classify_persistence_error
deadline = time.monotonic() + max(0.0, float(wait_seconds))
+ patience = acquire_patience_s
wait_started = None
last_notice_at = None
notice_every = max(0.0, float(wait_notice_interval_seconds))
@@ -594,13 +599,25 @@ class SessionCompressionMixin:
logger.debug("session turn lease should_abort callback failed", exc_info=True)
try:
if self.try_acquire_session_turn_lease(
- session_id, holder, ttl_seconds=ttl_seconds, patience_s=acquire_patience_s):
+ session_id, holder, ttl_seconds=ttl_seconds, patience_s=patience):
return True
except sqlite3.Error as exc:
- # Long holder transactions can exhaust one write-patience budget; keep
- # polling until wait_seconds or should_abort.
+ # Another writer's transaction outlasted the write patience. That is not a lease
+ # holder, so no poll sleep or "another process" notice; the retry waits on the write
+ # lock itself (the poll interval moves into its patience) and wins it once free.
if classify_persistence_error(exc) != "locked":
raise
+ if on_contended is not None:
+ try:
+ on_contended()
+ except Exception:
+ logger.debug("session turn lease on_contended callback failed", exc_info=True)
+ patience = min(acquire_patience_s + max(0.0, float(poll_interval_seconds)),
+ max(acquire_patience_s, deadline - time.monotonic()))
+ if not self._sleep_before_write_retry(deadline, 0.0):
+ return False
+ continue
+ patience = acquire_patience_s
now = time.monotonic()
remaining = deadline - now
if remaining <= 0:
diff --git a/tests/agent/test_cross_process_turn_lease.py b/tests/agent/test_cross_process_turn_lease.py
index 70bfbdb9264..f257b9a585e 100644
--- a/tests/agent/test_cross_process_turn_lease.py
+++ b/tests/agent/test_cross_process_turn_lease.py
@@ -69,7 +69,10 @@ def _agent_with_db(db, *, session_id="stale-parent", platform="desktop"):
return agent
-def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch):
[email protected]("signal", ["on_wait", "on_contended"])
+def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch, signal):
+ """A lease wait and a busy-database retry both reload after admission (the busy writer may
+ be the previous holder's final flush); only a real holder is announced to the user."""
db = _DB()
agent = _agent_with_db(db)
status_events = []
@@ -88,12 +91,9 @@ def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch):
observed["relay_cwd_session_id"] = session_id
return "", ""
- # Simulate a contended wait so the resume status path is covered.
def acquire_with_wait(session_id, holder, **kwargs):
db.events.append(("acquire", session_id, holder))
- on_wait = kwargs.get("on_wait")
- if on_wait is not None:
- on_wait(0.0)
+ kwargs[signal](*((0.0,) if signal == "on_wait" else ()))
return True
db.acquire_session_turn_lease = acquire_with_wait
@@ -122,7 +122,9 @@ def test_run_conversation_acquires_then_reloads_latest_tip(monkeypatch):
"repair_alternation": True,
"include_row_ids": True,
}
- assert any(kind == "lifecycle" and text for kind, text in status_events)
+ texts = [text or "" for _kind, text in status_events]
+ for notice in ("Another Hermes process", "Session is free"):
+ assert any(notice in text for text in texts) is (signal == "on_wait"), notice
def test_run_conversation_acquires_lease_when_session_probe_raises(monkeypatch):
diff --git a/tests/hermes_state/test_session_turn_lease.py b/tests/hermes_state/test_session_turn_lease.py
index d2322276f81..33860377360 100644
--- a/tests/hermes_state/test_session_turn_lease.py
+++ b/tests/hermes_state/test_session_turn_lease.py
@@ -366,7 +366,9 @@ def test_acquire_turn_lease_honors_should_abort(tmp_path):
def test_acquire_turn_lease_retries_sqlite_lock(tmp_path, monkeypatch):
- """Write-lock exhaustion is contended, not a hard abort of the wait."""
+ """Write-lock exhaustion is retried, not a hard abort of the wait, and is not a lease wait:
+ it reports on_contended instead of on_wait and does not sit out a poll interval on top of
+ the patience it already spent."""
db = SessionDB(tmp_path / "state.db")
db.create_session("shared", source="test")
holder = f"pid={os.getpid()}:turn=waiter"
@@ -383,17 +385,39 @@ def test_acquire_turn_lease_retries_sqlite_lock(tmp_path, monkeypatch):
return original(*args, **kwargs)
monkeypatch.setattr(db, "try_acquire_session_turn_lease", flaky_acquire)
+ notices, contended = [], []
+ started = time.monotonic()
assert db.acquire_session_turn_lease(
"shared",
holder,
- wait_seconds=2,
- poll_interval_seconds=0.02,
+ wait_seconds=10,
+ poll_interval_seconds=5,
+ on_wait=notices.append,
+ on_contended=lambda: contended.append(True),
acquire_patience_s=0.05,
)
+ assert time.monotonic() - started < 2.0
+ assert (notices, contended) == ([], [True])
assert attempts["n"] >= 2
db.release_session_turn_lease("shared", holder)
+def test_acquire_turn_lease_locked_for_the_whole_wait_times_out(tmp_path, monkeypatch):
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("shared", source="test")
+
+ def locked(*args, **kwargs):
+ raise sqlite3.OperationalError("database is locked")
+
+ monkeypatch.setattr(db, "try_acquire_session_turn_lease", locked)
+ notices = []
+ assert not db.acquire_session_turn_lease(
+ "shared", f"pid={os.getpid()}:turn=waiter", wait_seconds=0.3, poll_interval_seconds=5,
+ on_wait=notices.append,
+ )
+ assert notices == []
+
+
def test_acquire_turn_lease_reraises_non_lock_sqlite_error(tmp_path, monkeypatch):
db = SessionDB(tmp_path / "state.db")
db.create_session("shared", source="test")