The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): a racing cancel reaches the wire after its request
Maciej Lisiewski1a9082919660
diff --git a/tests/tui_gateway/test_server_requests.py b/tests/tui_gateway/test_server_requests.pynew file mode 100644index 00000000000..f7fc82fabf7--- /dev/null+++ b/tests/tui_gateway/test_server_requests.py@@ -0,0 +1,56 @@+"""Server→client request ordering on the wire (tui_gateway/server_requests.py).++A request is published in ``_open`` before its frame is written, so a cancel (session.interrupt / close /+shutdown on an RPC thread) can withdraw it in between. The renderer must still see the request before its+``request.cancel`` — a cancel for an id it never saw is dropped, and the late frame becomes a prompt card+the backend already withdrew.+"""++from __future__ import annotations++import threading++import pytest++from tui_gateway import server_requests+++def wire(monkeypatch):+ frames: list[tuple[str, str]] = []+ monkeypatch.setattr(server_requests, "_write", lambda frame: frames.append(("request", frame["id"])))+ monkeypatch.setattr(server_requests, "_emit",+ lambda event, sid, payload: frames.append((event, payload["id"])))+ monkeypatch.setattr(server_requests, "_answerable", lambda sid: True)+ server_requests.reset_for_tests()+ yield frames+ server_requests.reset_for_tests()+++def test_cancel_racing_the_request_write_reaches_the_wire_after_the_request(wire, monkeypatch):+ write_request = server_requests._write+ cancelled = []++ def write_after_an_interrupt(frame):+ # session.interrupt on another thread lands after registration, before the frame goes out.+ interrupt = threading.Thread(target=lambda: cancelled.append(server_requests.cancel("s1")))+ interrupt.start()+ interrupt.join(timeout=10)+ write_request(frame)++ monkeypatch.setattr(server_requests, "_write", write_after_an_interrupt)++ assert server_requests.send("sudo", "s1", {}, timeout=10) is None+ assert cancelled == [1]+ assert [event for event, _ in wire] == ["request", "request.cancel"]+ assert wire[0][1] == wire[1][1]+ assert server_requests.open_requests("s1") == []+++def test_cancel_after_the_write_is_emitted_once(wire):+ pending = server_requests.send_async("approval", "s1", {"request_id": "r1", "command": "rm", "description": ""},+ lambda result: None)++ assert server_requests.cancel("s1") == 1+ pending("resolved")+ assert [event for event, _ in wire] == ["request", "request.cancel"]diff --git a/tui_gateway/server_requests.py b/tui_gateway/server_requests.pyindex dfd39d84248..0cc4bbf01d6 100644--- a/tui_gateway/server_requests.py+++ b/tui_gateway/server_requests.py@@ -60,6 +60,8 @@ class ServerRequest:"qids","result","sid",+ "withdrawn",+ "writing",)def __init__(self, sid: str, method: str, params: dict, *, qids: list[str] | None = None,@@ -78,6 +80,9 @@ class ServerRequest:self.on_result = on_result# Client transports that answered NOT_SHOWN_CODE (no window there shows this session).self.declined: set = set()+ # Published but frame not yet written; a cancel in that gap parks its reason in ``withdrawn`` for _register.+ self.writing = False+ self.withdrawn: str | None = Nonedef frame(self) -> dict:return {"jsonrpc": "2.0", "id": self.id, "method": self.method,@@ -168,8 +173,17 @@ def _register(req: ServerRequest) -> None:if problem is not None:raise ValueError(problem) # a key the renderer's typed handler would never read: our bugwith _lock:+ req.writing = True_open[req.id] = req- _write(req.frame())+ try:+ _write(req.frame())+ finally:+ with _lock:+ req.writing = False+ withdrawn = req.withdrawn+ if withdrawn is not None:+ # cancel() landed between publish and write: its request.cancel must follow the frame, not precede it.+ _emit_cancel(req, withdrawn)def send(method: str, sid: str, params: dict, *, timeout: float | None,@@ -339,11 +353,15 @@ def cancel(sid: str | None = None, reason: str = "interrupted", *, method: str |req.result, req.answered = {"answers": dict(req.locked), "outcome": "cancelled"}, Trueelse:req.result, req.answered = None, False+ if req.writing:+ req.withdrawn = reason+ announced = {req.id for req in targets if not req.writing}for req in targets:if req.on_result is not None:req.on_result(None)req.event.set()- _emit_cancel(req, reason)+ if req.id in announced:+ _emit_cancel(req, reason)return len(targets)