From 7406daebd75d5f00e45d6578560c3d0158fcd22f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 11 Oct 2026 13:46:01 +0200 Subject: [PATCH 1/4] fix(daemon): a frame for a peer that hung up is dropped, not an unhandled rejection that kills the daemon A lease-lost push written to a connection whose peer had sent FIN but whose close event had not fired yet rejected with EPIPE. The push is fired without a catch, so the rejection was unhandled and the daemon exited, failing every waiting lease request. writeFrame now drops a failed write, as it already drops a write to a closed socket. Closes #354 --- src/daemon/server.test.ts | 39 +++++++++++++++++++++++++++++++++++++++ src/daemon/server.ts | 8 +++++++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 64b9883e6..6f020fdea 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -20,6 +20,7 @@ import { CryptoTokenSecrets, FakeClock, FakeSystemStats, + IpcError, JsonLinesLogger, MemoryFilesystem, MemoryLogSink, @@ -1023,6 +1024,34 @@ describe("DaemonServer", () => { await holder.close(); }); + it("drops a lease-lost push to a connection whose peer has hung up instead of leaving its failed write unhandled", async () => { + const connection = new BlockingConnection(); + const harness = await createHarness({ host: new SingleConnectionHost(connection) }); + await connection.request( + { clientVersion: "test", protocolVersion: DAEMON_PROTOCOL_VERSION }, + "hello", + ); + const grant = await connection.request( + { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + "lease.request", + ); + const unhandled: unknown[] = []; + const recordUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", recordUnhandled); + try { + connection.hangUp(); + // Another holder of the same principal releases the lease, so the daemon pushes + // lease-lost to this connection while its peer is gone and its close is still to come. + await harness.engine.release(leaseIdOf(grant), "explicit"); + await new Promise((resolve) => setImmediate(resolve)); + + expect(connection.frames.filter((frame) => frame.push === "lease-lost")).toHaveLength(1); + expect(unhandled).toEqual([]); + } finally { + process.off("unhandledRejection", recordUnhandled); + } + }); + it("ignores lease-lost facts for leases with no currently connected holder without breaking the daemon", async () => { const harness = await createHarness(); harness.eventBus.emit( @@ -3052,6 +3081,7 @@ class BlockingConnection implements IpcConnection { readonly closed = false; readonly frames: Record[] = []; #blocked = false; + #hungUp = false; #pending: Array<() => void> = []; #dataListeners = new Set<(chunk: string) => void>(); @@ -3072,6 +3102,9 @@ class BlockingConnection implements IpcConnection { for (const line of contents.split("\n")) { if (line.trim() !== "") this.frames.push(JSON.parse(line) as Record); } + if (this.#hungUp) { + throw new IpcError("unknown", "This socket has been ended by the other party", "EPIPE"); + } if (!this.#blocked) return; await new Promise((resolve) => this.#pending.push(resolve)); } @@ -3082,6 +3115,12 @@ class BlockingConnection implements IpcConnection { this.#blocked = true; } + /** From here on every write fails as a Node socket's does after its peer's FIN and before its + * `close` event: `closed` is still false, and the write rejects with EPIPE. */ + hangUp(): void { + this.#hungUp = true; + } + releaseAll(): void { this.#blocked = false; const pending = this.#pending; diff --git a/src/daemon/server.ts b/src/daemon/server.ts index e8417e9cc..9715acc57 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -1606,7 +1606,13 @@ function errorStack(error: unknown): string | undefined { return error instanceof Error ? error.stack : undefined; } +/** + * A frame for a peer that has gone is dropped, never rejected. `closed` turns true only on the + * socket's `close` event, which comes a turn after the peer's FIN; a write in between fails with + * EPIPE. Most pushes are fired without a catch, so that rejection would be unhandled and would + * take the daemon down, failing every lease request still waiting. + */ function writeFrame(socket: IpcConnection, frame: unknown): Promise { if (socket.closed) return Promise.resolve(); - return socket.write(serializeFrame(frame)); + return socket.write(serializeFrame(frame)).catch(() => undefined); } From 005fc793cc951d0741483bead1482a4434726e8d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 11 Oct 2026 14:12:57 +0200 Subject: [PATCH 2/4] docs(daemon): writeFrame's window is FIN to destroyed, not FIN to close NodeIpcConnection.closed is #closed || socket.destroyed, and destroyed turns true before the close event. The EPIPE window is from the peer's FIN until the socket is destroyed. --- src/daemon/server.test.ts | 6 +++--- src/daemon/server.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 6f020fdea..175a9ec5b 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1041,7 +1041,7 @@ describe("DaemonServer", () => { try { connection.hangUp(); // Another holder of the same principal releases the lease, so the daemon pushes - // lease-lost to this connection while its peer is gone and its close is still to come. + // lease-lost to this connection while its peer is gone and it is not yet destroyed. await harness.engine.release(leaseIdOf(grant), "explicit"); await new Promise((resolve) => setImmediate(resolve)); @@ -3115,8 +3115,8 @@ class BlockingConnection implements IpcConnection { this.#blocked = true; } - /** From here on every write fails as a Node socket's does after its peer's FIN and before its - * `close` event: `closed` is still false, and the write rejects with EPIPE. */ + /** From here on every write fails as a Node socket's does after its peer's FIN and before it is + * destroyed: `closed` is still false, and the write rejects with EPIPE. */ hangUp(): void { this.#hungUp = true; } diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 9715acc57..1a3b55728 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -1607,9 +1607,9 @@ function errorStack(error: unknown): string | undefined { } /** - * A frame for a peer that has gone is dropped, never rejected. `closed` turns true only on the - * socket's `close` event, which comes a turn after the peer's FIN; a write in between fails with - * EPIPE. Most pushes are fired without a catch, so that rejection would be unhandled and would + * A frame for a peer that has gone is dropped, never rejected. Once the peer's FIN arrives the + * socket fails every write with EPIPE, but `closed` stays false until the socket is destroyed. + * Most pushes are fired without a catch, so a write in that window would reject unhandled and * take the daemon down, failing every lease request still waiting. */ function writeFrame(socket: IpcConnection, frame: unknown): Promise { From ec90572cea7db93d848db44f5cd3eb9d6d6e6a14 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 11 Oct 2026 14:13:17 +0200 Subject: [PATCH 3/4] test(e2e): firstStdoutLine fails at once when the process exits without a line A held lease whose daemon crashed surfaced only as a 60 s timeout. The helper now rejects on the child's close with its exit code, signal and stderr; the timeout still covers a child that is alive but silent. --- e2e/helpers/cli.test.ts | 33 +++++++++++++++++++++++++++++++++ e2e/helpers/cli.ts | 28 ++++++++++++++++++++++------ 2 files changed, 55 insertions(+), 6 deletions(-) create mode 100644 e2e/helpers/cli.test.ts diff --git a/e2e/helpers/cli.test.ts b/e2e/helpers/cli.test.ts new file mode 100644 index 000000000..fcc227ee3 --- /dev/null +++ b/e2e/helpers/cli.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; + +import { withDaemon } from "./env.js"; + +describe("cliBackground firstStdoutLine", () => { + it("rejects with the exit code and stderr, not the timeout, when the process exits without a stdout line", async () => { + const env = await withDaemon(); + + await expect(env.cliBackground(["lease", "--bogus"]).firstStdoutLine(60_000)).rejects.toThrow( + /^simlock lease --bogus exited with code 2, signal null before printing a stdout line; stderr: .*Unknown option '--bogus'/, + ); + }); + + it("rejects a call made after the process has already exited without a stdout line", async () => { + const env = await withDaemon(); + const handle = env.cliBackground(["lease", "--bogus"]); + await handle.waitForExit(); + + await expect(handle.firstStdoutLine(60_000)).rejects.toThrow(/exited with code 2/); + }); + + it("resolves the line a process printed just before exiting, for a call made before or after the exit", async () => { + const env = await withDaemon(); + const handle = env.cliBackground(["--help"]); + const beforeExit = handle.firstStdoutLine(60_000); + + expect((await handle.waitForExit()).code).toBe(0); + await expect(beforeExit).resolves.toBe("Usage: simlock [options]"); + await expect(handle.firstStdoutLine(60_000)).resolves.toBe( + "Usage: simlock [options]", + ); + }); +}); diff --git a/e2e/helpers/cli.ts b/e2e/helpers/cli.ts index deb210863..d4a23b749 100644 --- a/e2e/helpers/cli.ts +++ b/e2e/helpers/cli.ts @@ -98,14 +98,15 @@ export function cliBackground( let stdout = ""; let stderr = ""; const progress: unknown[] = []; - const stdoutWaiters: ((line: string) => void)[] = []; + const stdoutWaiters: { resolve(line: string): void; reject(error: Error): void }[] = []; let firstLineSeen: string | undefined; + let exitedWithoutLine: Error | undefined; child.stdout.on("data", (chunk: Buffer) => { stdout += chunk.toString("utf8"); if (firstLineSeen === undefined && stdout.includes("\n")) { firstLineSeen = stdout.slice(0, stdout.indexOf("\n")); - for (const waiter of stdoutWaiters.splice(0)) waiter(firstLineSeen); + for (const waiter of stdoutWaiters.splice(0)) waiter.resolve(firstLineSeen); } }); child.stderr.on("data", (chunk: Buffer) => { @@ -126,7 +127,15 @@ export function cliBackground( // attached after the fact never fires. That would time out as "process never // exited" when it had in fact already exited. const exited = new Promise((resolve) => { - child.once("close", (code) => { + // A process that dies before printing would otherwise surface only as a timeout, a minute + // later and without its stderr. "close", not "exit": it comes after the last stdout chunk, + // so a line printed just before exiting has already been seen and its waiters resolved. A + // failed spawn emits "close" too. + child.once("close", (code, signal) => { + exitedWithoutLine = new Error( + `simlock ${args.join(" ")} exited with code ${code}, signal ${signal} before printing a stdout line; stderr: ${stderr.trim() || "(empty)"}`, + ); + for (const waiter of stdoutWaiters.splice(0)) waiter.reject(exitedWithoutLine); resolve({ code, stdout, stderr, ...parseOutputs(stdout, stderr) }); }); }); @@ -137,13 +146,20 @@ export function cliBackground( stdoutSoFar: () => stdout, async firstStdoutLine(timeout = 30_000) { if (firstLineSeen !== undefined) return firstLineSeen; + if (exitedWithoutLine !== undefined) throw exitedWithoutLine; return new Promise((resolve, reject) => { const timer = setTimeout(() => { reject(new Error(`Timed out after ${timeout}ms waiting for first stdout line`)); }, timeout); - stdoutWaiters.push((line) => { - clearTimeout(timer); - resolve(line); + stdoutWaiters.push({ + resolve(line) { + clearTimeout(timer); + resolve(line); + }, + reject(error) { + clearTimeout(timer); + reject(error); + }, }); }); }, From 07f125a4abd9aca4547de22d9172b869c39d865c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Sun, 11 Oct 2026 15:10:14 +0200 Subject: [PATCH 4/4] test(e2e): prove firstStdoutLine waits for close, not exit; drop what-comments 0 failing -> 0 failing --- e2e/helpers/cli.test.ts | 28 ++++++++++++++++++++++++++++ e2e/helpers/cli.ts | 5 ----- src/daemon/server.test.ts | 5 ----- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/e2e/helpers/cli.test.ts b/e2e/helpers/cli.test.ts index fcc227ee3..60dd948f6 100644 --- a/e2e/helpers/cli.test.ts +++ b/e2e/helpers/cli.test.ts @@ -1,3 +1,7 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + import { describe, expect, it } from "vitest"; import { withDaemon } from "./env.js"; @@ -30,4 +34,28 @@ describe("cliBackground firstStdoutLine", () => { "Usage: simlock [options]", ); }); + + it("resolves a line printed after the process exited, once the pipe closes", async () => { + const env = await withDaemon(); + const dir = mkdtempSync(join(tmpdir(), "late-stdout-")); + const preload = join(dir, "late-stdout.cjs"); + writeFileSync( + preload, + `process.on("exit", () => { + require("node:child_process") + .spawn("sh", ["-c", "sleep 1; echo late line"], { detached: true, stdio: "inherit" }) + .unref(); + });`, + ); + try { + const handle = env.cliBackground(["lease", "--bogus"], { + env: { NODE_OPTIONS: `--require ${preload}` }, + }); + + await expect(handle.firstStdoutLine(60_000)).resolves.toBe("late line"); + expect((await handle.waitForExit()).code).toBe(2); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); }); diff --git a/e2e/helpers/cli.ts b/e2e/helpers/cli.ts index d4a23b749..d197a623b 100644 --- a/e2e/helpers/cli.ts +++ b/e2e/helpers/cli.ts @@ -82,11 +82,6 @@ export interface CliBackgroundHandle { readonly pid: number | undefined; } -/** - * Starts a `simlock` invocation that stays running (held-mode `lease`), for tests - * that need to observe progress, kill the process, or hold a lease across other - * assertions. - */ export function cliBackground( args: readonly string[], env: NodeJS.ProcessEnv, diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 175a9ec5b..f477968a2 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1040,8 +1040,6 @@ describe("DaemonServer", () => { process.on("unhandledRejection", recordUnhandled); try { connection.hangUp(); - // Another holder of the same principal releases the lease, so the daemon pushes - // lease-lost to this connection while its peer is gone and it is not yet destroyed. await harness.engine.release(leaseIdOf(grant), "explicit"); await new Promise((resolve) => setImmediate(resolve)); @@ -3076,7 +3074,6 @@ class SingleConnectionHost implements ConnectionHost { async stop(): Promise {} } -/** One side of a connection whose writes complete only when this test says so. */ class BlockingConnection implements IpcConnection { readonly closed = false; readonly frames: Record[] = []; @@ -3128,7 +3125,6 @@ class BlockingConnection implements IpcConnection { for (const resolve of pending) resolve(); } - /** Sends a request frame and waits for its reply, which arrives on `frames`. */ async request(payload: unknown, type: string, id = type): Promise { for (const listener of this.#dataListeners) { listener(`${JSON.stringify({ id, payload, type })}\n`); @@ -3138,7 +3134,6 @@ class BlockingConnection implements IpcConnection { } } -/** A `FakeDriver` that claims the `simctl` wrapper, for the `device.exec` flows. */ function passthroughDriver(clock: FakeClock): FakeDriver { return new FakeDriver({ availableOsVersions: ["26.5"],