Skip to content
8 changes: 8 additions & 0 deletions docs/CONSOLE.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ Each worker shows:
| Devices | How many devices are running, and how many are leased |
| Capacity | Devices running out of the limit, per platform |
| Capabilities | Each optional module the worker knows of, such as agent-device: `available`, `off`, or `unavailable` with its reason |
| Load | The machine's CPU, memory and disk use, such as `CPU 34% · memory 9.8 of 32.0 GiB · disk 112.4 GiB free`. A figure the worker limits itself to, such as a container's, is marked `(limit)`, and one it could not read says `unavailable`. A disconnected worker says "No reading while disconnected" |

A worker the gateway could not read from yet says "Not reported" where it
has nothing to show. A worker that is still starting shows its health as
Expand Down Expand Up @@ -167,6 +168,13 @@ Select a worker to open its page. It adds:
each platform tool, such as Xcode or the Android emulator.
- **Catalog**: the models and runtimes the worker can lease. It is read again
straight after a component is installed, and otherwise every 30 seconds.
- **Load**: how busy the machine is right now: CPU busy share and cores,
memory available of total, swap used, memory pressure (`normal`, `warn` or
`critical`, left out where the system does not report it), and disk free of
total. A part the worker could not read says `Unavailable`. **Read** says how
long ago the reading was taken, and it ticks up until the next one. A
worker that sent no load says "Not reported.", and a disconnected one "No
reading while disconnected."
- **Warm pool**: whether the worker keeps devices warm, the running slots it
holds back per platform, and a row for each kind of device the targets name
(targets that resolve to the same device are one row, their counts added)
Expand Down
44 changes: 44 additions & 0 deletions e2e/console/workers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,50 @@ test.describe("the workers views", () => {
}
});

test("on a single host, a card shows its Load row and the detail shows the Load panel with an age that ticks", async ({
daemon,
page,
}) => {
const [host] = await workerList(daemon);
await openConsole(page, daemon);

const shown = card(page, host?.id ?? "");
await expect(fact(shown, "Load")).toHaveText(/^CPU .*memory .*disk /);
await shown.getByRole("link", { name: host?.id ?? "" }).click();

const panel = page.getByRole("region", { name: "Load", exact: true });
const read = fact(panel, "Read");
await expect(read).toHaveText(/^\d+ s ago$/);
const first = await read.textContent();
await expect(read).not.toHaveText(first ?? "", { timeout: 10_000 });
await expect(fact(panel, "Memory")).toContainText("available");
});

test("a disconnected worker's Load row says No reading while disconnected within a second", async ({
page,
}) => {
const fleet = await startFleet([
{ driverScript: { ios: IOS }, label: "worker-a" },
{ driverScript: { ios: IOS }, label: "worker-b" },
]);
try {
await openConsole(page, fleet.gateway);
const load = fact(card(page, "worker-b"), "Load");
// why: the gateway shows a worker's first reading after its refresh, so allow twice the default 5 s wait.
await expect(load).toHaveText(/^CPU /, { timeout: 10_000 });

await (fleet.workers[1] as RunningDaemon).stop();
await untilTheGatewaySays(
fleet.gateway,
(views) => views.find((view) => view.label === "worker-b")?.connection === "disconnected",
);

await expect(load).toHaveText("No reading while disconnected", { timeout: 1_000 });
} finally {
await disposeFleet(fleet);
}
});

