Skip to content

The agent that grows with you

fix(gateway): a guarded deferred pick asks for confirmation instead of being dropped

Tekniumdcb7db2d9482
diff --git a/gateway/session_deferred_pick.py b/gateway/session_deferred_pick.py
index a79711b9cda..8b29f8b1409 100644
--- a/gateway/session_deferred_pick.py
+++ b/gateway/session_deferred_pick.py
@@ -64,6 +64,8 @@ async def apply_deferred_pick(authority, ref, live):
if stored is None:
return
pick = json.loads(stored[0])
+ if 'awaiting_confirm' in pick:
+ return # asked once; the user's confirmed (or a newer) selection supersedes it
application_id = pick['application_id']
if await asyncio.to_thread(has_mutation_receipt, authority.db, pick['principal_id'], ref.session_id,
application_id):
@@ -85,11 +87,19 @@ async def apply_deferred_pick(authority, ref, live):
if exc.reason == 'session_busy':
return
result = {'session_id': ref.session_id, 'operation': 'model', 'status': 'refused', 'reason': exc.reason}
+ 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
+ # confirmed resend (``payload.confirm``) commits it through session.mutate.
+ from hermes_state_runtime import _json
+ await asyncio.to_thread(authority.db._execute_write, lambda conn: conn.execute(
+ 'UPDATE state_meta SET value=? WHERE key=? AND value=?',
+ (_json({**pick, 'awaiting_confirm': result['confirm']}), key, stored[0])))
+ live.event_stream.publish(ref.session_id, {**result, 'payload': pick['payload']},
+ event_type='session.updated')
+ return
await asyncio.to_thread(authority.db._execute_write, lambda conn: conn.execute(
'DELETE FROM state_meta WHERE key=? AND value=?', (key, stored[0])))
- if result.get('status') in {'refused', 'confirmation_required'}:
- logger.warning('Deferred model pick on %s not applied: %s', ref.session_id,
- result.get('reason') or result['status'])
- live.event_stream.publish(ref.session_id, {**result, 'status': 'refused',
- 'reason': result.get('reason') or result['status']},
- event_type='session.updated')
+ if result.get('status') == 'refused':
+ logger.warning('Deferred model pick on %s not applied: %s', ref.session_id, result.get('reason'))
+ live.event_stream.publish(ref.session_id, result, event_type='session.updated')
diff --git a/tests/gateway/test_session_mutation_model_busy.py b/tests/gateway/test_session_mutation_model_busy.py
index c73693c9ecf..8e05605364a 100644
--- a/tests/gateway/test_session_mutation_model_busy.py
+++ b/tests/gateway/test_session_mutation_model_busy.py
@@ -229,3 +229,60 @@ async def test_pending_pick_writes_do_not_stall_the_event_loop(tmp_path, monkeyp
release.set()
await owner.close()
store.close_all_db_handles()
+
+
+async def test_a_guarded_deferred_pick_asks_for_confirmation_instead_of_being_dropped(tmp_path, monkeypatch):
+ from agent.usage_anchor import USAGE_ANCHOR_MODEL_CONFIG_KEY, capture_usage_anchor
+ from gateway.session_contract import Submission
+ from hermes_cli import model_selection_guards
+ monkeypatch.setattr(model_selection_guards, '_context_cache_threshold', lambda: 1000)
+ started, release = threading.Event(), asyncio.Event()
+ seen, events = [], []
+ 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)
+ authority.runner._cached_agent_for = lambda route: None
+ 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:
+ db.append_message(ref.session_id, role='user', content='hello')
+ db.append_message(ref.session_id, role='assistant', content='hi')
+ db.patch_session_model_config(ref.session_id, {USAGE_ANCHOR_MODEL_CONFIG_KEY: capture_usage_anchor(
+ 250_000, 10, db.get_messages_as_conversation(ref.session_id))})
+ 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', 'guarded'))['result']['status'] == 'deferred'
+ release.set()
+
+ def asks():
+ return [p for t, p in events if t == 'session.updated' and p.get('status') == 'confirmation_required']
+ # The running turn settled: the drain resolves the pick and asks instead of dropping it.
+ await async_wait_until(lambda: asks(), timeout=10, what='the guarded pick asked for confirmation')
+ ask = asks()[0]
+ assert ask['target_model'] == 'guarded' and ask['payload'] == {'model': 'guarded'}
+ assert not [p for t, p in events if p.get('status') == 'refused']
+ assert _running_model(authority, ref) == 'frozen'
+ # The user confirms: the canonical resend carries the owner's token and commits.
+ snap = db.get_session(ref.session_id)
+ confirmed = await owner.dispatch({'id': 9, 'method': 'session.mutate', 'params': {
+ 'session_id': ref.session_id, 'request_id': 'confirmed', 'expected_revision': snap['runtime_revision'],
+ 'expected_generation': snap['runtime_generation'], 'operation': 'model',
+ 'payload': {'model': 'guarded', 'confirm': ask['confirm']}}})
+ assert confirmed['result']['model'] == 'guarded', confirmed
+ assert len(asks()) == 1
+ await _run_turn(authority, owner, db, ref, 'AFTER')
+ assert seen[-1] == ('AFTER', 'guarded')
+ finally:
+ release.set()
+ await owner.close()
+ store.close_all_db_handles()