diff --git a/loopx/control_plane/effect_runtime_server.ts b/loopx/control_plane/effect_runtime_server.ts index a4817c8282..1dacb9e7e8 100644 --- a/loopx/control_plane/effect_runtime_server.ts +++ b/loopx/control_plane/effect_runtime_server.ts @@ -118,7 +118,12 @@ function resetIdleTimer(server: ReturnType): void { clearTimeout(idleTimer); // Idleness starts after effects finish, not when their sockets connect. if (!publicationComplete || pendingRequests > 0 || shutdownRequested || !server.listening) return; - idleTimer = setTimeout(() => server.close(), idleMs); + idleTimer = setTimeout(() => { + server.close(); + // close() waits for every connection; one whose peer died without a + // request would keep this process alive but no longer listening. + for (const socket of sockets) socket.destroy(); + }, idleMs); idleTimer.unref(); } @@ -139,7 +144,10 @@ async function writeResponse(socket: Socket, response: JsonObject, sink: FileHan request_id: response.request_id, ok: true, result_ref: ref})}\n`); } +const sockets = new Set(); const server = createServer((socket) => { + sockets.add(socket); + socket.on("close", () => sockets.delete(socket)); resetIdleTimer(server); socket.setEncoding("utf8"); // A caller may close while a response is still buffered (for example after diff --git a/tests/control_plane/test_effect_runtime_restart.py b/tests/control_plane/test_effect_runtime_restart.py index bb32db9c34..a50227a3ef 100644 --- a/tests/control_plane/test_effect_runtime_restart.py +++ b/tests/control_plane/test_effect_runtime_restart.py @@ -171,6 +171,32 @@ def test_restart_stops_the_runtime_that_carries_the_serving_identity( effect_runtime.effect_runtime_result("runtime.shutdown", {}, retry_safe=False) +def test_idle_runtime_retires_despite_a_silent_connection( + tmp_path: Path, + monkeypatch, +) -> None: + _isolate_runtime(tmp_path, monkeypatch) + monkeypatch.setenv("LOOPX_EFFECT_RUNTIME_IDLE_MS", "1500") + started = effect_runtime.effect_runtime_result("runtime.ping", {}) + info = json.loads(_runtime_info_path().read_text(encoding="utf-8")) + try: + # A caller that connected and then died never sends a request or closes. + with socket.create_connection((info["host"], int(info["port"]))): + deadline = time.monotonic() + 20 + while True: + # A POSIX child stays visible to the probe until its parent reaps it. + effect_runtime._reap_exited_runtime_child(info) + if not effect_runtime._pid_is_alive(int(started["pid"])): + break + assert time.monotonic() < deadline, "idle runtime stayed alive without listening" + time.sleep(0.2) + assert not _runtime_info_path().exists() + replacement = effect_runtime.effect_runtime_result("runtime.ping", {}) + assert int(replacement["pid"]) != int(started["pid"]) + finally: + effect_runtime.effect_runtime_result("runtime.shutdown", {}, retry_safe=False) + + def test_unqualified_serving_runtime_is_reported_with_a_restart_action( tmp_path: Path, monkeypatch,