From 79660e635af82f30a5eaa332b80da8688be06f04 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 14:58:29 +0200 Subject: [PATCH 1/8] test: a gateway carries each worker's load in its view and reports its own (#533) --- e2e/single-host-fleet.test.ts | 13 ++- src/cli/index.test.ts | 130 ++++++++++++++++++++++++++++ src/contract/doc-samples.test.ts | 12 +++ src/contract/schemas.test.ts | 41 +++++++++ src/contract/schemas.ts | 2 + src/contract/worker-view.test.ts | 68 +++++++++++++++ src/contract/worker-view.ts | 3 + src/daemon/dispatcher.test.ts | 24 +++++ src/daemon/main.test.ts | 118 +++++++++++++++++++++++++ src/daemon/server.test.ts | 5 +- src/gateway/dispatcher.test.ts | 20 +++++ src/gateway/dispatcher.ts | 2 + src/gateway/routing.test.ts | 15 ++++ src/gateway/service.test.ts | 27 ++++++ src/gateway/worker-registry.test.ts | 62 +++++++++++++ src/gateway/worker-registry.ts | 1 + 16 files changed, 539 insertions(+), 4 deletions(-) diff --git a/e2e/single-host-fleet.test.ts b/e2e/single-host-fleet.test.ts index 32eea15ea..b0e474ff7 100644 --- a/e2e/single-host-fleet.test.ts +++ b/e2e/single-host-fleet.test.ts @@ -53,17 +53,26 @@ async function httpHost(): Promise { } describe("a single host as a fleet of one", () => { - it("simlock worker list against a worker prints that worker", async () => { + it("simlock worker list against a worker waits for the reading, then sees the worker line and its Load line", async () => { const env = await withDaemon({ configOverrides: { gateway: { label: "mac-mini-1" } } }); const id = await instanceId(env); + await waitFor( + async () => { + const read = await env.cli(["worker", "list", "--json"]); + const workers = (read.json as { workers?: { load?: unknown }[] }).workers; + return workers?.[0]?.load !== undefined; + }, + { label: "the worker's first load reading" }, + ); const text = await env.cli(["worker", "list"]); const json = await env.cli(["worker", "list", "--json"]); expect(text.code).toBe(0); const lines = text.stdout.trim().split("\n"); - expect(lines).toHaveLength(1); + expect(lines).toHaveLength(2); expect(lines[0]).toMatch(new RegExp(`^${id} \\(mac-mini-1\\): connected -- `)); + expect(lines[1]).toMatch(/^ {2}Load: .*memory .*read \d+s ago$/); expect(json.code).toBe(0); expect(json.json).toMatchObject({ workers: [{ connection: "connected", drained: false, id, label: "mac-mini-1" }], diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 7c0d17ab1..f36360c4f 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2941,6 +2941,136 @@ describe("CLI: worker commands (ADR 0005 §8/§23)", () => { ); }); + describe("a worker's Load line", () => { + const GIB = 2 ** 30; + const PARTS = { + cpu: { busyPercent: 34.2, cores: 10, limited: false }, + disk: { freeBytes: 120_688_581_018, totalBytes: 530_857_957_786 }, + memory: { + availableBytes: 10_522_669_875, + limited: false, + pressure: "normal" as const, + swapUsedBytes: 1_288_490_189, + totalBytes: 32 * GIB, + }, + }; + const READING = + "CPU 34% busy (10 cores) · memory 9.8 GiB of 32.0 GiB available · swap 1.2 GiB used · pressure normal · disk 112.4 GiB of 494.4 GiB free"; + const NOW = 61_000; + const install = { + component: "26.4", + platform: "ios" as const, + since: 1_000, + state: "downloading" as const, + waiters: 2, + }; + const printWorkers = async (workers: unknown[]) => { + const output = outputCapture(); + await runCli( + ["worker", "list"], + output.environmentWith({ + clock: new FakeClock(NOW), + connectAdmin: async () => + fakeClient({ listWorkers: () => Promise.resolve({ workers } as never) }), + }), + ); + return output.stdout; + }; + + it("simlock worker list prints a connected or starting worker's Load line after its own line and before its install lines", async () => { + const stdout = await printWorkers([ + { + ...connectedWorker, + installs: [install], + load: { ...PARTS, readAt: NOW - 12_000 }, + }, + { + connection: "connected", + drained: false, + health: "starting", + id: "wrk_2", + lastSeenAt: 1, + load: { memory: PARTS.memory, readAt: NOW - 3_000 }, + }, + ]); + + const lines = stdout.trimEnd().split("\n"); + expect(lines[0]).toMatch(/^wrk_1 \(mac-mini-1\): connected -- /); + expect(lines[1]).toBe(` Load: ${READING} · read 12s ago`); + expect(lines[2]).toMatch(/^ {2}Install ios 26\.4: downloading for 60s, 2 waiters$/); + expect(lines[3]).toMatch(/^wrk_2: connected, starting/); + expect(lines[4]).toBe( + " Load: memory 9.8 GiB of 32.0 GiB available · swap 1.2 GiB used · pressure normal · read 3s ago", + ); + }); + + it("simlock worker list prints `no reading while disconnected` for a disconnected worker, and no Load line for an incompatible one or one that sent none", async () => { + const stdout = await printWorkers([ + { ...connectedWorker, connection: "disconnected", drained: true, id: "wrk_a" }, + { + connection: "incompatible", + drained: false, + id: "wrk_b", + lastSeenAt: 1, + protocol: { gateway: { max: 35, min: 35 }, worker: { max: 4, min: 4 } }, + }, + { ...connectedWorker, id: "wrk_c" }, + { ...connectedWorker, id: "wrk_d", load: { ...PARTS, readAt: NOW - 1_000 } }, + ]); + + const lines = stdout.trimEnd().split("\n"); + const loadAfter = (id: string) => { + const index = lines.findIndex((line) => line.startsWith(`${id}:`)); + const next = lines[index + 1]; + return next?.startsWith(" Load:") === true ? next : undefined; + }; + expect(loadAfter("wrk_d")).toBe(` Load: ${READING} · read 1s ago`); + expect(loadAfter("wrk_a")).toBe(" Load: no reading while disconnected"); + expect(loadAfter("wrk_b")).toBeUndefined(); + expect(loadAfter("wrk_c")).toBeUndefined(); + }); + + it("simlock worker list prints `read 0s ago` for a readAt ahead of its clock", async () => { + const stdout = await printWorkers([ + { ...connectedWorker, load: { ...PARTS, readAt: NOW + 9_000 } }, + ]); + + expect(stdout).toContain(` Load: ${READING} · read 0s ago\n`); + }); + + it("simlock status against a gateway prints the gateway's own Load line, and each worker's Load line aged from the status time", async () => { + const output = outputCapture(); + const status: StatusGetOutput = { + ...EMPTY_STATUS, + daemon: { health: "running", mode: "gateway" }, + load: { ageMs: 4_000, ...PARTS }, + workers: [ + { + catalog: [], + connection: "connected", + devices: [], + drained: false, + id: "wrk_1", + lastSeenAt: 1, + leases: [], + load: { ...PARTS, readAt: NOW - 12_000 }, + }, + ], + }; + + await runCli( + ["status"], + output.environmentWith({ + clock: new FakeClock(NOW), + connectAdmin: async () => fakeClient({ getStatus: () => Promise.resolve(status) }), + }), + ); + + expect(output.stdout).toContain(`\nLoad: ${READING} · read 4s ago\n`); + expect(output.stdout).toContain(`\n Load: ${READING} · read 12s ago\n`); + }); + }); + it("prints a starting worker as starting, with its leases unknown rather than none", async () => { const output = outputCapture(); const environment = output.environmentWith({ diff --git a/src/contract/doc-samples.test.ts b/src/contract/doc-samples.test.ts index 174e7544f..8c2a75f45 100644 --- a/src/contract/doc-samples.test.ts +++ b/src/contract/doc-samples.test.ts @@ -38,4 +38,16 @@ describe("worker list samples in the docs", () => { expect(OPERATIONS["worker.list"].output.parse(sample)).toEqual(sample); } }); + + it('every { "workers": [...] } sample in the docs parses as a worker list, and one in HTTP-API.md shows a worker\'s load', () => { + const samples = workerListSamples(readFileSync(join(docsDir, "HTTP-API.md"), "utf8")); + + for (const sample of samples) { + expect(OPERATIONS["worker.list"].output.parse(sample)).toEqual(sample); + } + const shown = samples.flatMap( + (sample) => (sample as { workers: { load?: unknown }[] }).workers, + ); + expect(shown.some((worker) => worker.load !== undefined)).toBe(true); + }); }); diff --git a/src/contract/schemas.test.ts b/src/contract/schemas.test.ts index 1b429e143..085ab41c1 100644 --- a/src/contract/schemas.test.ts +++ b/src/contract/schemas.test.ts @@ -15,6 +15,7 @@ import { leaseRequestRecordSchema, platformCatalogSchema, statusDeviceSchema, + workerViewSchema, } from "./schemas.js"; /** @@ -836,3 +837,43 @@ describe("fitHostLoad", () => { expect(fitHostLoad(undefined)).toBeUndefined(); }); }); + +describe("the worker view's load", () => { + const view = { + connection: "connected" as const, + drained: false, + id: "wrk_1", + lastSeenAt: 1, + }; + const load = { + cpu: { busyPercent: 34.2, cores: 10, limited: false }, + disk: { freeBytes: 120, totalBytes: 500 }, + memory: { + availableBytes: 4_000, + limited: false, + pressure: "normal" as const, + swapUsedBytes: 100, + totalBytes: 16_000, + }, + readAt: 8_000, + }; + + it("the worker view schema round-trips load, and refuses a negative readAt, a negative figure or a busy % over 100", () => { + expect(workerViewSchema.parse({ ...view, load })).toEqual({ ...view, load }); + expect(workerViewSchema.parse({ ...view, load: { readAt: 0 } })).toEqual({ + ...view, + load: { readAt: 0 }, + }); + + expect(() => workerViewSchema.parse({ ...view, load: { ...load, readAt: -1 } })).toThrow(); + expect(() => + workerViewSchema.parse({ ...view, load: { ...load, disk: { ...load.disk, freeBytes: -1 } } }), + ).toThrow(); + expect(() => + workerViewSchema.parse({ + ...view, + load: { ...load, cpu: { ...load.cpu, busyPercent: 100.5 } }, + }), + ).toThrow(); + }); +}); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index a0aec147f..62130eaeb 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -1096,6 +1096,8 @@ export function capabilityReason(text: string): string { */ export const workerViewSchema = z.object({ capabilities: capabilityListSchema.optional(), + // why: placeholder so the red tests compile; green replaces it with the readAt-and-parts shape. + load: z.unknown().optional(), /** The worker's own instance identity (`instance.json`), ADR 0005 §3a: stable across * restarts, unique by construction, opaque to clients. Never a host name or an address. */ id: z.string(), diff --git a/src/contract/worker-view.test.ts b/src/contract/worker-view.test.ts index a94f65c38..8b540ea5e 100644 --- a/src/contract/worker-view.test.ts +++ b/src/contract/worker-view.test.ts @@ -226,4 +226,72 @@ describe("workerViewFields", () => { expect(Object.keys(view).sort()).toEqual(["health", "host", "installs", "waiting"]); }); + describe("a worker's load", () => { + const LOAD = { + ageMs: 4_000, + cpu: { busyPercent: 34.2, cores: 10, limited: false }, + disk: { freeBytes: 120, totalBytes: 500 }, + memory: { + availableBytes: 4_000, + limited: false, + pressure: "normal" as const, + swapUsedBytes: 100, + totalBytes: 16_000, + }, + }; + const { ageMs: _ageMs, ...PARTS } = LOAD; + const running = (load?: typeof LOAD) => + ({ + capacity: CAPACITY, + daemon: { health: "running", mode: "worker" }, + devices: [], + host: HOST, + leases: [], + queueDepth: 0, + ...(load === undefined ? {} : { load }), + }) as unknown as Parameters[0]["status"]; + + it("workerViewFields turns a status load's ageMs into readAt on the given receive time, keeping every part, and floors readAt at 0", () => { + const view = workerViewFields({ receivedAt: 10_000, status: running(LOAD) }); + + expect(view.load).toEqual({ readAt: 6_000, ...PARTS }); + expect(workerViewFields({ receivedAt: 4_000, status: running(LOAD) }).load).toMatchObject({ + readAt: 0, + }); + expect(workerViewFields({ receivedAt: 1_000, status: running(LOAD) }).load).toMatchObject({ + readAt: 0, + }); + }); + + it("workerViewFields copies load from a starting worker's status", () => { + const status = { + daemon: { health: "starting", mode: "worker" }, + host: HOST, + load: LOAD, + } as unknown as Parameters[0]["status"]; + + const view = workerViewFields({ receivedAt: 10_000, status }); + + expect(view).toEqual({ + health: "starting", + host: HOST, + load: { readAt: 6_000, ...PARTS }, + }); + }); + + it("workerViewFields leaves load out when the status has none", () => { + const starting = { + daemon: { health: "starting", mode: "worker" }, + host: HOST, + } as unknown as Parameters[0]["status"]; + + expect(workerViewFields({ receivedAt: 10_000, status: running(LOAD) })).toHaveProperty( + "load", + ); + expect(workerViewFields({ receivedAt: 10_000, status: running() })).not.toHaveProperty( + "load", + ); + expect(workerViewFields({ receivedAt: 10_000, status: starting })).not.toHaveProperty("load"); + }); + }); }); diff --git a/src/contract/worker-view.ts b/src/contract/worker-view.ts index cbd9c5bd2..a6f9fd27f 100644 --- a/src/contract/worker-view.ts +++ b/src/contract/worker-view.ts @@ -42,6 +42,8 @@ export interface WorkerReads { readonly devices?: Output<"list.get">; readonly catalog?: Output<"catalog.get">; readonly config?: Output<"config.get">; + // why: placeholder so the red tests compile; green makes it required and reads it. + readonly receivedAt?: number; } export type WorkerViewReport = Pick & @@ -56,6 +58,7 @@ export type WorkerViewReport = Pick & | "installs" | "lease" | "leases" + | "load" | "physicalQueueDepth" | "queueDepth" | "waiting" diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 87f0f3a7b..f61ef6651 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -229,6 +229,7 @@ async function buildDispatcher( readonly state?: object; readonly presence?: (driverDeviceId: string) => LatestPresence | undefined; readonly capabilitySources?: DispatcherOptions["capabilitySources"]; + readonly load?: DispatcherOptions["load"]; } = {}, ) { const clock = overrides.clock ?? new FakeClock(1_000); @@ -333,6 +334,7 @@ async function buildDispatcher( hostFacts: overrides.hostFacts ?? (() => ({ ...HOST_SYSTEM, tools: [] })), instanceId: "instance-1", leases: engine, + ...(overrides.load === undefined ? {} : { load: overrides.load }), ...(overrides.includeNuke === true ? { nuke: new Nuke({ executor: engine, registry }) } : {}), ...(overrides.includeEnrollment === true ? { enrollment: engine.core.enrollment } : {}), passthrough: resolvePassthroughOverride(engine, overrides.passthroughOverride), @@ -516,6 +518,28 @@ describe("Dispatcher: the fleet operations on a worker", () => { expect(workers[0]).not.toHaveProperty("protocol"); }); + it("a worker's own worker.list carries its load with readAt taken when its status answered, not after its catalog read", async () => { + const clock = new FakeClock(10_000); + const base = await buildDispatcher({ clock }); + const slowCatalog: CatalogReader = { + async listCatalog(...arguments_) { + // why: a later macrotask, so status's own answer has already been taken by then. + await new Promise((resolve) => setTimeout(resolve, 0)); + clock.advance(5_000); + return base.engine.listCatalog(...arguments_); + }, + }; + const { dispatcher } = await buildDispatcher({ + catalog: slowCatalog, + clock, + load: () => ({ ageMs: 2_000, disk: { freeBytes: 120, totalBytes: 500 } }), + }); + + const { workers } = await dispatcher.dispatch("worker.list", {}, admin); + + expect(workers[0]?.load).toEqual({ disk: { freeBytes: 120, totalBytes: 500 }, readAt: 8_000 }); + }); + it("worker.list on a worker carries gateway.label as label, and no label when it is unset", async () => { const labelled = await buildDispatcher({ gatewayLabel: "mac-mini-1" }); const unlabelled = await buildDispatcher(); diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 468153c7c..2c873a7b9 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -2851,3 +2851,121 @@ describe("startDaemon host load", () => { expect(withProbe.clock.pendingTimerCount).toBe(without.clock.pendingTimerCount); }); }); + +describe("startDaemon in gateway mode host load", () => { + const COUNTERS: HostLoadCounters = { + cpu: { busyTime: 100, cores: 4, limited: false, totalTime: 1_000 }, + disk: { freeBytes: 120, totalBytes: 500 }, + memory: { + availableBytes: 4_000, + limited: false, + pressure: "normal", + swapUsedBytes: 100, + totalBytes: 16_000, + }, + }; + const operator = { + manageEventSubscription: () => undefined, + principal: "test-operator", + role: "admin", + } as const; + + async function startGateway( + overrides: Partial & { readonly directory?: string } = {}, + ) { + const { directory: given, ...rest } = overrides; + const directory = given ?? (await mkdtemp(join(tmpdir(), "simlock-main-gw-load-"))); + if (given === undefined) temporaryDirectories.push(directory); + const clock = new FakeClock(1_000); + const daemon = await startDaemon({ + clock, + configOverrides: { + http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, + mode: "gateway", + }, + dataDirectory: directory, + drivers: [], + filesystem: new MemoryFilesystem(), + logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), + statePath: join(directory, "state.json"), + version: "1.2.3", + ...rest, + } as StartDaemonOptions); + runningDaemons.push(daemon); + return { clock, daemon, directory }; + } + + const statusOf = async (daemon: DaemonServer) => + (await daemon.dispatch("status.get", {}, operator)) as Record; + + it("a gateway started with a probe answers status.get with the gateway machine's load from it", async () => { + const probe = new FakeHostLoadProbe(COUNTERS); + const { daemon } = await startGateway({ hostLoadProbe: probe }); + + await expect + .poll(async () => (await statusOf(daemon)).load) + .toEqual({ ageMs: 0, disk: COUNTERS.disk, memory: COUNTERS.memory }); + expect(probe.reads).toBe(1); + }); + + it("a gateway started with hostLoadProbe: null answers status.get without load, and arms no host load timer", async () => { + const withProbe = await startGateway({ hostLoadProbe: new FakeHostLoadProbe(COUNTERS) }); + const without = await startGateway({ hostLoadProbe: null }); + + await expect.poll(async () => (await statusOf(withProbe.daemon)).load).toBeDefined(); + + expect(await statusOf(without.daemon)).not.toHaveProperty("load"); + expect(withProbe.clock.pendingTimerCount).toBeGreaterThan(without.clock.pendingTimerCount); + }); + + it("a gateway started with no hostLoadProbe builds the production probe, the same factory a worker uses", async () => { + const { daemon } = await startGateway({}); + + await expect + .poll( + async () => ((await statusOf(daemon)).load as { memory?: { totalBytes: number } })?.memory, + ) + .toMatchObject({ totalBytes: expect.any(Number) }); + }); + + it("a stopped gateway, and one that lost the start race, leave no host load timer pending", async () => { + const probe = new FakeHostLoadProbe(COUNTERS); + const withProbe = await startGateway({ hostLoadProbe: probe }); + const without = await startGateway({ hostLoadProbe: null }); + expect(withProbe.clock.pendingTimerCount).toBeGreaterThan(without.clock.pendingTimerCount); + + await withProbe.daemon.stop("test"); + await without.daemon.stop("test"); + + expect(withProbe.clock.pendingTimerCount).toBe(without.clock.pendingTimerCount); + + const first = await startGateway({ hostLoadProbe: null }); + const lost = async (hostLoadProbe: FakeHostLoadProbe | null) => { + const clock = new FakeClock(1_000); + await expect( + startDaemon({ + clock, + configOverrides: { + http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, + mode: "gateway", + }, + dataDirectory: first.directory, + drivers: [], + filesystem: new MemoryFilesystem(), + hostLoadProbe, + statePath: join(first.directory, "state.json"), + version: "1.2.3", + } as StartDaemonOptions), + ).rejects.toThrow(); + await new Promise((resolve) => setTimeout(resolve, 25)); + return clock.pendingTimerCount; + }; + const losingProbe = new FakeHostLoadProbe(COUNTERS); + + const withLoser = await lost(losingProbe); + const withoutLoser = await lost(null); + + expect(losingProbe.reads).toBe(0); + expect(withLoser).toBe(withoutLoser); + }); +}); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 7c1416a25..b5a3b8121 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -204,8 +204,9 @@ describe("DaemonServer", () => { ], [33, "cannot send relay.request's channel, or read a relayed body from its byte channel"], [34, "cannot read status.get's load block"], + [35, "cannot read a worker view's load"], ])( - "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 35, to a client on protocol %i, which %s", + "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 36, to a client on protocol %i, which %s", async (version) => { const harness = await createHarness(); const previous = await createClient(harness.socketPath); @@ -215,7 +216,7 @@ describe("DaemonServer", () => { ).resolves.toMatchObject({ error: { code: "PROTOCOL_VERSION_UNSUPPORTED", - details: { client: { min: version, max: version }, daemon: { min: 35, max: 35 } }, + details: { client: { min: version, max: version }, daemon: { min: 36, max: 36 } }, }, ok: false, }); diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 301563093..51306cee9 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -136,6 +136,7 @@ function harness( readonly http?: (typeof gatewayConfig)["http"]; /** The gateway's own health; `running` by default. */ readonly health?: "starting" | "running" | "failed"; + readonly load?: ConstructorParameters[0]["load"]; } = {}, ) { const clock = new FakeClock(1_000); @@ -193,6 +194,7 @@ function harness( }), health: () => options.health ?? "running", host: GATEWAY_HOST, + ...(options.load === undefined ? {} : { load: options.load }), leaseIndex, // `classifyError`'s answer for the errors this dispatcher throws itself. errorCode: (error) => (error instanceof DispatchError ? error.code : undefined), @@ -342,6 +344,24 @@ describe("GatewayDispatcher", () => { expect(status.host).toEqual(GATEWAY_HOST); }); + it("a gateway's status.get carries the gateway machine's own load, not its workers', on the starting answer and the running one", async () => { + const own = { ageMs: 3_000, disk: { freeBytes: 10, totalBytes: 100 } }; + const workerLoad = { readAt: 500, disk: { freeBytes: 99, totalBytes: 100 } }; + const askStatus = async (health: "starting" | "running") => { + const { dispatcher, workers } = harness({ health, load: () => own }); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { health: "running", load: workerLoad }); + return dispatcher.dispatch("status.get", {}, session()); + }; + + const starting = await askStatus("starting"); + const running = await askStatus("running"); + + expect(starting.load).toEqual(own); + expect(running.load).toEqual(own); + expect(running.workers?.[0]?.load).toEqual(workerLoad); + }); + it("status.get carries consoleUrl when HTTP is enabled and omits it when disabled", async () => { const enabled = harness({ http: { enabled: true, host: "0.0.0.0", port: 4711 } }); const disabled = harness({ http: { enabled: false, host: "0.0.0.0", port: 4711 } }); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 76e0ac18f..c987c2652 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -119,6 +119,8 @@ export interface GatewayDispatcherOptions { readonly errorCode?: (error: unknown) => string | undefined; readonly health: () => "starting" | "running" | "failed"; readonly host: AggregateStatusOptions["host"]; + // why: placeholder so the red tests compile; green reads it into status.get's own load. + readonly load?: () => z.infer<(typeof OPERATIONS)["status.get"]["output"]>["load"]; readonly awaitReady: () => Promise; readonly coordinator: Pick< FleetLeaseCoordinator, diff --git a/src/gateway/routing.test.ts b/src/gateway/routing.test.ts index 3d4460578..dd2981b2f 100644 --- a/src/gateway/routing.test.ts +++ b/src/gateway/routing.test.ts @@ -70,6 +70,21 @@ describe("the registered warm-then-free policy", () => { }); }); + it("the gateway picks the same worker for a request whether or not the views carry load", () => { + const load = { cpu: { busyPercent: 100, cores: 2, limited: false }, readAt: 1 }; + const quiet = view("wrk_a_quiet", { capacity: withIos({ maxRunning: 5 }) }); + const busy = view("wrk_z_busy", { capacity: withIos({ maxRunning: 9 }) }); + + const without = policy.select(REQUEST, [quiet, busy]); + const withLoad = policy.select(REQUEST, [ + { ...quiet, load: { readAt: 1 } }, + { ...busy, load }, + ]); + + expect(without).toMatchObject({ workerId: "wrk_z_busy" }); + expect(withLoad).toEqual(without); + }); + it("picks a worker with a warm device over a cold one with more free running capacity", () => { // The warm worker sorts last by id and has less room, so only warm-hit can pick it. const cold = view("wrk_a_cold", { capacity: withIos({ maxRunning: 5 }) }); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index b91fa3102..ff2e1315b 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -171,6 +171,33 @@ describe("GatewayService", () => { await harness.service.stop(); }); + it("WorkerLink stamps a view's load with the gateway clock's time when status.get answered", async () => { + const harness = fleet(); + await harness.service.start(); + harness.clock.advance(19_000); + // why: the device read lands later than status, so a stamp taken after it would be 5 s fresher. + class SlowDevices extends ScriptedWorkerClient { + override async list(input: { readonly kind?: string }): Promise { + await new Promise((resolve) => setTimeout(resolve, 0)); + harness.clock.advance(5_000); + return super.list(input); + } + } + const worker = new SlowDevices(); + worker.status = statusFixture({ + load: { ageMs: 2_000, disk: { freeBytes: 120, totalBytes: 500 } }, + }); + + await harness.join("wrk_1", worker); + await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.load).toBeDefined()); + + expect(harness.service.workers.view("wrk_1")?.load).toEqual({ + disk: { freeBytes: 120, totalBytes: 500 }, + readAt: 18_000, + }); + await harness.service.stop(); + }); + it("builds a starting worker's view from health and host alone, asks it for nothing else, and builds the full view once it answers running", async () => { const harness = fleet(); await harness.service.start(); diff --git a/src/gateway/worker-registry.test.ts b/src/gateway/worker-registry.test.ts index 0846301ba..8a8eb3870 100644 --- a/src/gateway/worker-registry.test.ts +++ b/src/gateway/worker-registry.test.ts @@ -400,6 +400,68 @@ describe("WorkerRegistry", () => { }, ); + describe("a worker's load on its view", () => { + const load = { + cpu: { busyPercent: 34, cores: 10, limited: false }, + readAt: 900, + }; + const incompatible = (workers: ReturnType["workers"], workerId: string) => + workers.incompatible( + workerId, + undefined, + { gateway: PROTOCOL_VERSION_RANGE, worker: { min: 4, max: 4 } }, + "0.2.0", + ); + + it("the registry drops a worker's load when it disconnects, turns incompatible, or connects again", () => { + const { workers } = registry(); + for (const id of ["wrk_1", "wrk_2", "wrk_3"]) { + workers.connected(id, undefined, "0.3.0"); + workers.refresh(id, { load }); + } + expect(workers.view("wrk_1")?.load).toEqual(load); + + workers.disconnected("wrk_1"); + const turned = incompatible(workers, "wrk_2"); + const reconnected = workers.connected("wrk_3", undefined, "0.3.0"); + + expect(workers.view("wrk_1")).not.toHaveProperty("load"); + expect(turned).not.toHaveProperty("load"); + expect(workers.view("wrk_2")).not.toHaveProperty("load"); + expect(reconnected).not.toHaveProperty("load"); + expect(workers.view("wrk_3")).not.toHaveProperty("load"); + }); + + it("a refresh without load leaves the view without load, after one with load", () => { + const { workers } = registry(); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { load }); + expect(workers.view("wrk_1")?.load).toEqual(load); + + workers.refresh("wrk_1", { queueDepth: 1 }); + + expect(workers.view("wrk_1")?.queueDepth).toBe(1); + expect(workers.view("wrk_1")).not.toHaveProperty("load"); + }); + + it("a refresh that reaches a disconnected or an incompatible view leaves no load on it", () => { + const { workers } = registry(); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.connected("wrk_2", undefined, "0.3.0"); + workers.refresh("wrk_1", { load }); + workers.disconnected("wrk_1"); + incompatible(workers, "wrk_2"); + + workers.refresh("wrk_1", { load }); + workers.refresh("wrk_2", { load }); + + expect(workers.view("wrk_1")?.connection).toBe("disconnected"); + expect(workers.view("wrk_1")).not.toHaveProperty("load"); + expect(workers.view("wrk_2")?.connection).toBe("incompatible"); + expect(workers.view("wrk_2")).not.toHaveProperty("load"); + }); + }); + it("drops a worker's installs from its view when it disconnects or turns incompatible", () => { const { workers } = registry(); const installs = [ diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index 5f76cce39..b0dbff4fe 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -38,6 +38,7 @@ export type WorkerViewSnapshot = Pick< | "installs" | "lease" | "leases" + | "load" | "queueDepth" | "version" | "waiting" From 2ea2ae763fe9c0979d1de55307b3184fe1efd415 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 15:02:09 +0200 Subject: [PATCH 2/8] feat(gateway): worker views carry load, the gateway reports its own, protocol 35 2 failing -> 1 failing (a spec test looks up a labelled worker by bare id) --- docs/CLI.md | 6 +++ docs/HTTP-API.md | 17 ++++++++ src/cli/index.ts | 68 ++++++++++++++++++-------------- src/contract/schemas.ts | 11 +++++- src/contract/worker-view.test.ts | 11 +++++- src/contract/worker-view.ts | 17 ++++++-- src/daemon/dispatcher.ts | 8 +++- src/daemon/main.ts | 13 ++++++ src/gateway/aggregate.ts | 2 + src/gateway/dispatcher.ts | 7 +++- src/gateway/worker-link.ts | 12 ++++-- src/gateway/worker-registry.ts | 27 ++++++++++--- 12 files changed, 149 insertions(+), 50 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 77241fe74..45661d951 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -2382,10 +2382,16 @@ gateway to take it out of rotation or forget it. ```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 + Load: CPU 34% busy (10 cores) · memory 9.8 GiB of 32.0 GiB available · swap 1.2 GiB used · pressure normal · disk 112.4 GiB of 494.4 GiB free · read 12s ago 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) + Load: no reading while disconnected ``` +A connected worker's `Load:` line is its latest host load and how long ago it +was read; `load` in `--json` carries the same with `readAt`. A worker that +sends none shows no line, and neither does an incompatible one. + ## `simlock config [get |set ]` Show the effective configuration (defaults + config file + overrides): the diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 2dca31b14..d3e07a561 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1300,12 +1300,29 @@ simulated (hence the thin Android catalog), trimmed to one worker: "osVersion": "26.6.1", "arch": "arm64", "tools": [{"platform": "ios", "name": "xcode", "version": "16.4", "build": "16F6"}] + }, + "load": { + "readAt": 1790864078200, + "cpu": {"busyPercent": 34.2, "cores": 10, "limited": false}, + "memory": { + "totalBytes": 34359738368, + "availableBytes": 10523000000, + "swapUsedBytes": 1288490188, + "pressure": "normal", + "limited": false + }, + "disk": {"freeBytes": 120700000000, "totalBytes": 530800000000} } } ] } ``` +`load` is the worker's latest host load, from its own +[`GET /v1/status`](#get-v1status), and `readAt` is when it was read, in +milliseconds since the epoch on the gateway's clock. A disconnected or +incompatible worker shows none, and so does a worker that does not send one. + `catalogReadAt` is when the gateway last read that worker's catalog since the worker connected. It is absent until the first read, and again after the worker reconnects until its new catalog arrives; a worker without it takes no diff --git a/src/cli/index.ts b/src/cli/index.ts index 18383ad24..eb6d1b226 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -1881,7 +1881,7 @@ async function runWorkerList( if (values.json) writeResult(environment, result); else environment.stdout.write( - `${formatWorkers(result.workers, { installsAt: environment.clock.now() })}\n`, + `${formatWorkers(result.workers, { installs: true, now: environment.clock.now() })}\n`, ); return 0; } @@ -2191,29 +2191,19 @@ function installTargets(named: string[] | undefined, all: unknown): "all" | stri return "all"; } -/** - * 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[], - options: { readonly installsAt?: number } = {}, + options: { readonly installs?: boolean; readonly now: number }, ): string { if (workers.length === 0) return "No workers have connected to this gateway."; - const { installsAt } = options; + const { installs: showInstalls, now } = options; return workers .map((worker) => { const installs = - installsAt === undefined - ? "" - : (worker.installs ?? []) - .map((install) => `\n ${formatInstall(install, installsAt)}`) - .join(""); + showInstalls === true + ? (worker.installs ?? []).map((install) => `\n ${formatInstall(install, now)}`).join("") + : ""; + const load = workerLoadLine(worker, now); const label = worker.label === undefined ? worker.id : `${worker.id} (${worker.label})`; const state = workerState(worker); const capacity = @@ -2234,11 +2224,18 @@ function formatWorkers( : ` -- ${entry.name} ${entry.state}`, ) .join(""); - return `${label}: ${state} -- ${capacity}, ${leaseCount(worker)}${skew}${host}${capabilities}${installs}`; + return `${label}: ${state} -- ${capacity}, ${leaseCount(worker)}${skew}${host}${capabilities}${load}${installs}`; }) .join("\n"); } +function workerLoadLine(worker: WorkerView, now: number): string { + if (worker.connection === "disconnected") return "\n Load: no reading while disconnected"; + if (worker.load === undefined) return ""; + const { readAt, ...parts } = worker.load; + return `\n ${formatLoadLine(parts, Math.ceil(Math.max(0, now - readAt) / 1000), "leave out")}`; +} + /** A worker's state words: its connection, then `starting` while it has not finished starting, then `drained`. */ function workerState(worker: WorkerView): string { return [ @@ -2411,17 +2408,24 @@ function formatLoadCores(cores: number): string { return String(roundHalfUp(cores, cores < 0.1 ? 2 : 1)); } -function formatLoadLine(load: NonNullable): string { +function formatLoadLine( + load: Pick, "cpu" | "disk" | "memory">, + ageSeconds: number, + unreadParts: "say" | "leave out" = "say", +): string { const { cpu, disk, memory } = load; + const unread = (text: string): string[] => (unreadParts === "say" ? [text] : []); const cpuPart = cpu === undefined - ? "CPU unavailable" - : `CPU ${roundHalfUp(cpu.busyPercent, 0)}% busy (${formatLoadCores(cpu.cores)} ${ - cpu.cores === 1 ? "core" : "cores" - }${cpu.limited ? ", limit" : ""})`; + ? unread("CPU unavailable") + : [ + `CPU ${roundHalfUp(cpu.busyPercent, 0)}% busy (${formatLoadCores(cpu.cores)} ${ + cpu.cores === 1 ? "core" : "cores" + }${cpu.limited ? ", limit" : ""})`, + ]; const memoryParts = memory === undefined - ? ["memory unavailable"] + ? unread("memory unavailable") : [ `memory ${formatLoadBytes(memory.availableBytes)} of ${formatLoadBytes(memory.totalBytes)} available${memory.limited ? " (limit)" : ""}`, `swap ${formatLoadBytes(memory.swapUsedBytes)} used`, @@ -2429,14 +2433,16 @@ function formatLoadLine(load: NonNullable): string { ]; const diskPart = disk === undefined - ? "disk unavailable" - : `disk ${formatLoadBytes(disk.freeBytes)} of ${formatLoadBytes(disk.totalBytes)} free`; - const age = `read ${Math.ceil(load.ageMs / 1000)}s ago`; - return `Load: ${[cpuPart, ...memoryParts, diskPart, age].join(" · ")}`; + ? unread("disk unavailable") + : [`disk ${formatLoadBytes(disk.freeBytes)} of ${formatLoadBytes(disk.totalBytes)} free`]; + const age = `read ${String(ageSeconds)}s ago`; + return `Load: ${[...cpuPart, ...memoryParts, ...diskPart, age].join(" · ")}`; } function loadLines(status: StatusGetOutput): string[] { - return status.load === undefined ? [] : [formatLoadLine(status.load)]; + return status.load === undefined + ? [] + : [formatLoadLine(status.load, Math.ceil(status.load.ageMs / 1000))]; } /** The web console's address line, for `status` and `daemon start`: none when HTTP is off. */ @@ -2477,7 +2483,9 @@ function formatStatus(status: StatusGetOutput, now: number): string { `RAM budget: ${formatGibibytes(ramBudget.usedBytes)}/${formatGibibytes(ramBudget.limitBytes)} used${ramBudget.overLimit ? " (over limit)" : ""}`, ]; const workerLines = - workers === undefined ? [] : [formatWorkers(workers), ""].filter((line) => line !== ""); + workers === undefined + ? [] + : [formatWorkers(workers, { now }), ""].filter((line) => line !== ""); // A gateway keeps no pool of its own: each worker's is on its entry in the JSON. const warmPoolLines = status.warmPool === undefined || daemon.mode === "gateway" diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 62130eaeb..a34a1d83f 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -529,6 +529,14 @@ export const hostLoadSchema = z.object({ disk: loadDiskSchema.optional(), }); +/** ADR 0029 §5: a worker's load as its view carries it: when it was read, on the viewer's clock. */ +export const workerLoadSchema = z.object({ + readAt: z.number().int().min(0), + cpu: loadCpuSchema.optional(), + memory: loadMemorySchema.optional(), + disk: loadDiskSchema.optional(), +}); + /** ADR 0029 §4: what `status.get` carries about the machine's load, as old as its last read. */ export type StatusLoad = z.infer; @@ -1096,8 +1104,7 @@ export function capabilityReason(text: string): string { */ export const workerViewSchema = z.object({ capabilities: capabilityListSchema.optional(), - // why: placeholder so the red tests compile; green replaces it with the readAt-and-parts shape. - load: z.unknown().optional(), + load: workerLoadSchema.optional(), /** The worker's own instance identity (`instance.json`), ADR 0005 §3a: stable across * restarts, unique by construction, opaque to clients. Never a host name or an address. */ id: z.string(), diff --git a/src/contract/worker-view.test.ts b/src/contract/worker-view.test.ts index 8b540ea5e..bca3d3f7e 100644 --- a/src/contract/worker-view.test.ts +++ b/src/contract/worker-view.test.ts @@ -46,6 +46,7 @@ describe("workerViewFields", () => { const reads = (devices: unknown[]) => ({ devices, + receivedAt: 0, status: { capacity: CAPACITY, daemon: { health: "running", mode: "worker" }, @@ -73,6 +74,7 @@ describe("workerViewFields", () => { const reads = (device: object) => ({ devices: [device], + receivedAt: 0, status: { capacity: CAPACITY, daemon: { health: "running", mode: "worker" }, @@ -106,6 +108,7 @@ describe("workerViewFields", () => { const reads = (device: object) => ({ devices: [device], + receivedAt: 0, status: { capacity: CAPACITY, daemon: { health: "running", mode: "worker" }, @@ -133,6 +136,7 @@ describe("workerViewFields", () => { it("builds a starting worker's view from its health and host alone, with every other field absent", () => { const view = workerViewFields({ + receivedAt: 0, status: { daemon: { health: "starting", mode: "worker" }, host: HOST }, }); @@ -141,6 +145,7 @@ describe("workerViewFields", () => { it("leaves a starting worker's view without the devices, catalog and config it would otherwise be given", () => { const view = workerViewFields({ + receivedAt: 0, catalog: { platforms: [] }, config: CONFIG, devices: [], @@ -158,6 +163,7 @@ describe("workerViewFields", () => { }; const running = workerViewFields({ + receivedAt: 0, devices: [], status: { capacity: CAPACITY, @@ -170,6 +176,7 @@ describe("workerViewFields", () => { }, }); const starting = workerViewFields({ + receivedAt: 0, status: { daemon: { health: "starting", mode: "worker" }, host: HOST, warmPool }, }); @@ -179,6 +186,7 @@ describe("workerViewFields", () => { it("copies every field a running worker reports, and makes an absent installs or waiting list empty", () => { const view = workerViewFields({ + receivedAt: 0, devices: [], status: { capacity: CAPACITY, @@ -213,7 +221,7 @@ describe("workerViewFields", () => { queueDepth: 2, } as unknown as Parameters[0]["status"]; - const view = workerViewFields({ devices: [], status }); + const view = workerViewFields({ devices: [], receivedAt: 0, status }); expect(view.queueDepth).toBe(2); expect(view).toHaveProperty("physicalQueueDepth", 1); @@ -221,6 +229,7 @@ describe("workerViewFields", () => { it("leaves a field out of a running worker's view when the worker's answer has none, rather than making it empty", () => { const view = workerViewFields({ + receivedAt: 0, status: { daemon: { health: "running", mode: "worker" }, host: HOST }, }); diff --git a/src/contract/worker-view.ts b/src/contract/worker-view.ts index a6f9fd27f..ed0aeb64b 100644 --- a/src/contract/worker-view.ts +++ b/src/contract/worker-view.ts @@ -42,8 +42,7 @@ export interface WorkerReads { readonly devices?: Output<"list.get">; readonly catalog?: Output<"catalog.get">; readonly config?: Output<"config.get">; - // why: placeholder so the red tests compile; green makes it required and reads it. - readonly receivedAt?: number; + readonly receivedAt: number; } export type WorkerViewReport = Pick & @@ -70,13 +69,23 @@ export type WorkerViewReport = Pick & const viewDevicesSchema = z.array(statusDeviceSchema); export function workerViewFields(reads: WorkerReads): WorkerViewReport { - const { catalog, config, devices, status } = reads; + const { catalog, config, devices, receivedAt, status } = reads; + // why: a worker's ageMs is a claim; it is already capped at a day, and readAt never goes below 0. + const load = + status.load === undefined + ? {} + : (() => { + const { ageMs, ...parts } = status.load; + return { load: { readAt: Math.max(0, receivedAt - ageMs), ...parts } }; + })(); // A starting worker has checked nothing: its view is its health and its host, and every other // field is absent -- never empty, which would read as "nothing is leased". - if (status.daemon.health === "starting") return { health: "starting", host: status.host }; + if (status.daemon.health === "starting") + return { health: "starting", host: status.host, ...load }; return { health: status.daemon.health, host: status.host, + ...load, installs: status.installs ?? [], waiting: status.waiting ?? [], ...(status.capabilities === undefined ? {} : { capabilities: status.capabilities }), diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 96b10a1b9..e64bbc243 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -798,8 +798,13 @@ export class Dispatcher { * holds that flag, not this host. */ #workerList: Handler<"worker.list"> = async (_input, session) => { + // why: taken as status resolves, not after the slower catalog read, so the load is not made to look fresher. + let receivedAt = this.options.clock.now(); const [status, devices, catalog] = await Promise.all([ - this.#statusGet({}, session), + Promise.resolve(this.#statusGet({}, session)).then((answer) => { + receivedAt = this.options.clock.now(); + return answer; + }), this.#listGet({ kind: "devices" }, session), this.#keptViewCatalog(session), ]); @@ -811,6 +816,7 @@ export class Dispatcher { catalog: OPERATIONS["catalog.get"].output.parse(catalog), config: OPERATIONS["config.get"].output.parse(this.#configGet({}, session)), devices: OPERATIONS["list.get"].output.parse(devices), + receivedAt, status: OPERATIONS["status.get"].output.parse(status), }), connection: "connected", diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 4559a3efe..d0922a379 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -224,6 +224,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise void; /** The gateway's own machine. It runs no drivers, so its host facts carry no tools. */ readonly hostSystem: HostSystem; + readonly hostLoadProbe?: HostLoadProbe | null; readonly idGenerator: IdGenerator; readonly ipc: IpcConnector & IpcListenerFactory; readonly logger: Logger; @@ -840,11 +842,21 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise Promise.resolve(), @@ -859,6 +871,7 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise daemon.health, host: fitHostFacts({ ...options.hostSystem, tools: [] }), + ...(hostLoad === undefined ? {} : { load: () => fitHostLoad(hostLoad.current()) }), leaseIndex, logger: logger.child("gateway"), tokens, diff --git a/src/gateway/aggregate.ts b/src/gateway/aggregate.ts index 420b905c4..b76ce646d 100644 --- a/src/gateway/aggregate.ts +++ b/src/gateway/aggregate.ts @@ -46,6 +46,7 @@ const EMPTY_GLOBAL_CAPACITY = { export interface AggregateStatusOptions { readonly health: StatusOutput["daemon"]["health"]; readonly host: StatusOutput["host"]; + readonly load?: StatusOutput["load"]; readonly queueDepth: number; readonly physicalQueueDepth?: number; readonly waiting?: StatusOutput["waiting"]; @@ -65,6 +66,7 @@ export function aggregateStatus( capacity: sumCapacity(views.filter((view) => view.connection === "connected")), daemon: { health: options.health, mode: "gateway" }, host: options.host, + ...(options.load === undefined ? {} : { load: options.load }), installs: fleetInstalls(views), devices: views.flatMap((view) => (view.devices ?? []).map((device) => ({ ...device, workerId: view.id })), diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index c987c2652..5f5266a44 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -119,8 +119,7 @@ export interface GatewayDispatcherOptions { readonly errorCode?: (error: unknown) => string | undefined; readonly health: () => "starting" | "running" | "failed"; readonly host: AggregateStatusOptions["host"]; - // why: placeholder so the red tests compile; green reads it into status.get's own load. - readonly load?: () => z.infer<(typeof OPERATIONS)["status.get"]["output"]>["load"]; + readonly load?: () => AggregateStatusOptions["load"]; readonly awaitReady: () => Promise; readonly coordinator: Pick< FleetLeaseCoordinator, @@ -236,15 +235,19 @@ export class GatewayDispatcher { #statusGet: Handler<"status.get"> = () => { const consoleUrl = consoleUrlField(this.options.config.http); + const load = this.options.load?.(); + const loadField = load === undefined ? {} : { load }; if (this.options.health() === "starting") { return { daemon: { health: "starting", mode: "gateway", ...consoleUrl }, host: this.options.host, + ...loadField, }; } const status = aggregateStatus(this.options.workers.views(), { health: this.options.health(), host: this.options.host, + ...(load === undefined ? {} : { load }), physicalQueueDepth: this.options.coordinator.physicalQueueDepth, queueDepth: this.options.coordinator.queueDepth, waiting: [...this.options.coordinator.waitingRequests()], diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index baeb1cf93..1a43182c0 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -368,17 +368,19 @@ export class WorkerLink { * -- application latency, not transport death, and P1's counter must not confuse the two. */ async #rebuildView(client: GatewayWorkerClient, includeCatalog: boolean): Promise { const status = await this.#withTimeout(client.getStatus(), "status.get"); + // why: taken the moment status answers, so a slow read beside it cannot make the load look fresher. + const receivedAt = this.options.clock.now(); this.#consecutiveRefreshTimeouts = 0; // why: a starting worker answers `status.get` with its health, host and load only, and the rest // is unchecked, so its view is built from those facts; the next refresh reads it in full. if (status.daemon.health === "starting") { - this.#refreshStarting(client, status); + this.#refreshStarting(client, status, receivedAt); return; } // A starting answer dropped the view's catalog, and a refresh that does not read one would // leave the worker without it (and so not taking requests) until the next periodic read. const catalogKnown = this.options.registry.view(this.workerId)?.catalog !== undefined; - await this.#refreshRunning(client, status, includeCatalog || !catalogKnown); + await this.#refreshRunning(client, status, receivedAt, includeCatalog || !catalogKnown); } /** The rest of a refresh once `status.get` has answered, for a worker that is not starting: @@ -386,6 +388,7 @@ export class WorkerLink { async #refreshRunning( client: GatewayWorkerClient, status: StatusGetOutput, + receivedAt: number, includeCatalog: boolean, ): Promise { const [devices, catalog, config] = await this.#withTimeout( @@ -414,6 +417,7 @@ export class WorkerLink { this.options.registry.refresh(this.workerId, { ...workerViewFields({ devices, + receivedAt, status, ...(catalog === undefined ? {} : { catalog }), ...(config === undefined ? {} : { config }), @@ -432,10 +436,10 @@ export class WorkerLink { /** A starting worker's view: its health and host, which `workerViewFields` builds from the * answer alone. Dropped for a link a reconnect or `stop()` has replaced, as `#rebuildView`'s own * write is (H2). */ - #refreshStarting(client: GatewayWorkerClient, status: StatusGetOutput): void { + #refreshStarting(client: GatewayWorkerClient, status: StatusGetOutput, receivedAt: number): void { if (this.#superseded()) return; this.options.registry.refresh(this.workerId, { - ...workerViewFields({ status }), + ...workerViewFields({ receivedAt, status }), version: client.daemonVersion, }); } diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index b0dbff4fe..6a9043d98 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -227,9 +227,12 @@ export class WorkerRegistry { * saw, which is more useful to a console than an empty one. */ connected(workerId: string, label: string | undefined, version: string | undefined): WorkerView { - // The catalog the last session read stays, so a reconnecting worker is still known from it + // why: the catalog the last session read stays, so a reconnecting worker is still known from it // (ADR 0009 §4); only when it was read is cleared, since nothing has been read this session. - const { catalogReadAt: _stale, ...existing } = this.#workers.get(workerId) ?? {}; + // why: a new session never shows the old session's reading. + const { catalogReadAt: _stale, ...existing } = withoutLoad>( + this.#workers.get(workerId) ?? {}, + ); const view: WorkerView = { ...existing, connection: "connected", @@ -277,7 +280,7 @@ export class WorkerRegistry { ): WorkerView { const existing = this.#workers.get(workerId); const view: WorkerView = { - ...existing, + ...(existing === undefined ? existing : withoutLoad(existing)), connection: "incompatible", drained: this.#drained.has(workerId), id: workerId, @@ -353,13 +356,16 @@ export class WorkerRegistry { if (existing === undefined) return; const { grantedDevices, ...snapshot } = refresh; const now = this.options.clock.now(); - const next: WorkerView = { - ...(snapshot.health === "starting" ? withoutReadFields(existing) : existing), + const { load: _old, ...held } = + snapshot.health === "starting" ? withoutReadFields(existing) : existing; + const built: WorkerView = { + ...held, ...snapshot, lastSeenAt: now, // ADR 0009 §4: a refresh that carries a catalog is a read of it. ...(snapshot.catalog === undefined ? {} : { catalogReadAt: now }), }; + const next = built.connection === "connected" ? built : withoutLoad(built); this.#workers.set(workerId, next); if (snapshot.catalog !== undefined) this.#lastCatalog.set(workerId, snapshot.catalog); if (snapshot.leases !== undefined) this.#lastLeases.set(workerId, snapshot.leases); @@ -423,7 +429,11 @@ export class WorkerRegistry { // 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. The same goes for the // requests waiting in that worker's own queue. - const { installs: _unknown, waiting: _unknownWaiting, ...withoutInstalls } = existing; + const { + installs: _unknown, + waiting: _unknownWaiting, + ...withoutInstalls + } = withoutLoad(existing); this.#workers.set(workerId, { ...withoutInstalls, connection: "disconnected", @@ -595,3 +605,8 @@ export class WorkerRegistry { return view; } } + +function withoutLoad(view: View): Omit { + const { load: _load, ...rest } = view; + return rest; +} From a8043b927cfadabe80e0357ecc650924c6721fc4 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 15:03:11 +0200 Subject: [PATCH 3/8] chore(contract): workerLoadSchema stays internal --- src/contract/schemas.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index a34a1d83f..cbbcc6183 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -530,7 +530,7 @@ export const hostLoadSchema = z.object({ }); /** ADR 0029 §5: a worker's load as its view carries it: when it was read, on the viewer's clock. */ -export const workerLoadSchema = z.object({ +const workerLoadSchema = z.object({ readAt: z.number().int().min(0), cpu: loadCpuSchema.optional(), memory: loadMemorySchema.optional(), From 132e9ef6bc3c7828a71d426d74f5c323faefc548 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 15:03:58 +0200 Subject: [PATCH 4/8] test(cli): worker list load lookup matches ids with a label --- src/cli/index.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index f36360c4f..bcc3abb17 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -3020,7 +3020,9 @@ describe("CLI: worker commands (ADR 0005 §8/§23)", () => { const lines = stdout.trimEnd().split("\n"); const loadAfter = (id: string) => { - const index = lines.findIndex((line) => line.startsWith(`${id}:`)); + const index = lines.findIndex( + (line) => line.startsWith(`${id}:`) || line.startsWith(`${id} (`), + ); const next = lines[index + 1]; return next?.startsWith(" Load:") === true ? next : undefined; }; From edbf06604516704fec65f7742931198272d9231f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 15:07:50 +0200 Subject: [PATCH 5/8] test(cli): worker list rounds a reading's age up --- src/cli/index.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index bcc3abb17..66a434a06 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -3040,6 +3040,14 @@ describe("CLI: worker commands (ADR 0005 §8/§23)", () => { expect(stdout).toContain(` Load: ${READING} · read 0s ago\n`); }); + it("simlock worker list rounds a reading's age up to whole seconds", async () => { + const stdout = await printWorkers([ + { ...connectedWorker, load: { ...PARTS, readAt: NOW - 1_001 } }, + ]); + + expect(stdout).toContain(` Load: ${READING} · read 2s ago\n`); + }); + it("simlock status against a gateway prints the gateway's own Load line, and each worker's Load line aged from the status time", async () => { const output = outputCapture(); const status: StatusGetOutput = { From 3fa202450a68803d787721b50c90c2f35a1bcf3c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 15:14:57 +0200 Subject: [PATCH 6/8] fix(cli): worker list says which load parts are unavailable, as status does; correct load comments (#533) --- src/cli/index.test.ts | 2 +- src/cli/index.ts | 5 ++--- src/contract/schemas.ts | 2 +- src/contract/worker-view.ts | 4 ++-- src/gateway/worker-link.ts | 2 +- src/gateway/worker-registry.ts | 2 +- 6 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 66a434a06..a84e1d63b 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -3000,7 +3000,7 @@ describe("CLI: worker commands (ADR 0005 §8/§23)", () => { expect(lines[2]).toMatch(/^ {2}Install ios 26\.4: downloading for 60s, 2 waiters$/); expect(lines[3]).toMatch(/^wrk_2: connected, starting/); expect(lines[4]).toBe( - " Load: memory 9.8 GiB of 32.0 GiB available · swap 1.2 GiB used · pressure normal · read 3s ago", + " Load: CPU unavailable · memory 9.8 GiB of 32.0 GiB available · swap 1.2 GiB used · pressure normal · disk unavailable · read 3s ago", ); }); diff --git a/src/cli/index.ts b/src/cli/index.ts index eb6d1b226..603177884 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -2233,7 +2233,7 @@ function workerLoadLine(worker: WorkerView, now: number): string { if (worker.connection === "disconnected") return "\n Load: no reading while disconnected"; if (worker.load === undefined) return ""; const { readAt, ...parts } = worker.load; - return `\n ${formatLoadLine(parts, Math.ceil(Math.max(0, now - readAt) / 1000), "leave out")}`; + return `\n ${formatLoadLine(parts, Math.ceil(Math.max(0, now - readAt) / 1000))}`; } /** A worker's state words: its connection, then `starting` while it has not finished starting, then `drained`. */ @@ -2411,10 +2411,9 @@ function formatLoadCores(cores: number): string { function formatLoadLine( load: Pick, "cpu" | "disk" | "memory">, ageSeconds: number, - unreadParts: "say" | "leave out" = "say", ): string { const { cpu, disk, memory } = load; - const unread = (text: string): string[] => (unreadParts === "say" ? [text] : []); + const unread = (text: string): string[] => [text]; const cpuPart = cpu === undefined ? unread("CPU unavailable") diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index cbbcc6183..965906a35 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -529,7 +529,7 @@ export const hostLoadSchema = z.object({ disk: loadDiskSchema.optional(), }); -/** ADR 0029 §5: a worker's load as its view carries it: when it was read, on the viewer's clock. */ +// why: a view stores when the load was read (`readAt`, the viewer's clock), not its age, so the age stays right as the view sits. const workerLoadSchema = z.object({ readAt: z.number().int().min(0), cpu: loadCpuSchema.optional(), diff --git a/src/contract/worker-view.ts b/src/contract/worker-view.ts index ed0aeb64b..450977c6c 100644 --- a/src/contract/worker-view.ts +++ b/src/contract/worker-view.ts @@ -78,8 +78,8 @@ export function workerViewFields(reads: WorkerReads): WorkerViewReport { const { ageMs, ...parts } = status.load; return { load: { readAt: Math.max(0, receivedAt - ageMs), ...parts } }; })(); - // A starting worker has checked nothing: its view is its health and its host, and every other - // field is absent -- never empty, which would read as "nothing is leased". + // why: a starting worker has checked nothing: its view is its health, its host and its load, and every + // other field is absent -- never empty, which would read as "nothing is leased". if (status.daemon.health === "starting") return { health: "starting", host: status.host, ...load }; return { diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index 1a43182c0..d70be2435 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -433,7 +433,7 @@ export class WorkerLink { return this.#closed || (this.options.isCurrentLink?.() ?? true) === false; } - /** A starting worker's view: its health and host, which `workerViewFields` builds from the + /** why: a starting worker's view is its health, host and load, which `workerViewFields` builds from the * answer alone. Dropped for a link a reconnect or `stop()` has replaced, as `#rebuildView`'s own * write is (H2). */ #refreshStarting(client: GatewayWorkerClient, status: StatusGetOutput, receivedAt: number): void { diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index 6a9043d98..d27bef7cf 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -345,7 +345,7 @@ export class WorkerRegistry { /** * why: replaces what the worker reports, and is partial on purpose: a refresh triggered by a lease event * re-reads status and devices but not the catalog (§7), and an absent key leaves the previous - * value standing rather than blanking it -- except for a `starting` refresh, which says the + * value standing rather than blanking it -- except `load`, which a refresh without one removes, and a `starting` refresh, which says the * worker has checked nothing: it drops capacity, catalog, catalogReadAt, devices, installs, * leases, queueDepth and waiting from the view (absent means "not known"), keeping the last * catalog, leases and physical devices aside for routing and retention. A refresh for a worker whose view is gone From ca7fef9ec7f8bd0fa39d21363e062f1e25894b47 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 15:20:27 +0200 Subject: [PATCH 7/8] docs(gateway): drop ADR section cites and history tags from comments --- src/gateway/worker-link.ts | 5 ++--- src/gateway/worker-registry.ts | 9 +++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index d70be2435..72bac0729 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -433,9 +433,8 @@ export class WorkerLink { return this.#closed || (this.options.isCurrentLink?.() ?? true) === false; } - /** why: a starting worker's view is its health, host and load, which `workerViewFields` builds from the - * answer alone. Dropped for a link a reconnect or `stop()` has replaced, as `#rebuildView`'s own - * write is (H2). */ + /** why: a link a reconnect or `stop()` has replaced must not write, so a stale answer never + * overwrites the view the current link owns. */ #refreshStarting(client: GatewayWorkerClient, status: StatusGetOutput, receivedAt: number): void { if (this.#superseded()) return; this.options.registry.refresh(this.workerId, { diff --git a/src/gateway/worker-registry.ts b/src/gateway/worker-registry.ts index d27bef7cf..4f7451f9a 100644 --- a/src/gateway/worker-registry.ts +++ b/src/gateway/worker-registry.ts @@ -227,8 +227,8 @@ export class WorkerRegistry { * saw, which is more useful to a console than an empty one. */ connected(workerId: string, label: string | undefined, version: string | undefined): WorkerView { - // why: the catalog the last session read stays, so a reconnecting worker is still known from it - // (ADR 0009 §4); only when it was read is cleared, since nothing has been read this session. + // why: the catalog the last session read stays, so a reconnecting worker is still known from it; + // only when it was read is cleared, since nothing has been read this session. // why: a new session never shows the old session's reading. const { catalogReadAt: _stale, ...existing } = withoutLoad>( this.#workers.get(workerId) ?? {}, @@ -344,8 +344,9 @@ export class WorkerRegistry { /** * why: replaces what the worker reports, and is partial on purpose: a refresh triggered by a lease event - * re-reads status and devices but not the catalog (§7), and an absent key leaves the previous - * value standing rather than blanking it -- except `load`, which a refresh without one removes, and a `starting` refresh, which says the + * re-reads status and devices but not the catalog, so an absent key leaves the previous + * value standing rather than blanking it, except `load` (a refresh without one removes it, since a + * stale load would mislead routing) and a `starting` refresh, which says the * worker has checked nothing: it drops capacity, catalog, catalogReadAt, devices, installs, * leases, queueDepth and waiting from the view (absent means "not known"), keeping the last * catalog, leases and physical devices aside for routing and retention. A refresh for a worker whose view is gone From 18183776fcf3f00a701c18ba8dc01658b431486b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 18:13:43 +0200 Subject: [PATCH 8/8] fix: the worker view's load moves the protocol to 36 --- src/contract/protocol.ts | 2 +- src/daemon-protocol/index.test.ts | 2 +- src/gateway/service.test.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 4d8e35cc7..2aabc064c 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 35, max: 35 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 36, max: 36 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 1bddba3d7..08dd076bf 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(35); + expect(DAEMON_PROTOCOL_VERSION).toBe(36); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index ff2e1315b..723b60798 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -1234,7 +1234,7 @@ describe("GatewayService", () => { min: PROTOCOL_VERSION_RANGE.max - 1, max: PROTOCOL_VERSION_RANGE.max - 1, }; - expect(PROTOCOL_VERSION_RANGE.max).toBe(35); + expect(PROTOCOL_VERSION_RANGE.max).toBe(36); expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, previous)).toBeUndefined(); const harness = fleet(); await harness.service.start();