Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/internal/flows/startup.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions src/daemon/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 `<root>/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 `<root>/daemon.log` as "Daemon failed to start"; exit 1.

## Rules

Expand Down
192 changes: 183 additions & 9 deletions src/daemon/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<MemoryFilesystem["writeFileAtomic"]>
Expand All @@ -4546,36 +4546,210 @@ describe("startDaemon version check", () => {
return super.writeFileAtomic(...arguments_);
}
}
const failedStart = async (check: boolean) => {
class ListenRefusingTransport extends MemoryIpcTransport {
override async listen(endpoint: string): Promise<never> {
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);
const clock = new FakeClock(1_000);
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<void>((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<never> {
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<string>((resolve) => {
seen = resolve;
});
let refuse!: () => void;
const refused = new Promise<void>((resolve) => {
refuse = resolve;
});
class SecretWithheldFilesystem extends MemoryFilesystem {
override async writeFileAtomic(
...arguments_: Parameters<MemoryFilesystem["writeFileAtomic"]>
): Promise<void> {
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 () => {
Expand Down
22 changes: 16 additions & 6 deletions src/daemon/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -1162,7 +1166,11 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise<Daemon
// settled fact so `daemon.stopping` cannot precede `daemon.started`.
await daemon.stop("http-start-failed").catch(() => 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;
}
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading