Skip to content

The agent that grows with you

fix(webapp): decide at disconnect which held frames are dropped

unsupportedpastelscedc56427913
diff --git a/tests/gateway/test_sibling_attach_while_profile_starting.py b/tests/gateway/test_sibling_attach_while_profile_starting.py
index 7205f984b62..e732bbef6b4 100644
--- a/tests/gateway/test_sibling_attach_while_profile_starting.py
+++ b/tests/gateway/test_sibling_attach_while_profile_starting.py
@@ -29,6 +29,7 @@ class _Socket:
self.order = []
self.arrived = asyncio.Event()
self.task: asyncio.Task | None = None # the handle_ws task serving this socket
+ self.on_disconnect = [] # run, in order and without yielding, as the disconnect is raised
async def accept(self, **_kw):
pass
@@ -45,6 +46,8 @@ class _Socket:
frame = await self.inbound.get()
if frame is None:
from tui_gateway.ws import _WebSocketDisconnect
+ for step in self.on_disconnect:
+ step()
raise _WebSocketDisconnect()
return json.dumps(frame)
@@ -321,6 +324,54 @@ async def test_a_disconnect_drops_the_frames_held_for_a_start_that_has_not_ended
assert ran == ['probe'], ran
+def _on_disconnect_path(monkeypatch, sock, step):
+ """Run *step* once, synchronously, at the first step of ``handle_ws``'s disconnect path (its first
+ ``asyncio.current_task()`` after the socket raised the disconnect): nothing else on the loop,
+ no held lane included, runs between the handler reaching that path and *step*."""
+ from tui_gateway import ws as ws_mod
+
+ real_current_task, armed = asyncio.current_task, []
+
+ def current_task(loop=None):
+ task = real_current_task(loop)
+ if armed and task is sock.task:
+ armed.clear()
+ step()
+ return task
+
+ monkeypatch.setattr(ws_mod.asyncio, 'current_task', current_task)
+ sock.on_disconnect.append(lambda: armed.append(True))
+
+
[email protected]('start_ends', ['just_after_the_disconnect', 'just_before_the_disconnect'])
+async def test_held_frames_run_only_when_their_start_ended_before_the_disconnect(rig, monkeypatch, start_ends):
+ """Whether held frames run is decided when the client leaves, not when their lane next resumes:
+ a start that ends right after the disconnect (no yield between the two, so the lane wakes to
+ both) still drops them, and one that ends right before it still runs them."""
+ from tui_gateway import ws as ws_mod
+
+ monkeypatch.setattr(ws_mod, '_WS_PROFILE_START_WAIT_S', 30.0)
+ ran = _record_dispatch(monkeypatch)
+ sock = await rig.connect()
+ for n in range(2):
+ sock.inbound.put_nowait({'jsonrpc': '2.0', 'id': f'held-{n}', 'method': 'ping', 'params': {'profile': 'beta'}})
+ sock.inbound.put_nowait({'jsonrpc': '2.0', 'id': 'probe', 'method': 'ping', 'params': {}})
+ await sock.reply('probe', timeout=10) # both beta frames were set aside before it
+ _, started = rig.runner.session_authorities.starting('beta')
+ if start_ends == 'just_after_the_disconnect':
+ _on_disconnect_path(monkeypatch, sock, started.set)
+ else:
+ sock.on_disconnect.append(started.set) # set as the socket raises the disconnect
+ sock.inbound.put_nowait(None) # the client disconnects
+
+ done, _ = await asyncio.wait({sock.task}, timeout=5)
+ assert sock.task in done, 'the handler did not return promptly after the disconnect'
+ assert started.is_set()
+ expected = ['probe'] if start_ends == 'just_after_the_disconnect' else ['probe', 'held-0', 'held-1']
+ assert ran == expected, ran
+
+
@pytest.mark.asyncio
async def test_frames_held_for_a_start_that_ended_before_the_disconnect_still_run(rig, monkeypatch):
"""Frames whose start ended while the client was connected finish as the serial lane's queue does."""
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index c4835d7d1e0..12f5139d721 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -456,6 +456,16 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
held_room = asyncio.Semaphore(_WS_DISPATCH_QUEUE_MAX)
# Set once the client is gone: frames still waiting for a start are dropped, not run for nobody.
client_gone = asyncio.Event()
+ # The start each lane still waits for, and the lanes the disconnect dropped: decided when the client
+ # leaves, so a start that ends a moment later (before the lane resumes) cannot run them.
+ held_waiting: dict[str, asyncio.Event] = {}
+ held_dropped: set[str] = set()
+
+ def _client_left() -> None:
+ """At the disconnect, with no yield: drop every lane whose start has not ended yet. A lane that
+ already dispatches keeps going (a viewer leaving never stops a turn)."""
+ client_gone.set()
+ held_dropped.update(key for key, started in held_waiting.items() if not started.is_set())
async def _dispatch_one(req: Any) -> None:
"""Dispatch one request and write its inline reply."""
@@ -510,8 +520,9 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
finally:
for wait in waits:
wait.cancel()
+ del held_waiting[key] # dispatching from here on: a later disconnect lets these frames finish
frames = held[key]
- if client_gone.is_set() and not started.is_set():
+ if key in held_dropped:
for _ in frames:
held_room.release()
frames.clear()
@@ -523,6 +534,8 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
if not send_failed.done():
send_failed.set_result(None)
finally:
+ held_waiting.pop(key, None) # cancelled while waiting (server shutdown)
+ held_dropped.discard(key)
del held[key]
async def _hold_for_profile_start(req: Any) -> bool:
@@ -540,6 +553,10 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
held[key].append(req)
else:
held[key] = collections.deque([req])
+ assert started is not None # a start not held yet comes from the registry, with its event
+ held_waiting[key] = started
+ if client_gone.is_set() and not started.is_set():
+ held_dropped.add(key) # read before the disconnect, for a start that had not ended by it
lane = asyncio.create_task(_dispatch_after_start(key, started))
held_lanes.add(lane)
lane.add_done_callback(held_lanes.discard)
@@ -684,7 +701,7 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:
except _SendFailed:
pass
finally:
- client_gone.set()
+ _client_left()
if dispatcher is not None:
# Finish the in-flight handler and the frames read before the disconnect (as the serial read loop
# did) before the teardown below parks this transport's sessions. A cancelled connection (server