Skip to content
6 changes: 6 additions & 0 deletions docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <key>|set <key> <value>]`

Show the effective configuration (defaults + config file + overrides): the
Expand Down
17 changes: 17 additions & 0 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 11 additions & 2 deletions e2e/single-host-fleet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,26 @@ async function httpHost(): Promise<HttpHost> {
}

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" }],
Expand Down
140 changes: 140 additions & 0 deletions src/cli/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2941,6 +2941,146 @@ 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: CPU unavailable · memory 9.8 GiB of 32.0 GiB available · swap 1.2 GiB used · pressure normal · disk unavailable · 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}:`) || 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 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 = {
...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({
Expand Down
67 changes: 37 additions & 30 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 =
Expand All @@ -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))}`;
}

/** A worker's state words: its connection, then `starting` while it has not finished starting, then `drained`. */
function workerState(worker: WorkerView): string {
return [
Expand Down Expand Up @@ -2411,32 +2408,40 @@ function formatLoadCores(cores: number): string {
return String(roundHalfUp(cores, cores < 0.1 ? 2 : 1));
}

function formatLoadLine(load: NonNullable<StatusGetOutput["load"]>): string {
function formatLoadLine(
load: Pick<NonNullable<StatusGetOutput["load"]>, "cpu" | "disk" | "memory">,
ageSeconds: number,
): string {
const { cpu, disk, memory } = load;
const unread = (text: string): string[] => [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`,
...(memory.pressure === undefined ? [] : [`pressure ${memory.pressure}`]),
];
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. */
Expand Down Expand Up @@ -2477,7 +2482,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"
Expand Down
12 changes: 12 additions & 0 deletions src/contract/doc-samples.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
2 changes: 1 addition & 1 deletion src/contract/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Loading
Loading