Skip to content

The agent that grows with you

fix(gateway): a deferred pick that fails to resolve is refused, never stalls the drain

Tekniumdb246c25f81c
diff --git a/gateway/session_deferred_pick.py b/gateway/session_deferred_pick.py
index 81372e864ea..725b6a02643 100644
--- a/gateway/session_deferred_pick.py
+++ b/gateway/session_deferred_pick.py
@@ -89,23 +89,28 @@ async def apply_deferred_pick(authority, ref, live):
if await asyncio.to_thread(has_mutation_receipt, authority.db, pick['principal_id'], ref.session_id,
application_id):
# Committed before a restart, not yet removed: never apply it twice.
- result = {}
- else:
- result = None
+ await asyncio.to_thread(authority.db._execute_write, lambda conn: conn.execute(
+ 'DELETE FROM state_meta WHERE key=? AND value=?', (key, stored[0])))
+ return
row = await asyncio.to_thread(authority.db.get_session, ref.session_id)
params = {'session_id': ref.session_id, 'request_id': application_id,
'expected_revision': row['runtime_revision'], 'expected_generation': row['runtime_generation'],
'operation': 'model', 'payload': pick['payload']}
from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS
try:
- if result is None:
- result = await write_mutation(authority, ref, params, None, principal_id=pick['principal_id'])
+ result = await write_mutation(authority, ref, params, None, principal_id=pick['principal_id'])
except MUTATION_GUARD_REFUSALS:
return # a worker still holds the transcript: the pick waits for the next boundary
except RuntimeStoreError as exc:
if exc.reason == 'session_busy':
return
result = {'session_id': ref.session_id, 'operation': 'model', 'status': 'refused', 'reason': exc.reason}
+ except Exception:
+ # Resolving the pick failed (provider auth, catalog, resolver crash). This runs before the
+ # claim, so letting it escape would kill or wedge the drain on the same pick forever.
+ logger.exception('Deferred model pick on %s failed to resolve', ref.session_id)
+ result = {'session_id': ref.session_id, 'operation': 'model', 'status': 'refused',
+ 'reason': 'model_resolution_failed'}
if result.get('status') == 'confirmation_required':
# A guarded target (cost / data policy / large context): nothing was written. The pick stays
# pending, marked as asked, and the owner's confirmation exchange goes to every viewer; the
diff --git a/hermes_state_mutation_retirement.py b/hermes_state_mutation_retirement.py
index 7d3402f3e17..b775f0743eb 100644
--- a/hermes_state_mutation_retirement.py
+++ b/hermes_state_mutation_retirement.py
@@ -1,7 +1,7 @@
"""Durable deletion fences outside prunable transcript rows."""
import json
import time
-from hermes_state_runtime import RuntimeStoreError, admission_fingerprint, _json, _text
+from hermes_state_runtime import RuntimeStoreError, admission_fingerprint, mutation_receipt_key, _json, _text
RETIRED_PREFIX = 'gateway.retired_session.v1.'
@@ -15,8 +15,8 @@ def retired_session(db, session_id):
def has_mutation_receipt(db, principal_id, session_id, request_id):
for value in (principal_id, session_id, request_id):
_text(value)
- key = 'gateway.mutation.v1.' + admission_fingerprint(
- canonical_target=session_id, payload={'principal': principal_id, 'request': request_id})
+ key, _digest = mutation_receipt_key(principal_id, session_id, request_id, operation='model', payload={},
+ expected_revision=0)
with db._read_ctx() as conn:
return conn.execute('SELECT 1 FROM state_meta WHERE key=?', (key,)).fetchone() is not None
diff --git a/tests/gateway/test_session_mutation_model_busy.py b/tests/gateway/test_session_mutation_model_busy.py
index 972f0c8030c..63596381142 100644
--- a/tests/gateway/test_session_mutation_model_busy.py
+++ b/tests/gateway/test_session_mutation_model_busy.py
@@ -324,3 +324,55 @@ async def test_a_refused_deferred_pick_names_the_reason_and_the_committed_model(
release.set()
await owner.close()
store.close_all_db_handles()
+
+
[email protected]('error', [RuntimeError, OSError])
+async def test_a_deferred_pick_that_raises_is_refused_and_the_queue_keeps_draining(tmp_path, monkeypatch, error):
+ from gateway.session_contract import Submission
+ from gateway.session_deferred_pick import _PREFIX
+ from hermes_cli import model_switch
+ import hermes_state_runtime as rt
+ started, release = threading.Event(), asyncio.Event()
+ events, seen, state, raising = [], [], {}, threading.Event()
+
+ async def handle(event):
+ seen.append((event.text, _running_model(state['authority'], state['ref'])))
+ if event.text == 'RUNNING':
+ started.set()
+ await release.wait()
+ return 'ok'
+ store, db, authority, owner, ref = _owner(tmp_path, monkeypatch, handle)
+ state.update(authority=authority, ref=ref)
+ switch = model_switch.switch_model
+
+ def resolve(**k):
+ if raising.is_set() and k['raw_input'] == 'boom':
+ raise error('resolver exploded')
+ return switch(**k)
+ monkeypatch.setattr(model_switch, 'switch_model', resolve)
+ stream = authority.sessions[ref.session_id].event_stream
+ publish = stream.publish
+ monkeypatch.setattr(stream, 'publish', lambda sid, payload, **k: (
+ events.append((k.get('event_type'), payload)), publish(sid, payload, **k))[1])
+ try:
+ await authority.submit(owner.actor, Submission('running', ref, {'text': 'RUNNING'}, 'queue'))
+ await async_wait_until(started.is_set, timeout=10, what='the first turn is running')
+ assert (await _mutate(owner, db, ref, 'pick', 'boom'))['result']['status'] == 'deferred'
+ raising.set()
+ nxt = await authority.submit(owner.actor, Submission('next', ref, {'text': 'NEXT'}, 'queue'))
+ release.set()
+ await async_wait_until(
+ lambda: rt.get_session_admission(db, admission_id=nxt.admission_id)['status'] == 'terminal',
+ timeout=10, what='the queued turn ran despite the failing pick')
+ assert seen == [('RUNNING', 'frozen'), ('NEXT', 'frozen')]
+ with db._read_ctx() as conn:
+ assert conn.execute('SELECT 1 FROM state_meta WHERE key=?',
+ (_PREFIX + ref.session_id,)).fetchone() is None
+ refused = [p for t, p in events if t == 'session.updated' and p.get('status') == 'refused']
+ assert refused and refused[0].items() >= {'operation': 'model', 'reason': 'model_resolution_failed',
+ 'target_model': 'boom', 'model': 'frozen'}.items()
+ finally:
+ release.set()
+ await owner.close()
+ store.close_all_db_handles()