The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): Windows hosted-room calls no longer deadlock on a shared multiplexer pipe
Teknium773d63b358b2
diff --git a/gateway/runtime_bootstrap_windows.py b/gateway/runtime_bootstrap_windows.pyindex 723a3b856ab..e7e41f93195 100644--- a/gateway/runtime_bootstrap_windows.py+++ b/gateway/runtime_bootstrap_windows.py@@ -1,6 +1,6 @@"""Native local-only bootstrap pipes with cancellable overlapped I/O.-The single pipe thread does not own session state. Handlers marshal authority+The pipe worker threads do not own session state. Handlers marshal authorityoperations to the gateway loop; the ticket store itself is thread-safe."""from __future__ import annotations@@ -189,30 +189,44 @@ def query_runtime_control(home: Path, request: bytes, timeout: float) -> bytes:win.CloseHandle(handle)+# Listening pipe instances, one worker each. Requests are served concurrently, as the POSIX+# socket does through its executor: a handler may dial this same pipe (a hosted room whose+# source and member share one multiplexer re-enters it via hosted-producer -> hosted-attest).+_PIPE_INSTANCES = 8++class NativeControlServer:- """One bounded native worker, independent of asyncio event-loop policy."""+ """Bounded native workers, independent of asyncio event-loop policy."""def __init__(self, home, handler):self.home, self.handler = home, handlerself._stop = threading.Event()self._ready = threading.Event()self._error = None- self._thread = threading.Thread(target=self._run, name='runtime-control-pipe', daemon=True)+ self._threads = [threading.Thread(target=self._run, args=(index == 0,), daemon=True,+ name=f'runtime-control-pipe-{index}')+ for index in range(_PIPE_INSTANCES)]+ self._thread = self._threads[0]def start(self):+ # The first instance claims the name (FILE_FLAG_FIRST_PIPE_INSTANCE) before any other.self._thread.start()if not self._ready.wait(5):self.close()raise TimeoutError('runtime control pipe startup deadline exceeded')if self._error:raise self._error+ for thread in self._threads[1:]:+ thread.start()def close(self):self._stop.set()- self._thread.join(timeout=5)- if self._thread.is_alive():+ for thread in self._threads:+ if thread.ident is not None:+ thread.join(timeout=5)+ if any(thread.is_alive() for thread in self._threads):raise TimeoutError('runtime control pipe did not stop')- def _create_pipe(self):+ def _create_pipe(self, first=True):from gateway.control_socket import windows_pipe_namewin = _native()class SecurityAttributes(ctypes.Structure):@@ -227,17 +241,17 @@ class NativeControlServer:attrs = SecurityAttributes(ctypes.sizeof(SecurityAttributes), descriptor, False)try:return win.CreateNamedPipe(windows_pipe_name(self.home),- 3 | win.FILE_FLAG_OVERLAPPED | 0x00080000,- 8, 1, 65536, 65536, 2000, ctypes.addressof(attrs))+ 3 | win.FILE_FLAG_OVERLAPPED | (0x00080000 if first else 0),+ 8, _PIPE_INSTANCES, 65536, 65536, 2000, ctypes.addressof(attrs))finally:k = ctypes.WinDLL('kernel32', use_last_error=True)_api(k, 'LocalFree', ctypes.c_void_p, [ctypes.c_void_p])(descriptor)- def _run(self):+ def _run(self, first=True):win = _native()handle = Nonetry:- handle = self._create_pipe()+ handle = self._create_pipe(first)self._ready.set()while not self._stop.is_set():try:@@ -252,9 +266,11 @@ class NativeControlServer:continuetry:subject = _peer_subject(handle, server=False)+ raw = _read_line(handle, time.monotonic() + 2, 64 * 1024)+ response = self.handler(raw, subject)+ # The I/O budget bounds the peer, not the handler's own (client-bounded) work.deadline = time.monotonic() + 2- raw = _read_line(handle, deadline, 64 * 1024)- _write(handle, self.handler(raw, subject), deadline)+ _write(handle, response, deadline)# DisconnectNamedPipe discards unread output. Let the client# consume and close, bounded by the same I/O deadline._read_line(handle, deadline, 64 * 1024)diff --git a/tests/gateway/test_runtime_bootstrap.py b/tests/gateway/test_runtime_bootstrap.pyindex f24427d82c0..13274902838 100644--- a/tests/gateway/test_runtime_bootstrap.py+++ b/tests/gateway/test_runtime_bootstrap.py@@ -125,6 +125,34 @@ def test_native_pipe_authenticated_peer_and_deadline(tmp_path):assert not server._thread.is_alive()[email protected]("windows")+def test_native_pipe_handler_may_dial_its_own_pipe(tmp_path):+ """A hosted room whose source and member share one multiplexer re-enters the control pipe+ from inside a handler (hosted-producer -> hosted-attest). A single serving instance cannot+ accept that nested request, so the outer call timed out; a slow handler must also still be+ able to answer once its own (client-bounded) work finishes."""+ import time+ from gateway.runtime_bootstrap_windows import NativeControlServer, query_runtime_control++ def handler(raw, subject):+ if raw == b'outer':+ try:+ inner = json.loads(query_runtime_control(tmp_path, b'inner', 5))+ except Exception as exc: # report, never kill the serving thread+ inner = {'error': repr(exc)}+ return json.dumps({'outer': inner}).encode() + b'\n'+ time.sleep(2.5) # longer than the per-peer I/O budget+ return json.dumps({'inner': raw.decode()}).encode() + b'\n'++ server = NativeControlServer(tmp_path, handler)+ server.start()+ try:+ assert json.loads(query_runtime_control(tmp_path, b'outer', 15)) == {'outer': {'inner': 'inner'}}+ assert server._error is None, server._error+ finally:+ server.close()++@pytest.mark.platforms("windows")def test_native_pipe_never_drops_a_client_that_lands_between_idle_accepts(tmp_path, monkeypatch):"""A listening pipe accepts CreateFile with no ConnectNamedPipe pending, so a client can land