Skip to content

The agent that grows with you

fix: retry a storage-refused claim in place instead of killing the drain

Teknium92771433d875
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index bb166f6b3eb..27f4a54e23a 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import asyncio
from dataclasses import asdict, dataclass, field
from functools import partial
+import sqlite3
import uuid
from gateway.session_contract import (
@@ -22,6 +23,9 @@ from hermes_state_runtime import (
list_session_admissions, recover_session_inputs, resolve_unknown_session_input,
)
+# Capped backoff for a claim refused by transient storage (writer lock, full disk).
+_CLAIM_RETRY_MIN_S, _CLAIM_RETRY_MAX_S = 0.25, 5.0
+
@dataclass
class LiveSession:
@@ -555,6 +559,7 @@ class SessionAuthority:
from gateway.session_finite import execute_finite_admission
from gateway.session_managed_worker import ManagedExecutionUnknown
live = self.sessions[ref.session_id]
+ backoff = 0.0
while True:
try:
row, first = await self._claim_next(ref, live)
@@ -563,6 +568,21 @@ class SessionAuthority:
logging.getLogger(__name__).warning('Session %s paused: %s', ref.session_id, exc.reason)
self._pause(ref, exc.reason)
return
+ except (OSError, sqlite3.OperationalError) as exc:
+ # A writer held past its patience or a full disk is transient, and every _schedule
+ # caller is event-driven: a dead drain would strand the committed head and hang its
+ # waiters until the next submit. Retry in place (like recover_failed_settlement),
+ # keeping waiters: releasing them fails requests that would run a moment later.
+ if self.runner._draining or self.retiring or self.sessions.get(ref.session_id) is not live:
+ self._pause(ref, 'runtime_draining')
+ return
+ backoff = min(max(backoff * 2, _CLAIM_RETRY_MIN_S), _CLAIM_RETRY_MAX_S)
+ import logging
+ logging.getLogger(__name__).warning(
+ 'Session %s claim deferred by storage (%r); retrying in %.1fs', ref.session_id, exc, backoff)
+ await asyncio.sleep(backoff)
+ continue
+ backoff = 0.0
if row is False:
continue
if row is None and first is not None:
diff --git a/tests/gateway/test_session_authority_cancel_settlement.py b/tests/gateway/test_session_authority_cancel_settlement.py
index 5c9c70d8dca..aa3b0e08bfd 100644
--- a/tests/gateway/test_session_authority_cancel_settlement.py
+++ b/tests/gateway/test_session_authority_cancel_settlement.py
@@ -229,3 +229,43 @@ async def test_settlement_failure_is_logged_and_does_not_kill_the_drain(tmp_path
if r['admission_id'] == head.admission_id]
assert row['status'] == 'unknown', 'explicit recovery is possible without inventing a terminal result'
assert authority.sessions['s'].event_stream.execution == {}, 'stamp cleared even on failure'
+
+
+async def test_storage_lock_during_claim_retries_in_place_and_keeps_waiters(tmp_path, monkeypatch):
+ """A writer held past the claim's patience (or a full disk) is transient. The drain must not die
+ with the committed head queued and its waiter parked forever: every _schedule caller is
+ event-driven, so nothing would re-arm it. It retries in place and runs the head once."""
+ import sqlite3
+ from gateway import session_authority, session_finite
+
+ db, authority = _authority(tmp_path, monkeypatch)
+ monkeypatch.setattr(db, '_WRITE_PATIENCE_S', 0.2)
+ monkeypatch.setattr(session_authority, '_CLAIM_RETRY_MIN_S', 0.05, raising=False)
+ ran = []
+
+ async def execute(authority, ref, row):
+ ran.append(row['request_id'])
+ return 'done'
+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
+ schedule = authority._schedule
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ with db:
+ head = await _submit(authority, 'head')
+ waiter = authority.waiters.setdefault(head.admission_id, asyncio.get_running_loop().create_future())
+ blocker = sqlite3.connect(tmp_path / 'state.db', isolation_level=None)
+ blocker.execute('BEGIN IMMEDIATE')
+ try:
+ schedule(REF)
+ task = authority.sessions['s'].task
+ await asyncio.sleep(0.6)
+ assert not task.done(), task.exception() if task.done() else None
+ assert not waiter.done(), 'a transient storage error must not release accepted work'
+ finally:
+ blocker.execute('ROLLBACK')
+ blocker.close()
+ assert await asyncio.wait_for(waiter, 10) == 'done'
+ await asyncio.wait_for(task, 5)
+ assert ran == ['head']
+ row, = list_session_admissions(db, session_id='s', pending_only=False)
+ assert (row['status'], row['outcome']) == ('terminal', 'completed')