Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
57f432d
test: each reading while warming is paused shuts down one idle device…
V3RON Nov 6, 2026
084d406
feat(warm-pool): each reading while warming is paused sheds one idle …
V3RON Nov 6, 2026
913509a
test: at warming-paused the warm pool starts nothing and reports why …
V3RON Nov 6, 2026
80b0a9f
feat(warm-pool): at warming-paused the pool proposes no boot or creat…
V3RON Nov 6, 2026
7a3c014
test: a capacity refusal for memory pressure reports the target short…
V3RON Nov 6, 2026
a36c7a0
feat(warm-pool): a memory-pressure capacity refusal is the short memo…
V3RON Nov 6, 2026
80c9376
test: a paused pool reports memory-pressure and keeps a target's own …
V3RON Nov 6, 2026
9f44796
test: a shed takes a device no configured target keeps first, never o…
V3RON Nov 6, 2026
86c1329
feat(warm-pool): a shed takes unkept devices first and spares waiters…
V3RON Nov 6, 2026
87ac1d4
test: the waiter in the shed test asks for the iPad Pro by model (#1363)
V3RON Nov 6, 2026
0e8b674
test: a shed skips a device whose shutdown just failed and none runs …
V3RON Nov 6, 2026
db12799
feat(warm-pool): a shed skips a device whose shutdown failed in the l…
V3RON Nov 6, 2026
16aa937
test: when warming resumes the pool fills its targets again on memory…
V3RON Nov 6, 2026
f98b441
feat(warm-pool): memory.pressure-changed asks for a pass (#1363)
V3RON Nov 6, 2026
ba446c7
docs(warm-pool): the pool pauses and sheds at memory pressure; memory…
V3RON Nov 6, 2026
ac2367c
refactor(warm-pool): the pressure hold of a target is one helper (#1363)
V3RON Nov 6, 2026
fafe42f
Merge remote-tracking branch 'origin/task/1362' into HEAD
V3RON Nov 6, 2026
5b47198
test(warm-pool): a shed never repeats a device the budget shuts down …
V3RON Nov 6, 2026
1b9ed76
Merge remote-tracking branch 'origin/task/1362' into task/1363
V3RON Nov 6, 2026
c31c67c
test(warm-pool): memory-pressure also replaces boot-failed (#1363)
V3RON Nov 6, 2026
4a50073
docs(warm-pool): the manual no longer copies the shutdown-failure del…
V3RON Nov 6, 2026
47a8fb1
refactor(warm-pool): fillTarget's early holds move to holdFill (#1363)
V3RON Nov 6, 2026
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
2 changes: 1 addition & 1 deletion docs/internal/EVENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ worker is ever contacted. `lease-id-taken` (ADR 0020; widens a published vocabul
|---|---|---|---|---|
| `capacity.changed` | per platform (`ios`, `android`) and `global`: running, max running, reserved, warm; `ramBudget` (used bytes, limit bytes) only under the `resource` capacity strategy | a worker's capacity figures differ from the last ones emitted: after a registry commit, or after a provisioning or boot reservation is taken or released. Emitted once when the daemon has started, so every run begins with a step; two consecutive events never carry equal figures. The figures are the ones `simlock status` reports | CapacityObserver (worker) | implemented |
| `queue.changed` | depth, `physical: true` when the physical line changed (ADR 0022 §3, additive, events rule 6) | the number of requests waiting in a queue changed: a request joined it or left it. A queue has two lines; `depth` is the changed line's, and the event without `physical` is the virtual line's. Emitted once when the daemon has started. A worker emits it for its own queue and a gateway for its fleet queue; a worker's events a gateway relays carry `workerId`, and the gateway's own do not | WaitQueue (worker) / FleetLeaseCoordinator (gateway) | implemented |
| `warm-pool.target-missed` | `{ platform, model, osVersion?, mode, origin, count, ready, reason }` — `origin` is always `configured`: the event is for the `warmPool.targets` entries, never for a kind the pool learned, and `count` is the configured count (ADR 0038 §8); `osVersion` is the resolved one, or the configured one for a target that did not resolve, and absent when it names none and did not resolve; `reason` is the one reason the pool records for the target (`warm-pool/policy.ts` for one that resolved, `warm-pool/converger.ts` for one the resolver refused), the one `short` carries in `status.get` (the one reason `simlock status` shows as the target's `short`, but never `disabled`, since a pool that is off reports no target: `no-driver`, `runtime-missing`, `unknown-model`, `unresolvable`, `boot-failed`, `device-limit`, `running-limit`, `reserve` or `ram-budget`) | a warm pool target went short: after a pass the pool could do nothing for a target that has fewer ready devices than its count, and it was not already missed (ADR 0017 §7). Emitted once the pass's actions have run (events rule 3), once per report on that edge (targets that resolve to one spec are one report and emit one event between them, with their counts added; each target the resolver refuses emits its own), not on each short pass after, nor when a retry or a boot fills it and it is short again; the edge is kept per configured target, and only ready devices reaching its count end the miss, so a target met in between and missed again emits again. A target that is filling, held by `warmPool.maxConcurrentBoots` or waiting behind a queued request the pool could not serve is not short | WarmPool (worker) | implemented |
| `warm-pool.target-missed` | `{ platform, model, osVersion?, mode, origin, count, ready, reason }` — `origin` is always `configured`: the event is for the `warmPool.targets` entries, never for a kind the pool learned, and `count` is the configured count (ADR 0038 §8); `osVersion` is the resolved one, or the configured one for a target that did not resolve, and absent when it names none and did not resolve; `reason` is the one reason the pool records for the target (`warm-pool/policy.ts` for one that resolved, `warm-pool/converger.ts` for one the resolver refused), the one `short` carries in `status.get` (the one reason `simlock status` shows as the target's `short`, but never `disabled`, since a pool that is off reports no target: `no-driver`, `runtime-missing`, `unknown-model`, `unresolvable`, `boot-failed`, `device-limit`, `running-limit`, `reserve`, `ram-budget` or `memory-pressure`) | a warm pool target went short: after a pass the pool could do nothing for a target that has fewer ready devices than its count, and it was not already missed (ADR 0017 §7). Emitted once the pass's actions have run (events rule 3), once per report on that edge (targets that resolve to one spec are one report and emit one event between them, with their counts added; each target the resolver refuses emits its own), not on each short pass after, nor when a retry or a boot fills it and it is short again; the edge is kept per configured target, and only ready devices reaching its count end the miss, so a target met in between and missed again emits again. A target that is filling, held by `warmPool.maxConcurrentBoots` or waiting behind a queued request the pool could not serve is not short | WarmPool (worker) | implemented |

## Device lifecycle

Expand Down
1 change: 1 addition & 0 deletions src/core/create-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@ export function createCore(options: CoreOptions): Core {
idle: options.config.idle,
lifecycle: deviceLifecycle,
...(options.logger === undefined ? {} : { logger: options.logger }),
memoryPressure,
provisioner,
registry,
state: options.state,
Expand Down
1 change: 1 addition & 0 deletions src/core/warm-pool/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ The plan (`evaluate`), in this order: pool off → over budget → the queue →
- No target is filled while a waiter on its platform is one the pass could not serve.
- Every configured count fills before any learned count.
- Only displacement shuts a device down for a target or learned kind, and never one a configured count keeps; what does not fit is reported short. Nothing is displaced when the capacity strategy would still refuse the kind after the shutdown.
- At memory pressure `warming-paused` or higher (ADR 0068) the queue, the targets and the learned kinds propose no boot or creation, and a short target reports `memory-pressure` instead of any capacity reason (a target that does not resolve keeps its own). Each reading not yet used sheds one idle device: first one no configured count keeps, then a kept one, least recently used first, never one a waiter would take or one whose shutdown failed recently. `memory.pressure-changed` asks for a pass, so the pool fills again at once when the step lifts.
- `reserveRunning` holds slots from idle devices only; it never holds back a request.
- An `unresolvable` target keeps its last spec, so its devices stay spared.

Expand Down
116 changes: 116 additions & 0 deletions src/core/warm-pool/converger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { WARM_POOL_TICK_MS } from "./converger.js";
import { LearnedKinds } from "./learned.js";
import {
device,
fakeMemoryPressure,
harness,
iphone15,
learnedState,
Expand Down Expand Up @@ -536,6 +537,121 @@ describe("warm pool converger", () => {
});
});

describe("warm pool memory pressure", () => {
const paused = (readingAt: number) => ({
cause: { availablePercent: 12, level: "warn" as const, trigger: "level" as const },
readingAt,
since: now,
step: "warming-paused" as const,
});

it("each reading while warming is paused shuts down one idle device", async () => {
const pressure = fakeMemoryPressure(paused(now));
const rig = harness(
[
device("old", "ready", 90 * minute),
device("mid", "ready", 60 * minute),
device("new", "ready", 5 * minute),
],
{ memoryPressure: pressure.reader },
);
rig.pool.start();

pressure.reading(paused(now + 15_000));
await rig.pool.settle();
expect(rig.shutdownCalls).toEqual(["old"]);

pressure.reading(paused(now + 30_000));
await rig.pool.settle();
expect(rig.shutdownCalls).toEqual(["old", "mid"]);

await rig.pool.pass();
expect(rig.shutdownCalls, "a second pass on the same reading").toEqual(["old", "mid"]);
});

it("sheds nothing for a reading before start, at step none, with no step reading or nothing idle, and skips a device whose shutdown just failed", async () => {
const idle = () => [device("old", "ready", 90 * minute), device("mid", "ready", 60 * minute)];
const none = { ...paused(now), step: "none" as const };
const cases = [
{ name: "before start", reading: paused(now + 15_000), start: false },
{ name: "step none", reading: none },
{ name: "no step reading", reading: undefined },
{
devices: [device("old", "leased", 90 * minute)],
name: "nothing idle",
reading: paused(now + 15_000),
},
];
for (const { devices = idle(), name, reading, start = true } of cases) {
const pressure = fakeMemoryPressure(reading);
const rig = harness(devices, { memoryPressure: pressure.reader });
if (start) rig.pool.start();
pressure.reading(reading === undefined ? undefined : { ...reading, readingAt: now + 15_000 });
await rig.pool.settle();
expect(rig.shutdownCalls, name).toEqual([]);
}

const pressure = fakeMemoryPressure(paused(now));
const failing = harness(idle(), {
memoryPressure: pressure.reader,
shutdown: async (target) => {
if (target.id === "old") throw new Error("the simulator would not stop");
return { ...target, state: "shutdown" };
},
});
failing.pool.start();
pressure.reading(paused(now + 15_000));
await failing.pool.settle();
pressure.reading(paused(now + 30_000));
await failing.pool.settle();
expect(failing.shutdownCalls, "the next reading takes the next device").toEqual(["old", "mid"]);
});

it("when warming resumes the pool fills its targets again on memory.pressure-changed, with no tick", async () => {
const pressure = fakeMemoryPressure(paused(now));
const rig = harness([], { memoryPressure: pressure.reader, targets: [iphone15] });
rig.pool.start();
await rig.pool.pass();
await rig.pool.settle();
expect(rig.provisionCalls, "nothing is created while paused").toEqual([]);

pressure.reading({ readingAt: now + 15_000, step: "none" });
rig.eventBus.emit(
"memory.pressure-changed",
{ from: "warming-paused", to: "none" },
"host-load",
);
await rig.pool.settle();

expect(rig.provisionCalls).toHaveLength(1);
});

it("at warming-paused reports a short target memory-pressure, a target that does not resolve its own reason, and boots nothing", async () => {
const rig = harness([device("shut", "shutdown", 1_000)], {
memoryPressure: fakeMemoryPressure(paused(now)).reader,
resolve: (request) =>
request.model === "iPhone 17"
? { message: "iOS 27.0 is not installed", refusal: "runtime-missing" }
: { spec: { model: "iPhone 15", osVersion: "26.0", physical: false, platform: "ios" } },
targets: [iphone15, { ...iphone15, model: "iPhone 17", osVersion: "27.0" }],
});
const reasons: Record<string, string> = {};
rig.eventBus.subscribe("warm-pool.target-missed", ({ payload }) => {
reasons[payload.model] = payload.reason;
});

await rig.pool.pass();
await rig.pool.settle();

expect(reasons).toEqual({ "iPhone 15": "memory-pressure", "iPhone 17": "runtime-missing" });
expect(
Object.fromEntries(rig.pool.figures().targets.map((target) => [target.model, target.short])),
).toEqual({ "iPhone 15": "memory-pressure", "iPhone 17": "runtime-missing" });
expect(rig.bootCalls).toEqual([]);
expect(rig.provisionCalls).toEqual([]);
});
});

describe("warm pool targets", () => {
const iphone17: WarmTarget = {
count: 1,
Expand Down
36 changes: 34 additions & 2 deletions src/core/warm-pool/converger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
type CapacityCoordinator,
plannedCapacityDevice,
} from "../capacity/index.js";
import type { MemoryPressureReader } from "../core-ports.js";
import type { DeviceOperationClaims } from "../device-operation-claims.js";
import type { DeviceProvisioner } from "../device-provisioner.js";
import {
Expand Down Expand Up @@ -81,6 +82,8 @@ export interface WarmPoolOptions {
readonly catalog: Pick<DriverCatalog, "listCatalog">;
readonly lifecycle: Pick<ManagedDeviceLifecycle, "bootWarm" | "shutdown">;
readonly logger?: Logger;
/** why: ADR 0068 §3: the pool starts nothing at `warming-paused` and sheds one idle device per reading. */
readonly memoryPressure: MemoryPressureReader;
readonly provisioner: Pick<DeviceProvisioner, "provision">;
readonly state: StateDatabase;
readonly registry: {
Expand Down Expand Up @@ -135,6 +138,8 @@ export class WarmPool {
/** A graceful stop is draining: what is in flight finishes, and nothing new starts. */
#draining = false;
#started = false;
/** why: the `readingAt` of the reading the last shed was proposed for: a reading sheds once, however many passes run on it. */
#shedAt: number | undefined;
/** Devices shut down under an operator reset that have not left `shutdown` since. */
readonly #reset = new Set<string>();
/** The targets the last pass planned for: their counts and specs, which `targeted()` also reads. */
Expand Down Expand Up @@ -184,6 +189,12 @@ export class WarmPool {
for (const event of TRIGGERS) {
this.#unsubscribe.push(this.options.eventBus.subscribe(event, () => this.#trigger()));
}
this.#unsubscribe.push(
this.options.memoryPressure.onReading(() => {
const step = this.options.memoryPressure.current()?.step ?? "none";
if (step !== "none") this.#trigger();
}),
);
this.#subscribeLearning();
this.#closeOpenRows();
this.#armTick();
Expand Down Expand Up @@ -449,7 +460,9 @@ export class WarmPool {
this.#closeOpenRows();
try {
const refused = await this.#resolveEnabled();
const plan = await this.options.decisions.run(() => evaluate(this.#view()));
const reading = this.options.memoryPressure.current();
const plan = await this.options.decisions.run(() => evaluate(this.#view(reading)));
if (reading !== undefined && plan.proposals.some(isShed)) this.#shedAt = reading.readingAt;
const everyReport = [...refused, ...plan.targets];
const reports = configuredOnly(everyReport);
this.#figured = everyReport;
Expand Down Expand Up @@ -617,7 +630,7 @@ export class WarmPool {
};
}

#view(): Parameters<typeof evaluate>[0] {
#view(reading: ReturnType<MemoryPressureReader["current"]>): Parameters<typeof evaluate>[0] {
const { leases, virtualDevices: all } = this.options.registry.snapshot;
for (const id of this.#reset) {
if (all.find((device) => device.id === id)?.state !== "shutdown") this.#reset.delete(id);
Expand Down Expand Up @@ -664,6 +677,12 @@ export class WarmPool {
leases,
now: this.options.clock.now(),
onItsWay: this.#onItsWay(devices),
pressure: {
mayShed:
reading !== undefined && reading.readingAt > (this.#shedAt ?? Number.NEGATIVE_INFINITY),
shedFailed: this.#recentShutdownFailures(),
step: reading?.step ?? "none",
},
resetDevices: new Set(this.#reset),
retry: this.#schedule,
spared: this.#spared,
Expand Down Expand Up @@ -857,6 +876,14 @@ export class WarmPool {
});
}

/** why: the devices whose shutdown failed less than a tick ago, which a shed skips so the next reading takes the next device. */
#recentShutdownFailures(): ReadonlySet<string> {
const now = this.options.clock.now();
return new Set(
[...this.#retryAfter].flatMap(([deviceId, after]) => (after > now ? [deviceId] : [])),
);
}

/** The device, when it is still in `state`, has no lease and no operation claim on it. */
#unleased(deviceId: string, state: VirtualDevice["state"]): VirtualDevice | undefined {
const { leases, virtualDevices: devices } = this.options.registry.snapshot;
Expand All @@ -883,6 +910,10 @@ export class WarmPool {
}
}

function isShed(proposal: WarmProposal): boolean {
return proposal.action === "shutdown" && proposal.reason === "memory-pressure";
}

/** why: `devices` with the ones in `down` as they are once shut down, for a capacity question about the plan so far. */
function shutDownIn(devices: readonly VirtualDevice[], down: ReadonlySet<string>): VirtualDevice[] {
return devices.map((device) => (down.has(device.id) ? { ...device, state: "shutdown" } : device));
Expand Down Expand Up @@ -940,6 +971,7 @@ const TRIGGERS = [
"cleanup.executed",
"capacity.changed",
"lease.queued",
"memory.pressure-changed",
] as const;

function kindFields(spec: VirtualSpec): Record<string, string> {
Expand Down
Loading
Loading