Skip to content

The agent that grows with you

fix(webapp): wait off the serial lane for a profile that is still starting

Adolanium32c03ed88d8a
diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.py
index b6ced3b2d5a..ba940b91828 100644
--- a/gateway/session_ancillary.py
+++ b/gateway/session_ancillary.py
@@ -190,7 +190,7 @@ def _reachable_upload_home(connection, raw_home) -> bool:
homes = {connection.authority.profile_id}
if connection.host_scoped:
registry = getattr(getattr(connection.authority, 'runner', None), 'session_authorities', None)
- homes |= {sibling.profile_id for sibling in (registry or ()) if sibling is not None}
+ homes |= {sibling.profile_id for sibling in (registry or ())}
try:
target = Path(raw_home).resolve()
return any(Path(home).resolve() == target for home in homes)
diff --git a/gateway/session_authorities.py b/gateway/session_authorities.py
index 83987ed9774..4c7032b66d1 100644
--- a/gateway/session_authorities.py
+++ b/gateway/session_authorities.py
@@ -27,8 +27,8 @@ class SessionAuthorities:
self.launch_key = hermes_home_key(launch_home)
self._by_key: dict[str, object] = {}
self._names: dict[str, str | None] = {}
- # Set when a None slot is filled or dropped. Hot-serve publishes the slot before
- # the authority exists, and a host-scoped attach waits on this instead of reading it.
+ # One event per slot reserved by ``add(home, None)`` while its authority is being built: set
+ # when ``replace`` fills the slot or ``remove`` drops it (the build failed).
self._starting: dict[str, asyncio.Event] = {}
# A multiplexing runtime (configured, or one that ever served a second home) keeps the
# scoped-lookup contract after its secondaries are removed: an unserved home is None.
@@ -45,18 +45,13 @@ class SessionAuthorities:
if key != self.launch_key:
self.multiplexed = True
- def _finish_start(self, key) -> None:
- event = self._starting.pop(key, None)
- if event is not None:
- event.set()
-
def replace(self, home, authority) -> None:
"""Fill the slot reserved by ``add(home, None, name=...)`` once the authority exists."""
key = hermes_home_key(home)
if key not in self._by_key or self._by_key[key] is not None:
raise RuntimeError(f'no reserved session authority slot for {home}')
self._by_key[key] = authority
- self._finish_start(key)
+ self._end_start(key)
def remove(self, home):
"""Drop *home*'s slot (a parked boot, a hot-unserved profile); returns the authority or None.
@@ -65,25 +60,20 @@ class SessionAuthorities:
if key == self.launch_key:
raise RuntimeError('the launch session authority cannot be removed')
self._names.pop(key, None)
- removed = self._by_key.pop(key, None)
- self._finish_start(key)
- return removed
+ self._end_start(key)
+ return self._by_key.pop(key, None)
- def starting(self, profile):
- """Event for the unbuilt slot *profile* names, or None when nothing is waiting on it.
+ def _end_start(self, key) -> None:
+ started = self._starting.pop(key, None)
+ if started is not None:
+ started.set()
- ``replace`` and ``remove`` set the event. A waiter then routes against the registry
- as it stands: the new authority, or no such profile."""
+ def starting(self, profile):
+ """``(key, started)`` for the reserved slot *profile* names while its authority is still being
+ built, else None. ``started`` is set once the build ends: filled, or dropped because it failed."""
from hermes_cli.profiles import profile_matches_home
- for key, authority in list(self._by_key.items()):
- if authority is not None:
- continue
- event = self._starting.get(key)
- if event is None or event.is_set():
- continue
- if profile_matches_home(profile, Path(key)):
- return event
- return None
+ return next(((key, started) for key, started in list(self._starting.items())
+ if profile_matches_home(profile, Path(key))), None)
def profile_name(self, authority):
"""Served profile name for *authority*; None for the launch profile (its adapters are
@@ -92,10 +82,13 @@ class SessionAuthorities:
return None if key == self.launch_key else self._names.get(key)
def __len__(self) -> int:
- return len(self._by_key)
+ return sum(authority is not None for authority in self._by_key.values())
def __iter__(self):
- return iter(self._by_key.values())
+ """The built authorities, retiring ones included. A slot still being built is no authority
+ yet: every walk sees its profile exactly as before ``add`` reserved it (``starting`` names it)."""
+ # A snapshot, as in ``serving``: other threads walk the set while the loop hot-serves.
+ return (authority for authority in list(self._by_key.values()) if authority is not None)
def __contains__(self, home) -> bool:
return hermes_home_key(home) in self._by_key
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 84a2eaa8521..d029c12dd1c 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -157,10 +157,6 @@ class AuthorityConnection:
raise RuntimeStoreError('profile_mismatch')
registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)
for sibling in (registry or ()):
- # The slot is reserved before the authority exists. Skip it; a host-scoped
- # attach waits in ``_routed_connection`` instead of reading ``profile_id`` here.
- if sibling is None:
- continue
if sibling is not self.authority and profile_matches_home(profile, Path(sibling.profile_id)):
connection = self._siblings.get(sibling.profile_id)
# A re-served profile is a new authority under the same id: never keep routing to
@@ -170,19 +166,26 @@ class AuthorityConnection:
connection = AuthorityConnection(sibling, self.transport, identity, operator=self._operator)
self._siblings[sibling.profile_id] = connection
return connection
+ if registry is not None and registry.starting(profile) is not None:
+ # Hot-serve is still building it: retryable, not the final verdict for an unserved profile.
+ # A shared socket holds such a frame until the start ends (``awaits_profile_start``); this
+ # answers one whose wait ran out.
+ raise RuntimeStoreError('runtime_draining', field='profile', detail='the profile is still starting')
raise RuntimeStoreError('profile_mismatch')
- async def _routed_connection(self, profile):
- """Sibling connection for *profile*, after a host-scoped attach's in-progress start.
-
- Hot-serve reserves the slot as None while ``initialize_session_authority`` is still
- awaiting. The Desktop shared socket and the dashboard gate wait for that start.
- A profile-bound grant does not: ``_sibling_for`` refuses it as a mismatch."""
- if self.host_scoped:
- registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)
- while registry is not None and (pending := registry.starting(profile)) is not None:
- await pending.wait()
- return self._sibling_for(profile)
+ def awaits_profile_start(self, request, held=()):
+ """Whether a shared socket holds *request* off its serial lane: ``(key, started)`` when a
+ host-scoped frame names a profile hot-serve is still building (``started`` is set once the
+ build ends), ``(key, None)`` when it names one of *held*, the starts whose earlier frames the
+ socket still holds, so it queues behind them. None for every other frame."""
+ params = request.get('params') if isinstance(request, dict) else None
+ profile = params.get('profile') if isinstance(params, dict) else None
+ registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)
+ if not (self.host_scoped and isinstance(profile, str) and profile and registry is not None):
+ return None
+ from hermes_cli.profiles import profile_matches_home
+ key = next((key for key in held if profile_matches_home(profile, Path(key))), None)
+ return (key, None) if key is not None else registry.starting(profile)
def handlers(self):
"""Method → handler for every verb ``dispatch`` serves outside the group controls; each
@@ -277,7 +280,7 @@ class AuthorityConnection:
profile = params.get('profile')
if isinstance(profile, str) and profile:
try:
- routed = await self._routed_connection(profile)
+ routed = self._sibling_for(profile)
except RuntimeStoreError as exc:
_log_refusal(getattr(self.actor, 'profile_id', None), method, exc)
return {'jsonrpc': '2.0', 'id': rid, 'error': {
diff --git a/tests/gateway/test_canonical_file_attach_staged_sources.py b/tests/gateway/test_canonical_file_attach_staged_sources.py
index ae7889b2eea..fddffb8a166 100644
--- a/tests/gateway/test_canonical_file_attach_staged_sources.py
+++ b/tests/gateway/test_canonical_file_attach_staged_sources.py
@@ -103,6 +103,17 @@ async def test_a_staged_pick_is_copied_into_the_session_cache_without_retransmis
assert attached['ref_text'].startswith('@file:')
+async def test_a_staged_pick_attaches_while_another_profile_is_starting(owner):
+ """Hot-serve reserves a starting profile's registry slot before its authority exists. A host-scoped
+ pick from a served profile still attaches meanwhile."""
+ starting = owner.home / 'profiles' / 'starting'
+ starting.mkdir()
+ owner.authority.runner.session_authorities.add(starting, None, name='starting') # as serve_profile_runtime does
+ attached = await owner.attach(owner.upload())
+ assert isinstance(attached, dict) and attached['attached'] is True, attached
+
+
@pytest.mark.asyncio
async def test_a_deleted_source_profile_does_not_vouch_for_its_receipt(owner):
"""The rule every named-home write follows (``assert_named_profile_home_live``): a profile whose
diff --git a/tests/gateway/test_sibling_attach_while_profile_starting.py b/tests/gateway/test_sibling_attach_while_profile_starting.py
index 7b045b5c664..c5e856e0b47 100644
--- a/tests/gateway/test_sibling_attach_while_profile_starting.py
+++ b/tests/gateway/test_sibling_attach_while_profile_starting.py
@@ -1,99 +1,189 @@
-"""A host-scoped attach while another profile is still starting.
+"""A shared socket's frame naming a profile that hot-serve is still starting.
-Hot-serve reserves the profile's registry slot before its authority exists. A shared
-socket (Desktop, gateway-hosted Webapp) must still open a session on a profile that is
-already running, and the attach to the profile being started must wait for that start
-and then succeed.
+``serve_profile_runtime`` reserves the profile's registry slot (``SessionAuthorities.add(home, None)``)
+before ``initialize_session_authority`` has built its authority. On main a host-scoped frame naming
+that profile walked into the reserved slot and raised AttributeError, which the socket answered with
+JSON-RPC -32603 "internal error". A frame for a profile that was already running matched its own slot
+first and never reached the reserved one.
+
+The real ``handle_ws`` lanes and a real multiplexing runtime; only the starting profile's
+``initialize_session_authority`` is held, or failed, to keep the start in progress.
"""
import asyncio
+import json
from pathlib import Path
import pytest
+import pytest_asyncio
from tests.gateway.test_session_authorities_multiplex import _reserve_homes, _runner
-from tests.gateway.test_ticket_profile_scope import _Transport
-async def test_host_attach_waits_while_another_profile_is_starting(tmp_path, monkeypatch):
+class _Socket:
+ """The browser end of one WebSocket: frames in, replies collected by id."""
+
+ def __init__(self, authority):
+ self.scope = {'hermes.session_authority': authority}
+ self.inbound = asyncio.Queue()
+ self.replies = {}
+ self.arrived = asyncio.Event()
+
+ async def accept(self, **_kw):
+ pass
+
+ async def send_text(self, line):
+ for part in line.splitlines():
+ frame = json.loads(part)
+ if 'id' in frame:
+ self.replies[frame['id']] = frame
+ self.arrived.set()
+
+ async def receive_text(self):
+ frame = await self.inbound.get()
+ if frame is None:
+ from tui_gateway.ws import _WebSocketDisconnect
+ raise _WebSocketDisconnect()
+ return json.dumps(frame)
+
+ async def close(self, **_kw):
+ pass
+
+ async def reply(self, request_id, timeout=30):
+ async def arrived():
+ while request_id not in self.replies:
+ self.arrived.clear()
+ await self.arrived.wait()
+ return self.replies[request_id]
+ return await asyncio.wait_for(arrived(), timeout)
+
+
+@pytest_asyncio.fixture
+async def rig(tmp_path, monkeypatch):
+ """Default and ``alpha`` served, ``beta`` held mid-start; ``connect`` opens a ticketed socket."""
+ from types import SimpleNamespace
+
from gateway import session_authority
from gateway.run_runtime import initialize_gateway_runtime, serve_profile_runtime
from gateway.runtime_ownership import process_ownership
- from gateway.session_authorities import authority_for_profile_id, owner_scope
- from gateway.session_controls import AuthorityConnection
+ from gateway.session_authorities import authority_for_profile_id
+ from tui_gateway import server
+ from tui_gateway import ws as ws_mod
+ monkeypatch.setattr(ws_mod, '_start_backend_liveness', lambda: None)
+ monkeypatch.setattr(server, '_ensure_skin_watcher', lambda: None)
+ monkeypatch.setattr(server, '_ensure_lease_watcher', lambda: None)
+ monkeypatch.setattr(server, '_WS_ORPHAN_REAP_GRACE_S', 0)
root, homes = _reserve_homes(tmp_path, monkeypatch, names=('alpha',))
- alpha_home = homes[1][1]
beta_home = root / 'profiles' / 'beta'
beta_home.mkdir(parents=True, mode=0o700)
(beta_home / 'config.yaml').write_text('{}')
- process_ownership.reserve([*(home for _, home in homes), beta_home])
- entered, release = asyncio.Event(), asyncio.Event()
- connection = runner = None
- serve_task = beta_task = None
+ all_homes = [*(home for _, home in homes), beta_home]
+ process_ownership.reserve(all_homes)
+ entered, release, fail = asyncio.Event(), asyncio.Event(), []
+ sockets, tasks, runner = [], [], None
try:
runner = _runner(root, homes)
await initialize_gateway_runtime(runner)
real_initialize = session_authority.initialize_session_authority
- async def hold_initialize(*args, **kwargs):
+ async def held_initialize(*args, **kwargs):
entered.set()
await release.wait()
+ if fail:
+ raise RuntimeError('beta store unusable')
return await real_initialize(*args, **kwargs)
- monkeypatch.setattr(session_authority, 'initialize_session_authority', hold_initialize)
- serve_task = asyncio.create_task(serve_profile_runtime(runner, 'beta', beta_home))
+ monkeypatch.setattr(session_authority, 'initialize_session_authority', held_initialize)
+ serving = asyncio.create_task(serve_profile_runtime(runner, 'beta', beta_home))
+ tasks.append(serving)
await asyncio.wait_for(entered.wait(), timeout=30)
- assert beta_home in runner.session_authorities
- assert runner.session_authorities.for_home(beta_home) is None
-
- store = runner.session_ticket_store
- ticket = store.mint(profile_id=str(root.resolve()), subject='uid:desk', purpose='interactive', scope='host')
- grant = store.redeem(ticket, profile_id=None, purpose='interactive')
- launch = authority_for_profile_id(runner, grant['profile_id'])
- identity = {'user_id': grant['subject'], 'provider': 'local', 'profile_id': grant['profile_id'],
- 'instance_id': grant['instance_id'], 'capabilities': grant['capabilities'],
- 'native_bootstrap': True, 'profile_scope': 'host'}
- with owner_scope(launch):
- connection = AuthorityConnection(launch, _Transport(), identity, operator=True)
-
- async def create(profile, request_id):
- with owner_scope(launch):
- return await connection.dispatch({'id': request_id, 'method': 'session.create', 'params': {
- 'profile': profile, 'request_id': request_id, 'source': 'cli', 'cwd': str(tmp_path),
- 'model': 'm', 'toolsets': []}})
-
- alpha = await create('alpha', 'alpha-while-beta-starts')
- assert 'result' in alpha, alpha
- alpha_authority = runner.session_authorities.for_home(alpha_home)
- assert alpha['result']['session_id'] in alpha_authority.sessions
-
- beta_task = asyncio.create_task(create('beta', 'beta-while-starting'))
- await asyncio.sleep(0) # one turn: the attach either waits or raises
- if beta_task.done():
- exc = beta_task.exception()
- raise AssertionError(f'attach while beta is still starting finished early: {exc!r}')
+ assert runner.session_authorities.for_home(beta_home) is None # reserved, not built yet
- release.set()
- served, beta = await asyncio.gather(serve_task, beta_task)
- assert 'result' in beta, beta
- assert beta['result']['session_id'] in served.sessions
- assert alpha['result']['session_id'] in alpha_authority.sessions
+ async def connect(scope='host'):
+ store = runner.session_ticket_store
+ ticket = store.mint(profile_id=str(root.resolve()), subject='uid:desk', purpose='interactive', scope=scope)
+ grant = store.redeem(ticket, profile_id=None, purpose='interactive')
+ identity = {'user_id': grant['subject'], 'provider': 'local', 'profile_id': grant['profile_id'],
+ 'instance_id': grant['instance_id'], 'capabilities': grant['capabilities'],
+ 'native_bootstrap': True, 'profile_scope': grant.get('scope', 'profile')}
+ sock = _Socket(authority_for_profile_id(runner, grant['profile_id']))
+ sockets.append(sock)
+ tasks.append(asyncio.create_task(ws_mod.handle_ws(sock, auth_identity=identity, operator=True)))
+ return sock
+
+ def create(sock, profile, request_id):
+ sock.inbound.put_nowait({'jsonrpc': '2.0', 'id': request_id, 'method': 'session.create', 'params': {
+ 'profile': profile, 'request_id': request_id, 'source': 'cli', 'cwd': str(tmp_path),
+ 'model': 'm', 'toolsets': []}})
+
+ yield SimpleNamespace(runner=runner, alpha=homes[1][1], beta=beta_home, serving=serving,
+ release=release, fail=fail, connect=connect, create=create)
finally:
release.set()
- for task in (serve_task, beta_task):
- if task is None:
- continue
- if not task.done():
- await asyncio.wait([task], timeout=30)
+ for sock in sockets:
+ sock.inbound.put_nowait(None)
+ if tasks:
+ await asyncio.wait(tasks, timeout=30)
+ for task in tasks:
if task.done() and not task.cancelled():
task.exception()
- if connection is not None:
- with owner_scope(connection.authority):
- await connection.close()
- for authority in list(getattr(runner, 'session_authorities', None) or []):
- db = getattr(authority, 'db', None)
- if db is not None:
- db.close()
- for home in [*(path for _, path in homes), beta_home]:
+ for authority in list(getattr(runner, 'session_authorities', None) or ()):
+ authority.db.close()
+ for home in all_homes:
process_ownership.release(Path(home))
+
+
+async def test_a_running_profile_is_answered_while_a_frame_waits_for_another_profile_to_start(rig):
+ """Head-of-line: the frame for the starting profile waits off the socket's serial lane, so the
+ next frame, for a profile already running, is answered without waiting for that start."""
+ sock = await rig.connect()
+ rig.create(sock, 'beta', 'beta-while-starting')
+ rig.create(sock, 'alpha', 'alpha-behind-it')
+ alpha = await sock.reply('alpha-behind-it', timeout=10)
+ assert 'result' in alpha, alpha
+ assert alpha['result']['session_id'] in rig.runner.session_authorities.for_home(rig.alpha).sessions
+ assert 'beta-while-starting' not in sock.replies # still waiting for beta, not refused
+
+ rig.release.set()
+ served = await asyncio.wait_for(rig.serving, 30)
+ beta = await sock.reply('beta-while-starting')
+ assert 'result' in beta, beta
+ assert beta['result']['session_id'] in served.sessions
+
+
+async def test_a_failed_start_answers_the_waiting_frame_with_profile_mismatch(rig):
+ """A start that fails drops the slot; the waiting frame is answered then, as for any profile this
+ process does not serve, not when its wait runs out (``_WS_PROFILE_START_WAIT_S``, 20 s)."""
+ sock = await rig.connect()
+ rig.create(sock, 'beta', 'beta-start-fails')
+ sock.inbound.put_nowait({'jsonrpc': '2.0', 'id': 'after-beta', 'method': 'ping', 'params': {}})
+ assert 'result' in await sock.reply('after-beta', timeout=10) # the beta frame was read first
+ rig.fail.append(True)
+ rig.release.set()
+ with pytest.raises(RuntimeError, match='beta store unusable'):
+ await asyncio.wait_for(rig.serving, 30)
+ reply = await sock.reply('beta-start-fails', timeout=10)
+ assert reply.get('error', {}).get('message') == 'profile_mismatch', reply
+
+
+async def test_a_profile_still_starting_when_the_wait_runs_out_is_refused_retryably(rig, monkeypatch):
+ from tui_gateway import ws as ws_mod
+ monkeypatch.setattr(ws_mod, '_WS_PROFILE_START_WAIT_S', 0.5)
+ sock = await rig.connect()
+ rig.create(sock, 'beta', 'beta-start-slow')
+ reply = await sock.reply('beta-start-slow', timeout=30)
+ assert rig.runner.session_authorities.for_home(rig.beta) is None # beta is still starting
+ assert reply.get('error', {}).get('data', {}).get('reason') == 'runtime_draining', reply
+ assert reply['error']['data'].get('field') == 'profile'
+
+
+async def test_a_profile_bound_grant_naming_a_starting_profile_is_refused_at_once(rig):
+ """Only a host-scoped grant reaches another profile; a profile-bound one never waits for it."""
+ sock = await rig.connect(scope='profile')
+ rig.create(sock, 'beta', 'bound-names-beta')
+ reply = await sock.reply('bound-names-beta', timeout=10)
+ assert reply.get('error', {}).get('message') == 'profile_mismatch', reply
diff --git a/tests/gateway/test_unmanaged_idle_exit.py b/tests/gateway/test_unmanaged_idle_exit.py
index 575f5526336..24852808e8d 100644
--- a/tests/gateway/test_unmanaged_idle_exit.py
+++ b/tests/gateway/test_unmanaged_idle_exit.py
@@ -91,6 +91,23 @@ async def test_queued_work_clients_adapters_and_cron_each_keep_it_up(tmp_path, m
db.close()
+def test_a_profile_still_starting_leaves_the_served_ledgers_readable(tmp_path, monkeypatch):
+ """Hot-serve reserves a starting profile's registry slot before its authority exists. The probe
+ still reads every built profile's ledger meanwhile, instead of failing on the slot."""
+ runner, _home, db, _stops = _runner(tmp_path, monkeypatch)
+ starting = tmp_path / "starting"
+ starting.mkdir()
+ runner.session_authorities.add(starting, None, name="starting") # as serve_profile_runtime does
+ try:
+ db.create_session("s", source="cli")
+ epoch = begin_runtime_epoch(db, instance_id="owner")
+ admit_session_input(db, epoch=epoch, principal_id="p", session_id="s", request_id="r",
+ payload={"text": "queued while another profile starts"})
+ assert "admissions pending" in run_idle_exit.busy_reason(runner, window=0.2)
+ finally:
+ db.close()
+
+
def test_secondary_local_session_adapter_does_not_count_as_messaging(tmp_path, monkeypatch):
"""A secondary local session leaves an adapter map behind after the client disconnects."""
runner, _home, db, _stops = _runner(tmp_path, monkeypatch)
diff --git a/tests/tui_gateway/test_tui_gateway_ws.py b/tests/tui_gateway/test_tui_gateway_ws.py
index db7a44b1c85..74a4c3e30e1 100644
--- a/tests/tui_gateway/test_tui_gateway_ws.py
+++ b/tests/tui_gateway/test_tui_gateway_ws.py
@@ -437,6 +437,9 @@ def _drive_authority_fallback(monkeypatch, *, capabilities, profile_id, method):
def __init__(self, authority, transport, identity, operator=False):
self.actor = type("Actor", (), {"capabilities": frozenset(capabilities), "profile_id": profile_id})()
+ def awaits_profile_start(self, req, held):
+ return None # no profile is starting
+
async def dispatch(self, req):
return {"jsonrpc": "2.0", "id": req["id"], "error": {"code": -32601, "message": "unknown method"}}
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 527e88cec00..d0df1439af7 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -6,6 +6,7 @@ after accept). Mount as ``@app.websocket("/api/ws") async def ws(ws): await hand
from __future__ import annotations
import asyncio
+import collections
import contextlib
import concurrent.futures
import json
@@ -104,6 +105,12 @@ _WS_CONCURRENT_READ_METHODS = frozenset({"session.context_breakdown"})
_WS_CONCURRENT_READ_LIMIT = 2
# Reads admitted beyond the running ones; one more parks the reader (as the serial lane did).
_WS_WAITING_READ_LIMIT = 8
+# A shared socket's frame naming a profile hot-serve is still starting (a chat opened on a profile
+# created a moment ago) waits for that start in a lane of its own: on the serial lane every later
+# control on the socket, other profiles' prompts and interrupts included, would queue behind it.
+# Bounded under the Desktop's 30 s request deadline; a start still running then is refused
+# retryably (``runtime_draining``).
+_WS_PROFILE_START_WAIT_S = 20.0
# A viewer's answer to an open server→client request (its response frame, a batch clarify's
# ``clarify.lock``) settles in memory and never queues: the serial lane may be running the very handler
# that waits for it (a plugin slash command's ``ctx.ask_choice`` under ``slash.exec``).
@@ -441,6 +448,9 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
# control handler the serial lane is running (it finishes, then the dispatcher stops).
send_failed: asyncio.Future = asyncio.get_running_loop().create_future()
stop = object() # queue sentinel; a JSON ``null`` frame parses to None, so None can't be it
+ # Frames waiting for a profile's start, per start, in arrival order; one lane task drains each.
+ held: dict[str, collections.deque] = {}
+ held_lanes: set[asyncio.Task] = set()
async def _dispatch_one(req: Any) -> None:
"""Dispatch one request and write its inline reply."""
@@ -483,6 +493,46 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
with contextlib.suppress(asyncio.CancelledError, _SendFailed):
task.result()
+ async def _dispatch_after_start(key: str, started: asyncio.Event) -> None:
+ """Dispatch the frames held for one start, in arrival order, once it ends or the wait runs out
+ (the authority then refuses a profile still starting retryably). A frame for that profile read
+ meanwhile joins the queue instead of overtaking it on the serial lane."""
+ try:
+ with contextlib.suppress(TimeoutError):
+ await asyncio.wait_for(started.wait(), _WS_PROFILE_START_WAIT_S)
+ frames = held[key]
+ while frames:
+ await _dispatch_one(frames[0])
+ frames.popleft()
+ except _SendFailed:
+ if not send_failed.done():
+ send_failed.set_result(None)
+ finally:
+ del held[key]
+
+ def _hold_for_profile_start(req: Any) -> bool:
+ start = authority_connection.awaits_profile_start(req, held) if authority_connection is not None else None
+ if start is None:
+ return False
+ key, started = start
+ if key in held:
+ held[key].append(req)
+ else:
+ held[key] = collections.deque([req])
+ lane = asyncio.create_task(_dispatch_after_start(key, started))
+ held_lanes.add(lane)
+ lane.add_done_callback(held_lanes.discard)
+ return True
+
+ async def _end_held() -> None:
+ """Held frames were read before the disconnect: their lanes finish, as the serial lane finishes
+ its queue, unless the connection itself was cancelled (server shutdown)."""
+ task = asyncio.current_task()
+ if task is not None and task.cancelling():
+ for lane in held_lanes:
+ lane.cancel()
+ await asyncio.gather(*held_lanes, return_exceptions=True)
+
async def _next_request() -> Any:
"""The next queued frame, or ``stop`` once the read lane failed to send a reply."""
step = asyncio.ensure_future(pending.get())
@@ -501,6 +551,8 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
concurrent_reads.add(task)
task.add_done_callback(_finish_concurrent_read)
continue
+ if _hold_for_profile_start(req):
+ continue
await _dispatch_one(req)
async def _queue_request(req: Any) -> None:
@@ -626,6 +678,7 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
if failure is not None and not isinstance(failure, _SendFailed):
_log.error("ws dispatcher failed peer=%s", peer, exc_info=failure)
await _end_reads()
+ await _end_held()
if authority_connection is not None:
# After the dispatcher drained: an in-flight authority call must not see its connection closed.
await authority_connection.close()