fix: retry a transient settlement failure before fencing the turn unknown
After 562aeb62 a settlement write that raised (writer held past its
patience, full disk) went straight to recover_failed_settlement: the claim
was stamped unknown, every waiter got unknown_execution, the FIFO paused and
the completed answer lived only in pending_results until an operator
discarded it. One transient storage blip therefore lost a finished answer
and stopped the conversation.
Settlement itself now retries transient storage errors (OSError /
sqlite3.Error) a bounded number of times (after 0.5 s and 2 s) before the
unknown fence. The retry is exact: finish_result reads back a write that
committed before reporting failure, a failure after the commit
('settled' in settlement) is never retried, and a fence refusal
(RuntimeStoreError, e.g. stale_generation) is not retried. Storage that stays
down across every attempt keeps 562aeb62's behaviour. The recovery stamp's
own retry stays unbounded by design: without it the claim cannot be fenced
at all, and it runs under tracked owner lifetime.
Two existing tests injected exactly one settlement failure to reach the
unknown fence; they now keep storage down across the bounded attempts
(still asserting the same unknown/discard/no-replay invariants), and a new
test pins that one transient failure commits the exact result, completes
the waiter, publishes one completion per turn and never re-runs inference.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5462648005
This commit is contained in:
@@ -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_retry
|
||||
captured = 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']
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -51,13 +51,16 @@ async def test_discard_during_recovery_stamp_does_not_replay_head_or_lose_follow
|
||||
return 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_unknown
|
||||
entered, 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)
|
||||
|
||||
@@ -24,10 +24,13 @@ async def test_failed_commit_retains_result_and_releases_fifo_for_explicit_disca
|
||||
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)
|
||||
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_recovery
|
||||
mark = session_settlement_recovery._mark_unknown
|
||||
@@ -41,6 +44,7 @@ async def test_failed_commit_retains_result_and_releases_fifo_for_explicit_disca
|
||||
waiting = [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.epoch
|
||||
assert 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 True
|
||||
assert receipt.admission_id not in authority.pending_results
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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']
|
||||
|
||||
Reference in New Issue
Block a user