Skip to content

The agent that grows with you

fix(gateway): a guarded deferred pick is asked again after an owner restart

Teknium0733db401351
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index a1bb6ee0005..e074c5b0417 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -54,6 +54,8 @@ class LiveSession:
# (a contended SQLite writer must not stall loop-side lock takers); readers holding that lock
# still see the claim as started, so no snapshot shows a terminal row without its completion.
settling: dict = field(default_factory=dict)
+ # A viewer attached while a guarded deferred pick awaits consent: the next boundary asks again.
+ reask_pick: bool = False
def __post_init__(self):
self.controls = PendingControls(self.event_stream)
@@ -235,9 +237,12 @@ class SessionAuthority:
active_generation = handle.execution_generation if handle.execution_state == "running" else None
prompts = live.controls.snapshot(ref.session_id, active_generation)
epoch, sequence = live.event_stream.watermark()
- return SubscriptionSnapshot(subscription, handle, epoch,
+ snapshot = SubscriptionSnapshot(subscription, handle, epoch,
sequence, tuple(local_history(self, ref)),
tuple(self._pending_receipt(r) for r in self._pending_rows(ref)), prompts)
+ from gateway.session_deferred_pick import reask_on_attach
+ await reask_on_attach(self, ref, live)
+ return snapshot
def _retire_overflowed(self, session_id, transport):
"""The fanout dropped this peer's backlog: its subscription is over even though the
diff --git a/gateway/session_deferred_pick.py b/gateway/session_deferred_pick.py
index 112cd36a3db..0b046acf253 100644
--- a/gateway/session_deferred_pick.py
+++ b/gateway/session_deferred_pick.py
@@ -49,6 +49,20 @@ def defer_pick(authority, actor, ref, params):
return authority.db._execute_write(write)
+async def reask_on_attach(authority, ref, live):
+ """A guarded pick asked only the viewers present at its boundary (and an owner restart drops
+ the stream): a newly attached viewer gets the ask again, re-checked at the next boundary."""
+ import asyncio
+
+ def read():
+ with authority.db._read_ctx() as conn:
+ return conn.execute('SELECT value FROM state_meta WHERE key=?', (_PREFIX + ref.session_id,)).fetchone()
+ stored = await asyncio.to_thread(read)
+ if stored is not None and 'awaiting_confirm' in json.loads(stored[0]):
+ live.reask_pick = True
+ authority._schedule(ref)
+
+
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."""
@@ -65,7 +79,12 @@ async def apply_deferred_pick(authority, ref, live):
return
pick = json.loads(stored[0])
if 'awaiting_confirm' in pick:
- return # asked once; the user's confirmed (or a newer) selection supersedes it
+ if not live.reask_pick:
+ return # asked; the user's confirmed (or a newer) selection supersedes it
+ # Asked again for a newly attached viewer: re-prepared under the current fences, so a guard
+ # that still applies mints a fresh token (the stored one is never replayed as consent).
+ pick = {k: v for k, v in pick.items() if k != 'awaiting_confirm'}
+ live.reask_pick = False
application_id = pick['application_id']
if await asyncio.to_thread(has_mutation_receipt, authority.db, pick['principal_id'], ref.session_id,
application_id):
diff --git a/tests/gateway/test_session_deferred_pick_restart.py b/tests/gateway/test_session_deferred_pick_restart.py
new file mode 100644
index 00000000000..bceba35fc33
--- /dev/null
+++ b/tests/gateway/test_session_deferred_pick_restart.py
@@ -0,0 +1,158 @@
+"""A guarded deferred model pick stays answerable across a real owner restart (#139604 review)."""
+import asyncio
+from http.server import ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import sqlite3
+import threading
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import daemon, websocket
+from tests.gateway.test_session_mutation_model import CatalogModel
+from tests.waiting import async_wait_until
+
+
+class _MeasuredModel(CatalogModel):
+ """Streams report provider usage, so the owner measures the session's context."""
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ if body.get('messages'):
+ self.server.requests.append(body)
+ text = next((m.get('content', '') for m in reversed(body.get('messages', [])) if m['role'] == 'user'), '')
+ if text == 'BLOCK_STARTED':
+ self.server.blocked.set()
+ self.server.release.wait(60)
+ message = {'role': 'assistant', 'content': 'ACK ' + str(text)}
+ usage = {'prompt_tokens': 250000, 'completion_tokens': 10, 'total_tokens': 250010}
+ if body.get('stream'):
+ payload = ('data: ' + json.dumps({'id': 'probe', 'choices': [{'index': 0, 'delta': message, 'finish_reason': 'stop'}],
+ 'usage': usage}) + '\n\ndata: [DONE]\n\n').encode()
+ kind = 'text/event-stream'
+ else:
+ payload = json.dumps({'id': 'probe', 'choices': [{'index': 0, 'message': message, 'finish_reason': 'stop'}],
+ 'usage': usage}).encode()
+ kind = 'application/json'
+ try:
+ self.send_response(200)
+ self.send_header('Content-Type', kind)
+ self.send_header('Content-Length', str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+
+class _Client:
+ def __init__(self, ws):
+ self.ws, self.events, self.count = ws, [], 0
+
+ async def call(self, method, **params):
+ self.count += 1
+ await self.ws.send(json.dumps({'jsonrpc': '2.0', 'id': self.count, 'method': method, 'params': params}))
+ async with asyncio.timeout(30):
+ while True:
+ message = json.loads(await self.ws.recv())
+ if message.get('id') == self.count:
+ assert 'result' in message, message
+ return message['result']
+ self.events.append(message)
+
+ async def pump(self, until, what):
+ async with asyncio.timeout(20):
+ while not until():
+ self.events.append(json.loads(await self.ws.recv()))
+
+ def asks(self):
+ return [e['params']['payload'] for e in self.events if e.get('method') == 'event'
+ and e['params'].get('type') == 'session.updated'
+ and e['params']['payload'].get('status') == 'confirmation_required']
+
+
+def test_a_guarded_deferred_pick_is_asked_again_after_an_owner_restart(tmp_path):
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), _MeasuredModel)
+ peer.requests = []
+ peer.blocked, peer.release = threading.Event(), threading.Event()
+ thread = threading.Thread(target=peer.serve_forever, daemon=True)
+ thread.start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ # Any measured context trips the large-context switch guard: the pick needs the user's consent.
+ cfg = {'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'original', 'base_url': url, 'switch_context_confirm_tokens': 1},
+ 'compression': {'enabled': False},
+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': []}}
+ (home / 'config.yaml').write_text(json.dumps(cfg))
+ (home / 'models_dev_cache.json').write_text(json.dumps({'custom': {'id': 'custom', 'models': {
+ name: {'id': name, 'name': name, 'limit': {'context': 1000000, 'output': 4000}}
+ for name in ('original', 'switched')}}}))
+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')
+
+ def terminal(name):
+ with sqlite3.connect(home / 'state.db') as db:
+ row = db.execute('SELECT status FROM session_admissions WHERE request_id=?', (name,)).fetchone()
+ return row and row[0] == 'terminal'
+
+ def pending(sid):
+ with sqlite3.connect(home / 'state.db') as db:
+ row = db.execute('SELECT value FROM state_meta WHERE key=?', ('gateway.deferred_pick.v1.' + sid,)).fetchone()
+ return json.loads(row[0]) if row else None
+
+ async def turn(c, sid, name):
+ await c.call('prompt.submit', session_id=sid, input_id=name, text=name)
+ await async_wait_until(lambda: terminal(name), timeout=30, what=name)
+
+ async def first(desc):
+ async with websocket(home, desc) as ws:
+ c = _Client(ws)
+ sid = (await c.call('session.create', source='tui', request_id='guarded', toolsets=[]))['session_id']
+ await turn(c, sid, 'WARM')
+ await c.call('prompt.submit', session_id=sid, input_id='block', text='BLOCK_STARTED')
+ assert await asyncio.to_thread(peer.blocked.wait, 20)
+ snap = await c.call('session.resume', session_id=sid)
+ busy = await c.call('session.mutate', session_id=sid, request_id='guarded-pick', operation='model',
+ payload={'model': 'switched'}, expected_revision=snap['revision'],
+ expected_generation=snap['execution_generation'])
+ assert busy['status'] == 'deferred', busy
+ await c.call('prompt.submit', session_id=sid, input_id='follower', text='FOLLOWER')
+ peer.release.set()
+ await async_wait_until(lambda: terminal('follower'), timeout=30, what='queued follower')
+ assert (pending(sid) or {}).get('awaiting_confirm'), (pending(sid), [r['model'] for r in peer.requests])
+ return sid
+
+ async def second(desc, sid):
+ async with websocket(home, desc) as ws:
+ c = _Client(ws)
+ snap = await c.call('session.resume', session_id=sid)
+ # The restarted owner asks the newly attached viewer again, with the guard re-checked.
+ await c.pump(lambda: c.asks(), 'the pending pick asked again after the restart')
+ ask = c.asks()[-1]
+ assert ask['target_model'] == 'switched' and ask['payload'] == {'model': 'switched'}, ask
+ snap = await c.call('session.resume', session_id=sid)
+ confirmed = await c.call('session.mutate', session_id=sid, request_id='confirmed', operation='model',
+ payload={'model': 'switched', 'confirm': ask['confirm']},
+ expected_revision=snap['revision'],
+ expected_generation=snap['execution_generation'])
+ assert confirmed.get('model') == 'switched', confirmed
+ await turn(c, sid, 'AFTER_RESTART')
+ assert pending(sid) is None
+
+ try:
+ with daemon(root, home, env, barrier=False) as (_, desc):
+ sid = asyncio.run(first(desc))
+ with daemon(root, home, env, barrier=False) as (_, desc):
+ asyncio.run(second(desc, sid))
+ assert peer.requests[-1]['model'] == 'switched', [r['model'] for r in peer.requests]
+ finally:
+ peer.release.set()
+ peer.shutdown()
+ peer.server_close()
+ thread.join(timeout=5)