From c8c60ce73406821351fcae30c111f4f182e34a34 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 12:56:49 +0200 Subject: [PATCH 1/3] feat(core,contract,daemon,gateway,cli): status lists the installs in progress The installer lists its waiting and running installs (the 16 oldest), status.get carries them, the gateway's worker view copies them and is refreshed on the component.install-* events, and simlock status and simlock worker list print them. The worker view also keeps the worker's downloads.timeoutMs. Closes #218 --- docs/CLI.md | 45 +++++++-- docs/CLIENT.md | 21 ++++ docs/HTTP-API.md | 46 +++++++-- docs/internal/ARCHITECTURE.md | 17 ++-- e2e/installs-in-progress.test.ts | 95 +++++++++++++++++ src/cli/index.test.ts | 95 +++++++++++++++++ src/cli/index.ts | 43 ++++++-- src/contract/operations.ts | 7 ++ src/contract/schemas.ts | 54 +++++++++- src/core/component-installer.test.ts | 68 +++++++++++++ src/core/component-installer.ts | 49 ++++++++- src/daemon/dispatcher.test.ts | 107 ++++++++++++++++++++ src/daemon/dispatcher.ts | 7 ++ src/daemon/main.ts | 1 + src/daemon/server.ts | 5 +- src/gateway/aggregate.test.ts | 61 +++++++++++ src/gateway/aggregate.ts | 21 +++- src/gateway/dispatcher.test.ts | 21 ++++ src/gateway/service.test.ts | 146 +++++++++++++++++++++++++++ src/gateway/test-support.ts | 17 +++- src/gateway/worker-link.ts | 94 ++++++++++++----- src/gateway/worker-registry.ts | 1 + 22 files changed, 954 insertions(+), 67 deletions(-) create mode 100644 e2e/installs-in-progress.test.ts diff --git a/docs/CLI.md b/docs/CLI.md index 35a14f368..325d18afe 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -779,11 +779,14 @@ why its Android catalog looks thin, trimmed to one worker: }, "global": {"running": 0, "maxRunning": 8, "reserved": 0, "overLimit": false, "warm": 0} }, - "downloads": {"policy": "on-request"}, + "downloads": {"policy": "on-request", "timeoutMs": 1200000}, "lease": {"maxTtlMs": 14400000}, "queueDepth": 0, "leases": [], "devices": [], + "installs": [ + {"platform": "ios", "component": "26.4", "state": "downloading", "since": 1790864071200, "waiters": 1} + ], "catalog": [ { "platform": "ios", @@ -814,11 +817,16 @@ why its Android catalog looks thin, trimmed to one worker: } ``` -`downloads.policy` and `lease.maxTtlMs` are that worker's own effective -config, read when its uplink connects and again on every periodic refresh. +`downloads.policy`, `downloads.timeoutMs` and `lease.maxTtlMs` are that +worker's own effective config, read when its uplink connects, again on every +periodic refresh, and after the worker installs a component. The policy is shown for reference; routing does not read it, since no -download is started through a gateway. `catalog` is what that -worker can lease, each model with the runtimes it pairs with. `host` is the +lease request through a gateway starts a download. `installs` lists the +component installs waiting or running on that worker, whoever started them, +in the shape [`simlock status`](#simlock-status) describes; it changes as +soon as an install starts or ends there. `catalog` is what that +worker can lease, each model with the runtimes it pairs with, and lists a +newly installed component as soon as its install ends. `host` is the machine: operating system, its version, CPU architecture, and the version of each platform tool its drivers use (`xcode` with its build; the Android `emulator`, `platform-tools` and `cmdline-tools`). A tool the worker does not @@ -976,10 +984,23 @@ platform), the RAM budget (`RAM budget: 4.50 GiB/12.00 GiB used`), every managed device with its state and device mode (`Device dev_7: ready, mode slim`), current leases (who — the agent id, see [Agent identity](#agent-identity) — since when, and when each was last -renewed), and queue depth. `--json` for the structured equivalent. `overLimit` +renewed), the component installs in progress, and queue depth. `--json` for +the structured equivalent. `overLimit` is true when a lowered limit cannot yet be met, for example because active leases consume all running slots. +Each install in progress gets one line: platform, component, state, how long +since it was first asked for, and how many requests wait on it +(`Install ios 26.4: downloading for 42s, 2 waiters`). Every install is +listed, whoever started it, for example a lease request with +`--allow-download`. `downloading` means the platform's installer is running; +`waiting` means it is queued behind another install on the same platform, or +about to start. A line goes away as soon as its install ends, whether it +succeeded, failed or timed out. In `--json` the list is `installs`, oldest +first, at most 16 entries: `platform`, `component` (the version, or the word +the platform uses for its newest), `state`, `since` (milliseconds since the +epoch) and `waiters`. It is empty when nothing is installing. + The RAM budget line appears only under the `resource` capacity strategy (see [CONFIGURATION.md](CONFIGURATION.md#capacity-strategies)); under `fixed` there is none. In `--json` it is `capacity.ramBudget`: @@ -994,10 +1015,12 @@ Against a **gateway** (`config.mode: "gateway"`) the same command answers for the whole fleet, in the same shape: the daemon line reads `running (gateway)`, capacity is summed across the connected workers (the RAM budget over those that report one, over its limit when any worker is), one line -per worker precedes the devices, and every device and lease names the worker it -lives on (`Device dev_7 on wrk_a: leased, mode full`). `--json` gains a `workers` array of +per worker precedes the devices, and every device, lease and install names the +worker it lives on (`Device dev_7 on wrk_a: leased, mode full`, +`Install ios 26.4 on wrk_a: waiting for 3s, 1 waiter`). Installs are listed +for the connected workers, the 16 oldest across the fleet. `--json` gains a `workers` array of [worker views](#simlock-worker-listdrainundrainremove) and a `workerId` on each -device and lease; `daemon.mode` says which kind of daemon answered. +device, lease and install; `daemon.mode` says which kind of daemon answered. The daemon block carries `mode` (`"worker"` or `"gateway"`) — the one field that tells a client which kind of daemon answered. Beside it, `host` says @@ -1290,7 +1313,8 @@ operation **on a gateway**; against a worker they answer `UNKNOWN_REQUEST` identity — stable across restarts, and not its label or host name), its label if it set one, connection state, capacity, how many leases it holds, and its host: operating system, version, architecture, and tool - versions. A worker the gateway cannot speak to shows `incompatible` with both + versions. Under each worker, one indented line per component install + waiting or running there, in the form `simlock status` prints. A worker the gateway cannot speak to shows `incompatible` with both protocol ranges, which is what version skew looks like from here. `--json` prints the raw worker views, which is what the console renders. - `drain ` / `undrain ` — a drained worker keeps its @@ -1311,6 +1335,7 @@ operation **on a gateway**; against a worker they answer `UNKNOWN_REQUEST` ```console $ simlock worker list wrk_9f2c (mac-mini-1): connected -- ios 1/2, android 0/1, 1 lease(s) -- macOS 15.5 arm64; xcode 16.4 (16F6), emulator 35.4.9 + Install ios 26.4: downloading for 42s, 1 waiter wrk_4a10 (ci-runner-3): disconnected, drained -- ios 0/4, android 0/2, 0 lease(s) -- macOS 14.7 x64; xcode 16.2 (16C5032a) ``` diff --git a/docs/CLIENT.md b/docs/CLIENT.md index c72758100..8108436be 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -245,6 +245,27 @@ const { host } = await client.getStatus(); drivers. Each worker's `host` is on its entry in `workers`, and on `listWorkers()` from the admin client. +## What is installing: `getStatus().installs` + +`getStatus()` lists the component installs waiting or running on the +machine, whoever started them, oldest first and at most 16: + +```ts +const { installs = [] } = await client.getStatus(); +// [{ platform: "ios", component: "26.4", state: "downloading", since: 1790864071200, waiters: 2 }] +``` + +- `state` is `downloading` while the platform's installer runs, and `waiting` + while the install is queued behind another one on the same platform or + about to start. `since` is when the first request for it arrived; `waiters` + is how many requests wait on it. +- An install leaves the list as soon as it ends, whether it succeeded, + failed or timed out. The field is absent only from an older daemon. +- On a gateway the list covers the connected workers, each entry with its + `workerId`, the 16 oldest across the fleet. Each worker's own list is on + its entry in `workers` and on `listWorkers()`, beside its + `downloads.timeoutMs`. + ## One connection, no reconnect, no retry This is the one thing to internalize before building anything on top of this diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 9244ce17b..ea0113b54 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -171,10 +171,31 @@ when the use exceeds the limit, for example after a restart with larger per-device sizes; until a device is deleted, none is created, and no shut-down slim device boots if its slim size is smaller than the full size. +**`installs`** lists the component installs waiting or running on the +machine, whoever started them (a lease request that allowed a download, for +example), oldest first and at most 16: + +```json +"installs": [ + { "platform": "ios", "component": "26.4", "state": "downloading", "since": 1790864071200, "waiters": 2 }, + { "platform": "ios", "component": "26.5", "state": "waiting", "since": 1790864075000, "waiters": 1 } +] +``` + +`state` is `downloading` while the platform's installer runs, and `waiting` +while the install is queued behind another one on the same platform or about +to start. `component` is the version, or the word the platform uses for its +newest. `since` is when the first request for that install arrived, in +milliseconds since the epoch, and `waiters` is how many requests wait on it. +An install leaves the list as soon as it ends, whether it succeeded, failed +or timed out. A worker always sends the field, empty when nothing is +installing; an older daemon leaves it out. + On a **gateway** the numbers are the fleet's — capacity summed across connected workers (`ramBudget` over the workers that report one, `overLimit` when any of -them is, absent when none does), every gateway-issued and local lease, every device, the gateway -queue's depth — every lease and device carries the **`workerId`** it lives +them is, absent when none does), every gateway-issued and local lease, every device, the +connected workers' installs (the 16 oldest across the fleet), the gateway +queue's depth — every lease, device and install carries the **`workerId`** it lives on, and an additive **`workers`** array carries one [worker view](#worker-routes) per worker: @@ -691,11 +712,14 @@ simulated (hence the thin Android catalog), trimmed to one worker: }, "global": {"running": 0, "maxRunning": 8, "reserved": 0, "overLimit": false, "warm": 0} }, - "downloads": {"policy": "on-request"}, + "downloads": {"policy": "on-request", "timeoutMs": 1200000}, "lease": {"maxTtlMs": 14400000}, "queueDepth": 0, "leases": [], "devices": [], + "installs": [ + {"platform": "ios", "component": "26.4", "state": "downloading", "since": 1790864071200, "waiters": 1} + ], "catalog": [ { "platform": "ios", @@ -726,13 +750,19 @@ simulated (hence the thin Android catalog), trimmed to one worker: } ``` -`downloads.policy` is that worker's own effective policy, read when its -uplink connects and again on every periodic refresh. It is shown for -reference; routing does not read it, since no download is started through a -gateway. +`downloads.policy` and `downloads.timeoutMs` are that worker's own effective +config, read when its uplink connects, again on every periodic refresh, and +after the worker installs a component. The policy is shown for reference; +routing does not read it, since no lease request through a gateway starts a +download. + +`installs` is the worker's own `installs` list from its +[`GET /v1/status`](#get-v1status), refreshed as soon as an install starts or +ends there. A worker that does not send one shows an empty list. `catalog` is what that worker can lease, each model with the runtimes it -pairs with. `host` is the worker's machine, the same block its own +pairs with, and lists a newly installed component as soon as its install +ends. `host` is the worker's machine, the same block its own `GET /v1/status` reports, as of the gateway's last refresh: a tool installed or upgraded on the worker shows here without a restart of either side. diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 76152b81a..cf6a6fe72 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -457,13 +457,16 @@ manually-advanced `Clock`, exactly as the core's tests script drivers. A **worker view** is what the gateway currently knows about one worker: its id, `label`, daemon health and version, negotiated protocol range (only when `incompatible`), capacity per platform, queue depth, leases, devices, -catalog, host facts, effective download policy and `lease.maxTtlMs`, and -drain state. On connect the gateway calls `status.get`, `list.get`, -`catalog.get`, `config.get`, and `events.subscribe` on the worker and builds -the view from the answers. It refreshes status and list on every worker event -that changes capacity or leases. A slow periodic tick refreshes all four -reads, catalog and config included, so a runtime installed on a worker -reaches its view without a restart of either side. +catalog, host facts, installs in progress, effective download policy and +timeout, `lease.maxTtlMs`, and drain state. On connect the gateway calls +`status.get`, `list.get`, `catalog.get`, `config.get`, and `events.subscribe` +on the worker and builds the view from the answers. It refreshes status and +list on every worker event that changes capacity or leases, and on +`component.install-started`, `component.installed` and +`component.install-failed` (ADR 0010 §7); after `component.installed` it +re-reads catalog and config too. A slow periodic tick refreshes all four +reads, catalog and config included, so a runtime installed on a worker by +other means still reaches its view without a restart of either side. The **host facts** are the `host` block of the worker's `status.get` (ADR 0008 §5-§8): operating system, version, architecture from the host diff --git a/e2e/installs-in-progress.test.ts b/e2e/installs-in-progress.test.ts new file mode 100644 index 000000000..b19bd040e --- /dev/null +++ b/e2e/installs-in-progress.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from "vitest"; + +import { freeLoopbackPort, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; + +interface Install { + readonly platform: string; + readonly component: string; + readonly state: string; +} + +interface WorkerView { + readonly connection: string; + readonly installs?: readonly Install[]; +} + +/** The installs a worker's own `simlock status --json` lists. */ +async function workerInstalls(worker: TestEnv): Promise { + const status = await worker.cli(["status", "--json"]); + expect(status.code, status.stderr).toBe(0); + return (status.json as { installs: readonly Install[] }).installs; +} + +/** The installs the gateway's `simlock worker list --json` shows on its only worker's view. */ +async function viewInstalls(gateway: TestEnv): Promise { + const listed = await gateway.cli(["worker", "list", "--json"]); + expect(listed.code, listed.stderr).toBe(0); + return (listed.json as { workers: readonly WorkerView[] }).workers[0]?.installs; +} + +describe("installs in progress", () => { + it("shows an install on the worker's status and on its gateway's worker list while it runs, and on neither after it ends", async () => { + const port = await freeLoopbackPort(); + const gateway = await withDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + driver: "none", + }); + const minted = await gateway.cli(["token", "create", "--role", "worker"]); + expect(minted.code, minted.stderr).toBe(0); + const { secret } = minted.json as { secret: string }; + const worker = await withDaemon({ + configOverrides: { gateway: { token: secret, url: `ws://127.0.0.1:${port}` } }, + driverScript: { + ios: { + availableOsVersions: ["18.4"], + knownModels: ["iPhone 16"], + // Held open long enough for both CLIs to look at it. + latencyMs: { installComponent: 8_000 }, + }, + }, + }); + await waitFor( + async () => { + const listed = await gateway.cli(["worker", "list", "--json"]); + const views = (listed.json as { workers?: readonly WorkerView[] } | undefined)?.workers; + return views?.[0]?.connection === "connected" && views[0].installs !== undefined; + }, + { label: "the worker joined the gateway and its first view arrived" }, + ); + expect(await workerInstalls(worker)).toEqual([]); + expect(await viewInstalls(gateway)).toEqual([]); + + // Through the worker's own socket: a gateway never asks a worker to download. + const lease = worker.cliBackground([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "19.0", + "--allow-download", + "--detach", + ]); + const downloading = expect.objectContaining({ + component: "19.0", + platform: "ios", + state: "downloading", + }); + await waitFor(async () => (await workerInstalls(worker)).length === 1, { + label: "the worker's status lists the install", + }); + expect(await workerInstalls(worker)).toEqual([downloading]); + await waitFor(async () => (await viewInstalls(gateway))?.length === 1, { + label: "the gateway's worker list shows the install", + }); + expect(await viewInstalls(gateway)).toEqual([downloading]); + + const granted = await lease.waitForExit(30_000); + expect(granted.code, granted.stderr).toBe(0); + expect(await workerInstalls(worker)).toEqual([]); + await waitFor(async () => (await viewInstalls(gateway))?.length === 0, { + label: "the gateway's worker list drops the install", + }); + }); +}); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index cb9848c48..8c6ca1c78 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1876,6 +1876,40 @@ describe("CLI: worker commands (ADR 0005 §8/§23)", () => { ); }); + it("prints each worker's installs in progress under it", async () => { + const output = outputCapture(); + const environment = output.environmentWith({ + clock: new FakeClock(61_000), + connectAdmin: async () => + fakeClient({ + listWorkers: () => + Promise.resolve({ + workers: [ + { + ...connectedWorker, + installs: [ + { + component: "26.4", + platform: "ios" as const, + since: 1_000, + state: "downloading" as const, + waiters: 2, + }, + ], + }, + { ...connectedWorker, id: "wrk_2", installs: [] }, + ], + }), + }), + }); + + await runCli(["worker", "list"], environment); + + expect(output.stdout).toContain( + "1 lease(s)\n Install ios 26.4: downloading for 60s, 2 waiters\nwrk_2 (mac-mini-1): connected", + ); + }); + it("says so plainly when no worker has ever connected", async () => { const output = outputCapture(); const environment = output.environmentWith({ connectAdmin: async () => fakeClient() }); @@ -2103,6 +2137,67 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = expect(output.stdout).toContain("Host: macOS 15.5 arm64; xcode 16.4 (16F6)\n"); }); + it("prints an install line while one runs and none after", async () => { + const install = { + component: "26.4", + platform: "ios" as const, + since: 1_000, + state: "downloading" as const, + waiters: 1, + }; + const print = async (installs: StatusGetOutput["installs"]) => { + const output = outputCapture(); + await runCli( + ["status"], + output.environmentWith({ + clock: new FakeClock(43_000), + connectAdmin: async () => + fakeClient({ getStatus: () => Promise.resolve({ ...EMPTY_STATUS, installs }) }), + }), + ); + return output.stdout; + }; + + expect(await print([install])).toContain("Install ios 26.4: downloading for 42s, 1 waiter\n"); + expect(await print([])).not.toContain("Install "); + }); + + it("prints a gateway's installs once each, naming the worker, not again under the worker", async () => { + const output = outputCapture(); + const install = { + component: "35", + platform: "android" as const, + since: 0, + state: "waiting" as const, + waiters: 3, + }; + const status: StatusGetOutput = { + ...EMPTY_STATUS, + daemon: { health: "running", mode: "gateway" }, + installs: [{ ...install, workerId: "wrk_1" }], + workers: [ + { + catalog: [], + connection: "connected", + devices: [], + drained: false, + id: "wrk_1", + installs: [install], + lastSeenAt: 1, + leases: [], + }, + ], + }; + const environment = output.environmentWith({ + connectAdmin: async () => fakeClient({ getStatus: () => Promise.resolve(status) }), + }); + + await runCli(["status"], environment); + + expect(output.stdout.match(/Install /g)).toHaveLength(1); + expect(output.stdout).toContain("Install android 35 on wrk_1: waiting for 0s, 3 waiters\n"); + }); + it("says worker on a worker, and leaves its devices and leases unqualified", async () => { const output = outputCapture(); const environment = output.environmentWith({ connectAdmin: async () => fakeClient() }); diff --git a/src/cli/index.ts b/src/cli/index.ts index 90770f639..5315b1dcf 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -1248,7 +1248,7 @@ async function runStatus( try { const status = await client.getStatus(); if (values.json) writeResult(environment, status); - else environment.stdout.write(`${formatStatus(status)}\n`); + else environment.stdout.write(`${formatStatus(status, environment.clock.now())}\n`); return 0; } finally { await client.close(); @@ -1555,7 +1555,7 @@ async function runDaemon( try { const status = await client.getStatus(); if (values.json) writeResult(environment, status); - else environment.stdout.write(`${formatStatus(status)}\n`); + else environment.stdout.write(`${formatStatus(status, environment.clock.now())}\n`); } finally { await client.close(); } @@ -1805,7 +1805,10 @@ async function runWorkerList( } const result = await client.listWorkers(); if (values.json) writeResult(environment, result); - else environment.stdout.write(`${formatWorkers(result.workers)}\n`); + else + environment.stdout.write( + `${formatWorkers(result.workers, { installsAt: environment.clock.now() })}\n`, + ); return 0; } @@ -1835,11 +1838,25 @@ async function runWorkerAction( * One line per worker, in the shape an operator scans: state first (that is the question), then * identity, then what it is carrying. `simlock worker list --json` is the machine-readable * answer, so this stays a summary rather than a dump. + * + * With `installsAt` (the time now), each worker's installs in progress follow it, indented. + * `simlock status` leaves it out: it lists the fleet's installs on their own lines, each naming + * its worker, the way it lists devices and leases. */ -function formatWorkers(workers: WorkerView[]): string { +function formatWorkers( + workers: WorkerView[], + options: { readonly installsAt?: number } = {}, +): string { if (workers.length === 0) return "No workers have connected to this gateway."; + const { installsAt } = options; return workers .map((worker) => { + const installs = + installsAt === undefined + ? "" + : (worker.installs ?? []) + .map((install) => `\n ${formatInstall(install, installsAt)}`) + .join(""); const label = worker.label === undefined ? worker.id : `${worker.id} (${worker.label})`; const state = worker.drained ? `${worker.connection}, drained` : worker.connection; const capacity = @@ -1853,11 +1870,22 @@ function formatWorkers(workers: WorkerView[]): string { : ` protocol ${worker.protocol.worker.min}-${worker.protocol.worker.max}` + ` vs gateway ${worker.protocol.gateway.min}-${worker.protocol.gateway.max}`; const host = worker.host === undefined ? "" : ` -- ${formatHost(worker.host)}`; - return `${label}: ${state} -- ${capacity}, ${String(worker.leases.length)} lease(s)${skew}${host}`; + return `${label}: ${state} -- ${capacity}, ${String(worker.leases.length)} lease(s)${skew}${host}${installs}`; }) .join("\n"); } +/** `Install ios 26.4: downloading for 42s, 2 waiters` -- platform, component, state, age, waiters. */ +function formatInstall( + install: NonNullable[number], + now: number, +): string { + const where = install.workerId === undefined ? "" : ` on ${install.workerId}`; + const ageSeconds = Math.max(0, Math.round((now - install.since) / 1000)); + const waiters = `${String(install.waiters)} waiter${install.waiters === 1 ? "" : "s"}`; + return `Install ${install.platform} ${install.component}${where}: ${install.state} for ${String(ageSeconds)}s, ${waiters}`; +} + function formatGibibytes(bytes: number): string { return `${(bytes / 1024 ** 3).toFixed(2)} GiB`; } @@ -1988,8 +2016,8 @@ function writeResult(environment: CliEnvironment, value: unknown): void { } // fallow-ignore-next-line complexity -- stable human status rendering is intentionally a single formatter. -function formatStatus(status: StatusGetOutput): string { - const { capacity, daemon, devices, host, leases, queueDepth, workers } = status; +function formatStatus(status: StatusGetOutput, now: number): string { + const { capacity, daemon, devices, host, installs, leases, queueDepth, workers } = status; const globalLine = `Running global: ${capacity.global.running} + ${capacity.global.reserved} reserved/${capacity.global.maxRunning}, warm ${capacity.global.warm}${capacity.global.overLimit ? " (over limit)" : ""}`; const capacityLines = (["ios", "android"] as const).map((platform) => { const usage = capacity[platform]; @@ -2035,6 +2063,7 @@ function formatStatus(status: StatusGetOutput): string { ...workerLines, ...deviceLines, ...leaseLines, + ...(installs ?? []).map((install) => formatInstall(install, now)), `Queue depth: ${queueDepth}`, ].join("\n"); } diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 012d3fe37..374ca6680 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -28,6 +28,7 @@ import { proposalSchema, statusCapacitySchema, statusDeviceSchema, + statusInstallsSchema, statusLeaseSchema, tokenRecordSchema, tokenRoleSchema, @@ -108,6 +109,12 @@ export const statusGet = defineOperation({ */ host: hostFactsSchema, queueDepth: z.number(), + /** + * ADR 0010 §3: the component installs waiting or running, the oldest first. A worker always + * sends it, empty when nothing is installing; a gateway lists its connected workers' + * installs, each with its `workerId`. Optional because an older daemon sends none. + */ + installs: statusInstallsSchema.optional(), /** * ADR 0005 §20: one entry per worker view, additive and gateway-only. Absent (not empty) * from a worker's answer -- a worker has no fleet, and an empty array would read as "a diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index cd70b8d4b..e6b874eda 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -702,6 +702,48 @@ const protocolRangeShapeSchema = z.object({ min: z.number().int(), max: z.number */ const workerConnectionStateSchema = z.enum(["connected", "disconnected", "incompatible"]); +// ---- installs in progress (ADR 0010 §3) --------------------------------------------------- + +const MAX_LISTED_INSTALLS = 16; +const MAX_INSTALL_COMPONENT_LENGTH = 64; + +/** + * One component install a daemon has waiting or running. A worker's list reaches the gateway as + * a claim (safety rule 10), so the bounds cut rather than refuse: an over-long list keeps its + * first (oldest) 16 entries and an over-long `component` its first 64 characters, and the view + * stays usable instead of failing its whole refresh over one field. + */ +const installInProgressSchema = z.object({ + platform: platformSchema, + /** As the daemon's driver named it: a version, or a word such as "newest". */ + component: z.string().transform((value) => value.slice(0, MAX_INSTALL_COMPONENT_LENGTH)), + /** `waiting` behind another install on its platform, or `downloading`. */ + state: z.enum(["waiting", "downloading"]), + /** When the first call for this install arrived. */ + since: z.number(), + /** How many calls are joined to it. */ + waiters: z.number().int().nonnegative(), +}); + +/** A list of at most `MAX_LISTED_INSTALLS` entries; a longer one is cut to its first ones. */ +function boundedInstalls(entry: Entry) { + return z.array(entry).transform((installs) => installs.slice(0, MAX_LISTED_INSTALLS)); +} + +/** A worker view's installs: the worker's own `status.get` list, copied (ADR 0010 §7). */ +const workerInstallsSchema = boundedInstalls(installInProgressSchema); + +/** `status.get`'s installs. On a gateway each entry names the worker it runs on. */ +export const statusInstallsSchema = boundedInstalls( + installInProgressSchema.extend({ workerId: z.string().optional() }), +); + +/** + * The bound above, for a producer that merges lists the schema checked one by one: a gateway's + * fleet list must itself fit, or the schema cuts it wherever the merge left it. + */ +export const INSTALL_LIST_LIMIT = MAX_LISTED_INSTALLS; + /** * What the gateway currently knows about one worker (ADR 0005's vocabulary table, §7, §31). * Rebuilt over the uplink, never persisted: a gateway restart re-derives every field from the @@ -741,7 +783,14 @@ export const workerViewSchema = z.object({ * worker whose `config.get` the gateway could not read (an incompatible one, or a call that * failed). */ - downloads: z.object({ policy: z.enum(["never", "on-request", "always"]) }).optional(), + downloads: z + .object({ + policy: z.enum(["never", "on-request", "always"]), + /** The worker's own `downloads.timeoutMs`, read with the policy (ADR 0010 §7). Optional + * so a gateway on an older build still parses a view. */ + timeoutMs: z.number().optional(), + }) + .optional(), /** * The worker's own `lease.maxTtlMs`, read once with `config.get` when the uplink connects * (and again on the periodic backstop tick, alongside the catalog and `downloads.policy` @@ -763,6 +812,9 @@ export const workerViewSchema = z.object({ /** ADR 0008 §8: the `host` block of the worker's last `status.get`. Absent for a worker the * gateway has not read status from, and for an `incompatible` one. */ host: hostFactsSchema.optional(), + /** ADR 0010 §7: the `installs` of the worker's last `status.get`. Empty for a worker whose + * status lists none, including one too old to list them. */ + installs: workerInstallsSchema.optional(), }); /** diff --git a/src/core/component-installer.test.ts b/src/core/component-installer.test.ts index 0441bd2e3..94c7de342 100644 --- a/src/core/component-installer.test.ts +++ b/src/core/component-installer.test.ts @@ -816,3 +816,71 @@ describe("ComponentInstaller", () => { ); }); }); + +describe("ComponentInstaller.inProgress", () => { + it("lists an install at the front of its queue that is still checking whether it is needed as waiting", async () => { + const harness = await createHarness(); + + void harness.installer.install(ios("27.0", { stillNeeded: () => new Promise(() => {}) })); + await flush(); + + expect(harness.installer.inProgress()).toEqual([ + { component: "27.0", platform: "ios", since: 1_000, state: "waiting", waiters: 1 }, + ]); + expect(installs(harness.ios)).toEqual([]); + }); + + it("lists an install whose driver returned and whose record is being written as downloading", async () => { + const harness = await createHarness({ + // A gate that never opens: the record write waits behind it. + decisions: { run: () => new Promise(() => {}) }, + }); + + void harness.installer.install(ios("27.0")); + await flush(); + + expect(installs(harness.ios)).toEqual(["27.0"]); + expect(harness.installer.inProgress()).toEqual([ + { component: "27.0", platform: "ios", since: 1_000, state: "downloading", waiters: 1 }, + ]); + }); + + it("does not list a waiting install whose only call timed out, though it is still in its queue", async () => { + const harness = await createHarness({ clock: new ManualClock() }); + harness.ios.holdInstalls(); + + void harness.installer.install(ios("27.0")); + void harness.installer.install(ios("28.0")).catch(() => undefined); + await flush(); + expect(harness.installer.inProgress().map((install) => install.component)).toEqual([ + "27.0", + "28.0", + ]); + (harness.clock as ManualClock).fire(1); + await flush(); + + expect(harness.installer.inProgress().map((install) => install.component)).toEqual(["27.0"]); + }); + + it("lists the 16 oldest installs across platforms, oldest first, when more are in progress", async () => { + const harness = await createHarness({ + drivers: (clock) => [ + new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }), + new FakeDriver({ availableOsVersions: [], clock, platform: "android" }), + ], + }); + for (const driver of harness.drivers) driver.holdInstalls(); + + // Alternating platforms, so the oldest are not the first ones of any one queue. + for (let index = 0; index < 20; index += 1) { + const platform = index % 2 === 0 ? "ios" : "android"; + void harness.installer.install({ component: `c${String(index)}`, platform }); + harness.clock.advance(1_000); + } + await flush(); + + expect(harness.installer.inProgress().map((install) => install.component)).toEqual( + Array.from({ length: 16 }, (_, index) => `c${String(index)}`), + ); + }); +}); diff --git a/src/core/component-installer.ts b/src/core/component-installer.ts index e893a25af..fbf93a6b8 100644 --- a/src/core/component-installer.ts +++ b/src/core/component-installer.ts @@ -52,6 +52,25 @@ export interface ComponentInstallerOptions { readonly timeoutMs: number; } +/** + * One install `status.get` lists (ADR 0010 §3). `waiting`: queued behind another install on its + * platform, or at the front checking whether it is still needed and fits on disk. `downloading`: + * the driver's installer is running, or has returned and its record is being written. + */ +export interface ComponentInstallInProgress { + readonly platform: Platform; + /** Carried unread, as the driver named it. */ + readonly component: string; + readonly state: "waiting" | "downloading"; + /** When the first call for this install arrived. */ + readonly since: number; + /** How many calls are joined to it. */ + readonly waiters: number; +} + +/** `inProgress()` lists at most this many installs, the oldest first. */ +const MAX_LISTED_INSTALLS = 16; + /** Every call still open when the daemon stops rejects with this; nothing is resumed. */ export class ComponentInstallerClosedError extends Error { constructor() { @@ -76,6 +95,8 @@ interface Install { readonly requesterId: string | undefined; /** The calls still open on it. A call leaves this list exactly when it settles. */ readonly calls: InstallCall[]; + /** When the call that created it arrived. */ + readonly since: number; state: InstallState; abort: AbortController | undefined; } @@ -108,7 +129,6 @@ export class ComponentInstaller { constructor(private readonly options: ComponentInstallerOptions) {} - // fallow-ignore-next-line unused-class-member -- called through the acquisition coordinator's components port. install(request: ComponentInstallRequest): Promise { if (this.#closed) return Promise.reject(new ComponentInstallerClosedError()); return new Promise((resolve, reject) => { @@ -133,6 +153,32 @@ export class ComponentInstaller { }); } + /** + * The installs waiting or running, read from the queues themselves (architecture rule 12): + * the oldest `MAX_LISTED_INSTALLS`, oldest first. An install no call waits on any more is not + * listed: it has ended for everyone who asked, even while it is still in its queue. + */ + // fallow-ignore-next-line unused-class-member -- called through the dispatcher's `components` option, a `Pick` of this class. + inProgress(): readonly ComponentInstallInProgress[] { + const listed: ComponentInstallInProgress[] = []; + for (const queue of this.#queues.values()) { + for (const install of queue) { + if (install.state === "ended" || install.calls.length === 0) continue; + listed.push({ + component: install.component, + platform: install.platform, + since: install.since, + state: + install.state === "running" || install.state === "recording" + ? "downloading" + : "waiting", + waiters: install.calls.length, + }); + } + } + return listed.sort((a, b) => a.since - b.since).slice(0, MAX_LISTED_INSTALLS); + } + /** * Ends the running installs through their `AbortSignal`, rejects every open call, and resolves * once each driver run has returned. Nothing is resumed after a restart. @@ -169,6 +215,7 @@ export class ComponentInstaller { component: request.component, platform: request.platform, requesterId: request.requesterId, + since: this.options.clock.now(), state: "waiting", }; queue.push(install); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 4b1958fcd..6ac01b5ea 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -4,8 +4,11 @@ import { testComponentWiring } from "../core/test-wiring.js"; import { EventBus, type EventEnvelope, EventHistory } from "../bus/index.js"; import { CleanupReaper, + ComponentInstaller, type Config, + DiskSpaceGuard, Doctor, + DriverCatalog, FakeDriver, type HostFacts, HostFactsReader, @@ -13,6 +16,7 @@ import { Nuke, PassthroughRefusedError, Registry, + SerializedDecision, } from "../core/index.js"; import { OPERATIONS } from "../contract/index.js"; import type { FakeDriverOptions } from "../core/fake-driver.js"; @@ -112,6 +116,8 @@ async function buildDispatcher( readonly hostFacts?: () => HostFacts; /** Replaces the capacity block, for a test about one strategy's options. */ readonly capacity?: Config["capacity"]; + /** The installer `status.get` lists installs from; none by default. */ + readonly components?: Pick; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -207,6 +213,7 @@ async function buildDispatcher( capacity: engine, catalog: overrides.catalog ?? engine, clock, + ...(overrides.components === undefined ? {} : { components: overrides.components }), config, doctor, eventHistory: resolveEventHistoryOverride(eventBus, filesystem, overrides.eventHistory), @@ -965,6 +972,106 @@ describe("Dispatcher: the download policy clamp applies regardless of caller", ( }); }); +describe("Dispatcher: status.get installs in progress", () => { + const installTimeoutMs = 60_000; + + /** A dispatcher whose `status.get` reads a real installer over an iOS fake driver that holds + * every install until the test releases it. */ + async function withInstaller() { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + driver.holdInstalls(); + const installer = new ComponentInstaller({ + clock, + decisions: new SerializedDecision(), + diskSpace: new DiskSpaceGuard(), + drivers: new DriverCatalog([driver]), + eventBus: new EventBus(clock), + filesystem: new MemoryFilesystem(), + registry: { recordComponent: () => Promise.resolve() }, + timeoutMs: installTimeoutMs, + }); + const { dispatcher } = await buildDispatcher({ clock, components: installer }); + const installs = async () => (await dispatcher.dispatch("status.get", {}, session())).installs; + return { clock, driver, installer, installs }; + } + + it("lists a running install as downloading and one behind it on the same platform as waiting", async () => { + const { clock, installer, installs } = await withInstaller(); + + void installer.install({ component: "27.0", platform: "ios" }); + await flushPromises(); + clock.advance(2_000); + void installer.install({ component: "28.0", platform: "ios" }); + await flushPromises(); + + expect(await installs()).toEqual([ + { component: "27.0", platform: "ios", since: 1_000, state: "downloading", waiters: 1 }, + { component: "28.0", platform: "ios", since: 3_000, state: "waiting", waiters: 1 }, + ]); + }); + + it("lists an install three calls joined once, with waiters: 3", async () => { + const { installer, installs } = await withInstaller(); + + for (let call = 0; call < 3; call += 1) { + void installer.install({ component: "27.0", platform: "ios" }); + } + await flushPromises(); + + expect(await installs()).toEqual([ + { component: "27.0", platform: "ios", since: 1_000, state: "downloading", waiters: 3 }, + ]); + }); + + it("lists no install once it has succeeded", async () => { + const { driver, installer, installs } = await withInstaller(); + const call = installer.install({ component: "27.0", platform: "ios" }); + await flushPromises(); + expect(await installs()).toHaveLength(1); + + driver.releaseInstalls(); + await call; + + expect(await installs()).toEqual([]); + }); + + it("lists no install once it has failed", async () => { + const { driver, installer, installs } = await withInstaller(); + driver.releaseInstalls(); + driver.failOn("installComponent", 1, new Error("installer exited 1")); + const call = installer.install({ component: "27.0", platform: "ios" }); + + await expect(call).rejects.toThrow("installer exited 1"); + expect(await installs()).toEqual([]); + }); + + it("lists no install once it has timed out, running or still waiting", async () => { + const { clock, installer, installs } = await withInstaller(); + const running = installer.install({ component: "27.0", platform: "ios" }); + const waiting = installer.install({ component: "28.0", platform: "ios" }); + await flushPromises(); + expect(await installs()).toHaveLength(2); + + clock.advance(installTimeoutMs); + await expect(running).rejects.toMatchObject({ name: "ComponentInstallTimeoutError" }); + await expect(waiting).rejects.toMatchObject({ name: "ComponentInstallTimeoutError" }); + + expect(await installs()).toEqual([]); + }); + + it("answers an empty list when nothing is installing", async () => { + const { installs } = await withInstaller(); + + expect(await installs()).toEqual([]); + }); +}); + +/** Lets every settled promise and queued continuation run. */ +async function flushPromises(): Promise { + for (let count = 0; count < 100; count += 1) await Promise.resolve(); +} + describe("Dispatcher: status.get host facts", () => { it("reports operating system, version, architecture, and every driver's tool versions", async () => { const hostFacts = new HostFactsReader({ diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 93cbf41ee..a6319c900 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import type { EventHistory } from "../bus/index.js"; import { type CleanupReaper, + type ComponentInstaller, type Config, type DeviceRecord, type DeviceRequest, @@ -81,6 +82,11 @@ export interface DispatcherOptions { readonly capacity: CapacityReader; readonly catalog: CatalogReader; readonly clock: Clock; + /** + * `status.get`'s installs in progress (ADR 0010 §3), read from the installer's own queues. + * Optional so tests that never install need not build one; without it the list is empty. + */ + readonly components?: Pick; readonly config: Config; readonly doctor?: Doctor; /** Answers `events.replay`: the ring, or the event file for a `sinceTs`. */ @@ -289,6 +295,7 @@ export class Dispatcher { // #117 is what makes `gateway` mean something beyond this field. daemon: { health: this.options.health(), mode: this.options.config.mode }, host: this.options.hostFacts(), + installs: [...(this.options.components?.inProgress() ?? [])], leases: [...snapshot.leases], queueDepth: this.options.queue.queueDepth, }; diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 4dd5185d1..96992efbb 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -347,6 +347,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise; readonly doctor?: Doctor; /** What `events.replay` answers from; see `EventHistory`. */ readonly eventHistory: Pick; @@ -282,6 +285,7 @@ function buildDispatcher( capacity: options.capacity, catalog: options.catalog, clock: options.clock, + ...(options.components === undefined ? {} : { components: options.components }), config: options.config, ...(options.doctor === undefined ? {} : { doctor: options.doctor }), // The `operation` log line's error code: the same classifier this server answers with. @@ -372,7 +376,6 @@ export class DaemonServer { } } - // fallow-ignore-next-line unused-class-member -- retained as a daemon compatibility facade. get socketPath(): string { return this.options.host.endpoint; } diff --git a/src/gateway/aggregate.test.ts b/src/gateway/aggregate.test.ts index 46e0c194e..57e81ff83 100644 --- a/src/gateway/aggregate.test.ts +++ b/src/gateway/aggregate.test.ts @@ -272,6 +272,67 @@ describe("aggregateStatus", () => { expect(status).toMatchObject({ daemon: { health: "starting" }, queueDepth: 0 }); expect(status.workers?.[0]).toMatchObject({ health: "failed", queueDepth: 7 }); }); + + describe("installs (ADR 0010 §3)", () => { + function install(component: string, since: number) { + return { + component, + platform: "ios" as const, + since, + state: "downloading" as const, + waiters: 1, + }; + } + + it("lists each connected worker's installs with its workerId", () => { + const status = aggregateStatus( + [ + view({ id: "wrk_a", installs: [install("26.4", 10)] }), + view({ id: "wrk_b", installs: [install("35", 5)] }), + view({ id: "wrk_c" }), + ], + { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, + ); + + expect(status.installs).toEqual([ + { ...install("35", 5), workerId: "wrk_b" }, + { ...install("26.4", 10), workerId: "wrk_a" }, + ]); + }); + + it("leaves a disconnected worker's last-known installs out", () => { + const status = aggregateStatus( + [view({ connection: "disconnected", id: "wrk_a", installs: [install("26.4", 10)] })], + { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, + ); + + expect(status.installs).toEqual([]); + }); + + it("keeps the 16 oldest across the fleet, so the list fits the contract's bound", () => { + const status = aggregateStatus( + [ + view({ + id: "wrk_a", + installs: Array.from({ length: 10 }, (_, index) => + install(`a${String(index)}`, index * 2 + 1), + ), + }), + view({ + id: "wrk_b", + installs: Array.from({ length: 10 }, (_, index) => + install(`b${String(index)}`, index * 2), + ), + }), + ], + { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, + ); + + expect(status.installs?.map((entry) => entry.since)).toEqual( + Array.from({ length: 16 }, (_, index) => index), + ); + }); + }); }); describe("aggregateCatalog", () => { diff --git a/src/gateway/aggregate.ts b/src/gateway/aggregate.ts index d59551dfa..db8ee682c 100644 --- a/src/gateway/aggregate.ts +++ b/src/gateway/aggregate.ts @@ -5,7 +5,12 @@ */ import type { z } from "zod"; -import { CATALOG_LIST_LIMITS, OPERATIONS, type Platform } from "../contract/index.js"; +import { + CATALOG_LIST_LIMITS, + INSTALL_LIST_LIMIT, + OPERATIONS, + type Platform, +} from "../contract/index.js"; import type { FleetLeaseIndex } from "./lease-index.js"; import type { WorkerView } from "./worker-registry.js"; @@ -75,6 +80,7 @@ export function aggregateStatus( capacity: sumCapacity(views.filter((view) => view.connection === "connected")), daemon: { health: options.health, mode: "gateway" }, host: options.host, + installs: fleetInstalls(views), devices: views.flatMap((view) => view.devices.map((device) => ({ ...device, workerId: view.id })), ), @@ -90,6 +96,19 @@ export function aggregateStatus( }; } +/** + * ADR 0010 §3/§7: the connected workers' installs, each naming its worker. Connected only, like + * capacity: what a machine that dropped off was installing is a last-known fact, not one in + * progress. The fleet list has the same bound as one worker's, so it keeps the oldest. + */ +function fleetInstalls(views: readonly WorkerView[]): NonNullable { + return views + .filter((view) => view.connection === "connected") + .flatMap((view) => (view.installs ?? []).map((install) => ({ ...install, workerId: view.id }))) + .sort((a, b) => a.since - b.since) + .slice(0, INSTALL_LIST_LIMIT); +} + function sumCapacity(views: readonly WorkerView[]): StatusCapacity { const capacity: StatusCapacity = { android: { ...EMPTY_PLATFORM_CAPACITY }, diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index acae03b66..653faa117 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -262,6 +262,27 @@ describe("GatewayDispatcher", () => { expect(status.leases).toEqual([expect.objectContaining({ workerId: "wrk_1" })]); }); + it("lists each worker's installs on status.get with its workerId, and on its view in worker.list", async () => { + const { dispatcher, workers } = harness(); + const install = { + component: "26.4", + platform: "ios" as const, + since: 500, + state: "downloading" as const, + waiters: 2, + }; + workers.connected("wrk_1", undefined, "0.3.0"); + workers.connected("wrk_2", undefined, "0.3.0"); + workers.refresh("wrk_1", { installs: [install] }); + workers.refresh("wrk_2", { installs: [] }); + + const status = await dispatcher.dispatch("status.get", {}, session()); + const list = await dispatcher.dispatch("worker.list", {}, session()); + + expect(status.installs).toEqual([{ ...install, workerId: "wrk_1" }]); + expect(list.workers.map((worker) => worker.installs)).toEqual([[install], []]); + }); + it("reports its own host with no tools on status.get, and each worker's on its view", async () => { const { dispatcher, workers } = harness(); workers.connected("wrk_1", "mac-mini-1", "0.3.0"); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 3860b4c59..5a1b387eb 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -411,6 +411,152 @@ describe("GatewayService", () => { await harness.service.stop(); }); + describe("installs in progress on the view (ADR 0010 §7)", () => { + const install = { + component: "26.4", + platform: "ios" as const, + since: 500, + state: "downloading" as const, + waiters: 1, + }; + + async function joined(worker: ScriptedWorkerClient) { + const harness = fleet(); + await harness.service.start(); + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(worker.subscribed).toBe(true)); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.downloads).toBeDefined(), + ); + return harness; + } + + it("shows a worker's install after component.install-started and drops it after component.installed, without waiting for the periodic refresh", async () => { + const worker = new ScriptedWorkerClient(); + const harness = await joined(worker); + expect(harness.service.workers.view("wrk_1")?.installs).toEqual([]); + + worker.status = statusFixture({ installs: [install] }); + worker.pushEvent({ event: "component.install-started" }); + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.installs).toEqual([install]), + ); + + worker.status = statusFixture({ installs: [] }); + worker.pushEvent({ event: "component.installed" }); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.installs).toEqual([])); + + await harness.service.stop(); + }); + + it("drops a worker's install after component.install-failed, without waiting for the periodic refresh", async () => { + const worker = new ScriptedWorkerClient(); + worker.status = statusFixture({ installs: [install] }); + const harness = await joined(worker); + expect(harness.service.workers.view("wrk_1")?.installs).toEqual([install]); + + worker.status = statusFixture({ installs: [] }); + worker.pushEvent({ event: "component.install-failed" }); + + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.installs).toEqual([])); + await harness.service.stop(); + }); + + it("lists the new runtime in the view's catalog after component.installed, without waiting for the periodic refresh", async () => { + const worker = new ScriptedWorkerClient(); + worker.catalog = catalogFixture([ + { models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }, + ]); + const harness = await joined(worker); + + worker.catalog = catalogFixture([ + { models: ["iPhone 17"], platform: "ios", runtimes: ["26.0", "26.4"] }, + ]); + worker.pushEvent({ event: "component.installed" }); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.catalog[0]?.runtimes).toEqual([ + "26.0", + "26.4", + ]), + ); + await harness.service.stop(); + }); + + it("re-reads the catalog for a component.installed that arrives while another refresh is in flight", async () => { + const worker = new ScriptedWorkerClient(); + worker.catalog = catalogFixture([ + { models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }, + ]); + const harness = await joined(worker); + + worker.catalog = catalogFixture([ + { models: ["iPhone 17"], platform: "ios", runtimes: ["26.0", "26.4"] }, + ]); + // The first starts a refresh without the catalog; the second queues behind it. + worker.pushEvent({ event: "lease.granted" }); + worker.pushEvent({ event: "component.installed" }); + + await vi.waitFor(() => + expect(harness.service.workers.view("wrk_1")?.catalog[0]?.runtimes).toEqual([ + "26.0", + "26.4", + ]), + ); + await harness.service.stop(); + }); + + it("yields a view with no installs, still connected, for a worker whose status has no installs field", async () => { + const worker = new ScriptedWorkerClient(); + const { installs: _absent, ...withoutInstalls } = statusFixture(); + worker.status = { ...withoutInstalls, queueDepth: 3 }; + + const harness = await joined(worker); + + const view = harness.service.workers.view("wrk_1"); + expect(view?.queueDepth).toBe(3); + expect(view?.installs).toEqual([]); + expect(view?.connection).toBe("connected"); + await harness.service.stop(); + }); + + it("truncates a worker's installs to 16 entries and an over-long component to 64 characters, rather than storing them as sent", async () => { + const worker = new ScriptedWorkerClient(); + worker.status = statusFixture({ + installs: Array.from({ length: 20 }, (_, index) => ({ + ...install, + component: `${String(index).padStart(2, "0")}${"x".repeat(100)}`, + since: index, + })), + }); + + const harness = await joined(worker); + + const installs = harness.service.workers.view("wrk_1")?.installs ?? []; + expect(installs).toHaveLength(16); + expect(installs.map((entry) => entry.component)).toEqual( + Array.from({ length: 16 }, (_, index) => + `${String(index).padStart(2, "0")}${"x".repeat(100)}`.slice(0, 64), + ), + ); + expect(harness.service.workers.view("wrk_1")?.connection).toBe("connected"); + await harness.service.stop(); + }); + + it("carries the worker's own downloads.timeoutMs on the view", async () => { + const worker = new ScriptedWorkerClient(); + worker.downloadTimeoutMs = 45 * 60_000; + + const harness = await joined(worker); + + expect(harness.service.workers.view("wrk_1")?.downloads).toEqual({ + policy: "on-request", + timeoutMs: 45 * 60_000, + }); + await harness.service.stop(); + }); + }); + describe("warning on a worker's lower lease.maxTtlMs (ADR 0005 §15)", () => { it("warns once the joining worker's own config.get reports a lower cap", async () => { const logger = new RecordingLogger(); diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index 8f3fbc3ee..37ee5eec0 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -25,8 +25,8 @@ import type { StatusGetOutput, } from "../admin/index.js"; import { SimlockError } from "../admin/index.js"; -import { PROTOCOL_VERSION_RANGE } from "../contract/index.js"; -import type { OPERATIONS, platformCatalogSchema } from "../contract/index.js"; +import { OPERATIONS, PROTOCOL_VERSION_RANGE } from "../contract/index.js"; +import type { platformCatalogSchema } from "../contract/index.js"; type CatalogOutput = z.infer<(typeof OPERATIONS)["catalog.get"]["output"]>; type PlatformCatalog = z.infer; @@ -210,6 +210,8 @@ export class ScriptedWorkerClient { catalog: CatalogOutput = catalogFixture([]); /** What `config.get` reports; the view carries it for display (ADR 0009 §3). */ downloadPolicy: DownloadPolicy = "on-request"; + /** What `config.get` reports for `downloads.timeoutMs` (ADR 0010 §7). */ + downloadTimeoutMs = 20 * 60_000; /** What `config.get` reports for `lease.maxTtlMs` (ADR 0005 §15) -- the routing-adjacent * counterpart to `downloadPolicy` above. Defaults comfortably above every gateway cap this * suite's fixtures use, so a test that never sets it cannot accidentally trip the new warning; @@ -298,7 +300,9 @@ export class ScriptedWorkerClient { this.calls.push("status.get"); if (this.hangingCalls.has("status.get")) return new Promise(() => {}); this.#throwIfFailing(); - return this.status; + // Parsed through the operation's output schema, as the real client parses every answer: + // that parse is where the contract bounds what a worker claims (safety rule 10). + return OPERATIONS["status.get"].output.parse(this.status); } // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. @@ -379,13 +383,16 @@ export class ScriptedWorkerClient { // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. async getConfig(): Promise<{ - readonly downloads: { readonly policy: DownloadPolicy }; + readonly downloads: { readonly policy: DownloadPolicy; readonly timeoutMs: number }; readonly lease: { readonly maxTtlMs: number }; }> { this.calls.push("config.get"); if (this.hangingCalls.has("config.get")) return new Promise(() => {}); this.#throwIfFailing(); - return { downloads: { policy: this.downloadPolicy }, lease: { maxTtlMs: this.leaseMaxTtlMs } }; + return { + downloads: { policy: this.downloadPolicy, timeoutMs: this.downloadTimeoutMs }, + lease: { maxTtlMs: this.leaseMaxTtlMs }, + }; } async subscribeEvents( diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index 02dca6bba..7afce5f08 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -6,11 +6,11 @@ * (`connectSimlockAdmin`), which is the whole reason the fleet needs no second API. What it * does with that client is exactly what §7 prescribes -- `status.get`, `list.get`, * `catalog.get` and `events.subscribe` on connect, a refresh on every worker event that can - * change capacity or leases, and a periodic refresh as a backstop -- plus §22's republishing of + * change capacity, leases or installs (ADR 0010 §7), and a periodic refresh as a backstop -- plus §22's republishing of * those events onto the gateway's own bus with `workerId` added. * * One call §7 does not name is here too: `config.get`, read once per session for the worker's - * `downloads.policy` and `lease.maxTtlMs`. The policy is shown on the view for display only: + * `downloads.policy`, `downloads.timeoutMs` and `lease.maxTtlMs`. The policy is shown on the view for display only: * routing counts installed runtimes and never reads it (ADR 0009 §3). Neither changes without a * worker restart -- which is a new session anyway -- and the uplink session is admin, so the * gateway may read it. @@ -23,7 +23,7 @@ import type { SimlockAdminClient } from "../admin/index.js"; import { connectSimlockAdmin } from "../admin/index.js"; import type { AcceptedUplink, Clock, IpcConnection, Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; -import type { WorkerRegistry } from "./worker-registry.js"; +import type { WorkerRegistry, WorkerViewSnapshot } from "./worker-registry.js"; /** * How long the gateway waits for one round trip to a worker before giving up on it. @@ -116,7 +116,8 @@ export class WorkerLink { #unsubscribeEvents: (() => Promise) | undefined; #closed = false; #refreshing = false; - #refreshQueued = false; + /** The one follow-up refresh queued behind the one in flight, if any. */ + #queuedRefresh: RefreshOptions | undefined; /** P1/C-1: consecutive `status.get` timeouts, reset to 0 the instant any `status.get` answers * (inside `#rebuildView`) rather than only once a whole refresh completes -- see * `MAX_CONSECUTIVE_REFRESH_TIMEOUTS`'s comment for why liveness is judged on that one call. */ @@ -275,11 +276,11 @@ export class WorkerLink { * its capacity changed) must not become a burst of round trips, but the *last* event in a * burst must still be reflected. */ - async refresh(options: { readonly includeCatalog?: boolean } = {}): Promise { + async refresh(options: RefreshOptions = {}): Promise { const client = this.#client; if (client === undefined || this.#closed) return; if (this.#refreshing) { - this.#refreshQueued = true; + this.#queuedRefresh = mergeQueuedRefresh(this.#queuedRefresh, options); return; } this.#refreshing = true; @@ -319,10 +320,9 @@ export class WorkerLink { } } finally { this.#refreshing = false; - if (this.#refreshQueued && !this.#closed) { - this.#refreshQueued = false; - void this.refresh(); - } + const queued = this.#queuedRefresh; + this.#queuedRefresh = undefined; + if (queued !== undefined && !this.#closed) void this.refresh(queued); } } @@ -356,23 +356,11 @@ export class WorkerLink { // overwriting a fresh view with a stale one for up to `WORKER_CALL_TIMEOUT_MS`. if (this.#closed || (this.options.isCurrentLink?.() ?? true) === false) return; this.options.registry.refresh(this.workerId, { - capacity: status.capacity, + ...viewStatus(status), devices: viewDevicesSchema.parse(devices), - health: status.daemon.health, - host: status.host, - leases: status.leases, - queueDepth: status.queueDepth, version: client.daemonVersion, ...(catalog === undefined ? {} : { catalog: catalog.platforms }), - ...(config === undefined - ? {} - : { - downloads: { policy: config.downloads.policy }, - // ADR 0005 §15: the one other field this gateway keeps out of a worker's config, - // alongside `downloads.policy` above -- `WorkerRegistry#refresh` is where it is - // compared against the gateway's own `lease.maxTtlMs` and warned about. - lease: { maxTtlMs: config.lease.maxTtlMs }, - }), + ...(config === undefined ? {} : viewConfig(config)), }); } @@ -474,7 +462,9 @@ export class WorkerLink { // `EventMap` has never heard of. Forwarding it is better than dropping it -- the envelope // is what `events.replay` returns, and a consumer that knows the name gets it either way. this.options.eventBus.emit(envelope.event as EventName, payload as never, envelope.module); - if (changesCapacityOrLeases(envelope.event)) void this.refresh(); + // ADR 0010 §7: an installed component is a new catalog entry, so that refresh re-reads it. + if (changesCapacityOrLeases(envelope.event)) + void this.refresh({ includeCatalog: envelope.event === "component.installed" }); } } @@ -499,9 +489,61 @@ const GATEWAY_OWN_EVENTS: ReadonlySet = new Set([ * about a lease or a device is, by construction, about something a view reports -- and a list * would silently miss the next one added to `EventMap`. The cost of being generous is one * coalesced round trip; the cost of missing one is a view that stays wrong until the next tick. + * + * ADR 0010 §7 adds the three install events by name: the view lists the worker's installs in + * progress, and an install that starts or ends changes that list. */ function changesCapacityOrLeases(event: string): boolean { - return event.startsWith("lease.") || event.startsWith("device."); + return event.startsWith("lease.") || event.startsWith("device.") || INSTALL_EVENTS.has(event); +} + +const INSTALL_EVENTS: ReadonlySet = new Set([ + "component.install-started", + "component.installed", + "component.install-failed", +]); + +interface RefreshOptions { + readonly includeCatalog?: boolean; +} + +/** One queued refresh stands for every request that queued; it reads the catalog when any of + * them asked for it. */ +function mergeQueuedRefresh( + queued: RefreshOptions | undefined, + next: RefreshOptions, +): RefreshOptions { + return { includeCatalog: queued?.includeCatalog === true || next.includeCatalog === true }; +} + +/** What a worker's view keeps of its `status.get`. */ +function viewStatus( + status: Awaited>, +): Pick { + return { + capacity: status.capacity, + health: status.daemon.health, + host: status.host, + // ADR 0010 §7: copied as the worker lists them, already bounded by the contract's parse + // (safety rule 10). A worker too old to list installs reports none. + installs: status.installs ?? [], + leases: status.leases, + queueDepth: status.queueDepth, + }; +} + +/** The few keys of a worker's config its view keeps. */ +function viewConfig( + config: Awaited>, +): Pick { + return { + // ADR 0010 §7: the worker's own install budget, read with its policy. + downloads: { policy: config.downloads.policy, timeoutMs: config.downloads.timeoutMs }, + // ADR 0005 §15: the one other field this gateway keeps out of a worker's config, + // alongside `downloads` -- `WorkerRegistry#refresh` is where it is compared against the + // gateway's own `lease.maxTtlMs` and warned about. + lease: { maxTtlMs: config.lease.maxTtlMs }, + }; } const defaultConnect: WorkerClientFactory = (connection, principal) => diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index 8021e19ca..3984978e0 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -30,6 +30,7 @@ export type WorkerViewSnapshot = Pick< | "downloads" | "health" | "host" + | "installs" | "lease" | "leases" | "queueDepth" From ea44bf2a204c42bbefd238bd75f57a350c5a935f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 13:08:15 +0200 Subject: [PATCH 2/3] fix(gateway,core,docs): a worker that drops off lists no installs; review fixes --- docs/CLI.md | 8 +++-- docs/HTTP-API.md | 10 +++--- src/cli/index.test.ts | 19 ++++++++++- src/contract/operations.test.ts | 51 ++++++++++++++++++++++++++++ src/core/component-installer.test.ts | 6 ++-- src/core/component-installer.ts | 6 ++-- src/gateway/aggregate.test.ts | 9 ----- src/gateway/aggregate.ts | 7 ++-- src/gateway/service.test.ts | 6 ++-- src/gateway/worker-link.ts | 14 ++++---- src/gateway/worker-registry.test.ts | 31 ++++++++++++++++- src/gateway/worker-registry.ts | 10 ++++-- 12 files changed, 139 insertions(+), 38 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 325d18afe..5fe64eed8 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -821,10 +821,12 @@ why its Android catalog looks thin, trimmed to one worker: worker's own effective config, read when its uplink connects, again on every periodic refresh, and after the worker installs a component. The policy is shown for reference; routing does not read it, since no -lease request through a gateway starts a download. `installs` lists the +download is started through a gateway. `installs` lists the component installs waiting or running on that worker, whoever started them, -in the shape [`simlock status`](#simlock-status) describes; it changes as -soon as an install starts or ends there. `catalog` is what that +in the shape [`simlock status`](#simlock-status) describes. It is re-read +when an install on that worker starts, finishes or fails, and on every +periodic refresh, so an install queued behind another may appear only then. +A disconnected or incompatible worker lists none. `catalog` is what that worker can lease, each model with the runtimes it pairs with, and lists a newly installed component as soon as its install ends. `host` is the machine: operating system, its version, CPU architecture, and the version of diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index ea0113b54..625e5e87b 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -753,12 +753,14 @@ simulated (hence the thin Android catalog), trimmed to one worker: `downloads.policy` and `downloads.timeoutMs` are that worker's own effective config, read when its uplink connects, again on every periodic refresh, and after the worker installs a component. The policy is shown for reference; -routing does not read it, since no lease request through a gateway starts a -download. +routing does not read it, since no download is started through a gateway. `installs` is the worker's own `installs` list from its -[`GET /v1/status`](#get-v1status), refreshed as soon as an install starts or -ends there. A worker that does not send one shows an empty list. +[`GET /v1/status`](#get-v1status). It is re-read when an install on that +worker starts, finishes or fails, and on every periodic refresh, so an +install queued behind another may appear only then. A worker that does not +send one shows an empty list; a disconnected or incompatible worker shows +none. `catalog` is what that worker can lease, each model with the runtimes it pairs with, and lists a newly installed component as soon as its install diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 8c6ca1c78..ef937f7fc 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1897,7 +1897,20 @@ describe("CLI: worker commands (ADR 0005 §8/§23)", () => { }, ], }, - { ...connectedWorker, id: "wrk_2", installs: [] }, + { + ...connectedWorker, + id: "wrk_2", + installs: [ + { + component: "35", + platform: "android" as const, + since: 31_000, + state: "waiting" as const, + waiters: 1, + }, + ], + }, + { ...connectedWorker, id: "wrk_3", installs: [] }, ], }), }), @@ -1908,6 +1921,10 @@ describe("CLI: worker commands (ADR 0005 §8/§23)", () => { expect(output.stdout).toContain( "1 lease(s)\n Install ios 26.4: downloading for 60s, 2 waiters\nwrk_2 (mac-mini-1): connected", ); + expect(output.stdout).toContain( + "1 lease(s)\n Install android 35: waiting for 30s, 1 waiter\nwrk_3 (mac-mini-1): connected", + ); + expect(output.stdout.match(/Install /g)).toHaveLength(2); }); it("says so plainly when no worker has ever connected", async () => { diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index c01602768..f4228a7ff 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -299,6 +299,57 @@ describe("operation input/output round trips", () => { expect(OPERATIONS["status.get"].output.parse(status)).toBeDefined(); }); + it("status.get: cuts installs to their first 16 and each component to 64 characters, on the status and on a worker view", () => { + const installs = Array.from({ length: 20 }, (_, index) => ({ + component: `${String(index).padStart(2, "0")}${"x".repeat(100)}`, + platform: "ios", + since: index, + state: "waiting", + waiters: 1, + })); + const cut = installs + .slice(0, 16) + .map((install) => ({ ...install, component: install.component.slice(0, 64) })); + const capacityEntry = { + running: 0, + maxRunning: 1, + reserved: 0, + overLimit: false, + limit: 1, + warm: 0, + used: 0, + }; + + const parsed = OPERATIONS["status.get"].output.parse({ + capacity: { + android: capacityEntry, + global: { running: 0, maxRunning: 1, reserved: 0, overLimit: false, warm: 0 }, + ios: capacityEntry, + }, + daemon: { health: "running", mode: "gateway" }, + devices: [], + host: { os: "Linux", osVersion: "6.8.0", arch: "x64", tools: [] }, + installs, + leases: [], + queueDepth: 0, + workers: [ + { + catalog: [], + connection: "connected", + devices: [], + drained: false, + id: "wrk_1", + installs, + lastSeenAt: 1, + leases: [], + }, + ], + }); + + expect(parsed.installs).toEqual(cut); + expect(parsed.workers?.[0]?.installs).toEqual(cut); + }); + it("status.get: round-trips a gateway's aggregate, workers and all (ADR 0005 §20)", () => { const capacityEntry = { running: 1, diff --git a/src/core/component-installer.test.ts b/src/core/component-installer.test.ts index 94c7de342..a1830f0f5 100644 --- a/src/core/component-installer.test.ts +++ b/src/core/component-installer.test.ts @@ -845,20 +845,22 @@ describe("ComponentInstaller.inProgress", () => { ]); }); - it("does not list a waiting install whose only call timed out, though it is still in its queue", async () => { + it("does not list a waiting install once its only call has timed out", async () => { const harness = await createHarness({ clock: new ManualClock() }); harness.ios.holdInstalls(); void harness.installer.install(ios("27.0")); - void harness.installer.install(ios("28.0")).catch(() => undefined); + const waiting = track(harness.installer.install(ios("28.0"))); await flush(); expect(harness.installer.inProgress().map((install) => install.component)).toEqual([ "27.0", "28.0", ]); + // Timer 1 is the budget of the call for 28.0. (harness.clock as ManualClock).fire(1); await flush(); + expect(waiting.error()).toEqual(new ComponentInstallTimeoutError("ios", "28.0", timeoutMs)); expect(harness.installer.inProgress().map((install) => install.component)).toEqual(["27.0"]); }); diff --git a/src/core/component-installer.ts b/src/core/component-installer.ts index fbf93a6b8..f218224d8 100644 --- a/src/core/component-installer.ts +++ b/src/core/component-installer.ts @@ -156,14 +156,16 @@ export class ComponentInstaller { /** * The installs waiting or running, read from the queues themselves (architecture rule 12): * the oldest `MAX_LISTED_INSTALLS`, oldest first. An install no call waits on any more is not - * listed: it has ended for everyone who asked, even while it is still in its queue. + * listed: it has ended for everyone who asked, even while it is still in its queue. That + * covers an `ended` install too, which never has a call: settling it empties its list, and + * nothing joins it after. */ // fallow-ignore-next-line unused-class-member -- called through the dispatcher's `components` option, a `Pick` of this class. inProgress(): readonly ComponentInstallInProgress[] { const listed: ComponentInstallInProgress[] = []; for (const queue of this.#queues.values()) { for (const install of queue) { - if (install.state === "ended" || install.calls.length === 0) continue; + if (install.calls.length === 0) continue; listed.push({ component: install.component, platform: install.platform, diff --git a/src/gateway/aggregate.test.ts b/src/gateway/aggregate.test.ts index 57e81ff83..8e08a5161 100644 --- a/src/gateway/aggregate.test.ts +++ b/src/gateway/aggregate.test.ts @@ -300,15 +300,6 @@ describe("aggregateStatus", () => { ]); }); - it("leaves a disconnected worker's last-known installs out", () => { - const status = aggregateStatus( - [view({ connection: "disconnected", id: "wrk_a", installs: [install("26.4", 10)] })], - { health: "running", host: GATEWAY_HOST, queueDepth: 0 }, - ); - - expect(status.installs).toEqual([]); - }); - it("keeps the 16 oldest across the fleet, so the list fits the contract's bound", () => { const status = aggregateStatus( [ diff --git a/src/gateway/aggregate.ts b/src/gateway/aggregate.ts index db8ee682c..dcdcd84d3 100644 --- a/src/gateway/aggregate.ts +++ b/src/gateway/aggregate.ts @@ -97,13 +97,12 @@ export function aggregateStatus( } /** - * ADR 0010 §3/§7: the connected workers' installs, each naming its worker. Connected only, like - * capacity: what a machine that dropped off was installing is a last-known fact, not one in - * progress. The fleet list has the same bound as one worker's, so it keeps the oldest. + * ADR 0010 §3/§7: the workers' installs, each naming its worker. Only a connected worker's view + * lists any: `WorkerRegistry` drops them when a worker disconnects or turns incompatible. The + * fleet list has the same bound as one worker's, so it keeps the oldest. */ function fleetInstalls(views: readonly WorkerView[]): NonNullable { return views - .filter((view) => view.connection === "connected") .flatMap((view) => (view.installs ?? []).map((install) => ({ ...install, workerId: view.id }))) .sort((a, b) => a.since - b.since) .slice(0, INSTALL_LIST_LIMIT); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 5a1b387eb..a0a0e220b 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -483,7 +483,7 @@ describe("GatewayService", () => { await harness.service.stop(); }); - it("re-reads the catalog for a component.installed that arrives while another refresh is in flight", async () => { + it("re-reads the catalog for a component.installed that queues behind a refresh in flight, and keeps it when another event queues after it", async () => { const worker = new ScriptedWorkerClient(); worker.catalog = catalogFixture([ { models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }, @@ -493,9 +493,11 @@ describe("GatewayService", () => { worker.catalog = catalogFixture([ { models: ["iPhone 17"], platform: "ios", runtimes: ["26.0", "26.4"] }, ]); - // The first starts a refresh without the catalog; the second queues behind it. + // The first starts a refresh without the catalog; the other two share the one queued + // behind it, and the last does not ask for the catalog. worker.pushEvent({ event: "lease.granted" }); worker.pushEvent({ event: "component.installed" }); + worker.pushEvent({ event: "lease.released" }); await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.catalog[0]?.runtimes).toEqual([ diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index 7afce5f08..a020279b1 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -9,11 +9,11 @@ * change capacity, leases or installs (ADR 0010 §7), and a periodic refresh as a backstop -- plus §22's republishing of * those events onto the gateway's own bus with `workerId` added. * - * One call §7 does not name is here too: `config.get`, read once per session for the worker's - * `downloads.policy`, `downloads.timeoutMs` and `lease.maxTtlMs`. The policy is shown on the view for display only: - * routing counts installed runtimes and never reads it (ADR 0009 §3). Neither changes without a - * worker restart -- which is a new session anyway -- and the uplink session is admin, so the - * gateway may read it. + * One call §7 does not name is here too: `config.get`, for the worker's `downloads.policy`, + * `downloads.timeoutMs` and `lease.maxTtlMs`, read with the catalog: on connect, on every + * periodic refresh, and after `component.installed`. The policy is shown on the view for display + * only: routing counts installed runtimes and never reads it (ADR 0009 §3). The uplink session is + * admin, so the gateway may read it. */ import { z } from "zod"; @@ -343,8 +343,8 @@ export class WorkerLink { Promise.all([ client.list({ kind: "devices" }), includeCatalog ? client.getCatalog() : undefined, - // Read on the same pass as the catalog: both are session-lifetime facts, and pairing - // them keeps the per-event refresh down to the two calls that actually go stale. + // Read on the same pass as the catalog: neither changes with a lease or a device, so + // the per-event refresh stays at the two calls that do. includeCatalog ? client.getConfig() : undefined, ]), "view refresh", diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index 9200e74cf..d584ecfef 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -292,7 +292,36 @@ describe("WorkerRegistry", () => { }, ); - it("keeps a disconnected view with everything it last reported", () => { + it("drops a worker's installs from its view when it disconnects or turns incompatible", () => { + const { workers } = registry(); + const installs = [ + { + component: "26.4", + platform: "ios" as const, + since: 1, + state: "downloading" as const, + waiters: 1, + }, + ]; + workers.connected("wrk_1", undefined, "0.3.0"); + workers.connected("wrk_2", undefined, "0.3.0"); + workers.refresh("wrk_1", { installs }); + workers.refresh("wrk_2", { installs }); + + workers.disconnected("wrk_1"); + const incompatible = workers.incompatible( + "wrk_2", + undefined, + { gateway: PROTOCOL_VERSION_RANGE, worker: { min: 4, max: 4 } }, + "0.2.0", + ); + + expect(workers.view("wrk_1")?.installs).toBeUndefined(); + expect(incompatible.installs).toBeUndefined(); + expect(workers.view("wrk_2")?.installs).toBeUndefined(); + }); + + it("keeps a disconnected view with the leases it last reported", () => { const { clock, events, workers } = registry(); workers.connected("wrk_1", "mac-mini-1", "0.3.0"); workers.refresh("wrk_1", { leases: [leaseFixture("lease_1", "dev_1")] }); diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index 3984978e0..f9b10d1cc 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -201,8 +201,9 @@ export class WorkerRegistry { ...(version === undefined ? {} : { version }), }; // ADR 0008 §8: host facts come from `status.get`, which an incompatible worker is never - // asked. A view left over from an earlier, compatible session must not keep showing them. - const { host: _stale, ...withoutHost } = view; + // asked. A view left over from an earlier, compatible session must not keep showing them, + // nor the installs that status listed (ADR 0010 §7). + const { host: _stale, installs: _staleInstalls, ...withoutHost } = view; this.#workers.set(workerId, withoutHost); this.#notifyViewsChanged(); return withoutHost; @@ -308,8 +309,11 @@ export class WorkerRegistry { disconnected(workerId: string): void { const existing = this.#workers.get(workerId); if (existing === undefined || existing.connection === "disconnected") return; + // ADR 0010 §7: an install on a worker nobody can reach is not known to be in progress, so + // the view stops listing it rather than showing it running for ever. + const { installs: _unknown, ...withoutInstalls } = existing; this.#workers.set(workerId, { - ...existing, + ...withoutInstalls, connection: "disconnected", lastSeenAt: this.options.clock.now(), }); From db56665706157cdeafdaab4cd05d23f6273a4f15 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 13:16:59 +0200 Subject: [PATCH 3/3] test(core,daemon,cli): review fixes for the installs in progress --- src/cli/index.test.ts | 23 +++++++++++++++++++++++ src/core/component-installer.ts | 1 - src/core/fake-driver.ts | 1 - src/daemon/dispatcher.test.ts | 2 ++ 4 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index ef937f7fc..f0edf1d76 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2179,6 +2179,29 @@ describe("CLI: status renders the fleet a gateway reports (ADR 0005 §20)", () = expect(await print([])).not.toContain("Install "); }); + it("prints an install whose start is ahead of this machine's clock as 0s old, not a negative age", async () => { + const output = outputCapture(); + const install = { + component: "26.4", + platform: "ios" as const, + since: 5_000, + state: "waiting" as const, + waiters: 1, + }; + await runCli( + ["status"], + output.environmentWith({ + clock: new FakeClock(1_000), + connectAdmin: async () => + fakeClient({ + getStatus: () => Promise.resolve({ ...EMPTY_STATUS, installs: [install] }), + }), + }), + ); + + expect(output.stdout).toContain("Install ios 26.4: waiting for 0s, 1 waiter\n"); + }); + it("prints a gateway's installs once each, naming the worker, not again under the worker", async () => { const output = outputCapture(); const install = { diff --git a/src/core/component-installer.ts b/src/core/component-installer.ts index f218224d8..e504a8290 100644 --- a/src/core/component-installer.ts +++ b/src/core/component-installer.ts @@ -160,7 +160,6 @@ export class ComponentInstaller { * covers an `ended` install too, which never has a call: settling it empties its list, and * nothing joins it after. */ - // fallow-ignore-next-line unused-class-member -- called through the dispatcher's `components` option, a `Pick` of this class. inProgress(): readonly ComponentInstallInProgress[] { const listed: ComponentInstallInProgress[] = []; for (const queue of this.#queues.values()) { diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index e65f293f9..a8a8400f2 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -274,7 +274,6 @@ export class FakeDriver implements Driver { this.#holdInstalls = true; } - // fallow-ignore-next-line unused-class-member -- a test-only control: tests end a held install with it. releaseInstalls(): void { this.#holdInstalls = false; for (const resolve of this.#pendingInstalls.splice(0)) resolve(); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 6ac01b5ea..d32b03a68 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1041,6 +1041,8 @@ describe("Dispatcher: status.get installs in progress", () => { driver.releaseInstalls(); driver.failOn("installComponent", 1, new Error("installer exited 1")); const call = installer.install({ component: "27.0", platform: "ios" }); + // Listed from the moment it is asked for, before the driver has run. + expect(installer.inProgress()).toHaveLength(1); await expect(call).rejects.toThrow("installer exited 1"); expect(await installs()).toEqual([]);