Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/cli/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,24 @@ export function formatWorkers(
: ` -- ${esc(entry.name)} ${esc(entry.state)}`,
)
.join("");
return `${label}: ${state} -- ${capacity}, ${leaseCount(worker)}${skew}${workerVersion(worker)}${host}${capabilities}${load}${workerBaselinesLine(worker)}${installs}`;
const memory = memoryStep(worker);
return `${label}: ${state} -- ${capacity}, ${leaseCount(worker)}${skew}${workerVersion(worker)}${host}${capabilities}${memory}${load}${workerBaselinesLine(worker)}${installs}`;
})
.join("\n");
}

function memoryStep(worker: WorkerView): string {
if (worker.connection === "disconnected") return "";
switch (worker.capacity?.memoryPressure?.step) {
case "warming-paused":
return " -- memory: warming paused";
case "new-devices-paused":
return " -- memory: new devices paused";
default:
return "";
}
}

function workerLoadLine(worker: WorkerView, now: number): string {
if (worker.connection === "disconnected") return "\n Load: no reading while disconnected";
if (worker.load === undefined) return "";
Expand Down
37 changes: 37 additions & 0 deletions src/cli/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10051,6 +10051,43 @@ describe("CLI: a worker's capabilities", () => {
expect(shown).toMatch(/^wrk_4 .* -- agent-device unavailable: starting$/m);
});

it("simlock worker list shows each worker's memory step as the end of its first line, and nothing at none, with no field, or for a disconnected worker", async () => {
const withStep = (
id: string,
step: "none" | "warming-paused" | "new-devices-paused",
extra = {},
) =>
worker({
capabilities: [{ name: "agent-device", state: "available" }],
capacity: { ...worker().capacity, memoryPressure: { step } },
id,
...extra,
});
const shown = await listed([
withStep("wrk_1", "warming-paused"),
withStep("wrk_2", "new-devices-paused"),
withStep("wrk_3", "none"),
worker({ id: "wrk_4" }),
withStep("wrk_5", "new-devices-paused", { connection: "disconnected" }),
]);

const lines = shown.trimEnd().split("\n");
const first = (id: string) => lines.find((line) => line.startsWith(`${id} `));
expect(first("wrk_1")).toBe(
"wrk_1 (mac-mini): connected -- ios 0/2, android 0/2, 0 lease(s) -- agent-device available -- memory: warming paused",
);
expect(first("wrk_2")).toBe(
"wrk_2 (mac-mini): connected -- ios 0/2, android 0/2, 0 lease(s) -- agent-device available -- memory: new devices paused",
);
expect(first("wrk_3")).toBe(
"wrk_3 (mac-mini): connected -- ios 0/2, android 0/2, 0 lease(s) -- agent-device available",
);
expect(first("wrk_4")).toBe("wrk_4 (mac-mini): connected -- ios 0/2, android 0/2, 0 lease(s)");
expect(first("wrk_5")).toBe(
"wrk_5 (mac-mini): disconnected -- ios 0/2, android 0/2, 0 lease(s) -- agent-device available",
);
});

it("worker list prints two entries in the order the worker sent them", async () => {
const shown = await listed([
worker({
Expand Down
48 changes: 46 additions & 2 deletions src/gateway/routing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
freeSlot,
healthy,
idleQueue,
memoryPressure,
ramBudget,
takesRequests,
warmHit,
Expand Down Expand Up @@ -203,6 +204,42 @@ describe("the registered warm-then-free policy", () => {
expect(policy.select(REQUEST, [full])).toMatchObject({ workerId: "wrk_b" });
});

it("ranks a worker whose new devices are paused below one that is not, still picks it for a warm device or when every worker is paused, explains it as memory-pressure, and ranks warming-paused as calm", () => {
const paused = (
id: string,
step: "none" | "warming-paused" | "new-devices-paused",
maxRunning: number,
devices: WorkerView["devices"] = [],
) =>
view(id, {
capacity: { ...withIos({ maxRunning }), memoryPressure: { step } },
devices,
});
// why: wrk_a has more free capacity, so only the pressure rank can prefer wrk_b over it.
const pausedRoomy = paused("wrk_a", "new-devices-paused", 5);
const calm = paused("wrk_b", "none", 1);

expect(policy.select(REQUEST, [pausedRoomy, calm])).toMatchObject({ workerId: "wrk_b" });
expect(
policy.select(REQUEST, [
paused("wrk_a", "new-devices-paused", 5, [deviceFixture("dev_1", "ready")]),
calm,
]),
).toMatchObject({ reason: "warm-hit", workerId: "wrk_a" });
expect(
policy.select(REQUEST, [pausedRoomy, paused("wrk_b", "new-devices-paused", 1)]),
).toMatchObject({
workerId: "wrk_a",
});
expect(policy.explain(REQUEST, [pausedRoomy, calm])).toMatchObject([
{ workerId: "wrk_a", zero: { capacityReason: "memory-pressure", reason: "full" } },
{ workerId: "wrk_b" },
]);
expect(policy.select(REQUEST, [paused("wrk_a", "warming-paused", 5), calm])).toMatchObject({
workerId: "wrk_a",
});
});

it("still picks a worker at its RAM budget for a warm device it holds", () => {
const capacity = withIos({ maxRunning: 1 });
const atBudget = view("wrk_a", {
Expand Down Expand Up @@ -375,7 +412,7 @@ describe("the warm-then-free policy for a physical request", () => {
expect(policy.select(REQUEST, [queued])).toBeUndefined();
});

it("picks, for a physical request, a worker that idle-queue and free-slot would drop and ram-budget would demote, by warm-hit; the four stages are the ones that skip a physical request", () => {
it("picks, for a physical request, a worker that idle-queue and free-slot would drop and ram-budget would demote, by warm-hit; the five stages are the ones that skip a physical request", () => {
const blocked = view("wrk_a", {
capacity: withIos({ atRamBudget: true, maxRunning: 0 }),
devices: [iphone()],
Expand All @@ -399,6 +436,7 @@ describe("the warm-then-free policy for a physical request", () => {
freeSlot,
healthy,
idleQueue,
memoryPressure,
ramBudget,
takesRequests,
warmHit,
Expand All @@ -407,7 +445,13 @@ describe("the warm-then-free policy for a physical request", () => {
.filter(([, stage]) => (stage as { appliesToPhysical?: boolean }).appliesToPhysical === false)
.map(([name]) => name)
.sort();
expect(skipped).toEqual(["freeCapacity", "freeSlot", "idleQueue", "ramBudget"]);
expect(skipped).toEqual([
"freeCapacity",
"freeSlot",
"idleQueue",
"memoryPressure",
"ramBudget",
]);
});

it("gives a virtual request the same pick, reason and stage with and without a ready physical device of its model in the views", () => {
Expand Down
2 changes: 2 additions & 0 deletions src/gateway/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
healthy,
idleQueue,
keepsExcept,
memoryPressure,
ramBudget,
type RoutableRequest,
type RoutingStage,
Expand Down Expand Up @@ -80,6 +81,7 @@ const routingPolicies = {
idleQueue,
warmHit,
freeSlot,
memoryPressure,
ramBudget,
freeCapacity,
],
Expand Down
1 change: 1 addition & 0 deletions src/gateway/routing/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export { hasCapabilities } from "./stages/has-capabilities.js";
export { keepsExcept } from "./stages/keeps-except.js";
export { healthy } from "./stages/healthy.js";
export { idleQueue } from "./stages/idle-queue.js";
export { memoryPressure } from "./stages/memory-pressure.js";
export { ramBudget } from "./stages/ram-budget.js";
export { takesRequests } from "./stages/takes-requests.js";
export { warmHit } from "./stages/warm-hit.js";
Expand Down
19 changes: 19 additions & 0 deletions src/gateway/routing/stages/memory-pressure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { RankStage } from "../pipeline.js";

/** why: ADR 0068 §6 -- a rank, so a paused worker is still asked when it is the only one or holds a
* warm device. It reads only the step the worker reports; `warming-paused` ranks as calm because
* that worker still takes leases. */
export const memoryPressure: RankStage = {
appliesToPhysical: false,
kind: "rank",
name: "memory-pressure",
score(worker) {
return worker.capacity?.memoryPressure?.step === "new-devices-paused" ? 0 : 1;
},
settles: false,
zeroReason(worker) {
return worker.capacity?.memoryPressure?.step === "new-devices-paused"
? { capacityReason: "memory-pressure", reason: "full" }
: undefined;
},
};
84 changes: 84 additions & 0 deletions src/gateway/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,90 @@ describe("GatewayService", () => {
await harness.service.stop();
});

it("refreshes a worker's view at once on its memory.pressure-changed", async () => {
const harness = fleet();
await harness.service.start();
const worker = new ScriptedWorkerClient();
await harness.join("wrk_1", worker);
await vi.waitFor(() => expect(worker.subscribed).toBe(true));
await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.capacity).toBeDefined());
const capacity = statusFixture().capacity;
worker.status = statusFixture({
capacity: { ...capacity, memoryPressure: { step: "new-devices-paused" } },
});

worker.pushEvent({ event: "memory.pressure-changed" });

await vi.waitFor(() =>
expect(harness.service.workers.view("wrk_1")?.capacity?.memoryPressure?.step).toBe(
"new-devices-paused",
),
);

await harness.service.stop();
});

it("asks a worker that refused a request again once its memory.pressure-changed lifts the step, and not before", async () => {
const harness = fleet();
await harness.service.start();
const coordinator = new FleetLeaseCoordinator({
clock: harness.clock,
describeFailure: (error) => ({ code: "INTERNAL", message: String(error) }),
directory: harness.service,
eventBus: harness.eventBus,
execTimeoutMs: 11 * 60_000,
idGenerator: {
generate: (() => {
let next = 1;
return () => `${next++}`;
})(),
},
leaseIndex: new FleetLeaseIndex("gw:instance-1:"),
leaseRequestLimits: { maxRecords: 10_000, retentionMs: 600_000 },
leaseRequestTimeoutMs: 5 * 60_000,
routing: createRoutingPolicy("warm-then-free"),
views: harness.service.workers,
});
const worker = new ScriptedWorkerClient();
const capacity = statusFixture().capacity;
worker.status = statusFixture({
capacity: { ...capacity, memoryPressure: { step: "new-devices-paused" } },
});
worker.catalog = catalogFixture([
{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] },
]);
await harness.join("wrk_1", worker);
await vi.waitFor(() =>
expect(harness.service.workers.view("wrk_1")?.capacity?.memoryPressure?.step).toBe(
"new-devices-paused",
),
);
await vi.waitFor(() => expect(harness.service.workers.view("wrk_1")?.catalog).toHaveLength(1));
const leaseRequests = () => worker.calls.filter((call) => call.startsWith("lease.request"));

void coordinator
.request(
{ model: "iPhone 17", platform: "ios" },
{ allowDownload: false, noWait: false, ownerId: "agent-1", requesterId: "agent-1" },
)
.catch(() => undefined);
await vi.waitFor(() => expect(leaseRequests()).toHaveLength(1));

worker.pushEvent({ event: "memory.pressure-changed" });
await vi.waitFor(() =>
expect(worker.calls.filter((c) => c === "status.get").length).toBeGreaterThan(1),
);
await new Promise((resolve) => setTimeout(resolve, 20));
expect(leaseRequests()).toHaveLength(1);

worker.status = statusFixture({ capacity: { ...capacity, memoryPressure: { step: "none" } } });
worker.pushEvent({ event: "memory.pressure-changed" });

await vi.waitFor(() => expect(leaseRequests()).toHaveLength(2));

await harness.service.stop();
});

it("does not re-read the fleet for an event that changes neither", async () => {
const harness = fleet();
await harness.service.start();
Expand Down
1 change: 1 addition & 0 deletions src/gateway/worker-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,7 @@ function changesCapacityOrLeases(event: string): boolean {
return (
event.startsWith("lease.") ||
event.startsWith("device.") ||
event === "memory.pressure-changed" ||
INSTALL_EVENTS.has(event) ||
(WORKER_VIEW_BASELINE_EVENTS as readonly string[]).includes(event) ||
(WORKER_VIEW_UPDATE_EVENTS as readonly string[]).includes(event)
Expand Down
2 changes: 1 addition & 1 deletion src/source-hygiene.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ type SizedFile = { path: string; lines: number };
* only shrink. A PR that has to grow one raises its number here, as a visible line of its diff.
*/
const SHRINK_ONLY: Record<string, number> = {
"src/cli/index.test.ts": 11637,
"src/cli/index.test.ts": 11674,
"src/drivers/ios/index.test.ts": 5996,
"src/drivers/ios/index.ts": 2700,
"src/leasing/create-leasing.test.ts": 5276,
Expand Down
1 change: 1 addition & 0 deletions website/src/content/docs/docs/gateway/managing-workers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Each worker's line shows:
- devices running out of the limit per platform, and how many leases it holds;
- its Simlock version, with the newest release in brackets when npm has a newer one, and `updating to <version>: <stage>` while it updates (the stage is `waiting for <n> leases`, `installing` or `restarting`);
- its operating system, platform tools and optional modules;
- `memory: warming paused` or `memory: new devices paused` while the worker reports host memory pressure at that step; nothing otherwise, and nothing for a disconnected worker;
- under it, the last load reading, the baselines it holds, and any runtime or system image being installed.

The `Baselines:` line gives each baseline's name and version, its device, and `stale` for one that cannot be used now, for example `Baselines: checkout v2: android Pixel 9, Android 36 (google_apis), full; smoke v1: ios iPhone 17, iOS 27.0, slim, stale`. It says `none` for a worker with no baselines, and is missing while a worker starts up.
Expand Down
2 changes: 1 addition & 1 deletion website/src/content/docs/docs/gateway/routing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ A worker can take a request only when it:
Among those workers, the gateway prefers:

1. **A worker with a warm device.** A booted, unleased device that matches the request, including its slim or full mode, means the agent gets a device without waiting for a boot. For a request that names a baseline, only a copy of the baseline's current version counts.
2. **A worker with room to boot one.** It needs a free device slot, or a warm device it can shut down to make room. Workers under their RAM budget come first, then the worker with the most free device slots.
2. **A worker with room to boot one.** It needs a free device slot, or a warm device it can shut down to make room. Workers whose new devices are not paused by host memory pressure come first (a worker that only paused warming still counts as calm), then workers under their RAM budget, then the worker with the most free device slots. A worker that paused new devices still gets the request when it has a warm match or when every worker is paused.

A request for a physical device goes only to a worker with a matching enrolled device that is free now. If none is free, the request waits.

Expand Down
Loading