Skip to content

The agent that grows with you

fix(gateway): a model pick on a running session applies to the next turn

Teknium51357f428393
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 3da20636edd..a1bb6ee0005 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -787,6 +787,10 @@ class SessionAuthority:
raise RuntimeStoreError('unknown_execution')
first = next((row for row in pending if row['status'] == 'queued'), None)
from gateway.config import Platform
+ if live.source.platform == Platform.LOCAL:
+ # A model pick made while the previous turn ran lands here, at the turn boundary.
+ from gateway.session_deferred_pick import apply_deferred_pick
+ await apply_deferred_pick(self, ref, live)
if first is not None and live.source.platform == Platform.LOCAL:
from gateway.session_local_recovery import restore_local_session
restore_local_session(self, ref.session_id)
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 80d322f8762..116adfa09e8 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -26,6 +26,9 @@ def _refusal_data(exc: RuntimeStoreError) -> dict:
value = getattr(exc, key, None)
if value:
data[key] = value
+ for key in ('revision', 'execution_generation'):
+ if isinstance(getattr(exc, key, None), int):
+ data[key] = getattr(exc, key)
return data
@@ -595,6 +598,13 @@ class AuthorityConnection:
# A live turn lease / compression lock is the same retryable busy verdict a
# running admission gets (REST maps it to 409), not an internal error.
raise RuntimeStoreError('session_busy') from exc
+ except RuntimeStoreError as exc:
+ if exc.reason in {'revision_conflict', 'stale_generation'}:
+ # The fresh fences ride on the refusal, so the client retries once without a re-read.
+ row = self.authority.db.get_session(ref.session_id)
+ if row is not None:
+ exc.revision, exc.execution_generation = row['runtime_revision'], row['runtime_generation']
+ raise
# The branching viewer navigates straight into its new child; attach it
# here (create parity) so the first submit is not refused as a stranger.
child = result.get('branched_session_id') if isinstance(result, dict) else None
diff --git a/gateway/session_deferred_pick.py b/gateway/session_deferred_pick.py
new file mode 100644
index 00000000000..909f95b4683
--- /dev/null
+++ b/gateway/session_deferred_pick.py
@@ -0,0 +1,63 @@
+"""A model pick on a session with a running turn lands for the next turn (RT-12).
+
+The pick is authorized and validated when it arrives, kept durably in ``state_meta`` (latest pick
+wins, survives an owner restart), and committed through ``session.mutate``'s own writer by the
+drain at the next claim boundary, when nothing is executing. The running turn keeps its route.
+"""
+import json
+import logging
+
+from hermes_state_runtime import RuntimeStoreError
+
+logger = logging.getLogger(__name__)
+_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)."""
+ from hermes_state_mutations import validate_action
+ from hermes_state_runtime import _json
+ 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']}
+
+
+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
+ 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])
+ 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,
+ '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'])
+ 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}
+ 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')
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index 0ee94c851fb..505cc34ea15 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -8,6 +8,7 @@ import asyncio
from contextlib import nullcontext
from functools import partial
+from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS
from hermes_state_runtime import RuntimeStoreError, mutate_runtime_session
_METADATA = frozenset({'rename', 'archive', 'sidebar'})
@@ -92,7 +93,14 @@ async def _owned_mutation(authority, actor, ref, params):
result = await _mutate_session(authority, actor, ref, params, commit_lock=live.mutation_lock)
else:
async with live.mutation_lock:
- result = await _mutate_session(authority, actor, ref, params)
+ try:
+ result = await _mutate_session(authority, actor, ref, params)
+ except (RuntimeStoreError, *MUTATION_GUARD_REFUSALS) as exc:
+ # A pick on a running session is for the next turn (the running turn keeps its route).
+ if params.get('operation') != 'model' or getattr(exc, 'reason', 'session_busy') != 'session_busy':
+ raise
+ from gateway.session_deferred_pick import defer_pick
+ return defer_pick(authority, actor, ref, params)
if params.get('operation') in {*_POLICY, 'compress', 'reset'}:
authority._schedule(ref)
return result
diff --git a/tests/gateway/test_session_mutation_model_busy.py b/tests/gateway/test_session_mutation_model_busy.py
new file mode 100644
index 00000000000..fd04896a8c2
--- /dev/null
+++ b/tests/gateway/test_session_mutation_model_busy.py
@@ -0,0 +1,108 @@
+"""A model pick on a session with a running turn lands for the next turn (RT-12, #138771)."""
+import asyncio
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from tests.waiting import async_wait_until
+
+
+def _owner(tmp_path, monkeypatch, handle):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import SessionAuthority
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_local import create_local_session
+ from hermes_cli import model_switch
+ import hermes_state_runtime as rt
+ monkeypatch.setattr(run, '_load_gateway_config', lambda *a: {})
+ monkeypatch.setattr(model_switch, 'switch_model', lambda **k: model_switch.ModelSwitchResult(
+ success=True, new_model=k['raw_input'], target_provider='custom', base_url='http://127.0.0.1:9/v1'))
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ db = store._db
+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,
+ _evict_cached_agent=lambda route: None, _handle_message=handle,
+ _resolve_session_agent_runtime=lambda **k: ('frozen', {}))
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db,
+ epoch=rt.begin_runtime_epoch(db, instance_id='owner'))
+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})
+ ref = create_local_session(authority, owner.actor, dict(request_id='m', source='gui', cwd=str(tmp_path),
+ model='frozen', toolsets=[]))
+ return store, db, authority, owner, ref
+
+
+def _running_model(authority, ref):
+ from gateway.config import Platform
+ from gateway.session_local_recovery import local_adapter_map
+ live = authority.sessions[ref.session_id]
+ return local_adapter_map(authority)[Platform.LOCAL].policies[live.source.chat_id].model
+
+
+async def test_model_pick_during_a_running_turn_applies_to_the_next_turn(tmp_path, monkeypatch):
+ from gateway.session_contract import Submission
+ import hermes_state_runtime as rt
+ 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:
+ first = 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)
+ reply = await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {
+ 'session_id': ref.session_id, 'request_id': 'pick', 'expected_revision': snap['runtime_revision'],
+ 'expected_generation': snap['runtime_generation'], 'operation': 'model', 'payload': {'model': 'picked'}}})
+ assert 'result' in reply, reply
+ assert reply['result']['status'] == 'deferred'
+ # The running turn keeps its route.
+ assert _running_model(authority, ref) == 'frozen'
+ release.set()
+ await async_wait_until(
+ lambda: rt.get_session_admission(db, admission_id=first.admission_id)['status'] == 'terminal',
+ timeout=10, what='the running turn settled')
+ await async_wait_until(lambda: _running_model(authority, ref) == 'picked',
+ timeout=10, what='the pick published at the turn boundary')
+ second = await authority.submit(owner.actor, Submission('next', ref, {'text': 'NEXT'}, 'queue'))
+ await async_wait_until(
+ lambda: rt.get_session_admission(db, admission_id=second.admission_id)['status'] == 'terminal',
+ timeout=10, what='the next turn ran')
+ assert seen == [('RUNNING', 'frozen'), ('NEXT', 'picked')]
+ assert db.get_session(ref.session_id)['model'] == 'picked'
+ finally:
+ release.set()
+ await owner.close()
+ store.close_all_db_handles()
+
+
+async def test_revision_conflict_refusal_carries_the_fresh_fences(tmp_path, monkeypatch):
+ async def handle(event):
+ return 'ok'
+ store, db, _authority, owner, ref = _owner(tmp_path, monkeypatch, handle)
+ try:
+ snap = db.get_session(ref.session_id)
+ reply = await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {
+ 'session_id': ref.session_id, 'request_id': 'stale', 'expected_revision': snap['runtime_revision'] + 7,
+ 'expected_generation': snap['runtime_generation'], 'operation': 'model', 'payload': {'model': 'picked'}}})
+ data = reply['error']['data']
+ assert data['reason'] == 'revision_conflict'
+ assert (data['revision'], data['execution_generation']) == (snap['runtime_revision'], snap['runtime_generation'])
+ retry = await owner.dispatch({'id': 2, 'method': 'session.mutate', 'params': {
+ 'session_id': ref.session_id, 'request_id': 'retry', 'expected_revision': data['revision'],
+ 'expected_generation': data['execution_generation'], 'operation': 'model', 'payload': {'model': 'picked'}}})
+ assert retry['result']['model'] == 'picked'
+ finally:
+ await owner.close()
+ store.close_all_db_handles()