test("a disconnected worker shows as disconnected within a second", async ({ page }) => {
const fleet = await startFleet([
{ driverScript: { ios: IOS }, label: "worker-a" },
Expand Down
25 changes: 25 additions & 0 deletions src/daemon/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2756,6 +2756,31 @@ describe("startDaemon host load", () => {
});
});

it("dials its gateway only after the first host load reading, so the gateway's first status.get carries load", async () => {
const dials: number[] = [];
const listener = createServer((socket) => {
dials.push(Date.now());
socket.destroy();
});
await new Promise<void>((resolve) => listener.listen(0, "127.0.0.1", resolve));
const { port } = listener.address() as { readonly port: number };
try {
const probe = new FakeHostLoadProbe();
await startOnClock({
configOverrides: { gateway: { token: "join-token-load", url: `ws://127.0.0.1:${port}` } },
hostLoadProbe: probe,
});
await new Promise((resolve) => setTimeout(resolve, 100));
expect(dials).toEqual([]);

probe.answer(COUNTERS);

await expect.poll(() => dials.length).toBeGreaterThan(0);
} finally {
await new Promise<void>((resolve) => listener.close(() => resolve()));
}
});

it("fits the load it answers with to the status.get bounds: an age over a day is capped at one day", async () => {
const probe = new FakeHostLoadProbe(COUNTERS);
const { clock, daemon } = await startOnClock({ hostLoadProbe: probe });
Expand Down
9 changes: 6 additions & 3 deletions src/daemon/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -592,14 +592,17 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise<Dae
// why: not awaited, since simlock's start never waits for agent-device, and a daemon that lost
// the socket race never gets here, so it reaps nothing.
if (options.agentDeviceUpstream === undefined) void agentDevice.start();
// Dialled here, once the socket is claimed and `#readyPromise` is set. The gateway's first
// why: dialled here, once the socket is claimed and `#readyPromise` is set. The gateway's first
// `status.get` never parks (it still answers `starting` during convergence), but its
// `events.subscribe` does park on startup readiness, so the refresh that follows the
// subscribe reads `running` instead of keeping `starting`. A daemon that fails its
// claim never reaches this line, so its uplink is never dialled. Nothing awaits the
// uplink: a worker whose gateway is down must still come up and serve its local agents
// (`GatewayUplink` retries on its own backoff).
gatewayUplink?.start();
// (`GatewayUplink` retries on its own backoff). The dial waits for the first host load reading,
// because the gateway reads `status.get` once on connect and next on its 30 s beat, so a dial that beats the first host load reading leaves the worker without a Load for that long.
if (gatewayUplink !== undefined) {
void (hostLoad?.firstReading() ?? Promise.resolve()).then(() => gatewayUplink.start());
}
if (!config.http.enabled) return;
void startHttpGateway().then(
() => resolveGatewayStarted?.(),
Expand Down
32 changes: 32 additions & 0 deletions src/host-load/sampler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,38 @@ describe("HostLoadSampler", () => {
sampler.dispose();
});

it("settles firstReading when the first read is recorded, not before, and whether it succeeded or failed", async () => {
const answered = harness();
let settled = false;
void answered.sampler.firstReading().then(() => (settled = true));
answered.sampler.start();
await flush();
expect(settled).toBe(false);
await answered.settle(counters(10, 100));
expect(settled).toBe(true);

const failed = harness();
let failedSettled = false;
void failed.sampler.firstReading().then(() => (failedSettled = true));
failed.sampler.start();
await failed.settle(new Error("no proc"));
expect(failedSettled).toBe(true);
});

it("settles firstReading at dispose when no read was ever recorded", async () => {
const { sampler } = harness();
let settled = false;
void sampler.firstReading().then(() => (settled = true));
sampler.start();
await flush();
expect(settled).toBe(false);

sampler.dispose();
await flush();

expect(settled).toBe(true);
});

it("holds no timer after dispose(), and a read in flight changes nothing and logs nothing", async () => {
const { clock, probe, sampler, settle, warnings } = harness();
sampler.start();
Expand Down
13 changes: 13 additions & 0 deletions src/host-load/sampler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,21 @@ export class HostLoadSampler {
#reading: { readonly at: number; readonly parts: Omit<HostLoadReading, "ageMs"> } | undefined;
#inFlight = false;
#disposed = false;
#firstReading: Promise<void>;
#markFirstReading: () => void = () => undefined;
#tickTimer: TimerHandle | undefined;
#boundTimer: TimerHandle | undefined;

constructor(private readonly options: HostLoadSamplerOptions) {
this.#logger = (options.logger ?? new NoopLogger()).child("host-load");
this.#firstReading = new Promise((resolve) => {
this.#markFirstReading = resolve;
});
}

/** why: settles once the first read has been recorded, whatever it found, or at dispose; the read's own bound keeps it from waiting longer than that. */
firstReading(): Promise<void> {
return this.#firstReading;
}

start(): void {
Expand All @@ -65,6 +75,7 @@ export class HostLoadSampler {

dispose(): void {
this.#disposed = true;
this.#markFirstReading();
if (this.#tickTimer !== undefined) this.options.clock.cancel(this.#tickTimer);
this.#tickTimer = undefined;
if (this.#boundTimer !== undefined) this.options.clock.cancel(this.#boundTimer);
Expand Down Expand Up @@ -132,6 +143,7 @@ export class HostLoadSampler {
if (this.#states[part] === "read") this.#states[part] = "failed";
}
this.#reading = { at: now, parts: {} };
this.#markFirstReading();
return;
}
for (const part of ["cpu", "memory", "disk"] as const) {
Expand All @@ -146,6 +158,7 @@ export class HostLoadSampler {
if (counters.memory !== undefined) parts.memory = counters.memory;
if (counters.disk !== undefined) parts.disk = counters.disk;
this.#reading = { at: now, parts };
this.#markFirstReading();
}

#note(part: Part, present: boolean): void {
Expand Down
3 changes: 3 additions & 0 deletions ui/src/status.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ const CONNECTIONS: Tones = { connected: "ok", disconnected: "error", incompatibl

const HEALTH: Tones = { running: "ok", starting: "warn", failed: "error" };

const PRESSURE: Tones = { normal: "ok", warn: "warn", critical: "error" };

const INSTALL_STATES: Tones = { downloading: "ok", waiting: "idle" };

const WAITING_STAGES: Tones = { queued: "idle", starting: "ok" };
Expand All @@ -46,3 +48,4 @@ export const connectionStatus = (connection: string) => statusOf(CONNECTIONS, co
export const healthStatus = (health: string) => statusOf(HEALTH, health);
export const installStatus = (state: string) => statusOf(INSTALL_STATES, state);
export const waitingStageStatus = (stage: string) => statusOf(WAITING_STAGES, stage);
export const pressureStatus = (pressure: string) => statusOf(PRESSURE, pressure);
66 changes: 66 additions & 0 deletions ui/src/views/load-model.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";

import { formatBusyPercent, formatBytes, formatCores, loadSummary } from "./load-model";

const MIB = 1024 ** 2;
const GIB = 1024 ** 3;

describe("the load figures", () => {
it("formats bytes, busy % and cores as the CLI's Load line does, including 0, 1023.6 MiB, 0.5 cores, 1 core and 0.001 cores", () => {
expect(formatBytes(0)).toBe("0 B");
expect(formatBytes(300 * MIB)).toBe("300 MiB");
expect(formatBytes(1023.6 * MIB)).toBe("1.0 GiB");
expect(formatBytes(9.8 * GIB)).toBe("9.8 GiB");
expect(formatBusyPercent(33.5)).toBe("34%");
expect(formatBusyPercent(33.4)).toBe("33%");
expect(formatCores(10)).toBe("10 cores");
expect(formatCores(0.5)).toBe("0.5 cores");
expect(formatCores(1)).toBe("1 core");
expect(formatCores(0.01)).toBe("0.01 cores");
expect(formatCores(0.001)).toBe("<0.01 cores");
});
});

const FULL = {
cpu: { busyPercent: 34, cores: 10, limited: false },
disk: { freeBytes: 112.4 * GIB, totalBytes: 494.4 * GIB },
memory: {
availableBytes: 9.8 * GIB,
limited: false,
swapUsedBytes: 0,
totalBytes: 32 * GIB,
},
readAt: 0,
};

describe("the card summary", () => {
it("lists CPU, memory and disk as the table shows, with (limit) on a limited part, including memory under 1 GiB", () => {
expect(loadSummary(FULL)).toBe("CPU 34% · memory 9.8 of 32.0 GiB · disk 112.4 GiB free");
expect(
loadSummary({
...FULL,
cpu: { busyPercent: 61, cores: 2, limited: true },
disk: { freeBytes: 40.2 * GIB, totalBytes: 100 * GIB },
memory: { ...FULL.memory, availableBytes: 3.1 * GIB, limited: true, totalBytes: 8 * GIB },
}),
).toBe("CPU 61% (limit) · memory 3.1 of 8.0 GiB (limit) · disk 40.2 GiB free");
expect(
loadSummary({
...FULL,
memory: { ...FULL.memory, availableBytes: 300 * MIB, totalBytes: 8 * GIB },
}),
).toContain("memory 300 MiB of 8.0 GiB");
});

it("says CPU unavailable, memory unavailable or disk unavailable for an absent part", () => {
const { cpu: _cpu, ...noCpu } = FULL;
const { memory: _memory, ...noMemory } = FULL;
const { disk: _disk, ...noDisk } = FULL;

expect(loadSummary(noCpu)).toBe(
"CPU unavailable · memory 9.8 of 32.0 GiB · disk 112.4 GiB free",
);
expect(loadSummary(noMemory)).toBe("CPU 34% · memory unavailable · disk 112.4 GiB free");
expect(loadSummary(noDisk)).toBe("CPU 34% · memory 9.8 of 32.0 GiB · disk unavailable");
});
});
52 changes: 52 additions & 0 deletions ui/src/views/load-model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type { WorkerView } from "./workers-model";

export type WorkerLoad = NonNullable<WorkerView["load"]>;

const MIB = 2 ** 20;
const GIB = 2 ** 30;

function roundHalfUp(value: number, decimals: number): number {
const scale = 10 ** decimals;
return Math.floor(value * scale + 0.5) / scale;
}

function isGib(bytes: number): boolean {
return bytes > 0 && Math.floor(bytes / MIB + 0.5) >= 1024;
}

export function formatBytes(bytes: number): string {
if (bytes <= 0) return "0 B";
const mebibytes = Math.floor(bytes / MIB + 0.5);
if (mebibytes < 1024) return `${mebibytes} MiB`;
return `${roundHalfUp(bytes / GIB, 1).toFixed(1)} GiB`;
}

export function formatBusyPercent(percent: number): string {
return `${roundHalfUp(percent, 0)}%`;
}

export function formatCores(cores: number): string {
const figure = cores < 0.005 ? "<0.01" : String(roundHalfUp(cores, cores < 0.1 ? 2 : 1));
return `${figure} ${cores === 1 ? "core" : "cores"}`;
}

export function loadSummary(load: WorkerLoad): string {
const { cpu, disk, memory } = load;
const cpuPart =
cpu === undefined
? "CPU unavailable"
: `CPU ${formatBusyPercent(cpu.busyPercent)}${cpu.limited ? " (limit)" : ""}`;
let memoryPart = "memory unavailable";
if (memory !== undefined) {
const bothGib = isGib(memory.availableBytes) && isGib(memory.totalBytes);
const available = bothGib
? roundHalfUp(memory.availableBytes / GIB, 1).toFixed(1)
: formatBytes(memory.availableBytes);
memoryPart = `memory ${available} of ${formatBytes(memory.totalBytes)}${
memory.limited ? " (limit)" : ""
}`;
}
const diskPart =
disk === undefined ? "disk unavailable" : `disk ${formatBytes(disk.freeBytes)} free`;
return [cpuPart, memoryPart, diskPart].join(" · ");
}
Loading
Loading