diff --git a/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index a18c5833e..55295ece7 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -85,6 +85,14 @@ 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 stop already running (a `daemon.stop` accepted after the claim) is the one teardown +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 f0e719577..9292ae23e 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -87,8 +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`). +- 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 the 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. @@ -136,7 +136,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, or a connect to its endpoint timing out (`connection-timeout`: a pipe whose every instance is busy), 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, or a connect to its endpoint timing out (`connection-timeout`: a pipe whose every instance is busy), 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 b9038a2d4..3d6055d14 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -4537,7 +4537,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 @@ -4546,7 +4546,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); @@ -4554,28 +4559,197 @@ 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 }, + ]); + }); + + 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: [], + }); + }); - expect(checked).toEqual({ calls: 1, pending: unchecked.pending }); + 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 () => { diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 72cd7a5c6..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; } @@ -1748,11 +1756,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 2ea5cb416..a44211d03 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1596,10 +1596,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, }); @@ -1731,21 +1732,99 @@ 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); + 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" }); + }, + ); +}); - converge.reject(new Error("boom")); - await startPromise.catch(() => undefined); - const outcome = await relaySupport.settleWithin(relay.result); - const read = await relay.readError(); +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 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({ + adminSecret: { + persist: () => persisting.promise, + remove: async () => { + 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, + 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().finally(() => startSettled.resolve()); + 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(() => stopBegun).toBe(true); + persisting.reject(new Error("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(outcome).toMatchObject({ code: "DAEMON_STARTUP_FAILED", state: "rejected" }); - expect(read).toEqual({ ended: false, reason: "aborted" }); + 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 14ae3381f..f5e056aaa 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,26 @@ 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; + // 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(); @@ -638,6 +646,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 +704,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 }); } /**