From 110046fe1805ce7bc188b6779b8640b344f15f74 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 13:49:17 +0200 Subject: [PATCH 1/4] feat(daemon,cli): log every request and background failure; follow the log live - runDispatch writes one operation line per call on every frontend, levelled by the operation's new contract effect (write: info, read: debug) - core modules log the background failures they handle, with device, step and error - LoggingProcessRunner logs each device command at debug - event subscriber failures go to daemon.log as JSON - simlock daemon logs --follow polls through the Filesystem/Clock ports and survives rotation --- CHANGELOG.md | 7 + docs/CLI.md | 37 ++- docs/CONFIGURATION.md | 2 + docs/internal/ARCHITECTURE.md | 48 ++- e2e/daemon-log.test.ts | 297 ++++++++++++++++++ e2e/helpers/cli.ts | 3 + src/cli/follow-log.ts | 127 ++++++++ src/cli/index.test.ts | 109 +++++++ src/cli/index.ts | 27 +- src/contract/operations.test.ts | 75 ++++- src/contract/operations.ts | 33 ++ src/core/device-provisioner.test.ts | 75 ++++- src/core/device-provisioner.ts | 25 +- .../lease-acquisition-coordinator.test.ts | 135 +++++++- src/core/lease-acquisition-coordinator.ts | 55 +++- src/core/lease-engine.test.ts | 44 ++- src/core/lease-engine.ts | 14 +- src/core/lease-expiry-scheduler.test.ts | 28 +- src/core/lease-expiry-scheduler.ts | 17 +- src/core/quarantine-coordinator.test.ts | 74 ++++- src/core/quarantine-coordinator.ts | 33 +- src/core/reaper.test.ts | 42 ++- src/core/reaper.ts | 31 +- src/core/warm-pool-coordinator.test.ts | 59 +++- src/core/warm-pool-coordinator.ts | 35 ++- src/daemon/admin-secret.test.ts | 7 + src/daemon/dispatch.test.ts | 213 +++++++++++++ src/daemon/dispatch.ts | 155 +++++++-- src/daemon/dispatcher.ts | 10 + src/daemon/main.test.ts | 64 +++- src/daemon/main.ts | 43 ++- src/daemon/server.test.ts | 14 +- src/daemon/server.ts | 5 +- src/gateway/dispatcher.test.ts | 40 ++- src/gateway/dispatcher.ts | 15 +- src/ports/filesystem.ts | 41 ++- src/ports/index.ts | 1 + src/ports/logger.ts | 5 +- src/ports/logging-process-runner.test.ts | 131 ++++++++ src/ports/logging-process-runner.ts | 114 +++++++ 40 files changed, 2179 insertions(+), 111 deletions(-) create mode 100644 e2e/daemon-log.test.ts create mode 100644 src/cli/follow-log.ts create mode 100644 src/daemon/dispatch.test.ts create mode 100644 src/ports/logging-process-runner.test.ts create mode 100644 src/ports/logging-process-runner.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ab1f99b56..600862786 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -216,6 +216,13 @@ those changes add, alongside the breaking changes above. `EXEC_TIMEOUT` error code (CLI exit `10`, the code the other "ran out of time" outcome already uses, and HTTP `504`) rather than reporting the exit code the kill produced. +- **daemon:** `daemon.log` records every request that changes state, on every + frontend, with who asked, how long it took and its error code; every + background failure Simlock handled by retrying or destroying a device, with + the device and the error; and at `log.level: debug`, read requests and every + device command with its exit code. A failing event subscriber is logged as a + JSON line. `simlock daemon logs --follow` prints new lines as they are + written, across rotations. ### ADR 0005: gateway and worker modes diff --git a/docs/CLI.md b/docs/CLI.md index 605dd9bf5..0b26e2242 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1057,7 +1057,7 @@ any other, so it resets when the gateway restarts and it holds only what arrived while the gateway was up — a worker's events from before its uplink connected are not backfilled. -## `simlock daemon ` +## `simlock daemon ` Manage the daemon explicitly. Other commands auto-start it on demand; `daemon` exists for operators and debugging. `start` starts whichever mode @@ -1069,8 +1069,12 @@ stop does end is the connections to it — a running `simlock lease` cannot reconnect, so it exits `1` with a `DAEMON_CONNECTION_LOST` line naming a lease that is still granted; renew it from a later invocation once the daemon is back. A lease whose deadline passed while no daemon was running expires as soon -as one is. `logs` tails daemon logs and works even when the daemon is dead — it -reads the log file directly, no connection attempted. `status` never +as one is. `logs` prints the last 100 lines of the daemon log and works even when +the daemon is dead — it reads the log file directly, no connection attempted. +`logs --follow` then keeps printing each new line as it is written, until you +press Ctrl-C (exit 0). It keeps following when the log rotates, and if no +daemon has written a log yet it waits for one. `--follow` cannot be combined +with `--json` (exit 2). `status` never auto-starts the daemon and distinguishes two failure shapes: `{"status":"stopped"}` when nothing is listening on the socket at all, versus `{"status":"handshake-refused","error":{"code":...}}` (exit 1) when a daemon @@ -1090,11 +1094,28 @@ about the config, because nothing ever answered — the reason is in `simlock daemon logs`, which reads the log file directly and so works even though the daemon never came up. -The daemon writes one structured JSON line per record to `~/.simlock/daemon.log` -(timestamp, level, module, message, and any fields) covering startup (version, -protocol version, socket path, effective config), socket claim/stale-endpoint -recovery, driver discovery, connection open/close, shutdown, and unexpected or -handled errors. Growth is bounded: once the file passes `log.rotateBytes` it is +The daemon writes one JSON line per record to `~/.simlock/daemon.log` +(timestamp, level, module, message, and any fields). The log says what the +daemon was asked to do and what went wrong; what happened to leases and +devices is in `simlock events`, not here. It records: + +- **Startup and shutdown**: version, protocol version, socket path, effective + config, socket claim, driver discovery, and why a driver was skipped. +- **Every request that changes something**, on every frontend (CLI, MCP, + HTTP, and a gateway's dispatch): one `operation` line when it finishes, + with the operation, who asked (`principal`, and `requesterId` or `leaseId` + when the request named one), how long it took, and the error code if it + failed. A request that only reads is logged at `debug`, unless it fails. +- **Background failures** that Simlock handled by retrying, waiting, or + destroying a device: the device, the lease when there is one, the step that + failed, and the error text. +- **At `log.level: debug`**, every device command (`simctl`, `adb`, + `sdkmanager`, …): the command, its arguments, its exit code, and how long it + took. Never its environment, its input, or its output. +- Connection open and close, and errors nobody expected. + +The wording and fields of a line can change in any release; don't parse them +as a contract. Growth is bounded: once the file passes `log.rotateBytes` it is rotated to `daemon.log.1` (replacing any previous generation), so `logs` always shows the current file with the immediately preceding one prepended. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index af66704f3..bbef5034b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -39,6 +39,8 @@ a warning. Inspect the effective, merged configuration at any time with | `gateway.leaseRequestTimeoutMs` | **Gateway side.** Backstop on a forwarded `lease.request` -- expiry answers `WORKER_UNREACHABLE`, freeing the request for the queue's own deadline/cancel handling again. | `5 minutes` | | `diskPressure.freeBytesThreshold` | Free disk space below which Simlock treats the machine as under disk pressure. | `10 GiB` | | `eventBuffer.capacity` | Number of business events kept in the in-memory ring buffer (see `simlock events`). | `1000` | +| `log.level` | Lowest level written to `daemon.log`: `debug`, `info`, `warn`, or `error`. `debug` adds a line for every request that only reads (such as `simlock status`) and for every device command Simlock runs (`simctl`, `adb`, …) with its arguments and exit code. | `info` | +| `log.rotateBytes` | Size at which `daemon.log` is rotated to `daemon.log.1`. One rotated file is kept. | `5 MiB` | | `health.enabled` | Master switch for leased-device crash detection and recovery. | `true` | | `health.probeIntervalMs` | How often the health monitor observes leased devices against driver reality. | `30 seconds` | | `health.stableObservations` | Consecutive `stopped` observations required before a leased device is treated as crashed; guards against transient `Booting`/`Shutting Down`/adb-offline readings. | `2` | diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 4fb88e966..86dc907c7 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -1371,19 +1371,53 @@ kicked off has settled — `simlock status` already reports each device's own state (`reclaiming` included), so a separate aggregate would duplicate information already visible per-device rather than add any. -Operational logging is a separate concern from the event bus: `simlock events` -carries business facts (lease granted, device cleaned up, …) in an in-memory -ring buffer that resets on restart, while the `Logger` port writes durable, -structured JSON lines — one per record — for startup, socket claim/recovery, -driver discovery, connection lifecycle, shutdown, and unexpected/handled -errors. `startDaemon` builds the production `Logger` (`JsonLinesLogger` over a +Operational logging is a separate concern from the event bus (ADR 0006): +`simlock events` carries business facts (lease granted, device cleaned up, …), +while the `Logger` port writes structured JSON lines saying what the daemon +was asked to do and what went wrong. No fact is copied into the log and no log +line becomes an event. The log records: + +- **One `operation` line per dispatched call**, built in exactly one place: + `runDispatch` (`src/daemon/dispatch.ts`), through the `observe` hook both + dispatchers pass (`logger.child("dispatch")`). It names the operation, + `principal`, `role`, `durationMs`, `leaseId`/`requesterId` from the + validated input when present (nothing else from the input, nothing from the + output), and on failure `code` and `message`. Level follows the operation's + contract `effect`: a `write` success is `info`, a `read` success `debug`, a + failure `info`, an `INTERNAL` failure `error`. A call refused before its + handler (`UNKNOWN_REQUEST`, `BAD_REQUEST`, `FORBIDDEN`) gets the line too. + `codeOf` is injected (`classifyError`) so `dispatch.ts` stays free of + `src/core`. The HTTP app's own `request` line stays as the transport's + record; `daemon.stop` and `hello` are answered by the socket server and keep + their own lines. +- **One line per handled background failure** — a boot, an eviction, a + quarantine retry, a warm-pool disposition, a scheduled cleanup run, a lease + expiry — from the core module that caught it (`logger.child("")`, + `NoopLogger` by default), with `deviceId`, `step`, `error`, and the lease or + requester where the site knows one. A failure whose error already travels on + an event (`device.purge-failed`, `device.recovery-failed`, + `device.quarantine-stranded`) is not logged again. +- **At `log.level: debug`, one `process` line per device command**: + `LoggingProcessRunner` wraps the daemon's one `ProcessRunner` and logs the + command, arguments, exit code and duration when it settles — never `env`, + `input`, or output. Below `debug` the runner is not wrapped at all. +- **A failing event subscriber**, through `logger.child("bus")`, as one JSON + line with the event, `seq`, message and stack. +- Startup, socket claim/recovery, driver discovery, connection lifecycle, + shutdown, and unexpected errors with their stacks. `startDaemon` builds the production `Logger` (`JsonLinesLogger` over a `NodeFileLogSink`) from `config.log` right after config loads, then hands module-scoped children (`logger.child("server")`, `.child("connection-host")`, `.child("driver-discovery")`) to each component so every line is attributable. The sink tracks bytes written and rotates `daemon.log` to `daemon.log.1` (replacing any previous generation) once `config.log.rotateBytes` is exceeded, so growth is bounded and `simlock daemon logs` reads the rotated generation -before the current file. The one exception is the fatal top-level handler: it +before the current file. `daemon logs --follow` (`src/cli/follow-log.ts`) polls +through the `Filesystem` and `Clock` ports every 250 ms, reading from a byte +offset (`readFileFrom`). It detects a rotation from `daemon.log.1` changing +identity (`FileStat.identity`), not from the current file shrinking, because a +fresh file can outgrow the old offset within one poll; it then prints the rest +of the rotated file and restarts at offset 0. Two rotations inside one poll lose +the middle generation, which the sink has already deleted. The one exception is the fatal top-level handler: it cannot depend on `config.log` having loaded successfully, so it builds its own logger straight from the default log path at a fixed level, falling back to `console.error` only if that itself fails. diff --git a/e2e/daemon-log.test.ts b/e2e/daemon-log.test.ts new file mode 100644 index 000000000..eb468ac05 --- /dev/null +++ b/e2e/daemon-log.test.ts @@ -0,0 +1,297 @@ +import { readFile } from "node:fs/promises"; +import { createServer } from "node:net"; + +import { describe, expect, it } from "vitest"; + +import { waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; + +/** + * What `daemon.log` records, read back from the file a real daemon wrote: one `operation` line + * per call that changes state, a line per handled background failure, and at `debug` the read + * calls and every device command. + */ + +interface LogLine { + readonly level: string; + readonly module: string; + readonly message: string; + readonly fields?: Record; +} + +async function logLines(env: TestEnv): Promise { + const text = await readFile(env.logPath, "utf8"); + return text + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => JSON.parse(line) as LogLine); +} + +async function operationLines(env: TestEnv, operation: string): Promise { + return (await logLines(env)).filter( + (line) => line.message === "operation" && line.fields?.operation === operation, + ); +} + +const IOS = { ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] } }; + +async function leaseDetached(env: TestEnv): Promise { + const lease = await env.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--detach", + ]); + expect(lease.code, lease.stderr).toBe(0); + return (lease.json as { lease: { id: string } }).lease.id; +} + +/** Config validation rejects `http.port: 0`, so a free port is found first. */ +async function reservePort(): Promise { + return new Promise((resolve, reject) => { + const probe = createServer(); + probe.once("error", reject); + probe.listen(0, "127.0.0.1", () => { + const address = probe.address(); + probe.close(() => { + if (address === null || typeof address === "string") reject(new Error("no port")); + else resolve(address.port); + }); + }); + }); +} + +describe("daemon.log", () => { + it("a lease and its release over the socket each leave one operation line naming the requester", async () => { + const env = await withDaemon({ agentId: "log-agent" }); + await env.driverScript.set(IOS); + + const leaseId = await leaseDetached(env); + const released = await env.cli(["release", leaseId]); + expect(released.code, released.stderr).toBe(0); + + await waitFor(async () => (await operationLines(env, "lease.release")).length > 0, { + label: "the lease.release line", + }); + const requests = await operationLines(env, "lease.request"); + const releases = await operationLines(env, "lease.release"); + expect(requests).toEqual([ + expect.objectContaining({ + level: "info", + fields: expect.objectContaining({ + principal: "log-agent", + requesterId: "log-agent", + durationMs: expect.any(Number), + }), + }), + ]); + expect(releases).toEqual([ + expect.objectContaining({ + level: "info", + fields: expect.objectContaining({ + principal: "log-agent", + leaseId, + durationMs: expect.any(Number), + }), + }), + ]); + }); + + it("a lease request for an unknown model leaves an operation line with its error code", async () => { + const env = await withDaemon(); + await env.driverScript.set({ + ios: { failures: { resolveSpec: { type: "UnknownModelError", model: "Bogus Phone" } } }, + }); + + const lease = await env.cli([ + "lease", + "--platform", + "ios", + "--device", + "Bogus Phone", + "--detach", + ]); + expect(lease.code).not.toBe(0); + + expect(await operationLines(env, "lease.request")).toEqual([ + expect.objectContaining({ + level: "info", + fields: expect.objectContaining({ code: "UNKNOWN_MODEL" }), + }), + ]); + }); + + it("at the default level simlock status leaves no operation line; at debug it leaves one", async () => { + const quiet = await withDaemon(); + expect((await quiet.cli(["status"])).code).toBe(0); + expect(await operationLines(quiet, "status.get")).toEqual([]); + + // `daemon start` asks for status itself, so the count is taken around this one call. + const verbose = await withDaemon({ configOverrides: { log: { level: "debug" } } }); + const before = (await operationLines(verbose, "status.get")).length; + expect((await verbose.cli(["status"])).code).toBe(0); + const after = await operationLines(verbose, "status.get"); + expect(after).toHaveLength(before + 1); + expect(after.at(-1)).toMatchObject({ level: "debug" }); + }); + + it("a scripted boot failure leaves a line naming the device and the driver's error text", async () => { + const env = await withDaemon(); + await env.driverScript.set({ + ios: { + ...IOS.ios, + failures: { makeReady: { type: "generic", message: "scripted boot failure 7f3a" } }, + }, + }); + + const lease = await env.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--detach", + ]); + expect(lease.code).not.toBe(0); + + const failures = (await logLines(env)).filter((line) => + String(line.fields?.error ?? "").includes("scripted boot failure 7f3a"), + ); + expect(failures).toContainEqual( + expect.objectContaining({ + level: "warn", + fields: expect.objectContaining({ deviceId: expect.any(String), step: "boot" }), + }), + ); + }); + + it("at debug, a device.exec command leaves one process line with its exit code and no line holding its output", async () => { + const port = await reservePort(); + const env = await withDaemon({ + configOverrides: { + http: { enabled: true, host: "127.0.0.1", port }, + log: { level: "debug" }, + }, + }); + await env.driverScript.set(IOS); + const baseUrl = `http://127.0.0.1:${port}`; + await waitFor( + async () => { + try { + return (await fetch(`${baseUrl}/v1/healthz`)).ok; + } catch { + return false; + } + }, + { label: "HTTP accepting connections" }, + ); + // `device.exec` is for the lease's own holder, so the lease is taken with the same token. + const created = await env.cli(["token", "create", "--role", "agent"]); + const auth = { + authorization: `Bearer ${(created.json as { secret: string }).secret}`, + "content-type": "application/json", + }; + const requested = await fetch(`${baseUrl}/v1/lease-requests`, { + body: JSON.stringify({ device: "iPhone 16", os: "18.4", platform: "ios" }), + headers: auth, + method: "POST", + }); + expect(requested.status).toBe(201); + const requestId = ((await requested.json()) as { request: { id: string } }).request.id; + let leaseId = ""; + await waitFor( + async () => { + const polled = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, { + headers: auth, + }); + const view = (await polled.json()) as { request: { lease?: { id: string } } }; + leaseId = view.request.lease?.id ?? ""; + return leaseId !== ""; + }, + { label: "the lease request is granted" }, + ); + + const response = await fetch(`${baseUrl}/v1/leases/${leaseId}/exec`, { + body: JSON.stringify({ + args: ["printed-output-9c1e", "--fake-exec-exit=4"], + tool: "simctl", + }), + headers: auth, + method: "POST", + }); + expect(response.status).toBe(200); + expect(await response.text()).toContain("printed-output-9c1e"); + + let processLines: LogLine[] = []; + await waitFor( + async () => { + processLines = (await logLines(env)).filter( + (line) => + line.message === "process" && + (line.fields?.args as unknown[] | undefined)?.includes("printed-output-9c1e") === true, + ); + return processLines.length > 0; + }, + { label: "the device.exec process line" }, + ); + expect(processLines).toEqual([ + expect.objectContaining({ + level: "debug", + module: "daemon.process", + fields: expect.objectContaining({ code: 4, durationMs: expect.any(Number) }), + }), + ]); + // The child prints its own argv as JSON; that output never reaches the log. + const raw = await readFile(env.logPath, "utf8"); + expect(raw).not.toContain('"argv"'); + await env.cli(["release", leaseId]); + }); + + it("simlock daemon logs --follow prints the operation line of a lease made after it started", async () => { + const env = await withDaemon({ agentId: "follow-agent" }); + await env.driverScript.set(IOS); + const follower = env.cliBackground(["daemon", "logs", "--follow"]); + await waitFor(() => follower.stdoutSoFar().includes("Daemon started"), { + label: "the follower printed the existing tail", + }); + expect(follower.stdoutSoFar()).not.toContain('"operation":"lease.request"'); + + const leaseId = await leaseDetached(env); + + await waitFor(() => follower.stdoutSoFar().includes('"operation":"lease.request"'), { + label: () => `the lease.request line, follower printed:\n${follower.stdoutSoFar()}`, + }); + follower.kill("SIGINT"); + expect((await follower.waitForExit(10_000)).code).toBe(0); + await env.cli(["release", leaseId]); + }); + + it("simlock daemon logs --follow keeps printing lines written after the log rotates", async () => { + const env = await withDaemon({ configOverrides: { log: { rotateBytes: 1_500 } } }); + await env.driverScript.set(IOS); + const follower = env.cliBackground(["daemon", "logs", "--follow"]); + await waitFor(() => follower.stdoutSoFar().includes("Daemon started"), { + label: "the follower printed the existing tail", + }); + + // Each cycle writes about 1 kB, so five of them rotate the log several times. A cycle waits + // for the follower before the next one: only one rotated generation is kept, so a second + // rotation inside one poll would delete lines before any reader could see them. + for (let cycle = 0; cycle < 5; cycle += 1) { + const leaseId = await leaseDetached(env); + expect((await env.cli(["release", leaseId])).code).toBe(0); + await waitFor(() => follower.stdoutSoFar().includes(`"leaseId":"${leaseId}"`), { + label: () => `release line ${cycle}, follower printed:\n${follower.stdoutSoFar()}`, + }); + } + + await expect(readFile(`${env.logPath}.1`, "utf8")).resolves.not.toBe(""); + follower.kill("SIGINT"); + expect((await follower.waitForExit(10_000)).code).toBe(0); + }); +}); diff --git a/e2e/helpers/cli.ts b/e2e/helpers/cli.ts index 2aaba636b..deb210863 100644 --- a/e2e/helpers/cli.ts +++ b/e2e/helpers/cli.ts @@ -75,6 +75,8 @@ export interface CliBackgroundHandle { firstStdoutLine(timeout?: number): Promise; /** The stderr progress JSON lines observed so far, in order. */ progressEvents(): readonly unknown[]; + /** Everything written to stdout so far, for a process that streams until it is stopped. */ + stdoutSoFar(): string; waitForExit(timeout?: number): Promise; kill(signal?: NodeJS.Signals): void; readonly pid: number | undefined; @@ -132,6 +134,7 @@ export function cliBackground( return { pid: child.pid, + stdoutSoFar: () => stdout, async firstStdoutLine(timeout = 30_000) { if (firstLineSeen !== undefined) return firstLineSeen; return new Promise((resolve, reject) => { diff --git a/src/cli/follow-log.ts b/src/cli/follow-log.ts new file mode 100644 index 000000000..4b00babbb --- /dev/null +++ b/src/cli/follow-log.ts @@ -0,0 +1,127 @@ +import { + isMissingPathError, + type Clock, + type Filesystem, + type TimerHandle, +} from "../ports/index.js"; + +export interface Signals { + on(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown; + off(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown; +} + +export interface FollowLogOptions { + readonly clock: Clock; + readonly filesystem: Filesystem; + /** The current log file; its one rotated generation is `.1`. */ + readonly path: string; + readonly signals: Signals; + readonly write: (text: string) => void; + readonly intervalMs?: number; + readonly tailLines?: number; +} + +const DEFAULT_INTERVAL_MS = 250; +const DEFAULT_TAIL_LINES = 100; + +/** + * `simlock daemon logs --follow`: prints the last lines of the log, then each new complete line + * as it is written, until `SIGINT` or `SIGTERM`. Polls through the `Filesystem` and `Clock` + * ports rather than watching, so it behaves the same against the in-memory filesystem. + * + * A rotation renames the current file to `.1` and starts a fresh one. It is detected from + * `.1` becoming a different file, never from the current file shrinking: a busy daemon + * can write more than the old offset into the fresh file between two polls. After a rotation + * the unread rest of the old file is printed first, then the new file from its start. + * + * A missing log file is not an error -- no daemon has written one yet -- so it waits. + * + * Resolves once interrupted, with its timer cancelled and its signal handlers removed. Rejects, + * leaving the same, if a read fails for any reason but a missing file. + */ +export async function followLog(options: FollowLogOptions): Promise { + const { clock, filesystem, path, signals, write } = options; + const rotatedPath = `${path}.1`; + const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS; + let rotatedIdentity = await identityOf(filesystem, rotatedPath); + + const rotated = + rotatedIdentity === undefined ? "" : await readFromOrEmpty(filesystem, rotatedPath, 0); + const current = await readFromOrEmpty(filesystem, path, 0); + const currentComplete = completeLines(current); + let offset = Buffer.byteLength(currentComplete, "utf8"); + const tail = `${rotated}${currentComplete}`.split("\n").filter((line) => line !== ""); + const tailLines = tail.slice(-(options.tailLines ?? DEFAULT_TAIL_LINES)); + if (tailLines.length > 0) write(`${tailLines.join("\n")}\n`); + + const poll = async (): Promise => { + const rotatedNow = await identityOf(filesystem, rotatedPath); + if (rotatedNow !== undefined && rotatedNow !== rotatedIdentity) { + rotatedIdentity = rotatedNow; + // The old current file, now finished: everything left in it, then start the new one. + const rest = await readFromOrEmpty(filesystem, rotatedPath, offset); + if (rest !== "") write(rest.endsWith("\n") ? rest : `${rest}\n`); + offset = 0; + } + const complete = completeLines(await readFromOrEmpty(filesystem, path, offset)); + if (complete !== "") write(complete); + offset += Buffer.byteLength(complete, "utf8"); + }; + + await new Promise((resolve, reject) => { + let timer: TimerHandle | undefined; + let stopped = false; + const detach = (): void => { + stopped = true; + signals.off("SIGINT", stop); + signals.off("SIGTERM", stop); + if (timer !== undefined) clock.cancel(timer); + timer = undefined; + }; + function stop(): void { + detach(); + resolve(); + } + const schedule = (): void => { + if (stopped) return; + timer = clock.setTimer(intervalMs, () => { + timer = undefined; + if (stopped) return; + poll().then(schedule, (error: unknown) => { + detach(); + reject(error); + }); + }); + }; + signals.on("SIGINT", stop); + signals.on("SIGTERM", stop); + schedule(); + }); +} + +/** Everything up to and including the last newline: a line still being written waits. */ +function completeLines(text: string): string { + return text.slice(0, text.lastIndexOf("\n") + 1); +} + +async function identityOf(filesystem: Filesystem, path: string): Promise { + try { + return (await filesystem.stat(path)).identity; + } catch (error: unknown) { + if (isMissingPathError(error)) return undefined; + throw error; + } +} + +async function readFromOrEmpty( + filesystem: Filesystem, + path: string, + offset: number, +): Promise { + try { + return await filesystem.readFileFrom(path, offset); + } catch (error: unknown) { + if (isMissingPathError(error)) return ""; + throw error; + } +} diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 1e92c4e65..f3324fd8f 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2766,6 +2766,115 @@ describe("CLI: daemon logs (ADR 0003 §11 -- must work when the daemon is dead)" }); }); +describe("CLI: daemon logs --follow", () => { + /** Runs `daemon logs --follow` against an in-memory log, driven by a fake clock and a fake + * signal source. `tick` advances one poll interval and lets the poll's reads settle. */ + async function follow(filesystem: MemoryFilesystem) { + const clock = new FakeClock(0); + const signals = new EventEmitter(); + const ports = { + ...realCliEnvironmentPorts(filesystem), + clock, + signals: signals as unknown as NonNullable, + }; + const output = outputCapture(ports); + const exit = runCli(["daemon", "logs", "--follow"], output.environmentWith()); + const settle = () => new Promise((resolve) => setImmediate(resolve)); + await settle(); + return { + clock, + exit, + output, + signals, + settle, + tick: async () => { + clock.advance(250); + await settle(); + }, + }; + } + + const LOG = "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/simlock/daemon.log"; + + it("daemon logs --follow prints the existing tail, then a line appended later", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/simlock"); + await filesystem.writeFileAtomic(LOG, "old one\nold two\n"); + const run = await follow(filesystem); + + expect(run.output.stdout).toBe("old one\nold two\n"); + await filesystem.writeFileAtomic(LOG, "old one\nold two\nnew three\n"); + await run.tick(); + + expect(run.output.stdout).toBe("old one\nold two\nnew three\n"); + run.signals.emit("SIGINT"); + await expect(run.exit).resolves.toBe(0); + }); + + it("it prints lines written after a rotation, when the new file is already larger than the old offset at the next poll", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/simlock"); + await filesystem.writeFileAtomic(LOG, "a\n"); + const run = await follow(filesystem); + + // Between two polls: one more line in the old file, a rotation, and a new file already + // longer than everything the follower had read of the old one. + await filesystem.writeFileAtomic(LOG, "a\nb\n"); + await filesystem.rename(LOG, `${LOG}.1`); + await filesystem.writeFileAtomic(LOG, "after rotation 1\nafter rotation 2\n"); + await run.tick(); + + expect(run.output.stdout).toBe("a\nb\nafter rotation 1\nafter rotation 2\n"); + run.signals.emit("SIGTERM"); + await expect(run.exit).resolves.toBe(0); + }); + + it("it waits while the log file is missing and prints lines once it appears", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/simlock"); + const run = await follow(filesystem); + await run.tick(); + expect(run.output.stdout).toBe(""); + expect(run.output.stderr).toBe(""); + + await filesystem.writeFileAtomic(LOG, "first line\n"); + await run.tick(); + + expect(run.output.stdout).toBe("first line\n"); + run.signals.emit("SIGINT"); + await expect(run.exit).resolves.toBe(0); + }); + + it("daemon logs --follow --json fails with USAGE, exit 2", async () => { + const output = outputCapture(); + + await expect( + runCli(["daemon", "logs", "--follow", "--json"], output.environmentWith()), + ).resolves.toBe(2); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { code: "USAGE", message: expect.stringContaining("--follow") }, + }); + }); + + it("an interrupt ends the follow with exit 0 and leaves no timer armed", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/simlock"); + await filesystem.writeFileAtomic(LOG, "line\n"); + const run = await follow(filesystem); + expect(run.clock.pendingTimerCount).toBe(1); + + run.signals.emit("SIGINT"); + + await expect(run.exit).resolves.toBe(0); + expect(run.clock.pendingTimerCount).toBe(0); + expect(run.signals.listenerCount("SIGINT")).toBe(0); + expect(run.signals.listenerCount("SIGTERM")).toBe(0); + await filesystem.writeFileAtomic(LOG, "line\nafter exit\n"); + await run.tick(); + expect(run.output.stdout).toBe("line\n"); + }); +}); + describe("CLI smoke test (ADR 0003 §12: one per frontend)", () => { it("lease --detach, status, release, and token create round-trip through a real daemon", async () => { const { socketPath } = await startTestDaemon(); diff --git a/src/cli/index.ts b/src/cli/index.ts index 1ea88ae01..371d1a0fa 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -43,6 +43,7 @@ import { startLeaseRenewal, type LeaseRenewal, } from "../lease-policy/index.js"; +import { followLog, type Signals } from "./follow-log.js"; import { spawnPassthrough } from "./passthrough.js"; import { ERROR_TABLE } from "../contract/index.js"; @@ -100,11 +101,6 @@ interface Output { write(value: string): unknown; } -interface Signals { - on(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown; - off(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown; -} - type McpStdioRunner = () => Promise; /** @@ -160,6 +156,8 @@ export interface CliEnvironment { * `writeConfigFile` is ever called. Throws (any error) for an invalid merged config. */ readonly validateConfig: (merged: Record) => Promise; readonly readLogFile?: () => Promise; + /** `daemon logs --follow`: prints the log's tail, then each new line, until interrupted. */ + readonly followLogFile?: () => Promise; /** Loads the MCP frontend only when the `mcp` command is dispatched. */ readonly loadMcpStdio?: () => Promise; readonly runMcpStdio?: () => Promise; @@ -450,6 +448,14 @@ export function buildCliEnvironment( if (unknownKeyWarnings.length > 0) throw new Error(unknownKeyWarnings.join("; ")); }, readLogFile: async () => readLogFile(filesystem, logPath), + followLogFile: () => + followLog({ + clock, + filesystem, + path: logPath, + signals: ports.signals ?? process, + write: (text) => (ports.stdout ?? process.stdout).write(text), + }), signals: ports.signals ?? process, stderr: ports.stderr ?? process.stderr, stdout: ports.stdout ?? process.stdout, @@ -1445,11 +1451,12 @@ async function runDaemon( ): Promise { const command = argv[0]; const values = commandArgs(argv.slice(1), { + follow: { type: "boolean" }, help: { type: "boolean", short: "h" }, json: { type: "boolean" }, }); if (command === undefined || isHelp(command) || values.help) { - environment.stdout.write("Usage: simlock daemon \n"); + environment.stdout.write("Usage: simlock daemon \n"); return 0; } if (values.positionals.length > 0) throw new UsageError("daemon accepts exactly one subcommand"); @@ -1510,6 +1517,14 @@ async function runDaemon( return 0; } } + if (command === "logs" && values.follow) { + if (values.json) throw new UsageError("--follow cannot be combined with --json"); + if (environment.followLogFile === undefined) { + throw new Error("Daemon log reader is unavailable"); + } + await environment.followLogFile(); + return 0; + } if (command === "logs") { if (environment.readLogFile === undefined) throw new Error("Daemon log reader is unavailable"); const lines = (await environment.readLogFile()).trimEnd().split("\n"); diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 039e9f461..b1793488b 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -1,7 +1,7 @@ import { z } from "zod"; import { describe, expect, it } from "vitest"; -import { defineOperation, OPERATIONS, type OperationName } from "./operations.js"; +import { defineOperation, OPERATIONS, type Effect, type OperationName } from "./operations.js"; import { PUSH_SCHEMAS } from "./pushes.js"; import { ROLES, type Role } from "./roles.js"; @@ -10,6 +10,7 @@ describe("defineOperation", () => { const echo = defineOperation({ name: "test.echo", role: "agent", + effect: "read", input: z.object({ value: z.string() }), output: z.object({ value: z.string() }), }); @@ -84,6 +85,78 @@ describe("operation role matrix", () => { }); }); +/** Which calls change state: the daemon log records a `write` at its default level and a + * `read` only at `debug`. Rows keyed like `ROLE_MATRIX`, input-dependent ones twice. */ +const EFFECT_MATRIX: ReadonlyArray<{ + readonly name: OperationName; + readonly input: unknown; + readonly effect: Effect; +}> = [ + { name: "catalog.get", input: {}, effect: "read" }, + { name: "status.get", input: {}, effect: "read" }, + { name: "lease.request", input: { model: "iPhone 17", platform: "ios" }, effect: "write" }, + { name: "lease.cancel", input: {}, effect: "write" }, + { name: "lease.renew", input: { leaseId: "lease_1" }, effect: "write" }, + { name: "lease.release", input: { leaseId: "lease_1" }, effect: "write" }, + { name: "lease.list", input: {}, effect: "read" }, + { name: "doctor.run", input: {}, effect: "read" }, + { name: "doctor.run", input: { fix: false }, effect: "read" }, + { name: "doctor.run", input: { fix: true }, effect: "write" }, + { name: "doctor.run", input: { purgeOrphans: true }, effect: "write" }, + { name: "lease.release-all", input: {}, effect: "write" }, + { name: "list.get", input: {}, effect: "read" }, + { name: "cleanup.run", input: {}, effect: "write" }, + { name: "cleanup.run", input: { dryRun: false }, effect: "write" }, + { name: "cleanup.run", input: { dryRun: true }, effect: "read" }, + { name: "nuke.run", input: {}, effect: "write" }, + { name: "config.get", input: {}, effect: "read" }, + { name: "daemon.stop", input: {}, effect: "write" }, + { name: "events.replay", input: {}, effect: "read" }, + { name: "events.subscribe", input: {}, effect: "read" }, + { name: "events.unsubscribe", input: {}, effect: "read" }, + { name: "token.create", input: { role: "agent" }, effect: "write" }, + { name: "driver.passthrough", input: { args: ["devices"], tool: "adb" }, effect: "read" }, + { + name: "device.exec", + input: { args: ["devices"], leaseId: "lease_1", tool: "adb" }, + effect: "write", + }, + { name: "token.list", input: {}, effect: "read" }, + { name: "token.revoke", input: { id: "tok_1" }, effect: "write" }, + { name: "worker.list", input: {}, effect: "read" }, + { name: "worker.drain", input: { workerId: "wrk_1" }, effect: "write" }, + { name: "worker.undrain", input: { workerId: "wrk_1" }, effect: "write" }, + { name: "worker.remove", input: { workerId: "wrk_1" }, effect: "write" }, +]; + +function resolvedEffect(name: OperationName, input: unknown): unknown { + const effect = OPERATIONS[name].effect as Effect | ((input: unknown) => Effect) | undefined; + return typeof effect === "function" ? effect(OPERATIONS[name].input.parse(input)) : effect; +} + +describe("operation effects", () => { + it("every operation declares an effect", () => { + for (const name of Object.keys(OPERATIONS) as OperationName[]) { + expect(["read", "write"], name).toContain( + resolvedEffect(name, EFFECT_MATRIX.find((row) => row.name === name)?.input), + ); + } + expect(new Set(EFFECT_MATRIX.map((row) => row.name))).toEqual(new Set(Object.keys(OPERATIONS))); + }); + + it("doctor.run is a write only with fix or purgeOrphans, and cleanup.run is a read only with dryRun", () => { + expect(resolvedEffect("doctor.run", {})).toBe("read"); + expect(resolvedEffect("doctor.run", { fix: true })).toBe("write"); + expect(resolvedEffect("doctor.run", { purgeOrphans: true })).toBe("write"); + expect(resolvedEffect("cleanup.run", {})).toBe("write"); + expect(resolvedEffect("cleanup.run", { dryRun: true })).toBe("read"); + }); + + it.each(EFFECT_MATRIX)("$name with $input is a $effect", ({ name, input, effect }) => { + expect(resolvedEffect(name, input)).toBe(effect); + }); +}); + describe("operation input/output round trips", () => { it("lease.request: round-trips a representative request and rejects legacy aliases", () => { const input = OPERATIONS["lease.request"].input.parse({ diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 28109e0f9..dc2eb1126 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -33,6 +33,8 @@ import { workerViewSchema, } from "./schemas.js"; +export type Effect = "read" | "write"; + export interface OperationDefinition< Name extends string = string, InputSchema extends z.ZodTypeAny = z.ZodTypeAny, @@ -40,6 +42,10 @@ export interface OperationDefinition< > { readonly name: Name; readonly role: Role | ((input: z.infer) => Role); + /** Whether a call changes state. The daemon log records every `write` at its default level + * and a `read` only at `debug`. Never sent on the wire. Like `role`, it may depend on the + * already-validated input. */ + readonly effect: Effect | ((input: z.infer) => Effect); readonly input: InputSchema; readonly output: OutputSchema; /** Ownership/ownership-adjacent gating a session-aware dispatcher would run after the role @@ -64,6 +70,7 @@ export function defineOperation< export const catalogGet = defineOperation({ name: "catalog.get", role: "agent", + effect: "read", input: z.object({ platform: platformSchema.optional() }), output: z.object({ platforms: z.array(platformCatalogSchema) }), }); @@ -74,6 +81,7 @@ export const catalogGet = defineOperation({ export const statusGet = defineOperation({ name: "status.get", role: "agent", + effect: "read", input: z.object({}), output: z.object({ // Agent-role, no ownership check (ADR §3) -- every device in the registry, not just ones @@ -148,6 +156,7 @@ const leaseRequestInputSchema = z export const leaseRequest = defineOperation({ name: "lease.request", role: "agent", + effect: "write", input: leaseRequestInputSchema, output: leaseGrantSchema, /** @@ -176,6 +185,7 @@ export const leaseRequest = defineOperation({ export const leaseCancel = defineOperation({ name: "lease.cancel", role: "agent", + effect: "write", input: z.object({ requesterId: z.string().optional() }), output: z.object({ result: z.enum(["cancelled", "not-found", "not-cancellable"]) }), /** @@ -213,6 +223,7 @@ export const leaseCancel = defineOperation({ export const leaseRenew = defineOperation({ name: "lease.renew", role: "agent", + effect: "write", input: z.object({ leaseId: z.string(), ttlMs: z.number().finite().positive().optional() }), output: leaseRecordSchema, authorize: ownsLease((input) => input.leaseId), @@ -223,6 +234,7 @@ export const leaseRenew = defineOperation({ export const leaseRelease = defineOperation({ name: "lease.release", role: "agent", + effect: "write", input: z.object({ leaseId: z.string() }), output: z.object({ leaseId: z.string() }), authorize: ownsLease((input) => input.leaseId), @@ -246,6 +258,7 @@ export const leaseRelease = defineOperation({ export const driverPassthrough = defineOperation({ name: "driver.passthrough", role: "agent", + effect: "read", input: z.object({ args: z.array(z.string()), tool: z.string().min(1) }), output: passthroughCommandSchema, }); @@ -290,6 +303,7 @@ export const driverPassthrough = defineOperation({ export const deviceExec = defineOperation({ name: "device.exec", role: "agent", + effect: "write", input: z .object({ leaseId: z.string(), @@ -366,6 +380,7 @@ export const deviceExec = defineOperation({ export const leaseList = defineOperation({ name: "lease.list", role: "agent", + effect: "read", input: z.object({}), output: z.object({ leases: z.array(statusLeaseSchema) }), }); @@ -400,6 +415,8 @@ export const doctorRun = defineOperation({ */ role: (input: z.infer): Role => input.fix || input.purgeOrphans ? "admin" : "agent", + effect: (input: z.infer): Effect => + input.fix || input.purgeOrphans ? "write" : "read", input: doctorRunInputSchema, output: doctorReportSchema, }); @@ -410,6 +427,7 @@ export const doctorRun = defineOperation({ export const leaseReleaseAll = defineOperation({ name: "lease.release-all", role: "admin", + effect: "write", input: z.object({}), output: z.object({ leaseIds: z.array(z.string()) }), }); @@ -434,6 +452,7 @@ export const leaseReleaseAll = defineOperation({ export const listGet = defineOperation({ name: "list.get", role: "admin", + effect: "read", input: z.object({ kind: z.enum(["devices", "leases", "rules"]).optional() }), output: z.union([ z.array(deviceRecordSchema), @@ -449,6 +468,7 @@ export const listGet = defineOperation({ export const cleanupRun = defineOperation({ name: "cleanup.run", role: "admin", + effect: (input: { dryRun?: boolean | undefined }): Effect => (input.dryRun ? "read" : "write"), input: z.object({ dryRun: z.boolean().optional(), rule: z.string().optional() }), output: z.array(proposalSchema), }); @@ -459,6 +479,7 @@ export const cleanupRun = defineOperation({ export const nukeRun = defineOperation({ name: "nuke.run", role: "admin", + effect: "write", input: z.object({ deleteDevices: z.boolean().optional() }), output: nukeReportSchema, }); @@ -469,6 +490,7 @@ export const nukeRun = defineOperation({ export const configGet = defineOperation({ name: "config.get", role: "admin", + effect: "read", input: z.object({}), output: configSchema, }); @@ -484,6 +506,7 @@ export const configGet = defineOperation({ export const daemonStop = defineOperation({ name: "daemon.stop", role: "admin", + effect: "write", input: z.object({}), output: z.object({ stopping: z.literal(true) }), }); @@ -494,6 +517,7 @@ export const daemonStop = defineOperation({ export const eventsReplay = defineOperation({ name: "events.replay", role: "admin", + effect: "read", input: z.object({ sinceTs: z.number().optional() }), output: z.array(eventEnvelopeSchema), }); @@ -504,6 +528,7 @@ export const eventsReplay = defineOperation({ export const eventsSubscribe = defineOperation({ name: "events.subscribe", role: "admin", + effect: "read", input: z.object({}), output: z.object({ subscribed: z.literal(true), subscriptionId: z.string() }), }); @@ -514,6 +539,7 @@ export const eventsSubscribe = defineOperation({ export const eventsUnsubscribe = defineOperation({ name: "events.unsubscribe", role: "admin", + effect: "read", input: z.object({}), output: z.object({ subscribed: z.literal(false) }), }); @@ -531,6 +557,7 @@ export const eventsUnsubscribe = defineOperation({ export const tokenCreate = defineOperation({ name: "token.create", role: "admin", + effect: "write", input: z.object({ role: tokenRoleSchema, label: z.string().optional() }), output: z.object({ secret: z.string(), token: tokenRecordSchema }), }); @@ -539,6 +566,7 @@ export const tokenCreate = defineOperation({ export const tokenList = defineOperation({ name: "token.list", role: "admin", + effect: "read", input: z.object({}), output: z.object({ tokens: z.array(tokenRecordSchema) }), }); @@ -547,6 +575,7 @@ export const tokenList = defineOperation({ export const tokenRevoke = defineOperation({ name: "token.revoke", role: "admin", + effect: "write", input: z.object({ id: z.string() }), output: z.object({ revoked: z.boolean() }), }); @@ -567,6 +596,7 @@ export const tokenRevoke = defineOperation({ export const workerList = defineOperation({ name: "worker.list", role: "admin", + effect: "read", input: z.object({}), output: z.object({ workers: z.array(workerViewSchema) }), }); @@ -586,6 +616,7 @@ export const workerList = defineOperation({ export const workerDrain = defineOperation({ name: "worker.drain", role: "admin", + effect: "write", input: z.object({ workerId: z.string().min(1) }), output: z.object({ workerId: z.string(), drained: z.literal(true) }), }); @@ -594,6 +625,7 @@ export const workerDrain = defineOperation({ export const workerUndrain = defineOperation({ name: "worker.undrain", role: "admin", + effect: "write", input: z.object({ workerId: z.string().min(1) }), output: z.object({ workerId: z.string(), drained: z.literal(false) }), }); @@ -612,6 +644,7 @@ export const workerUndrain = defineOperation({ export const workerRemove = defineOperation({ name: "worker.remove", role: "admin", + effect: "write", input: z.object({ workerId: z.string().min(1) }), output: z.object({ workerId: z.string(), removed: z.boolean() }), }); diff --git a/src/core/device-provisioner.test.ts b/src/core/device-provisioner.test.ts index 4e9409b63..1b7e864c4 100644 --- a/src/core/device-provisioner.test.ts +++ b/src/core/device-provisioner.test.ts @@ -1,7 +1,13 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, MemoryFilesystem } from "../ports/index.js"; +import { + FakeClock, + JsonLinesLogger, + type Logger, + MemoryFilesystem, + MemoryLogSink, +} from "../ports/index.js"; import { type CapacityReservation } from "./capacity/index.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; import { DeviceProvisioner } from "./device-provisioner.js"; @@ -20,10 +26,13 @@ function reservation(): CapacityReservation & { readonly releaseCount: () => num return { release: () => void releases++, releaseCount: () => releases }; } -async function createHarness(latencyMs?: { - readonly makeReady?: number; - readonly provision?: number; -}) { +async function createHarness( + latencyMs?: { + readonly makeReady?: number; + readonly provision?: number; + }, + logger?: Logger, +) { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); const driver = new FakeDriver({ @@ -53,6 +62,7 @@ async function createHarness(latencyMs?: { clock, decisions, lifecycle, + ...(logger === undefined ? {} : { logger }), registry, }); return { clock, driver, eventBus, lifecycle, provisioner, registry }; @@ -139,6 +149,61 @@ describe("DeviceProvisioner", () => { expect(reserved.releaseCount()).toBe(1); }); + it("A new device that fails to become ready logs the driver's error with the device id.", async () => { + const sink = new MemoryLogSink(); + const harness = await createHarness( + undefined, + new JsonLinesLogger({ clock: new FakeClock(1_000), sink }), + ); + harness.driver.failOn("makeReady", 1, new DriverCrashError("simulator never booted")); + + await expect( + harness.provisioner.provision(spec, { reservation: reservation() }), + ).rejects.toBeInstanceOf(BootTimeoutError); + + const deviceId = harness.registry.snapshot.devices[0]?.id; + expect(deviceId).toBeDefined(); + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "warn", + module: "daemon.device-provisioner", + fields: { + deviceId, + error: "DriverCrashError: simulator never booted", + step: "boot", + }, + }), + ]); + }); + + it("A failed destroy after a failed boot logs the device id and the error.", async () => { + const sink = new MemoryLogSink(); + const harness = await createHarness( + undefined, + new JsonLinesLogger({ clock: new FakeClock(1_000), sink }), + ); + harness.driver.failOn("makeReady", 1, new DriverCrashError("simulator never booted")); + harness.driver.failOn("destroy", 1, new DriverCrashError("simctl delete refused")); + + await expect( + harness.provisioner.provision(spec, { reservation: reservation() }), + ).rejects.toBeInstanceOf(BootTimeoutError); + + const deviceId = harness.registry.snapshot.devices[0]?.id; + expect(deviceId).toBeDefined(); + expect(harness.registry.snapshot.devices[0]?.state).not.toBe("deleted"); + expect(sink.records.filter((record) => record.fields?.["step"] === "destroy")).toEqual([ + expect.objectContaining({ + level: "warn", + fields: { + deviceId, + error: "DriverCrashError: simctl delete refused", + step: "destroy", + }, + }), + ]); + }); + it("releases its capacity reservation when the driver cannot provision", async () => { const harness = await createHarness(); const reserved = reservation(); diff --git a/src/core/device-provisioner.ts b/src/core/device-provisioner.ts index 9aaaf07b4..97e5adb52 100644 --- a/src/core/device-provisioner.ts +++ b/src/core/device-provisioner.ts @@ -1,4 +1,5 @@ -import type { Clock } from "../ports/index.js"; +import { type Clock, type Logger, NoopLogger } from "../ports/index.js"; +import { stableError } from "./stable-error.js"; import type { CapacityReservation } from "./capacity/index.js"; import type { DeviceRecord, DeviceSpec } from "./domain.js"; import { BootTimeoutError, type DriverDevice } from "./driver.js"; @@ -27,6 +28,7 @@ export interface DeviceProvisionerOptions { readonly decisions: SerializedDecision; readonly lifecycle: Pick; readonly registry: DeviceProvisionerRegistry; + readonly logger?: Logger; } export interface ProvisionDeviceOptions { @@ -36,7 +38,11 @@ export interface ProvisionDeviceOptions { /** Provisions a new driver device, registers it, and makes it ready. */ export class DeviceProvisioner { - constructor(private readonly options: DeviceProvisionerOptions) {} + readonly #logger: Logger; + + constructor(private readonly options: DeviceProvisionerOptions) { + this.#logger = options.logger?.child("device-provisioner") ?? new NoopLogger(); + } async provision(spec: DeviceSpec, options: ProvisionDeviceOptions): Promise { const driver = this.options.catalog.get(spec.platform); @@ -77,11 +83,22 @@ export class DeviceProvisioner { if (ready === undefined) throw new Error(`Registered device could not be made ready: ${device.id}`); return ready; - } catch { + } catch (error: unknown) { + // The caller only ever sees `BootTimeoutError`; the driver's own reason is kept here. + this.#logger.warn("new device failed to become ready", { + deviceId: device.id, + step: "boot", + error: stableError(error), + }); try { await this.options.lifecycle.destroy(device, "lease-engine", "boot"); - } catch { + } catch (destroyError: unknown) { // The registered record remains for reconcile when the driver cannot destroy it. + this.#logger.warn("destroying a device that failed to boot failed", { + deviceId: device.id, + step: "destroy", + error: stableError(destroyError), + }); } throw new BootTimeoutError(device.id); } finally { diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 0f1c03f1a..6b2678b1a 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -1,7 +1,14 @@ import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, FakeSystemStats, MemoryFilesystem } from "../ports/index.js"; +import { + FakeClock, + FakeSystemStats, + JsonLinesLogger, + type Logger, + MemoryFilesystem, + MemoryLogSink, +} from "../ports/index.js"; import { AcquisitionPlanner } from "./acquisition-planner.js"; import { CapacityCoordinator, createCapacityStrategy } from "./capacity/index.js"; import type { Config } from "./config.js"; @@ -75,7 +82,11 @@ function config(maxDevices = 1): Config { } async function createHarness( - options: { readonly drivers?: readonly FakeDriver[]; readonly maxDevices?: number } = {}, + options: { + readonly drivers?: readonly FakeDriver[]; + readonly logger?: Logger; + readonly maxDevices?: number; + } = {}, ) { const clock = new FakeClock(1_000); const bus = new EventBus(clock); @@ -130,6 +141,7 @@ async function createHarness( eventBus: bus, leases, lifecycle, + ...(options.logger === undefined ? {} : { logger: options.logger }), planner: new AcquisitionPlanner(capacity, claims), provisioner, queue, @@ -160,6 +172,32 @@ async function flush(): Promise { for (let count = 0; count < 20; count += 1) await Promise.resolve(); } +/** Lets fire-and-forget device work that crosses several registry writes run to rest. */ +async function settle(): Promise { + for (let count = 0; count < 20; count += 1) await new Promise((resolve) => setImmediate(resolve)); +} + +function capturingLogger(): { readonly logger: Logger; readonly sink: MemoryLogSink } { + const sink = new MemoryLogSink(); + return { logger: new JsonLinesLogger({ clock: new FakeClock(1_000), sink }), sink }; +} + +async function seedShutdown( + harness: Awaited>, + spec: DeviceSpec = request, +) { + const ready = await seedReady(harness, spec); + await harness.driver.shutdown({ + address: ready.address ?? "", + deviceId: ready.driverDeviceId, + driverData: ready.driverData, + }); + return harness.registry.transitionDevice(ready.id, "shutdown", { + event: "device.shutdown", + payload: { deviceId: ready.id, initiator: "test" }, + }); +} + describe("LeaseAcquisitionCoordinator", () => { it("admits one requester and rejects an active or pending duplicate", async () => { const harness = await createHarness(); @@ -597,4 +635,97 @@ describe("LeaseAcquisitionCoordinator", () => { expect(fullRequest.device.spec).not.toHaveProperty("full"); expect(fullRequest.device.spec).toEqual(request); }); + + it("A failed eviction shutdown logs the device id and the error, and the waiter is deferred as before.", async () => { + const { logger, sink } = capturingLogger(); + // Two devices allowed but only one running: a running device of another spec is + // evicted by shutdown (not deleted) to make room for the request. + const harness = await createHarness({ logger, maxDevices: 2 }); + const victim = await seedReady(harness, { ...request, model: "iPhone SE" }); + harness.driver.failOn("shutdown", 1, new DriverCrashError("shutdown wedged")); + + let settled = false; + const acquisition = harness.coordinator.request(request, { + ownerId: "evictor", + requesterId: "evictor", + }); + void acquisition.then( + () => (settled = true), + () => (settled = true), + ); + await settle(); + + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "warn", + module: "daemon.lease-acquisition-coordinator", + fields: { + deviceId: victim.id, + error: "DriverCrashError: shutdown wedged", + requesterId: "evictor", + step: "shutdown", + }, + }), + ]); + // Deferred: back in the queue, still pending, and the victim untouched. + expect(settled).toBe(false); + expect(harness.coordinator.queueDepth).toBe(1); + expect(harness.registry.snapshot.devices.find((device) => device.id === victim.id)?.state).toBe( + "ready", + ); + await harness.coordinator.cancelPending("evictor"); + await expect(acquisition).rejects.toMatchObject({ name: "RequestCancelledError" }); + }); + + it("A failed eviction delete logs the device id and the error.", async () => { + const { logger, sink } = capturingLogger(); + // One device allowed: a managed device of another spec is deleted to make room. + const harness = await createHarness({ logger, maxDevices: 1 }); + const victim = await seedShutdown(harness, { ...request, model: "iPhone SE" }); + harness.driver.failOn("destroy", 1, new DriverCrashError("simctl delete refused")); + + const acquisition = harness.coordinator.request(request, { + ownerId: "evictor", + requesterId: "evictor", + }); + await settle(); + + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "warn", + fields: { + deviceId: victim.id, + error: "DriverCrashError: simctl delete refused", + requesterId: "evictor", + step: "delete", + }, + }), + ]); + await harness.coordinator.cancelPending("evictor"); + await expect(acquisition).rejects.toMatchObject({ name: "RequestCancelledError" }); + }); + + it("A shut-down device that fails to boot for a waiter logs the driver's error.", async () => { + const { logger, sink } = capturingLogger(); + const harness = await createHarness({ logger }); + const shutdown = await seedShutdown(harness); + // Call 1 is seedReady's own boot; call 2 is the waiter's. + harness.driver.failOn("makeReady", 2, new DriverCrashError("simulator never booted")); + + await expect( + harness.coordinator.request(request, { ownerId: "booter", requesterId: "booter" }), + ).rejects.toMatchObject({ name: "BootTimeoutError" }); + + expect(sink.records.filter((record) => record.fields?.["step"] === "boot")).toEqual([ + expect.objectContaining({ + level: "warn", + fields: { + deviceId: shutdown.id, + error: "DriverCrashError: simulator never booted", + requesterId: "booter", + step: "boot", + }, + }), + ]); + }); }); diff --git a/src/core/lease-acquisition-coordinator.ts b/src/core/lease-acquisition-coordinator.ts index d802c471a..a8d35487e 100644 --- a/src/core/lease-acquisition-coordinator.ts +++ b/src/core/lease-acquisition-coordinator.ts @@ -1,4 +1,5 @@ import type { EventBus } from "../bus/index.js"; +import { type Logger, NoopLogger } from "../ports/index.js"; import type { CapacityReservation } from "./capacity/index.js"; import { type AcquisitionPlan, type AcquisitionPlanner } from "./acquisition-planner.js"; import { @@ -16,6 +17,7 @@ import { type ReadyDeviceHandoff, } from "./managed-device-lifecycle.js"; import { type SerializedDecision } from "./serialized-decision.js"; +import { stableError } from "./stable-error.js"; import { type LeaseGrant, type LeaseRequestOptions, @@ -91,6 +93,7 @@ export interface LeaseAcquisitionCoordinatorOptions { readonly provisioner: Pick; readonly queue: AcquisitionQueue; readonly registry: LeaseAcquisitionRegistry; + readonly logger?: Logger; } interface AcquisitionWaiter extends Waiter { @@ -117,8 +120,11 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { readonly #driving = new WeakSet(); #admissionClosed = false; #maintenanceDepth = 0; + readonly #logger: Logger; - constructor(private readonly options: LeaseAcquisitionCoordinatorOptions) {} + constructor(private readonly options: LeaseAcquisitionCoordinatorOptions) { + this.#logger = options.logger?.child("lease-acquisition-coordinator") ?? new NoopLogger(); + } get queueDepth(): number { return this.options.queue.depth; @@ -445,7 +451,14 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { ); if (shutdown === undefined) throw new Error(`Eviction target is no longer safe: ${device.id}`); - } catch { + } catch (error: unknown) { + this.#logFailure( + "shutting down an eviction target failed", + waiter, + device, + "shutdown", + error, + ); await this.options.decisions.run(async () => { claim.release(); this.#defer(waiter); @@ -468,7 +481,8 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { claim, ); if (deleted === undefined) throw new Error(`Eviction target is no longer safe: ${device.id}`); - } catch { + } catch (error: unknown) { + this.#logFailure("deleting an eviction target failed", waiter, device, "delete", error); await this.options.decisions.run(async () => { claim.release(); this.#defer(waiter); @@ -490,6 +504,23 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { await this.#perform(waiter, next); } + /** One `warn` line for a device step that failed in the background and is handled here by + * deferring the waiter or destroying the device. The waiter only ever sees a generic outcome. */ + #logFailure( + message: string, + waiter: AcquisitionWaiter, + device: DeviceRecord, + step: string, + error: unknown, + ): void { + this.#logger.warn(message, { + deviceId: device.id, + requesterId: waiter.options.requesterId, + step, + error: stableError(error), + }); + } + async #bootShutdown( waiter: AcquisitionWaiter, device: DeviceRecord, @@ -506,12 +537,26 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { const ready = await this.options.lifecycle.bootForLease(device, claim); if (ready === undefined) throw new Error(`Boot target is no longer safe: ${device.id}`); handoff = ready; - } catch { + } catch (error: unknown) { + this.#logFailure( + "booting a shut-down device for a waiter failed", + waiter, + device, + "boot", + error, + ); let destroyed = true; try { destroyed = (await this.options.lifecycle.destroy(device, "lease-engine", "boot")) !== undefined; - } catch { + } catch (destroyError: unknown) { + this.#logFailure( + "destroying a device that failed to boot failed", + waiter, + device, + "destroy", + destroyError, + ); destroyed = false; } await this.options.decisions.run(async () => { diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 0fa789cd4..77291f487 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -1,7 +1,14 @@ import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, FakeSystemStats, MemoryFilesystem } from "../ports/index.js"; +import { + FakeClock, + FakeSystemStats, + JsonLinesLogger, + type Logger, + MemoryFilesystem, + MemoryLogSink, +} from "../ports/index.js"; import type { CapacityLimits, ResourceStrategyOptions } from "./capacity/index.js"; import { BootTimeoutError, @@ -89,6 +96,7 @@ async function createHarness( readonly identity?: Config["lease"]["identity"]; readonly lease?: Partial; readonly limits?: CapacityLimits; + readonly logger?: Logger; } = {}, ) { const clock = new FakeClock(1_000); @@ -125,6 +133,7 @@ async function createHarness( drivers: options.drivers ?? [driver], eventBus: bus, idGenerator: { generate: () => `request-${nextId++}` }, + ...(options.logger === undefined ? {} : { logger: options.logger }), registry, systemStats: new FakeSystemStats({ cpuCount: 8, @@ -398,6 +407,39 @@ describe("LeaseEngine", () => { expect(harness.driver.calls.map((call) => call.operation)).toContain("destroy"); }); + it("A purge failure logs nothing, because device.purge-failed carries the error.", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); + driver.failOn("reclaim", 1, new DriverCrashError("purge exploded")); + const sink = new MemoryLogSink(); + const harness = await createHarness({ + driver, + logger: new JsonLinesLogger({ clock, level: "debug", sink }), + }); + const first = await harness.engine.request(request, { + ownerId: "first", + requesterId: "first", + }); + + await harness.engine.release(first.lease.id, "explicit"); + await harness.engine.settle(); + + expect( + harness.bus.replay().filter((event) => event.event === "device.purge-failed"), + ).toMatchObject([ + { + payload: { + deviceId: first.device.id, + error: "DriverCrashError: purge exploded", + leaseId: first.lease.id, + }, + }, + ]); + expect( + sink.records.filter((record) => record.level === "warn" || record.level === "error"), + ).toEqual([]); + }); + it("quarantines a release-time purge failure instead of keeping the device eligible", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); diff --git a/src/core/lease-engine.ts b/src/core/lease-engine.ts index 25355cfa2..45175c061 100644 --- a/src/core/lease-engine.ts +++ b/src/core/lease-engine.ts @@ -107,11 +107,16 @@ export class LeaseEngine { clock: options.clock, decisions: this.#decisions, lifecycle: this.#deviceLifecycle, + ...(options.logger === undefined ? {} : { logger: options.logger }), registry: options.registry, }); - this.#expiry = new LeaseExpiryScheduler(options.clock, async (leaseId, expectedDeadline) => { - await this.#releaseCoordinator.expire(leaseId, expectedDeadline); - }); + this.#expiry = new LeaseExpiryScheduler( + options.clock, + async (leaseId, expectedDeadline) => { + await this.#releaseCoordinator.expire(leaseId, expectedDeadline); + }, + options.logger, + ); this.#leases = new LeaseLifecycle({ clock: options.clock, eventBus: options.eventBus, @@ -141,6 +146,7 @@ export class LeaseEngine { planner: this.#planner, provisioner: this.#provisioner, queue: this.#queue, + ...(options.logger === undefined ? {} : { logger: options.logger }), registry: options.registry, }); this.#quarantine = new QuarantineCoordinator({ @@ -150,6 +156,7 @@ export class LeaseEngine { drivers: this.#drivers, eventBus: options.eventBus, notifyAvailability: () => this.#acquisition.kick(), + ...(options.logger === undefined ? {} : { logger: options.logger }), registry: options.registry, }); this.#warmPool = new WarmPoolCoordinator({ @@ -164,6 +171,7 @@ export class LeaseEngine { const spec = this.#acquisition.queueHeadSpec; return spec === undefined ? undefined : { spec }; }, + ...(options.logger === undefined ? {} : { logger: options.logger }), registry: options.registry, }); this.#releaseCoordinator = new LeaseReleaseCoordinator({ diff --git a/src/core/lease-expiry-scheduler.test.ts b/src/core/lease-expiry-scheduler.test.ts index 6993e4d8a..d7a9aebc4 100644 --- a/src/core/lease-expiry-scheduler.test.ts +++ b/src/core/lease-expiry-scheduler.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { FakeClock } from "../ports/index.js"; +import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; import { LeaseExpiryScheduler } from "./lease-expiry-scheduler.js"; const lease = (id: string, ttlDeadline: number) => ({ @@ -73,4 +73,30 @@ describe("LeaseExpiryScheduler", () => { expect(() => clock.advance(10)).not.toThrow(); await Promise.resolve(); }); + + it("A lease expiry that throws logs at error with the lease id.", async () => { + const clock = new FakeClock(100); + const sink = new MemoryLogSink(); + const scheduler = new LeaseExpiryScheduler( + clock, + async () => { + throw new Error("release exploded"); + }, + new JsonLinesLogger({ clock, sink }), + ); + + scheduler.arm(lease("one", 110)); + clock.advance(10); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "error", + module: "daemon.lease-expiry-scheduler", + fields: { error: "Error: release exploded", leaseId: "one", step: "expire" }, + }), + ]); + }); }); diff --git a/src/core/lease-expiry-scheduler.ts b/src/core/lease-expiry-scheduler.ts index 4f2b43eb4..618aa4248 100644 --- a/src/core/lease-expiry-scheduler.ts +++ b/src/core/lease-expiry-scheduler.ts @@ -1,5 +1,6 @@ -import type { Clock, TimerHandle } from "../ports/index.js"; +import { type Clock, type Logger, NoopLogger, type TimerHandle } from "../ports/index.js"; import type { LeaseRecord } from "./domain.js"; +import { stableError } from "./stable-error.js"; export type LeaseExpiryHandler = ( leaseId: string, @@ -10,11 +11,15 @@ export type LeaseExpiryHandler = ( export class LeaseExpiryScheduler { readonly #timers = new Map(); #disposed = false; + readonly #logger: Logger; constructor( private readonly clock: Clock, private readonly onExpiry: LeaseExpiryHandler, - ) {} + logger?: Logger, + ) { + this.#logger = logger?.child("lease-expiry-scheduler") ?? new NoopLogger(); + } arm(lease: LeaseRecord): void { if (this.#disposed) return; @@ -63,7 +68,13 @@ export class LeaseExpiryScheduler { } #deliverExpiry(leaseId: string, expectedDeadline: number): void { - void this.#expire(leaseId, expectedDeadline).catch(() => undefined); + void this.#expire(leaseId, expectedDeadline).catch((error: unknown) => { + this.#logger.error("lease expiry failed", { + leaseId, + step: "expire", + error: stableError(error), + }); + }); } async #expire(leaseId: string, expectedDeadline: number): Promise { diff --git a/src/core/quarantine-coordinator.test.ts b/src/core/quarantine-coordinator.test.ts index 7e1b7a194..163eb9082 100644 --- a/src/core/quarantine-coordinator.test.ts +++ b/src/core/quarantine-coordinator.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus, type EventEnvelope } from "../bus/index.js"; -import { FakeClock } from "../ports/index.js"; +import { FakeClock, JsonLinesLogger, type Logger, MemoryLogSink } from "../ports/index.js"; import { DriverCatalog } from "./driver-catalog.js"; import type { DeviceRecord, DeviceSpec } from "./domain.js"; import { FakeDriver } from "./fake-driver.js"; @@ -112,6 +112,7 @@ async function createHarness( readonly clock?: FakeClock; readonly config?: QuarantineRetryConfig; readonly driver?: FakeDriver; + readonly logger?: Logger; readonly target?: Pick; } = {}, ) { @@ -128,6 +129,7 @@ async function createHarness( decisions: new SerializedDecision(), drivers: new DriverCatalog([driver]), eventBus: bus, + ...(options.logger === undefined ? {} : { logger: options.logger }), notifyAvailability, registry, }); @@ -371,6 +373,76 @@ describe("QuarantineCoordinator", () => { expect(harness.driver.calls.map((call) => call.operation)).not.toContain("reclaim"); }); + it("A failed quarantine reclaim retry logs the error and the attempt number.", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ clock, platform: "ios" }); + driver.failOn("reclaim", 1, new Error("erase still stuck")); + const sink = new MemoryLogSink(); + const harness = await createHarness({ + clock, + driver, + logger: new JsonLinesLogger({ clock, sink }), + }); + await harness.coordinator.enter({ + attemptedStrategy: "wipe", + deviceId: harness.target.id, + duration: 0, + error: "boom", + leaseId: "lease-1", + }); + + harness.clock.advance(retryConfig.retryBackoffMs); + await flush(); + + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "warn", + module: "daemon.quarantine-coordinator", + fields: { + attempts: 1, + deviceId: harness.target.id, + error: "Error: erase still stuck", + step: "reclaim", + }, + }), + ]); + }); + + it("A failed quarantine delete retry logs the error and the attempt number.", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ clock, platform: "ios" }); + driver.failOn("destroy", 1, new Error("delete still stuck")); + const sink = new MemoryLogSink(); + const harness = await createHarness({ + clock, + driver, + logger: new JsonLinesLogger({ clock, sink }), + target: { lastLeaseEndedAt: 900, leaseIdentity: "fresh" }, + }); + await harness.coordinator.enter({ + attemptedStrategy: "delete", + deviceId: harness.target.id, + duration: 0, + error: "boom", + leaseId: "lease-1", + }); + + harness.clock.advance(retryConfig.retryBackoffMs); + await flush(); + + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "warn", + fields: { + attempts: 1, + deviceId: harness.target.id, + error: "Error: delete still stuck", + step: "delete", + }, + }), + ]); + }); + it("never touches a device that left quarantine before its retry timer fires", async () => { const harness = await createHarness(); await harness.coordinator.enter({ diff --git a/src/core/quarantine-coordinator.ts b/src/core/quarantine-coordinator.ts index 3fba849b4..008eecf51 100644 --- a/src/core/quarantine-coordinator.ts +++ b/src/core/quarantine-coordinator.ts @@ -1,5 +1,5 @@ import type { EventBus } from "../bus/index.js"; -import type { Clock, TimerHandle } from "../ports/index.js"; +import { type Clock, type Logger, NoopLogger, type TimerHandle } from "../ports/index.js"; import { type DeviceRecord, mayBeGranted, type Platform } from "./domain.js"; import type { Driver, DriverDevice } from "./driver.js"; import type { SerializedDecision } from "./serialized-decision.js"; @@ -47,6 +47,7 @@ export interface QuarantineCoordinatorOptions { readonly eventBus: Pick; readonly notifyAvailability: () => void; readonly registry: QuarantineRegistry; + readonly logger?: Logger; } /** @@ -70,8 +71,11 @@ export interface QuarantineCoordinatorOptions { export class QuarantineCoordinator { readonly #timers = new Map(); #disposed = false; + readonly #logger: Logger; - constructor(private readonly options: QuarantineCoordinatorOptions) {} + constructor(private readonly options: QuarantineCoordinatorOptions) { + this.#logger = options.logger?.child("quarantine-coordinator") ?? new NoopLogger(); + } /** * Commits quarantine entry for a device whose release-time purge just @@ -81,6 +85,7 @@ export class QuarantineCoordinator { * count as running -- so no queued waiter can be satisfied by this alone * and `notifyAvailability` is not called. */ + // fallow-ignore-next-line unused-class-member -- called through WarmPoolCoordinator's quarantine port. async enter(failure: QuarantinePurgeFailure): Promise { const nextRetryAt = this.options.clock.now() + this.options.config.retryBackoffMs; await this.options.decisions.run(async () => { @@ -154,7 +159,13 @@ export class QuarantineCoordinator { deviceId, this.options.clock.setTimer(delay, () => { this.#timers.delete(deviceId); - void this.#retry(deviceId).catch(() => undefined); + void this.#retry(deviceId).catch((error: unknown) => { + this.#logger.error("quarantine retry threw", { + deviceId, + step: "retry", + error: stableError(error), + }); + }); }), ); } @@ -180,7 +191,8 @@ export class QuarantineCoordinator { let result: Awaited>; try { result = await driver.reclaim(toDriverDevice(device), { clean: "standard" }); - } catch { + } catch (error: unknown) { + this.#logRetryFailure("quarantine reclaim retry failed", device, "reclaim", attempts, error); await this.#retryFailed(device, attempts); return; } @@ -204,7 +216,8 @@ export class QuarantineCoordinator { async #retryDelete(driver: Driver, device: DeviceRecord, attempts: number): Promise { try { await driver.destroy(toDriverDevice(device)); - } catch { + } catch (error: unknown) { + this.#logRetryFailure("quarantine delete retry failed", device, "delete", attempts, error); await this.#retryFailed(device, attempts); return; } @@ -214,6 +227,16 @@ export class QuarantineCoordinator { this.options.notifyAvailability(); } + #logRetryFailure( + message: string, + device: DeviceRecord, + step: string, + attempts: number, + error: unknown, + ): void { + this.#logger.warn(message, { deviceId: device.id, step, attempts, error: stableError(error) }); + } + async #retryFailed(device: DeviceRecord, attempts: number): Promise { if (attempts >= this.options.config.maxRetries) { await this.#giveUp(device, attempts); diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index 4721640e0..dbf93e21f 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -1,7 +1,14 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, FakeSystemStats, MemoryFilesystem } from "../ports/index.js"; +import { + FakeClock, + FakeSystemStats, + JsonLinesLogger, + type Logger, + MemoryFilesystem, + MemoryLogSink, +} from "../ports/index.js"; import { type CleanupRule, type Config, @@ -99,6 +106,7 @@ async function createHarness( options: { readonly cleanupConfig?: Config; readonly filesystem?: MemoryFilesystem; + readonly logger?: Logger; readonly tickMs?: number; readonly useLeaseEngineExecutor?: boolean; } = {}, @@ -156,6 +164,7 @@ async function createHarness( eventBus, filesystem, executor, + ...(options.logger === undefined ? {} : { logger: options.logger }), registry, rules, ...(options.tickMs === undefined ? {} : { tickMs: options.tickMs }), @@ -371,6 +380,37 @@ describe("CleanupReaper", () => { harness.reaper.dispose(); }); + it("A cleanup run that throws logs at error.", async () => { + const sink = new MemoryLogSink(); + const rule: CleanupRule = { + evaluate: () => { + throw new Error("rule exploded"); + }, + name: "exploding-rule", + }; + const harness = await createHarness( + [rule], + {}, + { logger: new JsonLinesLogger({ clock: new FakeClock(1_000), sink }), tickMs: 10_000 }, + ); + const expected = expect.objectContaining({ + level: "error", + module: "daemon.reaper", + fields: { error: "Error: rule exploded", step: "cleanup" }, + }); + + // An event-triggered run nobody awaits... + harness.eventBus.emit("daemon.started", { configSnapshot: {}, version: "test" }, "test"); + await flush(); + expect(sink.records).toEqual([expected]); + + // ...and a periodic tick's run. + harness.clock.advance(10_000); + await flush(); + expect(sink.records).toEqual([expected, expected]); + harness.reaper.dispose(); + }); + it("shuts down after T1 and destroys after T2 on periodic ticks following a release", async () => { const harness = await createHarness(automaticCleanupRules, {}, { tickMs: 10_000 }); const grant = await harness.engine.request(spec, { diff --git a/src/core/reaper.ts b/src/core/reaper.ts index bdd281ce4..70fdf6b7f 100644 --- a/src/core/reaper.ts +++ b/src/core/reaper.ts @@ -1,10 +1,17 @@ import type { EventBus } from "../bus/index.js"; -import type { Clock, Filesystem, TimerHandle } from "../ports/index.js"; +import { + type Clock, + type Filesystem, + type Logger, + NoopLogger, + type TimerHandle, +} from "../ports/index.js"; import type { Config } from "./config.js"; import type { CleanupActionExecutor } from "./cleanup-executor.js"; import { automaticCleanupRules } from "./cleanup/rules.js"; import type { CleanupRule, Proposal, RegistryView } from "./cleanup/types.js"; import type { Registry } from "./registry.js"; +import { stableError } from "./stable-error.js"; export interface CleanupReaperOptions { readonly clock: Clock; @@ -12,6 +19,7 @@ export interface CleanupReaperOptions { readonly eventBus: EventBus; readonly executor: CleanupActionExecutor; readonly filesystem: Filesystem; + readonly logger?: Logger; readonly registry: Registry; readonly rules?: readonly CleanupRule[]; readonly diskPath?: string; @@ -36,8 +44,10 @@ export class CleanupReaper { // Tracks the previous tick's pressure state so disk.pressure-detected fires // only on the crossing edge, not once per tick while pressure persists. #underPressure = false; + readonly #logger: Logger; constructor(private readonly options: CleanupReaperOptions) { + this.#logger = options.logger?.child("reaper") ?? new NoopLogger(); this.#automaticRules = options.rules ?? automaticCleanupRules; this.#unsubscribe = [ options.eventBus.subscribe("lease.released", () => this.#trigger()), @@ -97,7 +107,19 @@ export class CleanupReaper { if (this.#disposed) { return; } - void this.#scheduleRun().catch(() => undefined); + void this.#scheduleRunLogged(); + } + + /** A run nobody awaits: its failure has no caller to reach, so it is logged here. */ + async #scheduleRunLogged(): Promise { + try { + await this.#scheduleRun(); + } catch (error: unknown) { + this.#logger.error("scheduled cleanup run failed", { + step: "cleanup", + error: stableError(error), + }); + } } #scheduleRun(): Promise { @@ -138,10 +160,7 @@ export class CleanupReaper { } this.#tickTimer = this.options.clock.setTimer(this.options.tickMs ?? 60_000, () => { this.#tickTimer = undefined; - void this.#scheduleRun().then( - () => this.#armTick(), - () => this.#armTick(), - ); + void this.#scheduleRunLogged().then(() => this.#armTick()); }); } diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index f5c27db2c..26050a9e0 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -1,7 +1,13 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; -import { FakeClock, FakeSystemStats } from "../ports/index.js"; +import { + FakeClock, + FakeSystemStats, + JsonLinesLogger, + type Logger, + MemoryLogSink, +} from "../ports/index.js"; import { CapacityCoordinator, createCapacityStrategy } from "./capacity/index.js"; import type { Config } from "./config.js"; import type { DeviceRecord, DeviceSpec, DeviceTransitionUpdate, LeaseRecord } from "./domain.js"; @@ -135,6 +141,7 @@ async function createHarness( readonly driver?: FakeDriver; readonly headSpec?: DeviceSpec; readonly leases?: readonly LeaseRecord[]; + readonly logger?: Logger; } = {}, ) { const clock = new FakeClock(1_000); @@ -155,6 +162,7 @@ async function createHarness( decisions: new SerializedDecision(), drivers: new DriverCatalog([driver]), eventBus: bus, + ...(options.logger === undefined ? {} : { logger: options.logger }), notifyAvailability, quarantine, queueHeadDemand: () => @@ -315,6 +323,55 @@ describe("WarmPoolCoordinator", () => { expect(harness.notifyAvailability).not.toHaveBeenCalled(); }); + it("A reclaimed device that fails to shut down logs the error.", async () => { + const sink = new MemoryLogSink(); + // A different queue head cannot reserve capacity, so the reclaimed ready device is shut down. + const harness = await createHarness({ + headSpec: { model: "Pixel 9", osVersion: "36", platform: "android" }, + logger: new JsonLinesLogger({ clock: new FakeClock(1_000), sink }), + }); + harness.driver.failOn("shutdown", 1, new Error("shutdown wedged")); + + await harness.coordinator.reclaim(released(harness.reclaiming)); + + expect(harness.registry.snapshot.devices[0]?.state).toBe("ready"); + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "warn", + module: "daemon.warm-pool-coordinator", + fields: { + deviceId: harness.reclaiming.id, + error: "Error: shutdown wedged", + leaseId: "lease-1", + step: "shutdown", + }, + }), + ]); + }); + + it("A reclaimed device that fails to become ready logs the error.", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ clock, platform: "ios", reclaimResult: "shutdown" }); + driver.failOn("makeReady", 1, new Error("boot wedged")); + const sink = new MemoryLogSink(); + const harness = await createHarness({ driver, logger: new JsonLinesLogger({ clock, sink }) }); + + await harness.coordinator.reclaim(released(harness.reclaiming)); + + expect(harness.registry.snapshot.devices[0]?.state).toBe("shutdown"); + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "warn", + fields: { + deviceId: harness.reclaiming.id, + error: "Error: boot wedged", + leaseId: "lease-1", + step: "make-ready", + }, + }), + ]); + }); + it("recovers an unleased interrupted reclaim through shutdown and a committed fact", async () => { const harness = await createHarness(); let stateAtFact: DeviceRecord["state"] | undefined; diff --git a/src/core/warm-pool-coordinator.ts b/src/core/warm-pool-coordinator.ts index 887515589..71a0ff8a7 100644 --- a/src/core/warm-pool-coordinator.ts +++ b/src/core/warm-pool-coordinator.ts @@ -1,5 +1,5 @@ import type { EventBus } from "../bus/index.js"; -import type { Clock } from "../ports/index.js"; +import { type Clock, type Logger, NoopLogger } from "../ports/index.js"; import type { CapacityDecision, CapacityDevice, RunningCapacity } from "./capacity/index.js"; import { type DeviceRecord, @@ -66,6 +66,7 @@ export interface WarmPoolCoordinatorOptions { readonly quarantine: WarmPoolQuarantine; readonly queueHeadDemand: () => { readonly spec?: DeviceSpec } | undefined; readonly registry: WarmPoolRegistry; + readonly logger?: Logger; } /** @@ -73,7 +74,11 @@ export interface WarmPoolCoordinatorOptions { * work remains outside the serialized registry decision sections. */ export class WarmPoolCoordinator { - constructor(private readonly options: WarmPoolCoordinatorOptions) {} + readonly #logger: Logger; + + constructor(private readonly options: WarmPoolCoordinatorOptions) { + this.#logger = options.logger?.child("warm-pool-coordinator") ?? new NoopLogger(); + } async reclaim(released: ReleasedLease): Promise { if (!mayBeGranted(released.device)) { @@ -94,7 +99,7 @@ export class WarmPoolCoordinator { const keepReady = await this.options.decisions.run(async () => this.#mayRemainWarm(released.device), ); - const disposition = await this.#disposition(driver, released.device, result.state, keepReady); + const disposition = await this.#disposition(driver, released, result.state, keepReady); await this.options.decisions.run(async () => { await this.options.registry.transitionDevice( released.device.id, @@ -238,19 +243,21 @@ export class WarmPoolCoordinator { async #disposition( driver: Driver, - device: DeviceRecord, + released: ReleasedLease, reclaimedState: "ready" | "shutdown", keepReady: boolean, ): Promise<{ readonly state: "ready" | "shutdown"; readonly readyDevice?: DriverDevice }> { + const { device } = released; if (keepReady && reclaimedState === "shutdown") { - const readyDevice = await this.#tryMakeReady(driver, device); + const readyDevice = await this.#tryMakeReady(driver, released); return readyDevice === undefined ? { state: "shutdown" } : { readyDevice, state: "ready" }; } if (!keepReady && reclaimedState === "ready") { try { await driver.shutdown(toDriverDevice(device)); return { state: "shutdown" }; - } catch { + } catch (error: unknown) { + this.#logFailure("shutting down a reclaimed device failed", released, "shutdown", error); return { state: "ready" }; } } @@ -258,14 +265,24 @@ export class WarmPoolCoordinator { } /** Undefined on failure; otherwise the driver's freshly re-read device, address included. */ - async #tryMakeReady(driver: Driver, device: DeviceRecord): Promise { + async #tryMakeReady(driver: Driver, released: ReleasedLease): Promise { try { - return await driver.makeReady(toDriverDevice(device)); - } catch { + return await driver.makeReady(toDriverDevice(released.device)); + } catch (error: unknown) { + this.#logFailure("making a reclaimed device ready failed", released, "make-ready", error); return undefined; } } + #logFailure(message: string, released: ReleasedLease, step: string, error: unknown): void { + this.#logger.warn(message, { + deviceId: released.device.id, + leaseId: released.lease.id, + step, + error: stableError(error), + }); + } + #mayRemainWarm(device: DeviceRecord): boolean { const devices = capacityDevices(this.options.registry.snapshot.devices); const capacity = this.options.capacity.runningCapacity(devices); diff --git a/src/daemon/admin-secret.test.ts b/src/daemon/admin-secret.test.ts index 51a689328..c041f4c8f 100644 --- a/src/daemon/admin-secret.test.ts +++ b/src/daemon/admin-secret.test.ts @@ -43,6 +43,7 @@ describe("AdminSecretManager", () => { const calls: Array<{ readonly path: string; readonly mode: number | undefined }> = []; const filesystem: Filesystem = { readFile: () => Promise.reject(new Error("unused by this test")), + readFileFrom: () => Promise.reject(new Error("unused by this test")), writeFileAtomic: async (path, _contents, options) => { calls.push({ path, mode: options?.mode }); }, @@ -110,6 +111,9 @@ describe("AdminSecretManager", () => { readFile: () => { throw new Error("verify() must not touch the filesystem"); }, + readFileFrom: () => { + throw new Error("verify() must not touch the filesystem"); + }, writeFileAtomic: () => { throw new Error("verify() must not touch the filesystem"); }, @@ -180,6 +184,9 @@ describe("AdminSecretManager", () => { readFile: () => { throw new Error("must not touch the filesystem"); }, + readFileFrom: () => { + throw new Error("must not touch the filesystem"); + }, writeFileAtomic: () => { throw new Error("must not touch the filesystem"); }, diff --git a/src/daemon/dispatch.test.ts b/src/daemon/dispatch.test.ts new file mode 100644 index 000000000..033d076a6 --- /dev/null +++ b/src/daemon/dispatch.test.ts @@ -0,0 +1,213 @@ +import { describe, expect, it } from "vitest"; + +import { FakeClock, JsonLinesLogger, MemoryLogSink, type LogLevel } from "../ports/index.js"; +import { + DispatchError, + runDispatch, + type DispatchPipeline, + type DispatchSession, + type ErasedHandler, +} from "./dispatch.js"; + +function harness(handlers: DispatchPipeline["handlers"], level: LogLevel = "debug") { + const clock = new FakeClock(1_000); + const sink = new MemoryLogSink(); + const logger = new JsonLinesLogger({ clock, level, module: "dispatch", sink }); + const pipeline: DispatchPipeline = { + handlers, + observe: { + clock, + logger, + codeOf: (error) => (error instanceof DispatchError ? error.code : "INTERNAL"), + }, + }; + return { clock, pipeline, sink }; +} + +function session(overrides: Partial = {}): DispatchSession { + return { + manageEventSubscription: () => undefined, + principal: "agent-7", + role: "agent", + ...overrides, + }; +} + +/** A handler that takes `ms` of fake time and then answers `output`. */ +function slow(clock: FakeClock, ms: number, output: unknown): ErasedHandler { + return () => { + clock.advance(ms); + return output; + }; +} + +describe("runDispatch's operation line", () => { + it("a write that succeeds logs one info line with the operation, principal, role and duration", async () => { + const handlers: DispatchPipeline["handlers"] = {}; + const { clock, pipeline, sink } = harness(handlers); + handlers["lease.release"] = slow(clock, 40, { leaseId: "lse_1" }); + + await runDispatch("lease.release", { leaseId: "lse_1" }, session(), pipeline); + + expect(sink.records).toEqual([ + { + timestamp: 1_040, + level: "info", + module: "dispatch", + message: "operation", + fields: { + operation: "lease.release", + principal: "agent-7", + role: "agent", + durationMs: 40, + leaseId: "lse_1", + }, + }, + ]); + }); + + it("a read that succeeds logs at debug and nothing at info", async () => { + const handlers: DispatchPipeline["handlers"] = { "lease.list": () => ({ leases: [] }) }; + const debug = harness(handlers, "debug"); + const info = harness(handlers, "info"); + + await runDispatch("lease.list", {}, session(), debug.pipeline); + await runDispatch("lease.list", {}, session(), info.pipeline); + + expect(debug.sink.records).toEqual([ + expect.objectContaining({ + level: "debug", + message: "operation", + fields: expect.objectContaining({ operation: "lease.list" }), + }), + ]); + expect(info.sink.records).toEqual([]); + }); + + it("a read that fails logs at info with its error code", async () => { + const { pipeline, sink } = harness( + { + "lease.list": () => { + throw new DispatchError("UNKNOWN_LEASE", "no such lease"); + }, + }, + "info", + ); + + await expect(runDispatch("lease.list", {}, session(), pipeline)).rejects.toThrow( + "no such lease", + ); + + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "info", + message: "operation", + fields: expect.objectContaining({ + operation: "lease.list", + code: "UNKNOWN_LEASE", + message: "no such lease", + }), + }), + ]); + }); + + it("an error classified INTERNAL logs at error", async () => { + const { pipeline, sink } = harness({ + "lease.release": () => { + throw new Error("registry exploded"); + }, + }); + + await expect( + runDispatch("lease.release", { leaseId: "lse_1" }, session(), pipeline), + ).rejects.toThrow("registry exploded"); + + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "error", + message: "operation", + fields: expect.objectContaining({ code: "INTERNAL", message: "registry exploded" }), + }), + ]); + }); + + it("a request refused for its role logs one line with FORBIDDEN", async () => { + let called = false; + const { pipeline, sink } = harness({ + "nuke.run": () => { + called = true; + return {}; + }, + }); + + await expect(runDispatch("nuke.run", {}, session(), pipeline)).rejects.toMatchObject({ + code: "FORBIDDEN", + }); + + expect(called).toBe(false); + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "info", + message: "operation", + fields: expect.objectContaining({ + operation: "nuke.run", + code: "FORBIDDEN", + role: "agent", + }), + }), + ]); + }); + + it("the line carries leaseId and requesterId from the validated input and no other input field", async () => { + const { pipeline, sink } = harness({ + "lease.request": () => { + throw new DispatchError("NO_CAPACITY", "full"); + }, + "device.exec": () => { + throw new DispatchError("UNKNOWN_LEASE", "gone"); + }, + "lease.renew": () => { + throw new Error("never reached: the input is refused first"); + }, + }); + + await expect( + runDispatch( + "lease.request", + { model: "iPhone 17", platform: "ios", requesterId: "agent-session-9", ttlMs: 60_000 }, + session(), + pipeline, + ), + ).rejects.toThrow("full"); + await expect( + runDispatch( + "device.exec", + { args: ["shell", "echo", "s3cret"], leaseId: "lse_4", tool: "adb" }, + session(), + pipeline, + ), + ).rejects.toThrow("gone"); + + const common = ["code", "durationMs", "message", "operation", "principal", "role"]; + expect(Object.keys(sink.records[0]?.fields ?? {}).sort()).toEqual( + [...common, "requesterId"].sort(), + ); + expect(sink.records[0]?.fields).toMatchObject({ requesterId: "agent-session-9" }); + expect(Object.keys(sink.records[1]?.fields ?? {}).sort()).toEqual( + [...common, "leaseId"].sort(), + ); + expect(sink.records[1]?.fields).toMatchObject({ leaseId: "lse_4" }); + expect(JSON.stringify(sink.records)).not.toMatch(/iPhone 17|s3cret|60000/); + + // Refused before validation: a `leaseId` the input only claimed is not "from the validated + // input", so the line omits it. + await expect( + runDispatch("lease.renew", { leaseId: "lse_raw", ttlMs: -1 }, session(), pipeline), + ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + expect(sink.records[2]?.fields).toMatchObject({ + operation: "lease.renew", + code: "BAD_REQUEST", + }); + expect(sink.records[2]?.fields).not.toHaveProperty("leaseId"); + }); +}); diff --git a/src/daemon/dispatch.ts b/src/daemon/dispatch.ts index 906d06e19..84baf0833 100644 --- a/src/daemon/dispatch.ts +++ b/src/daemon/dispatch.ts @@ -10,15 +10,18 @@ * it without importing `src/core` through the back door -- which is exactly what importing * `dispatcher.ts` would do (see `src/gateway/boundary.test.ts`). * - * Nothing here imports from `src/core`, `src/drivers`, or `src/http`; the contract module and - * its zod-inferred types are the whole dependency surface. + * Nothing here imports from `src/core`, `src/drivers`, or `src/http`; the contract module, its + * zod-inferred types, and the `Clock`/`Logger` port types are the whole dependency surface. */ import type { z } from "zod"; +import type { Clock } from "../ports/clock.js"; +import type { Logger } from "../ports/logger.js"; import { describeSchemaIssues, OPERATIONS, type AuthorizeContext, + type Effect, type OperationDefinition, type OperationName, type Role, @@ -159,6 +162,21 @@ export interface DispatchPipeline { /** Called when a handler's result fails its contract output schema -- always a daemon-side * bug, so both implementations log it before the caller sees a generic `INTERNAL`. */ readonly onOutputMismatch?: (operation: string, issues: readonly unknown[]) => void; + /** Writes the one `operation` line per call to the daemon log. Omitted, nothing is logged. + * A success is `info` for a `write` and `debug` for a `read`; a failure, including one + * refused before its handler, is `info`, or `error` when its code is `INTERNAL`. */ + readonly observe?: DispatchObserver; +} + +/** + * What `runDispatch` needs to write a call's `operation` line. `codeOf` is the transport's own + * error classifier, injected so this module never imports `src/core` (see the module comment). + */ +export interface DispatchObserver { + readonly clock: Clock; + readonly logger: Logger; + /** The error's code; `INTERNAL` for anything it does not recognize. */ + codeOf(error: unknown): string; } /** @@ -176,6 +194,80 @@ export async function runDispatch( rawInput: unknown, session: DispatchSession, pipeline: DispatchPipeline, +): Promise> { + const observe = pipeline.observe; + if (observe === undefined) return dispatchSteps(operation, rawInput, session, pipeline, {}); + const startedAt = observe.clock.now(); + const call: ObservedCall = {}; + try { + const output = await dispatchSteps(operation, rawInput, session, pipeline, call); + logOperation(observe, operation, session, call, observe.clock.now() - startedAt, { ok: true }); + return output; + } catch (error) { + logOperation(observe, operation, session, call, observe.clock.now() - startedAt, { + ok: false, + error, + }); + throw error; + } +} + +/** What `dispatchSteps` learned about a call that its `operation` line reports. */ +interface ObservedCall { + input?: unknown; + effect?: Effect; +} + +/** + * The one place an `operation` line is built (architecture rule 10). It names the operation, + * who asked, how long it took and how it ended -- the request, never what it changed (ADR + * 0006 §3). From the input only `leaseId` and `requesterId`, as claimed: nothing else in an + * input is safe to assume free of secrets, and nothing from the output is logged at all. + */ +function logOperation( + observe: DispatchObserver, + operation: string, + session: DispatchSession, + call: ObservedCall, + durationMs: number, + outcome: { readonly ok: true } | { readonly ok: false; readonly error: unknown }, +): void { + const fields: Record = { + operation, + principal: session.principal, + role: session.role, + durationMs, + ...pickString(call.input, "leaseId"), + ...pickString(call.input, "requesterId"), + }; + if (outcome.ok) { + if (call.effect === "write") observe.logger.info("operation", fields); + else observe.logger.debug("operation", fields); + return; + } + const { error } = outcome; + const code = observe.codeOf(error); + const failed = { + ...fields, + code, + message: error instanceof Error ? error.message : String(error), + }; + if (code === "INTERNAL") observe.logger.error("operation", failed); + else observe.logger.info("operation", failed); +} + +function pickString(input: unknown, key: string): Record { + if (typeof input !== "object" || input === null) return {}; + const value = (input as Record)[key]; + return typeof value === "string" ? { [key]: value } : {}; +} + +async function dispatchSteps( + operation: Op, + rawInput: unknown, + session: DispatchSession, + pipeline: DispatchPipeline, + call: ObservedCall, ): Promise> { // "Generic-over-a-closed-union" cast: `OPERATIONS[operation]` for a generic `Op` collapses to // a union across every operation, and TypeScript refuses to call a union of functions @@ -190,26 +282,10 @@ export async function runDispatch( } const input = parseDispatchInput(definition.input, rawInput ?? {}); - const requiredRole: Role = - typeof definition.role === "function" ? definition.role(input) : definition.role; - if (!roleSatisfies(session.role, requiredRole)) { - throw new DispatchError( - "FORBIDDEN", - `Operation ${operation} requires role ${requiredRole}, session is ${session.role}`, - ); - } - if (definition.authorize !== undefined) { - const context: AuthorizeContext = { - leaseRequesterId: pipeline.authorizeLookups?.leaseRequesterId ?? (() => undefined), - ownerId: pipeline.authorizeLookups?.ownerId ?? (() => undefined), - pendingRequestOwner: pipeline.authorizeLookups?.pendingRequestOwner ?? (() => undefined), - principal: session.principal, - role: session.role, - }; - if (!definition.authorize(input, context)) { - throw new DispatchError("FORBIDDEN", `Not authorized for ${operation}`); - } - } + call.input = input; + call.effect = + typeof definition.effect === "function" ? definition.effect(input) : definition.effect; + checkAccess(operation, definition, input, session, pipeline); if (operation !== "status.get") { await pipeline.awaitReady?.(); @@ -224,6 +300,41 @@ export async function runDispatch( ) as z.infer<(typeof OPERATIONS)[Op]["output"]>; } +/** ADR 0003 §2's role check, then the operation's `authorize` hook. Throws `FORBIDDEN`. */ +function checkAccess( + operation: string, + definition: OperationDefinition, + input: unknown, + session: DispatchSession, + pipeline: DispatchPipeline, +): void { + const requiredRole: Role = + typeof definition.role === "function" ? definition.role(input) : definition.role; + if (!roleSatisfies(session.role, requiredRole)) { + throw new DispatchError( + "FORBIDDEN", + `Operation ${operation} requires role ${requiredRole}, session is ${session.role}`, + ); + } + if (definition.authorize?.(input, authorizeContext(session, pipeline)) === false) { + throw new DispatchError("FORBIDDEN", `Not authorized for ${operation}`); + } +} + +/** An absent lookup answers `undefined`, which every hook treats as authorized on purpose (see + * `DispatchPipeline.authorizeLookups`). */ +function authorizeContext(session: DispatchSession, pipeline: DispatchPipeline): AuthorizeContext { + const none = (): undefined => undefined; + const lookups = pipeline.authorizeLookups; + return { + leaseRequesterId: lookups?.leaseRequesterId ?? none, + ownerId: lookups?.ownerId ?? none, + pendingRequestOwner: lookups?.pendingRequestOwner ?? none, + principal: session.principal, + role: session.role, + }; +} + function roleSatisfies(sessionRole: Role, required: Role): boolean { return sessionRole === "admin" || required === "agent"; } diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 8ed9ece21..90656db74 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -85,6 +85,9 @@ export interface DispatcherOptions { readonly eventBus: EventBus; readonly leases: LeaseCommands; readonly logger?: Logger; + /** Classifies a thrown error for the `operation` log line (`classifyError` in production). + * Injected because `error-code.ts` imports this module. Unset or `undefined`: `INTERNAL`. */ + readonly errorCode?: (error: unknown) => string | undefined; readonly nuke?: Nuke; /** * Builds the scoped command behind `simlock simctl` / `simlock adb` (ADR 0001, decision 7). @@ -162,6 +165,7 @@ type WorkerOperationName = Exclude this.options.errorCode?.(error) ?? "INTERNAL", + }, }); } diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index b158c7d45..7b4b24768 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { connect, createServer, Server } from "node:net"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { FakeDriver, OWNED_ROOT_MARKER_FILE, type OwnedRootError } from "../core/index.js"; import { IosSimctlDriver } from "../drivers/ios/index.js"; @@ -25,6 +25,7 @@ import { discoverDrivers, emitComponentInstallDiagnostic, emitSlimDiagnostic, + processRunnerFor, startDaemon, wireComponentInstallLogging, type DriverDiscoveryContext, @@ -954,6 +955,34 @@ describe("slim diagnostic bridging", () => { }); }); +describe("processRunnerFor", () => { + async function runOnce(level: "debug" | "info") { + const clock = new FakeClock(1_000); + const sink = new MemoryLogSink(); + const logger = new JsonLinesLogger({ clock, level: "debug", sink }); + const inner = new ScriptedProcessRunner([ + { match: { args: ["devices"], command: "adb" }, result: { code: 0, stderr: "", stdout: "" } }, + ]); + + await processRunnerFor(level, inner, logger, clock).run("adb", ["devices"]); + return sink.records.filter((record) => record.message === "process"); + } + + it("at log.level: info no process line is written", async () => { + expect(await runOnce("info")).toEqual([]); + }); + + it("at log.level: debug each command leaves one process line under daemon.process", async () => { + expect(await runOnce("debug")).toEqual([ + expect.objectContaining({ + level: "debug", + module: "daemon.process", + fields: expect.objectContaining({ command: "adb", args: ["devices"], code: 0 }), + }), + ]); + }); +}); + describe("wireComponentInstallLogging", () => { it('writes a durable structured log line under logger.child("components") when component.installed fires', () => { const clock = new FakeClock(1_000); @@ -1152,6 +1181,39 @@ describe("discoverDrivers with SIMLOCK_DRIVERS_MODULE", () => { } }); + it("a throwing event subscriber writes one JSON line through the logger and nothing through console.error", async () => { + // The drivers module is the one seam that reaches the daemon's own bus from outside. + process.env.SIMLOCK_DRIVERS_MODULE = await writeModule( + `export function createDrivers(context) { + context.eventBus.subscribe("daemon.started", () => { + throw new Error("subscriber broke"); + }); + return []; + }`, + ); + const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); + + try { + const { sink } = await start({ drivers: undefined }); + + expect(consoleError).not.toHaveBeenCalled(); + expect(sink.records.filter((record) => record.message === "Event handler failed")).toEqual([ + expect.objectContaining({ + level: "error", + module: "daemon.bus", + fields: expect.objectContaining({ + event: "daemon.started", + seq: expect.any(Number), + message: "subscriber broke", + stack: expect.stringContaining("subscriber broke"), + }), + }), + ]); + } finally { + consoleError.mockRestore(); + } + }); + it("supports a synchronous createDrivers returning an array directly", async () => { process.env.SIMLOCK_DRIVERS_MODULE = await writeModule( `export function createDrivers() { return []; }`, diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 5aae95f17..f38c48e5b 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -2,7 +2,7 @@ import { homedir } from "node:os"; import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; -import { EventBus } from "../bus/index.js"; +import { EventBus, type EventBusLogger } from "../bus/index.js"; import { type Config, type ConfigOverrides, @@ -35,6 +35,7 @@ import { CryptoIdGenerator, CryptoTokenSecrets, JsonLinesLogger, + LoggingProcessRunner, NodeFileLogSink, type Clock, type Filesystem, @@ -42,6 +43,7 @@ import { type IpcConnector, type IpcListenerFactory, type Logger, + type LogLevel, NodeFilesystem, NodeIpcTransport, NodeProcessRunner, @@ -71,6 +73,7 @@ import { WebSocketUplinkConnector, WebSocketUplinkListenerFactory, } from "../ports/uplink-websocket.js"; +import { classifyError } from "./error-code.js"; import { DaemonServer } from "./server.js"; import { DaemonEndpointHost } from "./connection-host.js"; import { AdminSecretManager } from "./admin-secret.js"; @@ -106,7 +109,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise Promise.resolve(), + clock, + errorCode: classifyError, // C-2: makes `token.revoke` actually close the uplink it names (ADR 0005 §8), rather than // only writing the store and waiting for that worker's next reconnect. closeUplinksForToken: (tokenId) => gatewayService.closeLinksForToken(tokenId), @@ -1133,6 +1140,36 @@ export function wireComponentInstallLogging( }); } +/** + * The runner every driver and `device.exec` shell out through. At `log.level: debug` each + * command leaves a `process` line; at any other level the runner is used unwrapped, so a + * daemon not asked for that detail pays nothing for it. + */ +export function processRunnerFor( + level: LogLevel, + runner: ProcessRunner, + logger: Logger, + clock: Clock, +): ProcessRunner { + if (level !== "debug") return runner; + return new LoggingProcessRunner({ clock, inner: runner, logger: logger.child("process") }); +} + +/** Writes a failing event subscriber to the daemon log as one JSON line, not to stderr. */ +export function eventBusLogger(logger: Logger): EventBusLogger { + const bus = logger.child("bus"); + return { + error(message, { error, envelope }) { + bus.error(message, { + event: envelope.event, + seq: envelope.seq, + message: error instanceof Error ? error.message : String(error), + stack: error instanceof Error ? error.stack : undefined, + }); + }, + }; +} + /** * Best-effort logger for the fatal startup handler below. It cannot depend on the * daemon's own `Config` — that is exactly what may have failed to load — so it always diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index b5fb108bd..fe31d8c4e 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -1864,7 +1864,7 @@ describe("DaemonServer decorations", () => { // which `errorCode()` had no choice but to map to `INTERNAL` -- logged at error level // indistinguishably from a real bug. `DoctorUnavailableError`/`NukeUnavailableError` (ADR // 0003 §7: "one error class, closed codes") give this its own typed code, so it is now a - // *handled*, debug-level error like any other expected domain refusal. + // handled error like any other expected domain refusal: an info-level `operation` line. it("logs an unconfigured doctor as a handled DOCTOR_UNAVAILABLE, not an unhandled error", async () => { const { logger: log, sink } = logger(); const harness = await createHarness({ logger: log }); @@ -1875,9 +1875,9 @@ describe("DaemonServer decorations", () => { expect(sink.records).toContainEqual( expect.objectContaining({ - level: "debug", - message: "Handled request error", - fields: { code: "DOCTOR_UNAVAILABLE", type: "doctor.run" }, + level: "info", + message: "operation", + fields: expect.objectContaining({ code: "DOCTOR_UNAVAILABLE", operation: "doctor.run" }), }), ); expect(sink.records).not.toContainEqual( @@ -1896,9 +1896,9 @@ describe("DaemonServer decorations", () => { expect(sink.records).toContainEqual( expect.objectContaining({ - level: "debug", - message: "Handled request error", - fields: { code: "UNKNOWN_LEASE", type: "lease.release" }, + level: "info", + message: "operation", + fields: expect.objectContaining({ code: "UNKNOWN_LEASE", operation: "lease.release" }), }), ); expect(sink.records).not.toContainEqual( diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 15a0adb81..75d0c65e4 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -281,6 +281,8 @@ function buildDispatcher( clock: options.clock, config: options.config, ...(options.doctor === undefined ? {} : { doctor: options.doctor }), + // The `operation` log line's error code: the same classifier this server answers with. + errorCode: classifyError, eventBus: options.eventBus, health: hooks.health, leases: options.leases, @@ -780,14 +782,13 @@ export class DaemonServer { await writeFrame(connection.socket, { id: frame.id, ok: true, payload }); } catch (error: unknown) { const code = errorCode(error); + // A handled error is already on the dispatcher's `operation` line; this one adds the stack. if (code === "INTERNAL") { this.#logger.error("Unhandled request error", { message: errorMessage(error), stack: errorStack(error), type: frame.type, }); - } else { - this.#logger.debug("Handled request error", { code, type: frame.type }); } // ADR 0003 §7's typed `details` travel with the code when the thrown error carries any // (today: the gateway's `WORKER_CONNECTED`/`UNKNOWN_WORKER`/`UNSUPPORTED_IN_GATEWAY_MODE`), diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index b8e89a503..0a9a619e7 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -2,8 +2,8 @@ import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; import { OPERATIONS, type OperationName } from "../contract/index.js"; -import type { DispatchSession } from "../daemon/dispatch.js"; -import { FakeClock } from "../ports/index.js"; +import { DispatchError, type DispatchSession } from "../daemon/dispatch.js"; +import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; import { GatewayDispatcher, type GatewayTokenStore } from "./dispatcher.js"; import { MemoryDrainStore } from "./drain-store.js"; import { FleetLeaseCoordinator } from "./fleet-coordinator.js"; @@ -108,6 +108,7 @@ class FakeDirectory implements WorkerDirectory { function harness() { const clock = new FakeClock(1_000); + const logSink = new MemoryLogSink(); const eventBus = new EventBus(clock); const workers = new WorkerRegistry({ clock, @@ -139,6 +140,7 @@ function harness() { }); const dispatcher = new GatewayDispatcher({ awaitReady: async () => {}, + clock, closeUplinksForToken: async (tokenId) => { closedUplinkTokens.push(tokenId); }, @@ -147,11 +149,15 @@ function harness() { eventBus, health: () => "running", leaseIndex, + // `classifyError`'s answer for the errors this dispatcher throws itself. + errorCode: (error) => (error instanceof DispatchError ? error.code : undefined), + logger: new JsonLinesLogger({ clock, module: "gateway", sink: logSink }), tokens, workers, }); return { clock, + logSink, closedUplinkTokens, coordinator, directory, @@ -178,6 +184,36 @@ const EVERY_OPERATION = (Object.keys(OPERATIONS) as OperationName[]).filter( ); describe("GatewayDispatcher", () => { + it("logs the same operation line a worker's dispatcher does, through runDispatch", async () => { + const { dispatcher, logSink, workers } = harness(); + workers.connected("wrk_1", "mac-mini-1", "0.3.0"); + + await dispatcher.dispatch("worker.drain", { workerId: "wrk_1" }, session()); + await expect( + dispatcher.dispatch("worker.drain", { workerId: "wrk_1" }, session({ role: "agent" })), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + + expect(logSink.records.filter((record) => record.message === "operation")).toEqual([ + { + timestamp: 1_000, + level: "info", + module: "gateway.dispatch", + message: "operation", + fields: { + operation: "worker.drain", + principal: "operator-1", + role: "admin", + durationMs: 0, + }, + }, + expect.objectContaining({ + level: "info", + module: "gateway.dispatch", + fields: expect.objectContaining({ operation: "worker.drain", code: "FORBIDDEN" }), + }), + ]); + }); + it("answers status.get from the fleet", async () => { const { dispatcher, workers } = harness(); workers.connected("wrk_1", "mac-mini-1", "0.3.0"); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 9f712a266..84e50e5a9 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -37,7 +37,7 @@ import { type DispatchSession, type ErasedHandler, } from "../daemon/dispatch.js"; -import type { Logger } from "../ports/index.js"; +import type { Clock, Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; import { aggregateCatalog, aggregateStatus } from "./aggregate.js"; import type { FleetLeaseCoordinator } from "./fleet-coordinator.js"; @@ -95,7 +95,13 @@ export interface GatewayDispatcherOptions { * not supply one -- revocation still writes the store either way. */ readonly closeUplinksForToken?: (tokenId: string) => Promise; + /** Times each call for its `operation` log line. */ + readonly clock: Clock; readonly logger?: Logger; + /** Classifies a thrown error for the `operation` log line (`classifyError` in production), + * injected because `src/gateway` imports nothing from `src/core`. Unset or `undefined`: + * `INTERNAL`. */ + readonly errorCode?: (error: unknown) => string | undefined; /** The gateway's own health, for `status.get`. */ readonly health: () => "starting" | "running" | "failed"; readonly awaitReady: () => Promise; @@ -127,10 +133,12 @@ export interface GatewayDispatcherOptions { export class GatewayDispatcher { readonly #logger: Logger; + readonly #dispatchLogger: Logger; readonly #handlers: Record, ErasedHandler>; constructor(private readonly options: GatewayDispatcherOptions) { this.#logger = options.logger ?? new NoopLogger(); + this.#dispatchLogger = this.#logger.child("dispatch"); this.#handlers = { "catalog.get": this.#catalogGet, "status.get": this.#statusGet, @@ -186,6 +194,11 @@ export class GatewayDispatcher { issues, }); }, + observe: { + clock: this.options.clock, + logger: this.#dispatchLogger, + codeOf: (error) => this.options.errorCode?.(error) ?? "INTERNAL", + }, }); } diff --git a/src/ports/filesystem.ts b/src/ports/filesystem.ts index ead1e1e68..6ad65767c 100644 --- a/src/ports/filesystem.ts +++ b/src/ports/filesystem.ts @@ -2,6 +2,7 @@ import { chmod, lstat, mkdir, + open, readdir, readFile, realpath, @@ -21,6 +22,10 @@ export interface FileStat { * caller's needs -- only relevant for callers verifying a file's permissions after creation * (e.g. the daemon's per-start admin secret, ADR 0003 §5). */ readonly mode?: number; + /** Which file this is, stable across a rename and different for a new file at the same path + * (device and inode). Lets a reader that follows a rotating log tell a rotation apart from + * the same file growing. */ + readonly identity: string; } export interface WriteFileAtomicOptions { @@ -45,6 +50,9 @@ export interface PathDetails { export interface Filesystem { readFile(path: string): Promise; + /** The file's contents from byte `offset` to its current end; empty past the end. `offset` + * must fall on a character boundary, as a line boundary always does. */ + readFileFrom(path: string, offset: number): Promise; writeFileAtomic(path: string, contents: string, options?: WriteFileAtomicOptions): Promise; /** * Writes a file only when nothing is there, failing `EEXIST` otherwise. The kernel @@ -81,6 +89,19 @@ export class NodeFilesystem implements Filesystem { return readFile(path, "utf8"); } + async readFileFrom(path: string, offset: number): Promise { + const handle = await open(path, "r"); + try { + const { size } = await handle.stat(); + if (size <= offset) return ""; + const buffer = Buffer.alloc(size - offset); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset); + return buffer.subarray(0, bytesRead).toString("utf8"); + } finally { + await handle.close(); + } + } + async writeFileAtomic( path: string, contents: string, @@ -129,6 +150,7 @@ export class NodeFilesystem implements Filesystem { size: details.size, modifiedAtMs: details.mtimeMs, mode: details.mode & 0o777, + identity: `${details.dev}:${details.ino}`, }; } @@ -182,6 +204,8 @@ export class NodeFilesystem implements Filesystem { /** Attributes every in-memory entry carries, so callers can read them without a `kind` check. */ interface MemoryAttributes { + /** Stands in for an inode: assigned on creation, carried by `rename`. */ + readonly identity: number; modifiedAtMs: number; uid: number; mode: number; @@ -210,6 +234,7 @@ const DEFAULT_FILE_MODE = 0o644; export class MemoryFilesystem implements Filesystem { readonly #entries = new Map(); readonly #failures = new Map(); + #nextIdentity = 1; constructor( private readonly freeDiskBytes = Number.MAX_SAFE_INTEGER, @@ -229,6 +254,12 @@ export class MemoryFilesystem implements Filesystem { return entry.contents; } + async readFileFrom(path: string, offset: number): Promise { + return Buffer.from(await this.readFile(path), "utf8") + .subarray(offset) + .toString("utf8"); + } + async writeFileAtomic( path: string, contents: string, @@ -335,6 +366,7 @@ export class MemoryFilesystem implements Filesystem { size: entry.kind === "file" ? Buffer.byteLength(entry.contents) : 0, modifiedAtMs: entry.modifiedAtMs, mode: entry.kind === "file" ? entry.mode : 0o755, + identity: String(entry.identity), }; } @@ -425,7 +457,6 @@ export class MemoryFilesystem implements Filesystem { * Test-only: makes every operation on `path` fail with `code`, which is the only way to * reach the branches that turn an unexpected filesystem failure into a typed rejection. */ - // fallow-ignore-next-line unused-class-member -- test-only state the port itself cannot create. defineFailure(path: string, code: string): void { this.#failures.set(path, code); } @@ -460,7 +491,13 @@ export class MemoryFilesystem implements Filesystem { } #newEntry(kind: MemoryEntryKind): MemoryEntry { - return { ...kind, modifiedAtMs: 0, mode: DEFAULT_MEMORY_MODE, uid: this.uid }; + return { + ...kind, + identity: this.#nextIdentity++, + modifiedAtMs: 0, + mode: DEFAULT_MEMORY_MODE, + uid: this.uid, + }; } /** The entry a following call (`stat`, `readFile`) sees: symlinks resolved. */ diff --git a/src/ports/index.ts b/src/ports/index.ts index 0932b902f..c65534914 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -66,6 +66,7 @@ export { FakeTcpProbe, NodeTcpProbe } from "./tcp-probe.js"; // fallow-ignore-next-line unused-type -- public shape of FakeTcpProbe.sends. export type { FakeSend } from "./tcp-probe.js"; export type { TcpProbe } from "./tcp-probe.js"; +export { LoggingProcessRunner } from "./logging-process-runner.js"; export { exitCodeOf, ExecOutputDeliveryStalledError, diff --git a/src/ports/logger.ts b/src/ports/logger.ts index cd20eb210..fc6d16025 100644 --- a/src/ports/logger.ts +++ b/src/ports/logger.ts @@ -134,8 +134,9 @@ export interface NodeFileLogSinkOptions { * across an interleaved write to the same fd (`NodeDaemonLauncher` hands the child an * inherited append fd on this same path for uncaught fatal output -- see below), and is * the only kind of write that reliably lands from a handler where the process is about - * to exit. This is sound only because volume is low by design: operational lifecycle - * lines (startup, connection churn, shutdown), not per-request logging. + * to exit. The cost is that every line blocks its caller on a disk write, and volume is + * no longer low: the daemon writes a line per operation, and at `debug` a line per device + * command. Accepted as long as a line stays one small `writeSync`. * * `#bytesWritten` only counts what this sink itself writes. The daemon launcher's * inherited fd can append a fatal crash dump to the same file without going through diff --git a/src/ports/logging-process-runner.test.ts b/src/ports/logging-process-runner.test.ts new file mode 100644 index 000000000..33cc11614 --- /dev/null +++ b/src/ports/logging-process-runner.test.ts @@ -0,0 +1,131 @@ +import { describe, expect, it } from "vitest"; + +import { FakeClock } from "./clock.js"; +import { LoggingProcessRunner } from "./logging-process-runner.js"; +import { JsonLinesLogger, MemoryLogSink } from "./logger.js"; +import { ScriptedProcessRunner, type ProcessRunner } from "./process-runner.js"; + +function wrap(inner: ProcessRunner) { + const clock = new FakeClock(1_000); + const sink = new MemoryLogSink(); + const runner = new LoggingProcessRunner({ + clock, + inner, + logger: new JsonLinesLogger({ clock, level: "debug", module: "process", sink }), + }); + return { runner, sink }; +} + +describe("LoggingProcessRunner", () => { + it("run logs the command, arguments, exit code and duration, and never the environment or the input", async () => { + const clock = new FakeClock(1_000); + const inner: ProcessRunner = { + run: async () => { + clock.advance(25); + return { code: 3, stderr: "boom-stderr", stdout: "boom-stdout" }; + }, + spawn: () => { + throw new Error("unused"); + }, + spawnStreaming: () => { + throw new Error("unused"); + }, + }; + const sink = new MemoryLogSink(); + const runner = new LoggingProcessRunner({ + clock, + inner, + logger: new JsonLinesLogger({ clock, level: "debug", module: "process", sink }), + }); + + const result = await runner.run("xcrun", ["simctl", "boot", "ABC"], { + env: { SECRET_TOKEN: "env-secret" }, + input: "stdin-secret", + }); + + expect(result.code).toBe(3); + expect(sink.records).toEqual([ + { + timestamp: 1_025, + level: "debug", + module: "process", + message: "process", + fields: { command: "xcrun", args: ["simctl", "boot", "ABC"], code: 3, durationMs: 25 }, + }, + ]); + expect(JSON.stringify(sink.records)).not.toMatch(/env-secret|SECRET_TOKEN|stdin-secret|boom-/); + }); + + it("a run that throws logs the error and rethrows it", async () => { + const failure = new Error("spawn ENOENT"); + const { runner, sink } = wrap({ + run: () => Promise.reject(failure), + spawn: () => { + throw new Error("unused"); + }, + spawnStreaming: () => { + throw new Error("unused"); + }, + }); + + await expect(runner.run("adb", ["devices"])).rejects.toBe(failure); + + expect(sink.records).toEqual([ + expect.objectContaining({ + message: "process", + fields: { command: "adb", args: ["devices"], error: "spawn ENOENT", durationMs: 0 }, + }), + ]); + }); + + it("spawn logs once, when the process exits", async () => { + const inner = new ScriptedProcessRunner([ + { hangs: true, match: { args: ["-avd", "a"], command: "emulator" } }, + ]); + const { runner, sink } = wrap(inner); + + const handle = runner.spawn("emulator", ["-avd", "a"]); + await Promise.resolve(); + expect(sink.records).toEqual([]); + + handle.kill("SIGTERM"); + await handle.wait(); + await Promise.resolve(); + + expect(sink.records).toEqual([ + expect.objectContaining({ + message: "process", + fields: expect.objectContaining({ command: "emulator", args: ["-avd", "a"] }), + }), + ]); + }); + + it("spawnStreaming logs once, when the process exits, and no chunk of its output", async () => { + const inner = new ScriptedProcessRunner([ + { + chunks: [{ chunk: "chunk-output-text", stream: "stdout" }], + match: { args: ["shell", "ls"], command: "adb" }, + result: { code: 0, stderr: "", stdout: "" }, + }, + ]); + const { runner, sink } = wrap(inner); + const seen: string[] = []; + + const handle = runner.spawnStreaming("adb", ["shell", "ls"], { + onChunk: (_stream, chunk) => { + seen.push(chunk); + }, + }); + await handle.wait(); + await Promise.resolve(); + + expect(seen).toEqual(["chunk-output-text"]); + expect(sink.records).toEqual([ + expect.objectContaining({ + message: "process", + fields: { command: "adb", args: ["shell", "ls"], code: 0, durationMs: 0 }, + }), + ]); + expect(JSON.stringify(sink.records)).not.toContain("chunk-output-text"); + }); +}); diff --git a/src/ports/logging-process-runner.ts b/src/ports/logging-process-runner.ts new file mode 100644 index 000000000..a3b490b49 --- /dev/null +++ b/src/ports/logging-process-runner.ts @@ -0,0 +1,114 @@ +import type { Clock } from "./clock.js"; +import type { Logger } from "./logger.js"; +import { + exitCodeOf, + type ProcessHandle, + type ProcessResult, + type ProcessRunner, + type ProcessRunOptions, + type ProcessStreamOptions, + type StreamingProcessHandle, +} from "./process-runner.js"; + +export interface LoggingProcessRunnerOptions { + readonly clock: Clock; + readonly inner: ProcessRunner; + readonly logger: Logger; +} + +/** + * Writes one `debug` line per device command when it settles: the command, its arguments, its + * exit code (or the error it threw) and how long it took. Never its environment, its input, or + * anything it printed -- an environment can hold credentials, and a `device.exec` command's + * output belongs to the caller who ran it, not to the daemon log. + * + * Errors pass through unchanged; this wrapper only watches. + */ +export class LoggingProcessRunner implements ProcessRunner { + readonly #clock: Clock; + readonly #inner: ProcessRunner; + readonly #logger: Logger; + + constructor(options: LoggingProcessRunnerOptions) { + this.#clock = options.clock; + this.#inner = options.inner; + this.#logger = options.logger; + } + + async run( + command: string, + args: readonly string[], + options?: ProcessRunOptions, + ): Promise { + const startedAt = this.#clock.now(); + try { + const result = await this.#inner.run(command, args, options); + this.#exited(command, args, startedAt, result.code); + return result; + } catch (error) { + this.#failed(command, args, startedAt, error); + throw error; + } + } + + spawn(command: string, args: readonly string[], options?: ProcessRunOptions): ProcessHandle { + const startedAt = this.#clock.now(); + const handle = this.#watchStart(command, args, startedAt, () => + this.#inner.spawn(command, args, options), + ); + handle.wait().then( + (result) => this.#exited(command, args, startedAt, result.code), + (error: unknown) => this.#failed(command, args, startedAt, error), + ); + return handle; + } + + spawnStreaming( + command: string, + args: readonly string[], + options: ProcessStreamOptions, + ): StreamingProcessHandle { + const startedAt = this.#clock.now(); + const handle = this.#watchStart(command, args, startedAt, () => + this.#inner.spawnStreaming(command, args, options), + ); + handle.wait().then( + (result) => this.#exited(command, args, startedAt, exitCodeOf(result)), + (error: unknown) => this.#failed(command, args, startedAt, error), + ); + return handle; + } + + /** A child that could not be started at all throws here, synchronously: log it, rethrow. */ + #watchStart( + command: string, + args: readonly string[], + startedAt: number, + start: () => Handle, + ): Handle { + try { + return start(); + } catch (error) { + this.#failed(command, args, startedAt, error); + throw error; + } + } + + #exited(command: string, args: readonly string[], startedAt: number, code: number | null): void { + this.#logger.debug("process", { + command, + args: [...args], + code, + durationMs: this.#clock.now() - startedAt, + }); + } + + #failed(command: string, args: readonly string[], startedAt: number, error: unknown): void { + this.#logger.debug("process", { + command, + args: [...args], + error: error instanceof Error ? error.message : String(error), + durationMs: this.#clock.now() - startedAt, + }); + } +} From dbe7751743c8e1ab74b199433485a93e742a8569 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 14:04:33 +0200 Subject: [PATCH 2/4] =?UTF-8?q?fix(cli,core):=20review=20round=201=20?= =?UTF-8?q?=E2=80=94=20follow=20survives=20a=20mid-read=20rotation,=20one?= =?UTF-8?q?=20log=20line=20per=20failed=20cleanup=20run,=20untested=20path?= =?UTF-8?q?s=20covered?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/internal/ARCHITECTURE.md | 5 +- src/cli/follow-log.test.ts | 123 ++++++++++++++++++ src/cli/follow-log.ts | 34 +++-- .../lease-acquisition-coordinator.test.ts | 24 ++++ src/core/lease-engine.test.ts | 3 +- src/core/quarantine-coordinator.test.ts | 36 +++++ src/core/reaper.test.ts | 22 ++++ src/core/reaper.ts | 12 +- src/gateway/dispatcher.test.ts | 46 ++++--- src/ports/filesystem.test.ts | 27 ++++ src/ports/logging-process-runner.test.ts | 22 ++++ 11 files changed, 319 insertions(+), 35 deletions(-) create mode 100644 src/cli/follow-log.test.ts diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 86dc907c7..f6649f9ea 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -1374,8 +1374,9 @@ information already visible per-device rather than add any. Operational logging is a separate concern from the event bus (ADR 0006): `simlock events` carries business facts (lease granted, device cleaned up, …), while the `Logger` port writes structured JSON lines saying what the daemon -was asked to do and what went wrong. No fact is copied into the log and no log -line becomes an event. The log records: +was asked to do and what went wrong. No log line becomes an event, and nothing +below copies a fact into the log; the `component.installed` copy described at +the end of this section predates ADR 0006. The log records: - **One `operation` line per dispatched call**, built in exactly one place: `runDispatch` (`src/daemon/dispatch.ts`), through the `observe` hook both diff --git a/src/cli/follow-log.test.ts b/src/cli/follow-log.test.ts new file mode 100644 index 000000000..f1aee06be --- /dev/null +++ b/src/cli/follow-log.test.ts @@ -0,0 +1,123 @@ +import { EventEmitter } from "node:events"; + +import { describe, expect, it } from "vitest"; + +import { FakeClock, MemoryFilesystem } from "../ports/index.js"; +import { followLog } from "./follow-log.js"; + +const LOG = "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/simlock/daemon.log"; + +/** A filesystem that rotates the log once, from inside the next read of `trigger` -- the + * narrowest window a real rotation can land in. */ +class RotatingFilesystem extends MemoryFilesystem { + #armed: { readonly trigger: string; readonly rotate: () => Promise } | undefined; + + rotateDuringNextReadOf(trigger: string, rotate: () => Promise): void { + this.#armed = { rotate, trigger }; + } + + override async readFileFrom(path: string, offset: number): Promise { + const armed = this.#armed; + if (armed !== undefined && armed.trigger === path) { + this.#armed = undefined; + await armed.rotate(); + } + return super.readFileFrom(path, offset); + } +} + +async function start(filesystem: MemoryFilesystem) { + const clock = new FakeClock(0); + const signals = new EventEmitter(); + let out = ""; + const done = followLog({ + clock, + filesystem, + path: LOG, + signals, + write: (text) => { + out += text; + }, + }); + const settle = () => new Promise((resolve) => setImmediate(resolve)); + await settle(); + return { + clock, + done, + output: () => out, + signals, + tick: async () => { + clock.advance(250); + await settle(); + }, + }; +} + +async function seed(filesystem: MemoryFilesystem, contents: string): Promise { + await filesystem.mkdirp("/simlock"); + await filesystem.writeFileAtomic(LOG, contents); +} + +describe("followLog", () => { + it("a rotation between a poll's rotation check and its read loses no line and prints none twice", async () => { + const filesystem = new RotatingFilesystem(); + await seed(filesystem, "a\n"); + const run = await start(filesystem); + + await filesystem.writeFileAtomic(LOG, "a\nb\n"); + filesystem.rotateDuringNextReadOf(LOG, async () => { + await filesystem.rename(LOG, `${LOG}.1`); + await filesystem.writeFileAtomic(LOG, "after rotation 1\nafter rotation 2\n"); + }); + await run.tick(); + await run.tick(); + + expect(run.output()).toBe("a\nb\nafter rotation 1\nafter rotation 2\n"); + run.signals.emit("SIGINT"); + await run.done; + }); + + it("a rotation during the initial tail does not reprint the tail as new lines", async () => { + const filesystem = new RotatingFilesystem(); + await seed(filesystem, "a\nb\n"); + filesystem.rotateDuringNextReadOf(LOG, async () => { + await filesystem.rename(LOG, `${LOG}.1`); + await filesystem.writeFileAtomic(LOG, "c\n"); + }); + const run = await start(filesystem); + await run.tick(); + + expect(run.output()).toBe("a\nb\nc\n"); + run.signals.emit("SIGINT"); + await run.done; + }); + + it("the unfinished last line of a rotated file is printed, ending in a newline", async () => { + const filesystem = new MemoryFilesystem(); + await seed(filesystem, "a\n"); + const run = await start(filesystem); + + await filesystem.writeFileAtomic(LOG, "a\npartial"); + await filesystem.rename(LOG, `${LOG}.1`); + await filesystem.writeFileAtomic(LOG, "next\n"); + await run.tick(); + + expect(run.output()).toBe("a\npartial\nnext\n"); + run.signals.emit("SIGINT"); + await run.done; + }); + + it("a read that fails for a reason other than a missing file rejects, leaving no timer or handler", async () => { + const filesystem = new MemoryFilesystem(); + await seed(filesystem, "a\n"); + const run = await start(filesystem); + + filesystem.defineFailure(LOG, "EACCES"); + await run.tick(); + + await expect(run.done).rejects.toMatchObject({ code: "EACCES" }); + expect(run.clock.pendingTimerCount).toBe(0); + expect(run.signals.listenerCount("SIGINT")).toBe(0); + expect(run.signals.listenerCount("SIGTERM")).toBe(0); + }); +}); diff --git a/src/cli/follow-log.ts b/src/cli/follow-log.ts index 4b00babbb..3e0ea0793 100644 --- a/src/cli/follow-log.ts +++ b/src/cli/follow-log.ts @@ -23,6 +23,9 @@ export interface FollowLogOptions { const DEFAULT_INTERVAL_MS = 250; const DEFAULT_TAIL_LINES = 100; +/** Retries of the initial tail when a rotation keeps landing mid-read; past it, the last read + * is used as it is. */ +const MAX_TAIL_ATTEMPTS = 3; /** * `simlock daemon logs --follow`: prints the last lines of the log, then each new complete line @@ -43,15 +46,25 @@ export async function followLog(options: FollowLogOptions): Promise { const { clock, filesystem, path, signals, write } = options; const rotatedPath = `${path}.1`; const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS; - let rotatedIdentity = await identityOf(filesystem, rotatedPath); - - const rotated = - rotatedIdentity === undefined ? "" : await readFromOrEmpty(filesystem, rotatedPath, 0); - const current = await readFromOrEmpty(filesystem, path, 0); - const currentComplete = completeLines(current); - let offset = Buffer.byteLength(currentComplete, "utf8"); - const tail = `${rotated}${currentComplete}`.split("\n").filter((line) => line !== ""); - const tailLines = tail.slice(-(options.tailLines ?? DEFAULT_TAIL_LINES)); + // The tail: the rotated file, then the current one. Both reads are only trusted if the + // rotated file is still the same one afterwards; otherwise a rotation landed in between and + // the offset would belong to the wrong file, so the tail is read again. + let rotatedIdentity: string | undefined; + let tail = ""; + let offset = 0; + for (let attempt = 0; attempt < MAX_TAIL_ATTEMPTS; attempt += 1) { + rotatedIdentity = await identityOf(filesystem, rotatedPath); + const rotated = + rotatedIdentity === undefined ? "" : await readFromOrEmpty(filesystem, rotatedPath, 0); + const current = completeLines(await readFromOrEmpty(filesystem, path, 0)); + tail = `${rotated}${current}`; + offset = Buffer.byteLength(current, "utf8"); + if ((await identityOf(filesystem, rotatedPath)) === rotatedIdentity) break; + } + const tailLines = tail + .split("\n") + .filter((line) => line !== "") + .slice(-(options.tailLines ?? DEFAULT_TAIL_LINES)); if (tailLines.length > 0) write(`${tailLines.join("\n")}\n`); const poll = async (): Promise => { @@ -64,6 +77,9 @@ export async function followLog(options: FollowLogOptions): Promise { offset = 0; } const complete = completeLines(await readFromOrEmpty(filesystem, path, offset)); + // A rotation between the check above and this read means `offset` was applied to the new + // file. Drop the read; the next poll sees the rotation and reads both files correctly. + if ((await identityOf(filesystem, rotatedPath)) !== rotatedIdentity) return; if (complete !== "") write(complete); offset += Buffer.byteLength(complete, "utf8"); }; diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 6b2678b1a..71c931a5c 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -705,6 +705,30 @@ describe("LeaseAcquisitionCoordinator", () => { await expect(acquisition).rejects.toMatchObject({ name: "RequestCancelledError" }); }); + it("A failed destroy after a shut-down device fails to boot for a waiter logs the device id and the error.", async () => { + const { logger, sink } = capturingLogger(); + const harness = await createHarness({ logger }); + const shutdown = await seedShutdown(harness); + harness.driver.failOn("makeReady", 2, new DriverCrashError("simulator never booted")); + harness.driver.failOn("destroy", 1, new DriverCrashError("simulator would not die")); + + await expect( + harness.coordinator.request(request, { ownerId: "booter", requesterId: "booter" }), + ).rejects.toMatchObject({ name: "BootTimeoutError" }); + + expect(sink.records.filter((record) => record.fields?.["step"] === "destroy")).toEqual([ + expect.objectContaining({ + level: "warn", + fields: { + deviceId: shutdown.id, + error: "DriverCrashError: simulator would not die", + requesterId: "booter", + step: "destroy", + }, + }), + ]); + }); + it("A shut-down device that fails to boot for a waiter logs the driver's error.", async () => { const { logger, sink } = capturingLogger(); const harness = await createHarness({ logger }); diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 77291f487..1e5f92d61 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -435,8 +435,9 @@ describe("LeaseEngine", () => { }, }, ]); + // At `debug`, so a line at any level would be caught. expect( - sink.records.filter((record) => record.level === "warn" || record.level === "error"), + sink.records.filter((record) => JSON.stringify(record).includes("purge exploded")), ).toEqual([]); }); diff --git a/src/core/quarantine-coordinator.test.ts b/src/core/quarantine-coordinator.test.ts index 163eb9082..636157e23 100644 --- a/src/core/quarantine-coordinator.test.ts +++ b/src/core/quarantine-coordinator.test.ts @@ -408,6 +408,42 @@ describe("QuarantineCoordinator", () => { ]); }); + it("a quarantine retry that itself throws logs at error with the device id", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ clock, platform: "ios" }); + driver.failOn("reclaim", 1, new Error("erase still stuck")); + const sink = new MemoryLogSink(); + const harness = await createHarness({ + clock, + driver, + logger: new JsonLinesLogger({ clock, sink }), + }); + await harness.coordinator.enter({ + attemptedStrategy: "wipe", + deviceId: harness.target.id, + duration: 0, + error: "boom", + leaseId: "lease-1", + }); + vi.spyOn(harness.registry, "recordQuarantineRetryFailure").mockRejectedValue( + new Error("state.json unwritable"), + ); + + harness.clock.advance(retryConfig.retryBackoffMs); + await flush(); + + expect(sink.records.filter((record) => record.level === "error")).toEqual([ + expect.objectContaining({ + module: "daemon.quarantine-coordinator", + fields: { + deviceId: harness.target.id, + error: "Error: state.json unwritable", + step: "retry", + }, + }), + ]); + }); + it("A failed quarantine delete retry logs the error and the attempt number.", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ clock, platform: "ios" }); diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index dbf93e21f..ec8c633e0 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -411,6 +411,28 @@ describe("CleanupReaper", () => { harness.reaper.dispose(); }); + it("a cleanup run that throws is logged once, however many triggers joined it", async () => { + const sink = new MemoryLogSink(); + const rule: CleanupRule = { + evaluate: () => { + throw new Error("rule exploded"); + }, + name: "exploding-rule", + }; + const harness = await createHarness( + [rule], + {}, + { logger: new JsonLinesLogger({ clock: new FakeClock(1_000), sink }), tickMs: 10_000 }, + ); + + harness.eventBus.emit("daemon.started", { configSnapshot: {}, version: "test" }, "test"); + harness.eventBus.emit("daemon.started", { configSnapshot: {}, version: "test" }, "test"); + await flush(); + + expect(sink.records.map((record) => record.message)).toEqual(["scheduled cleanup run failed"]); + harness.reaper.dispose(); + }); + it("shuts down after T1 and destroys after T2 on periodic ticks following a release", async () => { const harness = await createHarness(automaticCleanupRules, {}, { tickMs: 10_000 }); const grant = await harness.engine.request(spec, { diff --git a/src/core/reaper.ts b/src/core/reaper.ts index 70fdf6b7f..02535cd49 100644 --- a/src/core/reaper.ts +++ b/src/core/reaper.ts @@ -45,6 +45,7 @@ export class CleanupReaper { // only on the crossing edge, not once per tick while pressure persists. #underPressure = false; readonly #logger: Logger; + readonly #loggedRuns = new WeakSet>(); constructor(private readonly options: CleanupReaperOptions) { this.#logger = options.logger?.child("reaper") ?? new NoopLogger(); @@ -110,11 +111,18 @@ export class CleanupReaper { void this.#scheduleRunLogged(); } - /** A run nobody awaits: its failure has no caller to reach, so it is logged here. */ + /** + * A run nobody awaits: its failure has no caller to reach, so it is logged here. Triggers that + * arrive while a run is in flight share its promise, so a run is logged once, not once per + * trigger that joined it. + */ async #scheduleRunLogged(): Promise { + const run = this.#scheduleRun(); try { - await this.#scheduleRun(); + await run; } catch (error: unknown) { + if (this.#loggedRuns.has(run)) return; + this.#loggedRuns.add(run); this.#logger.error("scheduled cleanup run failed", { step: "cleanup", error: stableError(error), diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 0a9a619e7..a298edc3f 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { EventBus } from "../bus/index.js"; import { OPERATIONS, type OperationName } from "../contract/index.js"; -import { DispatchError, type DispatchSession } from "../daemon/dispatch.js"; +import { DispatchError, runDispatch, type DispatchSession } from "../daemon/dispatch.js"; import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; import { GatewayDispatcher, type GatewayTokenStore } from "./dispatcher.js"; import { MemoryDrainStore } from "./drain-store.js"; @@ -184,34 +184,38 @@ const EVERY_OPERATION = (Object.keys(OPERATIONS) as OperationName[]).filter( ); describe("GatewayDispatcher", () => { - it("logs the same operation line a worker's dispatcher does, through runDispatch", async () => { - const { dispatcher, logSink, workers } = harness(); + it("The gateway dispatcher logs the same line for the same operation", async () => { + const { clock, dispatcher, logSink, workers } = harness(); workers.connected("wrk_1", "mac-mini-1", "0.3.0"); + // The line `runDispatch` writes for the same call through any other dispatcher, a worker's + // included: only the module differs. + const otherSink = new MemoryLogSink(); + const other = (role: "admin" | "agent") => + runDispatch("worker.drain", { workerId: "wrk_1" }, session({ role }), { + handlers: { "worker.drain": () => ({ drained: true, workerId: "wrk_1" }) }, + observe: { + clock, + codeOf: (error) => (error instanceof DispatchError ? error.code : "INTERNAL"), + logger: new JsonLinesLogger({ clock, module: "other.dispatch", sink: otherSink }), + }, + }); await dispatcher.dispatch("worker.drain", { workerId: "wrk_1" }, session()); + await other("admin"); await expect( dispatcher.dispatch("worker.drain", { workerId: "wrk_1" }, session({ role: "agent" })), ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect(other("agent")).rejects.toMatchObject({ code: "FORBIDDEN" }); - expect(logSink.records.filter((record) => record.message === "operation")).toEqual([ - { - timestamp: 1_000, - level: "info", - module: "gateway.dispatch", - message: "operation", - fields: { - operation: "worker.drain", - principal: "operator-1", - role: "admin", - durationMs: 0, - }, - }, - expect.objectContaining({ - level: "info", - module: "gateway.dispatch", - fields: expect.objectContaining({ operation: "worker.drain", code: "FORBIDDEN" }), - }), + const gatewayLines = logSink.records.filter((record) => record.message === "operation"); + expect(gatewayLines.map((record) => record.module)).toEqual([ + "gateway.dispatch", + "gateway.dispatch", ]); + expect(gatewayLines.map(({ module: _module, ...rest }) => rest)).toEqual( + otherSink.records.map(({ module: _module, ...rest }) => rest), + ); + expect(gatewayLines[1]?.fields).toMatchObject({ code: "FORBIDDEN" }); }); it("answers status.get from the fleet", async () => { diff --git a/src/ports/filesystem.test.ts b/src/ports/filesystem.test.ts index 3362b78c7..a082d2b25 100644 --- a/src/ports/filesystem.test.ts +++ b/src/ports/filesystem.test.ts @@ -47,6 +47,33 @@ describe.each(implementations)("Filesystem contract: $name", ({ create, link }) ]); }); + it("reads a file from a byte offset, and nothing past its end", async () => { + const filesystem = create(); + const file = `${temporaryDirectory}/daemon.log`; + await filesystem.mkdirp(temporaryDirectory); + await filesystem.writeFileAtomic(file, "é line one\nline two\n"); + + // "é" is two bytes: the offset counts bytes, not characters. + await expect(filesystem.readFileFrom(file, 12)).resolves.toBe("line two\n"); + await expect(filesystem.readFileFrom(file, 0)).resolves.toBe("é line one\nline two\n"); + await expect(filesystem.readFileFrom(file, 21)).resolves.toBe(""); + await expect(filesystem.readFileFrom(file, 500)).resolves.toBe(""); + }); + + it("keeps a file's identity across a rename and gives a new file at the same path another", async () => { + const filesystem = create(); + const file = `${temporaryDirectory}/daemon.log`; + await filesystem.mkdirp(temporaryDirectory); + await filesystem.writeFileAtomic(file, "old\n"); + const original = (await filesystem.stat(file)).identity; + + await filesystem.rename(file, `${file}.1`); + await filesystem.writeFileAtomic(file, "new\n"); + + expect((await filesystem.stat(`${file}.1`)).identity).toBe(original); + expect((await filesystem.stat(file)).identity).not.toBe(original); + }); + it("creates nested directories idempotently", async () => { const filesystem = create(); const directory = `${temporaryDirectory}/devices/ready`; diff --git a/src/ports/logging-process-runner.test.ts b/src/ports/logging-process-runner.test.ts index 33cc11614..3e79a8ac0 100644 --- a/src/ports/logging-process-runner.test.ts +++ b/src/ports/logging-process-runner.test.ts @@ -78,6 +78,28 @@ describe("LoggingProcessRunner", () => { ]); }); + it("a spawn that cannot start logs the error and rethrows it", () => { + const failure = new Error("spawn EACCES"); + const { runner, sink } = wrap({ + run: () => Promise.reject(new Error("unused")), + spawn: () => { + throw failure; + }, + spawnStreaming: () => { + throw new Error("unused"); + }, + }); + + expect(() => runner.spawn("emulator", ["-avd", "a"])).toThrow(failure); + + expect(sink.records).toEqual([ + expect.objectContaining({ + message: "process", + fields: { command: "emulator", args: ["-avd", "a"], error: "spawn EACCES", durationMs: 0 }, + }), + ]); + }); + it("spawn logs once, when the process exits", async () => { const inner = new ScriptedProcessRunner([ { hangs: true, match: { args: ["-avd", "a"], command: "emulator" } }, From 5cf1702834a633291b2e0d8ce67801ac958542b1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 14:09:59 +0200 Subject: [PATCH 3/4] test(cli): attach the follow rejection handler before the failing poll --- src/cli/follow-log.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cli/follow-log.test.ts b/src/cli/follow-log.test.ts index f1aee06be..5ecc61f5b 100644 --- a/src/cli/follow-log.test.ts +++ b/src/cli/follow-log.test.ts @@ -113,9 +113,10 @@ describe("followLog", () => { const run = await start(filesystem); filesystem.defineFailure(LOG, "EACCES"); + const rejected = expect(run.done).rejects.toMatchObject({ code: "EACCES" }); await run.tick(); - await expect(run.done).rejects.toMatchObject({ code: "EACCES" }); + await rejected; expect(run.clock.pendingTimerCount).toBe(0); expect(run.signals.listenerCount("SIGINT")).toBe(0); expect(run.signals.listenerCount("SIGTERM")).toBe(0); From 320e0149afed0ae719f79f59751eb37c92455b86 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 14:31:11 +0200 Subject: [PATCH 4/4] =?UTF-8?q?fix(daemon,cli):=20review=20round=202=20?= =?UTF-8?q?=E2=80=94=20no=20raw=20wire=20input=20in=20operation=20lines,?= =?UTF-8?q?=20authorize=20fails=20closed,=20--follow=20only=20on=20logs,?= =?UTF-8?q?=20wiring=20covered=20by=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/internal/ARCHITECTURE.md | 3 +- e2e/daemon-log.test.ts | 6 ++ src/cli/follow-log.test.ts | 14 +++ src/cli/index.test.ts | 12 +++ src/cli/index.ts | 1 + src/core/lease-engine.test.ts | 166 +++++++++++++++++++++++++++++++++- src/daemon/dispatch.test.ts | 25 +++++ src/daemon/dispatch.ts | 12 ++- src/daemon/main.test.ts | 60 ++++++++++++ 9 files changed, 292 insertions(+), 7 deletions(-) diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index f6649f9ea..349ff251f 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -1383,7 +1383,8 @@ the end of this section predates ADR 0006. The log records: dispatchers pass (`logger.child("dispatch")`). It names the operation, `principal`, `role`, `durationMs`, `leaseId`/`requesterId` from the validated input when present (nothing else from the input, nothing from the - output), and on failure `code` and `message`. Level follows the operation's + output), and on failure `code`, plus `message` once the input has passed + its schema (before that the message quotes raw wire input). Level follows the operation's contract `effect`: a `write` success is `info`, a `read` success `debug`, a failure `info`, an `INTERNAL` failure `error`. A call refused before its handler (`UNKNOWN_REQUEST`, `BAD_REQUEST`, `FORBIDDEN`) gets the line too. diff --git a/e2e/daemon-log.test.ts b/e2e/daemon-log.test.ts index eb468ac05..b676cb4b8 100644 --- a/e2e/daemon-log.test.ts +++ b/e2e/daemon-log.test.ts @@ -282,15 +282,21 @@ describe("daemon.log", () => { // Each cycle writes about 1 kB, so five of them rotate the log several times. A cycle waits // for the follower before the next one: only one rotated generation is kept, so a second // rotation inside one poll would delete lines before any reader could see them. + let lastLeaseId = ""; for (let cycle = 0; cycle < 5; cycle += 1) { const leaseId = await leaseDetached(env); + lastLeaseId = leaseId; expect((await env.cli(["release", leaseId])).code).toBe(0); await waitFor(() => follower.stdoutSoFar().includes(`"leaseId":"${leaseId}"`), { label: () => `release line ${cycle}, follower printed:\n${follower.stdoutSoFar()}`, }); } + // The log has rotated, and the last release line -- already printed above -- sits in the + // file started by a rotation, so it was written after one. await expect(readFile(`${env.logPath}.1`, "utf8")).resolves.not.toBe(""); + const current = await readFile(env.logPath, "utf8"); + expect(current).toContain(`"leaseId":"${lastLeaseId}"`); follower.kill("SIGINT"); expect((await follower.waitForExit(10_000)).code).toBe(0); }); diff --git a/src/cli/follow-log.test.ts b/src/cli/follow-log.test.ts index 5ecc61f5b..a7c3cb087 100644 --- a/src/cli/follow-log.test.ts +++ b/src/cli/follow-log.test.ts @@ -92,6 +92,20 @@ describe("followLog", () => { await run.done; }); + it("a line still being written is printed once, when it is complete", async () => { + const filesystem = new MemoryFilesystem(); + await seed(filesystem, "a\npart"); + const run = await start(filesystem); + expect(run.output()).toBe("a\n"); + + await filesystem.writeFileAtomic(LOG, "a\npartial\n"); + await run.tick(); + + expect(run.output()).toBe("a\npartial\n"); + run.signals.emit("SIGINT"); + await run.done; + }); + it("the unfinished last line of a rotated file is printed, ending in a newline", async () => { const filesystem = new MemoryFilesystem(); await seed(filesystem, "a\n"); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index f3324fd8f..cdad18124 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2856,6 +2856,18 @@ describe("CLI: daemon logs --follow", () => { }); }); + it("--follow on any daemon subcommand but logs fails with USAGE, exit 2", async () => { + for (const command of ["start", "stop", "status"]) { + const output = outputCapture(); + await expect(runCli(["daemon", command, "--follow"], output.environmentWith())).resolves.toBe( + 2, + ); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "")).toEqual({ + error: { code: "USAGE", message: expect.stringContaining("--follow") }, + }); + } + }); + it("an interrupt ends the follow with exit 0 and leaves no timer armed", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/simlock"); diff --git a/src/cli/index.ts b/src/cli/index.ts index 371d1a0fa..5e7362ab8 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -1460,6 +1460,7 @@ async function runDaemon( return 0; } if (values.positionals.length > 0) throw new UsageError("daemon accepts exactly one subcommand"); + if (values.follow && command !== "logs") throw new UsageError("--follow applies only to logs"); if (command === "start") { const client = await connectDaemonClient(environment, token, { launch: true }); try { diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 1e5f92d61..6dc82f3a2 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -142,7 +142,7 @@ async function createHarness( }), }); - return { bus, clock, driver, engine, registry }; + return { bus, clock, driver, engine, filesystem, registry }; } async function seedReady( @@ -435,9 +435,12 @@ describe("LeaseEngine", () => { }, }, ]); - // At `debug`, so a line at any level would be caught. + // At `debug`, so a line at any level would be caught: nothing names the device or the error. expect( - sink.records.filter((record) => JSON.stringify(record).includes("purge exploded")), + sink.records.filter((record) => { + const line = JSON.stringify(record); + return line.includes("purge exploded") || line.includes(first.device.id); + }), ).toEqual([]); }); @@ -1812,3 +1815,160 @@ describe("LeaseEngine fresh lease identity (#75)", () => { expect(restarted.operationsSinceStart()).toEqual(["destroy"]); }); }); + +describe("LeaseEngine logger wiring", () => { + function debugLogger(): { readonly logger: Logger; readonly sink: MemoryLogSink } { + const sink = new MemoryLogSink(); + return { logger: new JsonLinesLogger({ clock: new FakeClock(0), level: "debug", sink }), sink }; + } + + it("LeaseEngine hands its logger to the quarantine coordinator: a failed retry is logged", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); + driver.failOn("reclaim", 1, new DriverCrashError("purge exploded")); + driver.failOn("reclaim", 2, new DriverCrashError("retry exploded")); + const { logger, sink } = debugLogger(); + const harness = await createHarness({ driver, logger }); + const first = await harness.engine.request(request, { + ownerId: "first", + requesterId: "first", + }); + await harness.engine.release(first.lease.id, "explicit"); + await harness.engine.settle(); + expect(harness.registry.snapshot.devices[0]?.state).toBe("quarantined"); + + harness.clock.advance(config().warmPool.quarantine.retryBackoffMs); + await flush(); + + expect( + sink.records.filter((record) => record.message === "quarantine reclaim retry failed"), + ).toMatchObject([ + { + level: "warn", + module: "daemon.quarantine-coordinator", + fields: { + attempts: 1, + deviceId: first.device.id, + error: "DriverCrashError: retry exploded", + step: "reclaim", + }, + }, + ]); + }); + + it("LeaseEngine hands its logger to the device provisioner: a new device that fails to boot is logged", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); + driver.failOn("makeReady", 1, new DriverCrashError("first boot exploded")); + const { logger, sink } = debugLogger(); + const harness = await createHarness({ driver, logger }); + + await expect( + harness.engine.request(request, { ownerId: "first", requesterId: "first" }), + ).rejects.toMatchObject({ name: "BootTimeoutError" }); + + expect( + sink.records.filter((record) => record.message === "new device failed to become ready"), + ).toMatchObject([ + { + level: "warn", + module: "daemon.device-provisioner", + fields: { error: "DriverCrashError: first boot exploded", step: "boot" }, + }, + ]); + }); + + it("LeaseEngine hands its logger to the lease expiry scheduler: an expiry that fails is logged", async () => { + const { logger, sink } = debugLogger(); + const harness = await createHarness({ lease: { defaultTtlMs: 10 }, logger }); + const granted = await harness.engine.request(request, { + ownerId: "agent-1", + requesterId: "agent-1", + }); + // The expiry's release has to commit to the state file; a disk that refuses the write + // makes the expiry throw out of the scheduler's timer. + harness.filesystem.defineFailure(statePath, "EIO"); + + harness.clock.advance(10); + await flush(); + + expect(sink.records.filter((record) => record.message === "lease expiry failed")).toMatchObject( + [ + { + level: "error", + module: "daemon.lease-expiry-scheduler", + fields: { leaseId: granted.lease.id, step: "expire" }, + }, + ], + ); + }); + + it("LeaseEngine hands its logger to the acquisition coordinator: a failed eviction is logged", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); + driver.failOn("shutdown", 1, new DriverCrashError("cannot stop victim")); + const { logger, sink } = debugLogger(); + const harness = await createHarness({ + driver, + limits: { + android: { maxDevices: 1, maxRunning: 1 }, + ios: { maxDevices: 2, maxRunning: 1 }, + maxRunning: 1, + }, + logger, + }); + const victim = await seedReady(harness); + + await expect( + harness.engine.request( + { ...request, model: "iPhone SE" }, + { noWait: true, ownerId: "new-spec", requesterId: "new-spec" }, + ), + ).rejects.toBeInstanceOf(NoCapacityError); + + expect( + sink.records.filter((record) => record.message === "shutting down an eviction target failed"), + ).toMatchObject([ + { + level: "warn", + module: "daemon.lease-acquisition-coordinator", + fields: { deviceId: victim.id, requesterId: "new-spec", step: "shutdown" }, + }, + ]); + }); + + it("LeaseEngine hands its logger to the warm-pool coordinator: a failed post-purge boot is logged", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ + availableOsVersions: ["26.5"], + clock, + platform: "ios", + reclaimResult: "shutdown", + }); + driver.failOn("makeReady", 2, new Error("not ready")); + const { logger, sink } = debugLogger(); + const harness = await createHarness({ driver, logger }); + const first = await harness.engine.request(request, { + ownerId: "first", + requesterId: "first", + }); + + await harness.engine.release(first.lease.id, "explicit"); + await harness.engine.settle(); + + expect( + sink.records.filter((record) => record.message === "making a reclaimed device ready failed"), + ).toMatchObject([ + { + level: "warn", + module: "daemon.warm-pool-coordinator", + fields: { + deviceId: first.device.id, + error: "Error: not ready", + leaseId: first.lease.id, + step: "make-ready", + }, + }, + ]); + }); +}); diff --git a/src/daemon/dispatch.test.ts b/src/daemon/dispatch.test.ts index 033d076a6..fc721c4eb 100644 --- a/src/daemon/dispatch.test.ts +++ b/src/daemon/dispatch.test.ts @@ -210,4 +210,29 @@ describe("runDispatch's operation line", () => { }); expect(sink.records[2]?.fields).not.toHaveProperty("leaseId"); }); + + it("a request refused by its input schema logs its code and nothing the input said", async () => { + const { pipeline, sink } = harness({ + "lease.request": () => { + throw new Error("never reached: the input is refused first"); + }, + }); + + await expect( + runDispatch( + "lease.request", + { model: "iPhone 17", platform: "hunter2-wire-value", "s3cret-key-name": 1 }, + session(), + pipeline, + ), + ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + + expect(sink.records).toEqual([ + expect.objectContaining({ + level: "info", + fields: expect.objectContaining({ operation: "lease.request", code: "BAD_REQUEST" }), + }), + ]); + expect(JSON.stringify(sink.records)).not.toMatch(/hunter2|s3cret/); + }); }); diff --git a/src/daemon/dispatch.ts b/src/daemon/dispatch.ts index 84baf0833..5857c6b63 100644 --- a/src/daemon/dispatch.ts +++ b/src/daemon/dispatch.ts @@ -222,7 +222,8 @@ interface ObservedCall { * The one place an `operation` line is built (architecture rule 10). It names the operation, * who asked, how long it took and how it ended -- the request, never what it changed (ADR * 0006 §3). From the input only `leaseId` and `requesterId`, as claimed: nothing else in an - * input is safe to assume free of secrets, and nothing from the output is logged at all. + * input is safe to assume free of secrets, and nothing from the output is logged at all. A + * failure's `message` is logged only once the input has been validated (see below). */ function logOperation( observe: DispatchObserver, @@ -247,10 +248,14 @@ function logOperation( } const { error } = outcome; const code = observe.codeOf(error); + // Until the input has passed its schema, the error describes the raw wire input -- a schema + // issue quotes the rejected value and unknown key names -- so only the code is logged. const failed = { ...fields, code, - message: error instanceof Error ? error.message : String(error), + ...(call.input === undefined + ? {} + : { message: error instanceof Error ? error.message : String(error) }), }; if (code === "INTERNAL") observe.logger.error("operation", failed); else observe.logger.info("operation", failed); @@ -316,7 +321,8 @@ function checkAccess( `Operation ${operation} requires role ${requiredRole}, session is ${session.role}`, ); } - if (definition.authorize?.(input, authorizeContext(session, pipeline)) === false) { + const authorize = definition.authorize; + if (authorize !== undefined && !authorize(input, authorizeContext(session, pipeline))) { throw new DispatchError("FORBIDDEN", `Not authorized for ${operation}`); } } diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 7b4b24768..bd40ac66b 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -1340,3 +1340,63 @@ async function readFileRetrying( } } } + +/** A disk whose free-space query fails, as `statfs` does on a data directory gone unreadable. */ +class UnmeasurableDiskFilesystem extends MemoryFilesystem { + async diskFree(_path: string): Promise { + throw Object.assign(new Error("statfs failed"), { code: "EIO" }); + } +} + +describe("startDaemon logger wiring", () => { + it("startDaemon hands its logger to the cleanup reaper: a scheduled cleanup run that fails is logged", async () => { + const { sink } = await start({ filesystem: new UnmeasurableDiskFilesystem() }); + + // `daemon.started` triggers a run nobody awaits; its failure has no caller to reach. + await pollUntil(() => + sink.records.some((record) => record.message === "scheduled cleanup run failed"), + ); + expect( + sink.records.filter((record) => record.message === "scheduled cleanup run failed"), + ).toMatchObject([ + { + level: "error", + module: "daemon.reaper", + fields: { step: "cleanup", error: expect.stringContaining("statfs failed") }, + }, + ]); + }); + + it("startDaemon hands the gateway dispatcher its error classifier: a typed refusal is logged with its code at info, not as INTERNAL at error", async () => { + const { daemon, sink } = await start({ configOverrides: { mode: "gateway" } }); + + await expect( + daemon.dispatch( + "worker.drain", + { workerId: "wrk_ghost" }, + { manageEventSubscription: () => undefined, principal: "test-operator", role: "admin" }, + ), + ).rejects.toMatchObject({ code: "UNKNOWN_WORKER" }); + + expect( + sink.records.filter( + (record) => record.message === "operation" && record.fields?.operation === "worker.drain", + ), + ).toMatchObject([ + { + level: "info", + module: "daemon.gateway.dispatch", + fields: { code: "UNKNOWN_WORKER", principal: "test-operator" }, + }, + ]); + }); +}); + +/** Polls until `condition` holds or the time runs out, without failing: the caller's own + * assertion afterwards is what names a miss. */ +async function pollUntil(condition: () => boolean, timeoutMs = 2_000): Promise { + const deadline = Date.now() + timeoutMs; + while (!condition() && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 5)); + } +}