The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: retry a transient settlement failure before fencing the turn unknown
Teknium524316b31ed3
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex a89d063ea1d..f136e29cf24 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -642,12 +642,10 @@ class SessionAuthority:# Redaction, encoding and the SQLite write run off-loop: one turn's settlement must# not stall every other session. Commit and completion share one stream-lock hold# there; a tracked writer outlives a cancelled drain like the recovery stamp does.- from gateway.session_runtime_workers import track_mutation- from gateway.session_settlement_recovery import commit_and_publish+ from gateway.session_settlement_recovery import settle_with_retrycaptured = self.pending_results.get(admission_id)try:- await asyncio.shield(track_mutation(self, asyncio.to_thread(- commit_and_publish, self, live, ref, row, response, outcome, captured, settlement)))+ await settle_with_retry(self, live, ref, row, response, outcome, captured, settlement)finally:if 'settled' in settlement:settled, response = settlement['settled'], settlement['response']diff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.pyindex 5b778b8bfae..fdfbb470470 100644--- a/gateway/session_settlement_recovery.py+++ b/gateway/session_settlement_recovery.py@@ -94,6 +94,31 @@ def commit_and_publish(authority, live, ref, row, response, outcome, captured, s_publish_completion(authority, live, ref, row, settlement['settled'], settlement['response'], captured)+# Pauses between settlement attempts after a transient storage error (held writer past its+# patience, full disk). Bounded: the attempts after the last one fall back to the unknown fence.+_SETTLE_RETRY_DELAYS_S = (0.5, 2.0)+++async def settle_with_retry(authority, live, ref, row, response, outcome, captured, settlement):+ """Commit the captured result, retrying a transient storage failure a bounded number of times.++ One locked or full write must not turn a finished answer into an ``unknown`` turn whose result+ lives only in memory. Retrying is exact: a write that committed before reporting failure is+ read back by ``finish_result``, and a failure after the commit (``settled`` set) never retries.+ A fence refusal (``RuntimeStoreError``) is not transient and is raised at once."""+ from gateway.session_runtime_workers import track_mutation+ for delay in (*_SETTLE_RETRY_DELAYS_S, None):+ try:+ return await asyncio.shield(track_mutation(authority, asyncio.to_thread(+ commit_and_publish, authority, live, ref, row, response, outcome, captured, settlement)))+ except (OSError, sqlite3.Error) as exc:+ if delay is None or 'settled' in settlement:+ raise+ logger.warning('Settlement of admission %s deferred by storage (%r); retrying in %.1fs',+ row['admission_id'], exc, delay)+ await asyncio.sleep(delay)++def publish_terminal(authority, ref, row, settled, response, captured):"""Cleanup cannot withhold a committed outcome; publication is attempted once."""_publish_completion(authority, authority.sessions[ref.session_id], ref, row, settled, response, captured)diff --git a/tests/gateway/test_adversarial_settlement_review.py b/tests/gateway/test_adversarial_settlement_review.pyindex 8d8b32a75f9..95a6281a44b 100644--- a/tests/gateway/test_adversarial_settlement_review.py+++ b/tests/gateway/test_adversarial_settlement_review.py@@ -51,13 +51,16 @@ async def test_discard_during_recovery_stamp_does_not_replay_head_or_lose_followreturn row['request_id']monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)original = session_results.finish_result+ # Storage stays down across every bounded settlement attempt, so the claim reaches the+ # recovery stamp; it comes back once the stamp is entered (the follower settles normally).+ monkeypatch.setattr(session_settlement_recovery, '_SETTLE_RETRY_DELAYS_S', (0.01, 0.01), raising=False)def unavailable(*args, **kwargs):- monkeypatch.setattr(session_results, 'finish_result', original)raise OSError('lost settlement')monkeypatch.setattr(session_results, 'finish_result', unavailable)mark = session_settlement_recovery._mark_unknownentered, release = threading.Event(), threading.Event()def held_mark(*args):+ monkeypatch.setattr(session_results, 'finish_result', original)result = mark(*args)entered.set()assert release.wait(10)diff --git a/tests/gateway/test_live_settlement_recovery.py b/tests/gateway/test_live_settlement_recovery.pyindex 236bcf95e3d..d18a94edea9 100644--- a/tests/gateway/test_live_settlement_recovery.py+++ b/tests/gateway/test_live_settlement_recovery.py@@ -24,10 +24,13 @@ async def test_failed_commit_retains_result_and_releases_fifo_for_explicit_discareturn row['request_id'] + ' done'monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)original = session_results.finish_result- def fail_once(*args, **kwargs):- monkeypatch.setattr(session_results, 'finish_result', original)- raise OSError('temporary settlement write failure')- monkeypatch.setattr(session_results, 'finish_result', fail_once)+ from gateway import session_settlement_recovery as recovery+ # Settlement retries a transient failure a bounded number of times; storage that stays down+ # across every attempt is what leaves the claim as recoverable uncertainty.+ monkeypatch.setattr(recovery, '_SETTLE_RETRY_DELAYS_S', (0.01, 0.01), raising=False)+ def unavailable(*args, **kwargs):+ raise OSError('settlement storage unavailable')+ monkeypatch.setattr(session_results, 'finish_result', unavailable)if retry_recovery_write:from gateway import session_settlement_recoverymark = session_settlement_recovery._mark_unknown@@ -41,6 +44,7 @@ async def test_failed_commit_retains_result_and_releases_fifo_for_explicit_discawaiting = [authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())for receipt in (head, follower)]await asyncio.wait_for(authority._drain(REF), 5)+ monkeypatch.setattr(session_results, 'finish_result', original)row = get_session_admission(db, admission_id=head.admission_id)assert row['status'] == 'unknown' and row['owner_epoch'] == authority.epochassert authority.pending_results[head.admission_id]['result']['final_response'] == 'head done'@@ -80,3 +84,40 @@ async def test_commit_then_error_publishes_the_exact_committed_result(tmp_path,complete, = [f['params']['payload'] for f in frames if f['params']['type'] == 'message.complete']assert complete['text'] == 'done' and complete['response_reused'] is Trueassert receipt.admission_id not in authority.pending_results+++async def test_transient_settlement_failure_commits_the_completed_result(tmp_path, monkeypatch):+ """One locked/full write must not turn a finished answer into an ``unknown`` turn whose result+ lives only in memory: settlement retries, commits the exact result once, and the FIFO moves on."""+ from gateway import session_results+ from gateway import session_settlement_recovery as recovery+ db, authority = _authority(tmp_path, monkeypatch)+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ monkeypatch.setattr(recovery, '_SETTLE_RETRY_DELAYS_S', (0.01, 0.01), raising=False)+ calls, frames = [], []+ authority.sessions['s'].event_stream.observers.add(frames.append)+ async def execute(owner, ref, row):+ calls.append(row['request_id'])+ owner.pending_results[row['admission_id']] = {+ 'result': {'final_response': row['request_id'] + ' done', 'completed': True}, 'usage': {}}+ return row['request_id'] + ' done'+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ original = session_results.finish_result+ def fail_once(*args, **kwargs):+ monkeypatch.setattr(session_results, 'finish_result', original)+ raise OSError('temporary settlement write failure')+ monkeypatch.setattr(session_results, 'finish_result', fail_once)+ with db:+ head = await authority.submit(ACTOR, Submission('head', REF, {'text': 'head'}, 'queue'))+ follower = await authority.submit(ACTOR, Submission('follower', REF, {'text': 'follower'}, 'queue'))+ waiter = authority.waiters.setdefault(head.admission_id, asyncio.get_running_loop().create_future())+ await asyncio.wait_for(authority._drain(REF), 5)+ assert await waiter == 'head done'+ row = get_session_admission(db, admission_id=head.admission_id)+ assert (row['status'], row['outcome']) == ('terminal', 'completed')+ assert head.admission_id not in authority.pending_results+ assert get_session_admission(db, admission_id=follower.admission_id)['status'] == 'terminal'+ assert calls == ['head', 'follower'], 'a settlement retry must never re-run inference'+ completions = [f['params']['payload'] for f in frames if f['params']['type'] == 'message.complete']+ assert [c['text'] for c in completions] == ['head done', 'follower done']