From 26c9f45379b2810736734e7c5549b10d14532ba7 Mon Sep 17 00:00:00 2001 From: Xavier Date: Fri, 30 Oct 2026 10:44:29 -0300 Subject: [PATCH 1/3] fix(daemon): a start that fails at the socket claim exits A start that failed at the socket claim or the admin.token write threw out of DaemonServer.start without releasing what the composition had built. The CleanupReaper arms its tick in its constructor, so that timer (and any driver child) kept the node process alive after "Daemon failed to start" was logged. On Windows every start fails this way (listen on daemon.sock is EACCES), so a scheduled `simlock daemon start` piled up live daemon processes (#1051). The failed start now writes DAEMON_STARTUP_FAILED to parked requests, then runs #stop's disposal order (engine, settle, dispose, connections, a claimed socket) without daemon.stopping or the admin.token removal. A start that lost the claim to a live daemon skips settle and dispose, since its drivers may have adopted that daemon's adb server. The entry exits after logging either outcome. Co-Authored-By: Claude Opus 5.5 --- docs/internal/flows/startup.md | 5 ++ src/daemon/AGENTS.md | 6 ++- src/daemon/main.test.ts | 86 +++++++++++++++++++++++++++---- src/daemon/main.ts | 10 ++-- src/daemon/server.test.ts | 46 ++++++++++------- src/daemon/server.ts | 93 ++++++++++++++++++++++++---------- 6 files changed, 189 insertions(+), 57 deletions(-) diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index a18c5833e..f0b39ffe5 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -85,6 +85,11 @@ Arm (skipped when a stop already ran): Converge throws → health `failed`; parked requests get `DAEMON_STARTUP_FAILED`; stop `convergence-failed`; the start rejects. +The claim (step 11) or the `admin.token` write (step 13) throws → parked requests get +`DAEMON_STARTUP_FAILED`; the start runs Stop's steps 4 to 6 and closes connections and a claimed +socket, with no `daemon.stopping` and no `admin.token` removal, then rejects; the entry logs it +and exits. A `DaemonAlreadyRunningError` skips steps 5 and 6: the live daemon may share what the +drivers hold (Simlock's adb server, adopted through its record). HTTP fails to bind → the converge hook waits for the listener before step 22's `running`, so health `failed`, no `daemon.started`, stop `http-start-failed`; the start rejects. ### Lease reconciler outcomes (ADR 0019) diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 77f7fd250..93da280ad 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -89,6 +89,10 @@ Health: `starting` → `running`, or `failed`. `daemon`, `host` and `load` only. - Converge fails → parked requests get `DAEMON_STARTUP_FAILED`; daemon stops (`convergence-failed`). +- Claim or `admin.token` write fails → parked requests get `DAEMON_STARTUP_FAILED`; `start` disposes + what `#stop` does (engine, `settle`, `dispose`, connections, a claimed socket) without + `daemon.stopping` or the `admin.token` removal, then rejects; a later `stop()` gets that release's promise. + `DaemonAlreadyRunningError` skips `settle` and `dispose`: the live daemon may share the drivers' adb server. - A stop during converge → nothing is armed, no `daemon.started`; parked requests get `DAEMON_STOPPING`. - Arm: owner-routed push subscription → `daemon.started` → driver refusal events → health monitor and physical device watcher start. @@ -136,7 +140,7 @@ Security model: cooperative identity, not a hostile-process boundary. `eventLog.maxBytes` (256 MiB); usage rows are kept `metrics.retention` (90 days). `onSocketClaimed` starts it in both modes with the role and `metrics.retention`; `dispose` stops it last. A file that fails costs only history. A start the history refuses (a newer stored projection version, a failed migration) stops the daemon with reason `history-refused` and exit 1. `status.get` carries its `history`, also while starting. `inbox.get` (worker mode) runs `inboxItems` over its own `worker.list` view, `lease.list` and its queue. `usage.get` (both dispatchers, `usageAnswer` in `dispatch.ts`) reads the same file's usage rows through `core/usage` on a read thread; `main.ts` passes `historyPath` in both modes, and `dispose` stops the thread. `history.status().opened` false → `HISTORY_UNAVAILABLE`; a window ending before the oldest row → `HISTORY_NOT_KEPT`. -- SIGTERM to a running daemon runs `stop("signal")` and exits 0; one that arrives before the start finishes exits 0 at once (one handler in `main.ts`, the entry). A start that finds a daemon answering logs `Daemon already running` at `info` to the role's `daemon.log` and exits 0. A start that throws is logged by a fallback logger to the role's `daemon.log`; exit 1. An entry argument other than none or `--gateway` is logged to `/daemon.log` as "Daemon failed to start"; exit 1. +- SIGTERM to a running daemon runs `stop("signal")` and exits 0; one that arrives before the start finishes exits 0 at once (one handler in `main.ts`, the entry). A start that finds a daemon answering logs `Daemon already running` at `info` to the role's `daemon.log` and exits 0. A start that throws is logged by a fallback logger to the role's `daemon.log`; exit 1. Both exit at once (`process.exit`) after the line, since a start that lost the claim keeps its drivers' children. An entry argument other than none or `--gateway` is logged to `/daemon.log` as "Daemon failed to start"; exit 1. ## Rules diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 5320edac9..669c82868 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -50,8 +50,10 @@ import { type ServiceState, FakeSystemStats, FakeTcpProbe, + IpcError, JsonLinesLogger, MemoryFilesystem, + MemoryIpcTransport, MemoryLogSink, NodeFilesystem, NodeSqliteOpener, @@ -4630,7 +4632,7 @@ describe("startDaemon version check", () => { ((await daemon.dispatch("status.get", {}, operator)) as { daemon: { latestVersion: unknown } }) .daemon.latestVersion; - it("a start that fails after the version check began leaves no timer and asks npm no more", async () => { + it("a start of either role that fails at the socket claim or the admin.token write leaves no timer and asks npm no more", async () => { class SecretRefusingFilesystem extends MemoryFilesystem { override async writeFileAtomic( ...arguments_: Parameters @@ -4639,7 +4641,12 @@ describe("startDaemon version check", () => { return super.writeFileAtomic(...arguments_); } } - const failedStart = async (check: boolean) => { + class ListenRefusingTransport extends MemoryIpcTransport { + override async listen(endpoint: string): Promise { + throw new IpcError("unknown", `listen EACCES: permission denied ${endpoint}`, undefined); + } + } + const failedStart = async (role: "worker" | "gateway", refused: "listen" | "admin.token") => { const npm = new FakeNpmCli({ view: [{ ok: true, output: "0.4.0\n" }] }); const directory = await mkdtemp(join(tmpdir(), "simlock-main-version-fail-")); temporaryDirectories.push(directory); @@ -4647,28 +4654,89 @@ describe("startDaemon version check", () => { await expect( startDaemon({ clock, - configOverrides: { ...STANDALONE_OFF, update: { check } }, + configOverrides: role === "gateway" ? {} : STANDALONE_OFF, dataDirectory: directory, drivers: [], - filesystem: new SecretRefusingFilesystem(), + filesystem: + refused === "admin.token" ? new SecretRefusingFilesystem() : new MemoryFilesystem(), hostLoadProbe: null, + ipc: refused === "listen" ? new ListenRefusingTransport() : new MemoryIpcTransport(), logger: new NoopLogger(), npm, + role, socketPath: join(directory, "daemon.sock"), version: "0.3.0", } as StartDaemonOptions), - ).rejects.toThrow("disk is read-only"); + ).rejects.toThrow(refused === "listen" ? "listen EACCES" : "disk is read-only"); // why: the answer is processed after the call; wait it out so a leaked next-check timer exists before it is counted. await new Promise((resolve) => setTimeout(resolve, 25)); const pending = clock.pendingTimerCount; clock.advance(2 * 24 * 60 * 60 * 1000); - return { calls: npm.calls.length, pending }; + return { role, refused, calls: npm.calls.length, pending }; }; - const checked = await failedStart(true); - const unchecked = await failedStart(false); + const outcomes = []; + for (const role of ["worker", "gateway"] as const) { + for (const refused of ["listen", "admin.token"] as const) { + outcomes.push(await failedStart(role, refused)); + } + } + + expect(outcomes).toEqual([ + { role: "worker", refused: "listen", calls: 1, pending: 0 }, + { role: "worker", refused: "admin.token", calls: 1, pending: 0 }, + { role: "gateway", refused: "listen", calls: 1, pending: 0 }, + { role: "gateway", refused: "admin.token", calls: 1, pending: 0 }, + ]); + }); - expect(checked).toEqual({ calls: 1, pending: unchecked.pending }); + it("a worker whose socket claim is refused disposes its drivers, and one that loses the claim to a live daemon leaves them to that daemon", async () => { + class ListenFailingTransport extends MemoryIpcTransport { + constructor(readonly code: "address-in-use" | "unknown") { + super(); + } + override async listen(endpoint: string): Promise { + throw new IpcError(this.code, `listen failed: ${endpoint}`, undefined); + } + } + const failedStart = async (code: "address-in-use" | "unknown") => { + const directory = await mkdtemp(join(tmpdir(), "simlock-main-claim-drivers-")); + temporaryDirectories.push(directory); + const clock = new FakeClock(1_000); + const disposed: string[] = []; + const driver = Object.assign( + new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }), + { + dispose: async () => { + disposed.push("ios"); + }, + }, + ); + const error: unknown = await startDaemon({ + clock, + configOverrides: STANDALONE_OFF, + dataDirectory: directory, + deviceDataTables: fakeDeviceDataTables, + drivers: [driver], + filesystem: new MemoryFilesystem(), + hostLoadProbe: null, + ipc: new ListenFailingTransport(code), + logger: new NoopLogger(), + npm: new FakeNpmCli({ view: [{ ok: true, output: "0.3.0\n" }] }), + socketPath: join(directory, "daemon.sock"), + version: "0.3.0", + } as StartDaemonOptions).then( + () => undefined, + (rejection: unknown) => rejection, + ); + return { name: (error as Error | undefined)?.name, disposed }; + }; + + expect(await failedStart("unknown")).toEqual({ name: "IpcError", disposed: ["ios"] }); + expect(await failedStart("address-in-use")).toEqual({ + name: "DaemonAlreadyRunningError", + disposed: [], + }); }); it("a daemon runs the version check at start without delaying ready, then after 24 h, and reports a newer latest in status.get and the daemon.update query; npm failing or answering junk keeps the last value; a stopped daemon never schedules the next check", async () => { diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 72cd7a5c6..a5108b586 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -1748,11 +1748,13 @@ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { .catch((error: unknown) => { if (error instanceof DaemonAlreadyRunningError) { logAlreadyRunning(role, error); - return; + } else { + logFatalStart(role, error instanceof Error ? error.message : String(error), { + stack: error instanceof Error ? error.stack : undefined, + }); } - logFatalStart(role, error instanceof Error ? error.message : String(error), { - stack: error instanceof Error ? error.stack : undefined, - }); + // why: a start that lost the claim leaves its drivers to the live daemon, so a child one of them spawned (Simlock's adb server) can still hold this process open with nothing to serve; the line above is written synchronously. + process.exit(); }); process.once("SIGTERM", () => { if (running === undefined) { diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 054ff3bd1..b710cfdc2 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1617,10 +1617,11 @@ describe("DaemonServer stored lease requests", () => { }); describe("DaemonServer relays during startup", () => { - async function startParked(relayTargets: RelayTargets) { + async function startParked(relayTargets: RelayTargets, host?: ConnectionHost) { const converge = deferred(); const harness = await createHarness({ converge: () => converge.promise, + ...(host === undefined ? {} : { host }), relayTargets, start: false, }); @@ -1752,22 +1753,33 @@ describe("DaemonServer relays during startup", () => { expect(calls).toBe(0); }); - it("a parked relay whose startup fails answers DAEMON_STARTUP_FAILED and leaves its channel errored aborted", async () => { - const { converge, pair, startPromise } = await startParked({ - echo: () => Promise.resolve(new Response("ok")), - }); - const uplink = await wireOf(pair); - const relay = await relaySupport.openRelay(uplink, relaySupport.relayInput()); - await relaySupport.sleep(100); - - converge.reject(new Error("boom")); - await startPromise.catch(() => undefined); - const outcome = await relaySupport.settleWithin(relay.result); - const read = await relay.readError(); - - expect(outcome).toMatchObject({ code: "DAEMON_STARTUP_FAILED", state: "rejected" }); - expect(read).toEqual({ ended: false, reason: "aborted" }); - }); + it.each(["convergence", "socket claim"] as const)( + "a parked relay whose startup fails at its %s answers DAEMON_STARTUP_FAILED and leaves its channel errored aborted", + async (failing) => { + const claim = deferred(); + const host: ConnectionHost = { + endpoint: "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/claim-refused/daemon.sock", + start: () => claim.promise, + stop: async () => undefined, + }; + const { converge, pair, startPromise } = await startParked( + { echo: () => Promise.resolve(new Response("ok")) }, + failing === "socket claim" ? host : undefined, + ); + const uplink = await wireOf(pair); + const relay = await relaySupport.openRelay(uplink, relaySupport.relayInput()); + await relaySupport.sleep(100); + + if (failing === "socket claim") claim.reject(new Error("listen EACCES")); + else converge.reject(new Error("boom")); + await startPromise.catch(() => undefined); + const outcome = await relaySupport.settleWithin(relay.result); + const read = await relay.readError(); + + expect(outcome).toMatchObject({ code: "DAEMON_STARTUP_FAILED", state: "rejected" }); + expect(read).toEqual({ ended: false, reason: "aborted" }); + }, + ); }); async function createClientRetrying(socketPath: string, timeoutMs = 2_000): Promise { diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 14ae3381f..6980327ca 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -49,7 +49,7 @@ import { type StatusLoad, } from "../contract/index.js"; import type { LinkChannel, LinkConnection } from "../link/index.js"; -import type { ConnectionHost } from "./connection-host.js"; +import { DaemonAlreadyRunningError, type ConnectionHost } from "./connection-host.js"; import { resolveAgentRole, type Auth, @@ -219,8 +219,9 @@ export interface DaemonServerCommonOptions { */ readonly beginStop?: () => void; /** - * why: Releases what the daemon holds beyond its own state on shutdown: timers the lease - * subsystem armed (quarantine retries), and every driver's own external resources. + * why: Releases what the daemon holds beyond its own state on shutdown, and on a start that + * fails at the claim or the `admin.token` write: timers the lease subsystem armed (quarantine + * retries), and every driver's own external resources. * Awaited, because a driver's release is asynchronous and a stop that returned before it * finished would report a shutdown that had not happened. */ @@ -451,19 +452,23 @@ export class DaemonServer { } async #start(): Promise { - await this.options.host.start((connection) => this.#accept(connection)); - // why: ADR §5: written only after the socket claim above has succeeded -- a daemon that loses - // the start race throws out of `host.start()` and never reaches this line, so it never - // touches `admin.token`. Awaited before convergence starts (not raced with it): the file - // landing is not itself gated on convergence -- `hello` already verifies the in-memory - // hash regardless -- but there is no reason to let two startup-time writes race each other - // for no benefit. - this.options.hostLoad?.start(); try { + await this.options.host.start((connection) => this.#accept(connection)); + // why: ADR §5: written only after the socket claim above has succeeded -- a daemon that loses + // the start race throws out of `host.start()` and never reaches this line, so it never + // touches `admin.token`. Awaited before convergence starts (not raced with it): the file + // landing is not itself gated on convergence -- `hello` already verifies the in-memory + // hash regardless -- but there is no reason to let two startup-time writes race each other + // for no benefit. + this.options.hostLoad?.start(); await this.options.adminSecret?.persist(); } catch (error: unknown) { - // why: startDaemon does not call stop() on a rejected start, and a pending timer would keep the process alive. - this.options.hostLoad?.dispose(); + // why: as on a convergence failure below, a request already parked (an uplink's, or a socket's after the claim) gets its DAEMON_STARTUP_FAILED written before the release closes its connection. + this.#beforeReady.reject(error); + await Promise.allSettled(this.#parkedDispatches); + this.#stopping = true; + this.#stopPromise = this.#releaseFailedStart(error); + await this.#stopPromise; throw error; } const readyPromise = this.#converge(); @@ -638,6 +643,52 @@ export class DaemonServer { await this.options.stopAuxiliary?.(); this.#logger.info("Daemon stopping", { reason }); this.options.eventBus.emit("daemon.stopping", { reason }, "daemon"); + await this.#disposeEngine(); + // why: a stop releases nothing; leases persist with their deadline. Only work already in + // flight is drained, so `daemon stop` finishes on a settled pool. Disposal follows rather than + // precedes it, so a retry timer armed by a reclaim that settles into quarantine is still cancelled. + await this.options.settle?.(); + await this.options.dispose?.(); + await this.#closeConnections(); + // why: releasing the endpoint lets a replacement write its credential, so removal must happen while this daemon still owns it. + // why: a failed removal must still release the endpoint, or the stopping daemon keeps listening and blocks its replacement. + try { + await this.options.adminSecret?.remove(); + } finally { + await this.options.host.stop(); + } + this.#logger.info("Daemon stopped", { reason }); + } + + /** + * why: a start that fails at the claim or the `admin.token` write never reaches `#stop`, and + * `startDaemon` hands its caller no daemon to stop, so the reaper's tick and every timer or + * child the composition armed would keep the process alive with nothing to serve. It runs + * `#stop`'s order without the stop's facts: no `daemon.stopping` for a daemon that never + * started, and no `admin.token` removal, since this start never wrote one. Never rejects, so + * the start's own error is the one its caller sees. + */ + async #releaseFailedStart(error: unknown): Promise { + try { + await this.#disposeEngine(); + // why: a start that lost the race to a live daemon on this folder keeps the composition's + // parts: its Android driver may have adopted that daemon's adb server through its record, + // and disposing the driver would reap the server from under the winner. + if (!(error instanceof DaemonAlreadyRunningError)) { + await this.options.settle?.(); + await this.options.dispose?.(); + } + await this.#closeConnections(); + // why: a host that never claimed owns no endpoint, so this removes nothing a live daemon holds. + await this.options.host.stop(); + } catch (releaseError: unknown) { + this.#logger.error("Could not release a failed start", { + message: errorMessage(releaseError), + }); + } + } + + async #disposeEngine(): Promise { for (const unsubscribe of this.#unsubscribeLeaseLost.splice(0)) unsubscribe(); this.#ownerRoutedFacts.dispose(); this.options.hostLoad?.dispose(); @@ -650,22 +701,12 @@ export class DaemonServer { // why: a health tick or recovery reboot already running still acts on a device; it ends before the drivers are disposed. await this.#engine?.healthMonitor?.settle(); this.#engine?.physicalDeviceWatcher?.dispose(); - // why: a stop releases nothing; leases persist with their deadline. Only work already in - // flight is drained, so `daemon stop` finishes on a settled pool. Disposal follows rather than - // precedes it, so a retry timer armed by a reclaim that settles into quarantine is still cancelled. - await this.options.settle?.(); - await this.options.dispose?.(); + } + + async #closeConnections(): Promise { for (const connection of this.#connections) { await connection.socket.close(); } - // why: releasing the endpoint lets a replacement write its credential, so removal must happen while this daemon still owns it. - // why: a failed removal must still release the endpoint, or the stopping daemon keeps listening and blocks its replacement. - try { - await this.options.adminSecret?.remove(); - } finally { - await this.options.host.stop(); - } - this.#logger.info("Daemon stopped", { reason }); } /** From 6774e054d9e2e50733e5d8443ad6eaae3e9d476e Mon Sep 17 00:00:00 2001 From: Xavier Date: Fri, 30 Oct 2026 11:33:30 -0300 Subject: [PATCH 2/3] fix(daemon): a stop during a failed start is the one teardown A daemon.stop accepted after the socket claim but before the admin.token write failed made the start's catch overwrite the stop's promise with a second release, disposing the drivers twice. The failed start now waits for a stop already running and rejects with its own error. Co-Authored-By: Claude Opus 5.5 --- docs/internal/flows/startup.md | 3 +- src/daemon/AGENTS.md | 8 ++---- src/daemon/server.test.ts | 51 ++++++++++++++++++++++++++++++++++ src/daemon/server.ts | 5 ++-- 4 files changed, 58 insertions(+), 9 deletions(-) diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index f0b39ffe5..f69f05865 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -88,7 +88,8 @@ stop `convergence-failed`; the start rejects. The claim (step 11) or the `admin.token` write (step 13) throws → parked requests get `DAEMON_STARTUP_FAILED`; the start runs Stop's steps 4 to 6 and closes connections and a claimed socket, with no `daemon.stopping` and no `admin.token` removal, then rejects; the entry logs it -and exits. A `DaemonAlreadyRunningError` skips steps 5 and 6: the live daemon may share what the +and exits. A stop already running (a `daemon.stop` accepted after the claim) is the one teardown +instead: the start waits for it, then rejects with its own error. A `DaemonAlreadyRunningError` skips steps 5 and 6: the live daemon may share what the drivers hold (Simlock's adb server, adopted through its record). HTTP fails to bind → the converge hook waits for the listener before step 22's `running`, so health `failed`, no `daemon.started`, stop `http-start-failed`; the start rejects. diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 93da280ad..07eef1d26 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -87,12 +87,8 @@ Health: `starting` → `running`, or `failed`. - `hello`, `status.get` and `daemon.update` with `query` answer at once; `status.get` while `starting` carries `daemon`, `host` and `load` only. -- Converge fails → parked requests get `DAEMON_STARTUP_FAILED`; daemon stops - (`convergence-failed`). -- Claim or `admin.token` write fails → parked requests get `DAEMON_STARTUP_FAILED`; `start` disposes - what `#stop` does (engine, `settle`, `dispose`, connections, a claimed socket) without - `daemon.stopping` or the `admin.token` removal, then rejects; a later `stop()` gets that release's promise. - `DaemonAlreadyRunningError` skips `settle` and `dispose`: the live daemon may share the drivers' adb server. +- Converge fails → parked requests get `DAEMON_STARTUP_FAILED`; daemon stops (`convergence-failed`). +- Claim or `admin.token` write fails → parked requests get `DAEMON_STARTUP_FAILED`; `start` disposes what `#stop` does (engine, `settle`, `dispose`, connections, a claimed socket) without `daemon.stopping` or the `admin.token` removal, then rejects; a later `stop()` gets that release's promise. A stop already running (a `daemon.stop` after the claim) is the one teardown instead: `start` waits for it, then rejects with its own error. `DaemonAlreadyRunningError` skips `settle` and `dispose`: the live daemon may share the drivers' adb server. - A stop during converge → nothing is armed, no `daemon.started`; parked requests get `DAEMON_STOPPING`. - Arm: owner-routed push subscription → `daemon.started` → driver refusal events → health monitor and physical device watcher start. diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index b710cfdc2..99f5939bd 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1782,6 +1782,57 @@ describe("DaemonServer relays during startup", () => { ); }); +describe("DaemonServer failed start", () => { + it("a daemon.stop accepted while the admin.token write is pending is the one teardown when that write then fails, and the start rejects with the write's error", async () => { + const persisting = deferred(); + let disposals = 0; + let removals = 0; + const harness = await createHarness({ + adminSecret: { + persist: () => persisting.promise, + remove: async () => { + removals += 1; + }, + }, + dispose: () => { + disposals += 1; + }, + host: { + endpoint: "memory://failed-start", + start: async () => undefined, + stop: async () => undefined, + }, + start: false, + }); + const events: string[] = []; + harness.eventBus.subscribeAll((event) => { + if (event.event.startsWith("daemon.")) events.push(event.event); + }); + const startPromise = harness.daemon.start(); + startPromise.catch(() => undefined); + const pair = linkPair(); + harness.daemon.acceptUplink(pair.worker); + const gateway = driveConnection(pair.gateway); + await gateway.request("hello", { + clientVersion: "gateway", + protocolVersion: DAEMON_PROTOCOL_VERSION, + principal: "gw:test", + }); + + await expect(gateway.request("daemon.stop", {})).resolves.toMatchObject({ ok: true }); + await expect.poll(() => events).toEqual(["daemon.stopping"]); + persisting.reject(new Error("disk is read-only")); + await expect(startPromise).rejects.toThrow("disk is read-only"); + await harness.daemon.stop(); + + expect({ disposals, removals, events }).toEqual({ + disposals: 1, + removals: 1, + events: ["daemon.stopping"], + }); + }); +}); + async function createClientRetrying(socketPath: string, timeoutMs = 2_000): Promise { const deadline = Date.now() + timeoutMs; for (;;) { diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 6980327ca..6eb553ee4 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -467,8 +467,9 @@ export class DaemonServer { this.#beforeReady.reject(error); await Promise.allSettled(this.#parkedDispatches); this.#stopping = true; - this.#stopPromise = this.#releaseFailedStart(error); - await this.#stopPromise; + // why: a `daemon.stop` accepted after the claim already runs the one teardown; releasing again would dispose the drivers twice. + this.#stopPromise ??= this.#releaseFailedStart(error); + await this.#stopPromise.catch(() => undefined); throw error; } const readyPromise = this.#converge(); From 14b25711a5d9ff00fe03676a84aa4eb37828658a Mon Sep 17 00:00:00 2001 From: Xavier Date: Fri, 30 Oct 2026 11:53:16 -0300 Subject: [PATCH 3/3] fix(daemon): a failed start rejects without waiting for a stop that waits for it Waiting for a daemon.stop accepted after the claim deadlocked when the admin.token write then failed: both roles' stopAuxiliary waits for the HTTP frontend's start, which only the start settling releases. The start now rejects at once and startDaemon waits for that stop before it rejects, so the entry's process.exit still follows the one teardown. Co-Authored-By: Claude Opus 5.5 --- docs/internal/flows/startup.md | 6 +- src/daemon/AGENTS.md | 2 +- src/daemon/main.test.ts | 108 +++++++++++++++++++++++++++++++++ src/daemon/main.ts | 12 +++- src/daemon/server.test.ts | 26 ++++++-- src/daemon/server.ts | 8 ++- 6 files changed, 149 insertions(+), 13 deletions(-) diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index f69f05865..55295ece7 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -89,8 +89,10 @@ The claim (step 11) or the `admin.token` write (step 13) throws → parked reque `DAEMON_STARTUP_FAILED`; the start runs Stop's steps 4 to 6 and closes connections and a claimed socket, with no `daemon.stopping` and no `admin.token` removal, then rejects; the entry logs it and exits. A stop already running (a `daemon.stop` accepted after the claim) is the one teardown -instead: the start waits for it, then rejects with its own error. A `DaemonAlreadyRunningError` skips steps 5 and 6: the live daemon may share what the -drivers hold (Simlock's adb server, adopted through its record). +instead: the start rejects at once with its own error, since that stop's `stopAuxiliary` waits for +the start to settle, and `startDaemon` waits for the stop before it rejects. A +`DaemonAlreadyRunningError` skips steps 5 and 6: the live daemon may share what the drivers hold +(Simlock's adb server, adopted through its record). HTTP fails to bind → the converge hook waits for the listener before step 22's `running`, so health `failed`, no `daemon.started`, stop `http-start-failed`; the start rejects. ### Lease reconciler outcomes (ADR 0019) diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 07eef1d26..6ca5f0334 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -88,7 +88,7 @@ Health: `starting` → `running`, or `failed`. - `hello`, `status.get` and `daemon.update` with `query` answer at once; `status.get` while `starting` carries `daemon`, `host` and `load` only. - Converge fails → parked requests get `DAEMON_STARTUP_FAILED`; daemon stops (`convergence-failed`). -- Claim or `admin.token` write fails → parked requests get `DAEMON_STARTUP_FAILED`; `start` disposes what `#stop` does (engine, `settle`, `dispose`, connections, a claimed socket) without `daemon.stopping` or the `admin.token` removal, then rejects; a later `stop()` gets that release's promise. A stop already running (a `daemon.stop` after the claim) is the one teardown instead: `start` waits for it, then rejects with its own error. `DaemonAlreadyRunningError` skips `settle` and `dispose`: the live daemon may share the drivers' adb server. +- Claim or `admin.token` write fails → parked requests get `DAEMON_STARTUP_FAILED`; `start` disposes what `#stop` does (engine, `settle`, `dispose`, connections, a claimed socket) without `daemon.stopping` or the `admin.token` removal, then rejects; a later `stop()` gets that release's promise. A stop already running (a `daemon.stop` after the claim) is the one teardown instead: `start` rejects at once with its own error (that stop's `stopAuxiliary` waits for the start to settle), and `startDaemon` waits for the stop before it rejects. `DaemonAlreadyRunningError` skips `settle` and `dispose`: the live daemon may share the drivers' adb server. - A stop during converge → nothing is armed, no `daemon.started`; parked requests get `DAEMON_STOPPING`. - Arm: owner-routed push subscription → `daemon.started` → driver refusal events → health monitor and physical device watcher start. diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 669c82868..235129248 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -4739,6 +4739,114 @@ describe("startDaemon version check", () => { }); }); + it("a start of either role whose admin.token write fails after a daemon.stop was accepted rejects with the write's error, and only once that stop has run its one teardown", async () => { + const failedStart = async (role: "worker" | "gateway") => { + let seen!: (secret: string) => void; + const secretSeen = new Promise((resolve) => { + seen = resolve; + }); + let refuse!: () => void; + const refused = new Promise((resolve) => { + refuse = resolve; + }); + class SecretWithheldFilesystem extends MemoryFilesystem { + override async writeFileAtomic( + ...arguments_: Parameters + ): Promise { + if (!arguments_[0].endsWith("admin.token")) return super.writeFileAtomic(...arguments_); + seen(arguments_[1].trim()); + await refused; + throw new Error("disk is read-only"); + } + } + const directory = await mkdtemp(join(tmpdir(), "simlock-main-stop-then-fail-")); + temporaryDirectories.push(directory); + const clock = new FakeClock(1_000); + const sink = new MemoryLogSink(); + const ipc = new MemoryIpcTransport(); + const socketPath = join(directory, "daemon.sock"); + const disposed: string[] = []; + const driver = Object.assign( + new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }), + { + dispose: async () => { + disposed.push("ios"); + }, + }, + ); + const stoppedLines = () => + sink.records.filter((record) => record.message === "Daemon stopped").length; + const settled = startDaemon({ + clock, + // why: an HTTP frontend whose start the claim's hooks never began, so the stop's `stopAuxiliary` waits for the start to settle. + configOverrides: + role === "gateway" + ? {} + : { ...STANDALONE_OFF, http: { enabled: true, host: "127.0.0.1", port: 1 } }, + dataDirectory: directory, + deviceDataTables: fakeDeviceDataTables, + drivers: role === "gateway" ? [] : [driver], + filesystem: new SecretWithheldFilesystem(), + hostLoadProbe: null, + ipc, + logger: new JsonLinesLogger({ clock, level: "debug", sink }), + npm: new FakeNpmCli({ view: [{ ok: true, output: "0.3.0\n" }] }), + role, + socketPath, + version: "0.3.0", + } as StartDaemonOptions).then( + () => ({ outcome: "resolved" }), + (error: unknown) => ({ + outcome: (error as Error).message, + stoppedBefore: stoppedLines(), + disposedBefore: [...disposed], + }), + ); + const secret = await secretSeen; + const connection = await ipc.connect(socketPath); + let received = ""; + connection.onData((chunk) => { + received += chunk; + }); + const send = (id: number, type: string, payload: unknown) => + connection.write(`${JSON.stringify({ id, payload, type })}\n`); + await send(1, "hello", { + clientVersion: "test", + credential: secret, + protocolVersion: DAEMON_PROTOCOL_VERSION, + }); + await expect.poll(() => received).toContain('"role":"admin"'); + await send(2, "daemon.stop", {}); + await expect.poll(() => received).toContain('"stopping":true'); + + refuse(); + const result = await Promise.race([ + settled, + new Promise<{ outcome: string }>((resolve) => + setTimeout(() => resolve({ outcome: "still pending after 2 s" }), 2_000), + ), + ]); + return { role, ...result, stoppedAfter: stoppedLines(), disposedAfter: disposed }; + }; + + expect(await failedStart("worker")).toEqual({ + role: "worker", + outcome: "disk is read-only", + stoppedBefore: 1, + disposedBefore: ["ios"], + stoppedAfter: 1, + disposedAfter: ["ios"], + }); + expect(await failedStart("gateway")).toEqual({ + role: "gateway", + outcome: "disk is read-only", + stoppedBefore: 1, + disposedBefore: [], + stoppedAfter: 1, + disposedAfter: [], + }); + }); + it("a daemon runs the version check at start without delaying ready, then after 24 h, and reports a newer latest in status.get and the daemon.update query; npm failing or answering junk keeps the last value; a stopped daemon never schedules the next check", async () => { const pending: ((outcome: NpmOutcome) => void)[] = []; const npm: NpmCli = { diff --git a/src/daemon/main.ts b/src/daemon/main.ts index a5108b586..a8cba72cc 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -847,7 +847,11 @@ async function composeDaemon( // even if `stopAuxiliary`'s own path already ran one. await daemon.stop("http-start-failed").catch(() => undefined); } - if (daemonResult.status === "rejected") throw daemonResult.reason; + if (daemonResult.status === "rejected") { + // why: a stop accepted before the start failed may still run, and `stopAuxiliary` above waits for the start, so the start rejects without it; waiting here keeps the entry's `process.exit` from cutting that teardown short. + await daemon.stop().catch(() => undefined); + throw daemonResult.reason; + } if (gatewayResult.status === "rejected") throw gatewayResult.reason; return daemon; } @@ -1162,7 +1166,11 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise undefined); } - if (daemonResult.status === "rejected") throw daemonResult.reason; + if (daemonResult.status === "rejected") { + // why: as for a worker: `stopAuxiliary` waits for `httpStarted`, which only the start's settling releases here. + await daemon.stop().catch(() => undefined); + throw daemonResult.reason; + } if (httpResult.status === "rejected") throw httpResult.reason; return daemon; } diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 99f5939bd..8741662eb 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1783,8 +1783,10 @@ describe("DaemonServer relays during startup", () => { }); describe("DaemonServer failed start", () => { - it("a daemon.stop accepted while the admin.token write is pending is the one teardown when that write then fails, and the start rejects with the write's error", async () => { + it("a daemon.stop accepted while the admin.token write is pending is the one teardown when that write then fails, and the start rejects with the write's error without waiting for a stop whose auxiliary waits for the start", async () => { const persisting = deferred(); + const startSettled = deferred(); + let stopBegun = false; let disposals = 0; let removals = 0; const harness = await createHarness({ @@ -1794,9 +1796,14 @@ describe("DaemonServer failed start", () => { removals += 1; }, }, + beginStop: () => { + stopBegun = true; + }, dispose: () => { disposals += 1; }, + // why: as `main.ts`'s does: the HTTP frontend's start is settled only once `start()` settles when the claim's hooks never ran. + stopAuxiliary: () => startSettled.promise, host: { endpoint: "memory://failed-start", start: async () => undefined, @@ -1808,7 +1815,7 @@ describe("DaemonServer failed start", () => { harness.eventBus.subscribeAll((event) => { if (event.event.startsWith("daemon.")) events.push(event.event); }); - const startPromise = harness.daemon.start(); + const startPromise = harness.daemon.start().finally(() => startSettled.resolve()); startPromise.catch(() => undefined); const pair = linkPair(); harness.daemon.acceptUplink(pair.worker); @@ -1820,12 +1827,21 @@ describe("DaemonServer failed start", () => { }); await expect(gateway.request("daemon.stop", {})).resolves.toMatchObject({ ok: true }); - await expect.poll(() => events).toEqual(["daemon.stopping"]); + await expect.poll(() => stopBegun).toBe(true); persisting.reject(new Error("disk is read-only")); - await expect(startPromise).rejects.toThrow("disk is read-only"); + const outcome = await Promise.race([ + startPromise.then( + () => "resolved", + (error: unknown) => (error as Error).message, + ), + relaySupport.sleep(1_000).then(() => "still pending after 1 s"), + ]); + // why: unwinds a start that waits for the stop, so a failing run ends instead of hanging the stop below. + startSettled.resolve(); await harness.daemon.stop(); - expect({ disposals, removals, events }).toEqual({ + expect({ outcome, disposals, removals, events }).toEqual({ + outcome: "disk is read-only", disposals: 1, removals: 1, events: ["daemon.stopping"], diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 6eb553ee4..f5e056aaa 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -467,9 +467,11 @@ export class DaemonServer { this.#beforeReady.reject(error); await Promise.allSettled(this.#parkedDispatches); this.#stopping = true; - // why: a `daemon.stop` accepted after the claim already runs the one teardown; releasing again would dispose the drivers twice. - this.#stopPromise ??= this.#releaseFailedStart(error); - await this.#stopPromise.catch(() => undefined); + // why: a `daemon.stop` accepted after the claim already runs the one teardown, and it is not awaited here: the composition's `stopAuxiliary` waits for this start to settle, so the caller awaits `stop()` once the start has rejected. + if (this.#stopPromise === undefined) { + this.#stopPromise = this.#releaseFailedStart(error); + await this.#stopPromise; + } throw error; } const readyPromise = this.#converge();