Skip to content

The agent that grows with you

fix(gateway): a deferred model pick is accepted with a durable receipt and applied once

Teknium4dcad0e701a9
diff --git a/gateway/session_deferred_pick.py b/gateway/session_deferred_pick.py
index 909f95b4683..038ffc01b1c 100644
--- a/gateway/session_deferred_pick.py
+++ b/gateway/session_deferred_pick.py
@@ -14,39 +14,68 @@ _PREFIX = 'gateway.deferred_pick.v1.'
def defer_pick(authority, actor, ref, params):
- """Record *params* (an authorized ``model`` mutation refused only because a turn is running)."""
+ """Record *params* (an authorized ``model`` mutation refused only because a turn is running).
+
+ Blocking SQLite: callers run it off the event loop. Acceptance writes the request's durable
+ mutation receipt in the same transaction, so an exact retry returns this result instead of
+ overwriting a newer pick, and the stored pick carries a stable application id."""
from hermes_state_mutations import validate_action
- from hermes_state_runtime import _json
+ from hermes_state_runtime import _epoch, _json, mutation_receipt_key
validate_action('model', params['payload'])
- value = _json({'principal_id': actor.subject, 'request_id': params['request_id'], 'payload': params['payload']})
- authority.db._execute_write(lambda conn: conn.execute(
- 'INSERT INTO state_meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',
- (_PREFIX + ref.session_id, value)))
- row = authority.db.get_session(ref.session_id)
- return {'session_id': ref.session_id, 'operation': 'model', 'status': 'deferred',
- 'model': params['payload']['model'], 'revision': row['runtime_revision'],
- 'execution_generation': row['runtime_generation']}
+ key, digest = mutation_receipt_key(actor.subject, ref.session_id, params['request_id'], operation='model',
+ payload=params['payload'], expected_revision=params.get('expected_revision'),
+ expected_generation=params.get('expected_generation'))
+ value = _json({'principal_id': actor.subject, 'request_id': params['request_id'], 'payload': params['payload'],
+ 'application_id': 'deferred-pick:' + params['request_id']})
+
+ def write(conn):
+ _epoch(conn, authority.epoch)
+ old = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()
+ if old is not None:
+ receipt = json.loads(old[0])
+ if receipt['digest'] != digest:
+ raise RuntimeStoreError('admission_conflict')
+ return receipt['result']
+ row = conn.execute('SELECT runtime_revision, runtime_generation FROM sessions WHERE id=?',
+ (ref.session_id,)).fetchone()
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ result = {'session_id': ref.session_id, 'operation': 'model', 'status': 'deferred',
+ 'model': params['payload']['model'], 'revision': row[0], 'execution_generation': row[1]}
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',
+ (_PREFIX + ref.session_id, value))
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, _json({'digest': digest, 'result': result})))
+ return result
+ return authority.db._execute_write(write)
async def apply_deferred_pick(authority, ref, live):
"""Commit a deferred pick. The drain calls this under the claim gate and mutation lock, before
claiming, so no turn is running. A pick that no longer resolves is dropped and announced."""
import asyncio
- import uuid
from gateway.session_mutations import write_mutation
+ from hermes_state_mutation_retirement import has_mutation_receipt
key = _PREFIX + ref.session_id
with authority.db._read_ctx() as conn:
stored = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()
if stored is None:
return
pick = json.loads(stored[0])
+ application_id = pick['application_id']
+ 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
row = await asyncio.to_thread(authority.db.get_session, ref.session_id)
- params = {'session_id': ref.session_id, 'request_id': 'deferred-pick:' + uuid.uuid4().hex,
+ 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:
- result = await write_mutation(authority, ref, params, None, principal_id=pick['principal_id'])
+ if result is None:
+ 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:
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 8611f7313eb..8bebe15ec9e 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -269,6 +269,17 @@ def recover_session_inputs(db, *, epoch: int) -> int:
return db._execute_write(write)
+def mutation_receipt_key(principal_id, session_id, request_id, *, operation, payload, expected_revision,
+ expected_generation=None):
+ """``(state_meta key, digest)`` of a mutation request's durable exact-retry receipt."""
+ key = 'gateway.mutation.v1.' + admission_fingerprint(
+ canonical_target=session_id, payload={'principal': principal_id, 'request': request_id})
+ fingerprint = {'operation': operation, 'payload': payload, 'expected_revision': expected_revision}
+ if expected_generation is not None:
+ fingerprint['expected_generation'] = expected_generation
+ return key, admission_fingerprint(canonical_target=session_id, payload=fingerprint)
+
+
def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str,
request_id: str, expected_revision: int,
operation: str, payload: dict, expected_generation: int | None = None,
@@ -291,12 +302,8 @@ def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str
raise RuntimeStoreError('invalid_params')
# Snapshot caller data before waiting for the writer lock.
payload = json.loads(_json(payload))
- key = 'gateway.mutation.v1.' + admission_fingerprint(
- canonical_target=session_id, payload={'principal': principal_id, 'request': request_id})
- fingerprint = {'operation': operation, 'payload': payload, 'expected_revision': expected_revision}
- if expected_generation is not None:
- fingerprint['expected_generation'] = expected_generation
- digest = admission_fingerprint(canonical_target=session_id, payload=fingerprint)
+ key, digest = mutation_receipt_key(principal_id, session_id, request_id, operation=operation, payload=payload,
+ expected_revision=expected_revision, expected_generation=expected_generation)
def write(conn):
_epoch(conn, epoch)
diff --git a/tests/gateway/test_session_mutation_model_busy.py b/tests/gateway/test_session_mutation_model_busy.py
index fd04896a8c2..007a6197cc9 100644
--- a/tests/gateway/test_session_mutation_model_busy.py
+++ b/tests/gateway/test_session_mutation_model_busy.py
@@ -106,3 +106,56 @@ async def test_revision_conflict_refusal_carries_the_fresh_fences(tmp_path, monk
finally:
await owner.close()
store.close_all_db_handles()
+
+
+async def _mutate(owner, db, ref, rid, model, snap=None, *, call=1):
+ snap = snap or db.get_session(ref.session_id)
+ return await owner.dispatch({'id': call, 'method': 'session.mutate', 'params': {
+ 'session_id': ref.session_id, 'request_id': rid, 'expected_revision': snap['runtime_revision'],
+ 'expected_generation': snap['runtime_generation'], 'operation': 'model', 'payload': {'model': model}}})
+
+
+async def _run_turn(authority, owner, db, ref, name):
+ from gateway.session_contract import Submission
+ import hermes_state_runtime as rt
+ turn = await authority.submit(owner.actor, Submission(name, ref, {'text': name}, 'queue'))
+ await async_wait_until(
+ lambda: rt.get_session_admission(db, admission_id=turn.admission_id)['status'] == 'terminal',
+ timeout=10, what=f'turn {name} settled')
+
+
+async def test_a_retried_deferred_pick_does_not_undo_a_newer_pick(tmp_path, monkeypatch):
+ from gateway.session_contract import Submission
+ started, release = threading.Event(), asyncio.Event()
+ seen = []
+ state = {}
+
+ 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)
+ 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')
+ snap = db.get_session(ref.session_id)
+ first = await _mutate(owner, db, ref, 'pick-a', 'model-a', snap)
+ assert first['result']['status'] == 'deferred', first
+ newer = await _mutate(owner, db, ref, 'pick-b', 'model-b', call=2)
+ assert newer['result']['status'] == 'deferred', newer
+ # A's reply was lost: the client retries it with the same identity and fences.
+ retry = await _mutate(owner, db, ref, 'pick-a', 'model-a', snap, call=3)
+ assert retry['result'] == first['result']
+ release.set()
+ await _run_turn(authority, owner, db, ref, 'NEXT')
+ assert seen[-1] == ('NEXT', 'model-b')
+ assert db.get_session(ref.session_id)['model'] == 'model-b'
+ finally:
+ release.set()
+ await owner.close()
+ store.close_all_db_handles()
+