diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index cedb99f1d..ccc026e90 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -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 diff --git a/src/core/create-core.ts b/src/core/create-core.ts index bd7e04d78..0ba5711af 100644 --- a/src/core/create-core.ts +++ b/src/core/create-core.ts @@ -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, diff --git a/src/core/warm-pool/AGENTS.md b/src/core/warm-pool/AGENTS.md index c4a3e4c5d..da158eec7 100644 --- a/src/core/warm-pool/AGENTS.md +++ b/src/core/warm-pool/AGENTS.md @@ -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. diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index cb2f459b7..fb1eabeae 100644 --- a/src/core/warm-pool/converger.test.ts +++ b/src/core/warm-pool/converger.test.ts @@ -6,6 +6,7 @@ import { WARM_POOL_TICK_MS } from "./converger.js"; import { LearnedKinds } from "./learned.js"; import { device, + fakeMemoryPressure, harness, iphone15, learnedState, @@ -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 = {}; + 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, diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index 87c0c7400..015af42fe 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -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 { @@ -81,6 +82,8 @@ export interface WarmPoolOptions { readonly catalog: Pick; readonly lifecycle: Pick; 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; readonly state: StateDatabase; readonly registry: { @@ -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(); /** The targets the last pass planned for: their counts and specs, which `targeted()` also reads. */ @@ -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(); @@ -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; @@ -617,7 +630,7 @@ export class WarmPool { }; } - #view(): Parameters[0] { + #view(reading: ReturnType): Parameters[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); @@ -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, @@ -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 { + 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; @@ -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): VirtualDevice[] { return devices.map((device) => (down.has(device.id) ? { ...device, state: "shutdown" } : device)); @@ -940,6 +971,7 @@ const TRIGGERS = [ "cleanup.executed", "capacity.changed", "lease.queued", + "memory.pressure-changed", ] as const; function kindFields(spec: VirtualSpec): Record { diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 0ea1d90ab..047a73315 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -185,6 +185,11 @@ function view( /** why: a creation the capacity strategy refuses until the plan has shut a device down. */ refuseProvisionUntilDown?: CapacityRefusalReason; unplanned?: readonly VirtualSpec[]; + pressure?: { + step?: WarmPolicyView["pressure"]["step"]; + mayShed?: boolean; + shedFailed?: readonly string[]; + }; } = {}, ): WarmPolicyView { return { @@ -217,6 +222,11 @@ function view( devices, handoffInFlight: options.handoffInFlight ?? false, resetDevices: new Set(options.reset ?? []), + pressure: { + mayShed: options.pressure?.mayShed ?? true, + shedFailed: new Set(options.pressure?.shedFailed ?? []), + step: options.pressure?.step ?? "none", + }, isClaimed: (id) => options.claimed?.includes(id) ?? false, leases: (options.leased ?? devices.filter((item) => item.state === "leased")).map(leaseOn), now, @@ -1905,4 +1915,130 @@ describe("warm pool policy", () => { }); }); }); + describe("memory pressure", () => { + const kind = spec("iPhone 17"); + const paused = { mayShed: false, step: "warming-paused" as const }; + const waiter = (inFlight = false) => classDemand("full", "ios", inFlight, "iPhone 17"); + + it("at warming-paused starts nothing and reports every short target as memory-pressure, in place of any other reason", () => { + const busy = device("busy", "leased", { spec: spec("iPad Pro") }); + const shut = device("shut", "shutdown", { endedAgo: 20 * minute, spec: kind }); + const cases = [ + { name: "configured target", options: { targets: [{ count: 1, spec: kind }] } }, + { name: "learned kind", options: { learned: [learnedOf(kind)] } }, + { + name: "configured target also short for the reserve", + options: { + limits: { ios: 2 }, + reserve: { ios: 1 }, + targets: [{ count: 1, spec: kind }], + }, + other: "reserve", + proposes: false, + }, + { + name: "configured target also short for a boot that failed", + options: { blocked: [kind], targets: [{ count: 1, spec: kind }] }, + other: "boot-failed", + proposes: false, + }, + { + name: "creation for a queued request", + options: { maxConcurrentBoots: 3, waiting: [waiter(true), waiter(), waiter()] }, + }, + { + name: "boot of a shut-down device for a queued request", + devices: [busy, shut], + options: { waiting: [waiter()] }, + }, + ]; + + const refused = plan( + view([busy], { refuseProvision: "memory-pressure", targets: [{ count: 1, spec: kind }] }), + ); + expect(refused.targets[0]?.short, "a capacity refusal for memory pressure").toBe( + "memory-pressure", + ); + + for (const { devices = [busy], name, options, other, proposes = true } of cases) { + const open = plan(view(devices, options)); + const held = plan(view(devices, { ...options, pressure: paused })); + if (proposes) + expect(open.proposals, `${name} is proposed when memory is not short`).not.toEqual([]); + expect(held.proposals, name).toEqual([]); + expect(open.targets[0]?.short, name).toBe(other); + if (options.targets !== undefined || options.learned !== undefined) + expect(held.targets[0]?.short, name).toBe("memory-pressure"); + } + }); + + it("sheds one idle device a reading: a device no configured target keeps first, then a kept one, least recently used first, never one a waiter would take, one the budget already shuts down or one whose shutdown just failed", () => { + const ofKind = (id: string, endedAgo: number) => + device(id, "ready", { endedAgo, spec: kind }); + const keptOldest = ofKind("kept", 90 * minute); + const extra = ofKind("extra", 40 * minute); + const olderOther = device("older", "ready", { + endedAgo: 60 * minute, + spec: spec("iPad Pro"), + }); + const newerOther = device("newer", "ready", { endedAgo: 5 * minute, spec: spec("iPad Pro") }); + const learnedOnly = device("learned", "ready", { endedAgo: 30 * minute }); + const targets = [{ count: 1, spec: kind }]; + const sheds = ( + devices: readonly VirtualDevice[], + options: Parameters[1] = {}, + pressure: NonNullable[1]>["pressure"]> = {}, + ): string[] => + evaluate( + view(devices, { targets, ...options, pressure: { step: "warming-paused", ...pressure } }), + ).flatMap((proposal) => + proposal.action === "shutdown" && proposal.reason === "memory-pressure" + ? [proposal.deviceId] + : [], + ); + + expect(sheds([keptOldest, newerOther, olderOther]), "unkept, least recently used").toEqual([ + "older", + ]); + expect(sheds([keptOldest, extra]), "a copy past the configured count").toEqual(["extra"]); + expect(sheds([keptOldest]), "a kept device when nothing else is idle").toEqual(["kept"]); + expect( + sheds([learnedOnly, keptOldest], { learned: [learnedOf(learnedOnly.spec)] }), + "a learned kind keeps nothing", + ).toEqual(["learned"]); + expect( + sheds([keptOldest, extra], { spared: targets, targets: [] }), + "a spared target's device counts as kept", + ).toEqual(["extra"]); + expect( + sheds([keptOldest, olderOther, newerOther], { + waiting: [modelDemand("iPad Pro")], + }), + "a device a waiter would take", + ).toEqual(["kept"]); + expect( + sheds([keptOldest, olderOther, newerOther], { claimed: ["older"] }), + "a claimed device", + ).toEqual(["newer"]); + expect( + sheds([keptOldest, olderOther, newerOther], {}, { shedFailed: ["older"] }), + "a device whose shutdown just failed", + ).toEqual(["newer"]); + expect(sheds([keptOldest, olderOther], {}, { mayShed: false }), "no new reading").toEqual([]); + expect(sheds([keptOldest, olderOther], {}, { step: "none" }), "step none").toEqual([]); + expect(sheds([device("busy", "leased")]), "nothing idle").toEqual([]); + + const overBudget = evaluate( + view([keptOldest, olderOther, newerOther], { + limit: 2, + pressure: { step: "warming-paused" }, + targets: [], + }), + ).flatMap((proposal) => (proposal.action === "shutdown" ? [proposal.deviceId] : [])); + expect(overBudget, "a device the budget shuts down is not shed again").toEqual([ + "kept", + "older", + ]); + }); + }); }); diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 56fe2e322..af540eada 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -30,7 +30,8 @@ export type WarmProposal = | "waiting-request" | "displaced" | "target" - | "never-leased-idle"; + | "never-leased-idle" + | "memory-pressure"; readonly target?: VirtualSpec; } | { @@ -57,7 +58,8 @@ export type TargetShort = | "running-limit" | "device-limit" | "ram-budget" - | "reserve"; + | "reserve" + | "memory-pressure"; /** A target's kind as reported: the platform, the exact model, and the OS and mode it names. */ export interface TargetKind { @@ -132,6 +134,12 @@ export interface WarmPolicyView { * the reset's point is that they stay down, so they are never booted back unasked. */ readonly resetDevices: ReadonlySet; + /** why: the worker's memory pressure step (ADR 0068), whether a reading not yet used may shed a device, and the devices whose shutdown failed in the last 30 s. */ + readonly pressure: { + readonly step: "none" | "warming-paused" | "new-devices-paused"; + readonly mayShed: boolean; + readonly shedFailed: ReadonlySet; + }; } type Slots = { global: number; ios: number; android: number }; @@ -173,11 +181,17 @@ export function evaluate(view: WarmPolicyView): WarmPlan { const bootable = view.devices.filter( (device) => device.state === "shutdown" && mayBeGranted(device) && idle(device), ); - const queued = boots(view, running, bootable, room); + // why: ADR 0068 §3: at `warming-paused` the pool starts nothing, for a target, a learned kind or a waiter. + const queued: QueuePass = + view.pressure.step === "none" + ? boots(view, running, bootable, room) + : { proposals: [], started: 0, stuck: new Set() }; const keeps = queued.proposals; const targets = mergeTargets(view.targets); const unneeded = neverLeasedIdle(view, running, shutdowns, room); const proposed = new Set([...shutdowns, ...unneeded].map((proposal) => proposal.deviceId)); + const shed = shedForPressure(view, running, proposed); + for (const proposal of shed) proposed.add(proposal.deviceId); const sparedDevices = targetedDevices({ ...view, learned: [], targets: view.spared }); const wanted = planTargets( view, @@ -195,7 +209,7 @@ export function evaluate(view: WarmPolicyView): WarmPlan { : running.filter((device) => !proposed.has(device.id) && !sparedDevices.has(device.id)), ); return { - proposals: [...shutdowns, ...keeps, ...unneeded, ...wanted.proposals], + proposals: [...shutdowns, ...keeps, ...unneeded, ...shed, ...wanted.proposals], targets: wanted.reports, }; } @@ -574,6 +588,36 @@ function neverLeasedIdle( return proposals; } +/** + * why: ADR 0068 §3: while warming is paused each new reading gives memory back by shutting down + * one idle device: first one no configured target keeps, then a kept one, least recently used + * first, never one a waiting request would be granted (the budget's own shield) or one whose + * shutdown just failed. + */ +function shedForPressure( + view: WarmPolicyView, + running: readonly VirtualDevice[], + proposed: ReadonlySet, +): DeviceProposal[] { + if (view.pressure.step === "none" || !view.pressure.mayShed) return []; + const kept = targetedDevices({ + ...view, + learned: [], + targets: [...view.targets, ...view.spared], + waiting: [], + }); + const candidates = running.filter( + (device) => + !proposed.has(device.id) && + !view.pressure.shedFailed.has(device.id) && + !view.waiting.some((demand) => !demand.inFlight && serves(device, demand)), + ); + const victim = candidates.find((device) => !kept.has(device.id)) ?? candidates[0]; + return victim === undefined + ? [] + : [{ action: "shutdown", deviceId: victim.id, reason: "memory-pressure" }]; +} + /** Why a slot of `platform` is not free for an idle warm device, when it is not. */ function slotShort( room: Slots, @@ -588,7 +632,9 @@ function slotShort( /** What the capacity strategy's refusal means for a target's report. */ function shortOf(refusal: CapacityRefusalReason | undefined): TargetShort | undefined { if (refusal === undefined) return undefined; - return refusal === "device-limit" || refusal === "ram-budget" ? refusal : "running-limit"; + return refusal === "device-limit" || refusal === "ram-budget" || refusal === "memory-pressure" + ? refusal + : "running-limit"; } /** What `planTargets` shares across targets: the room left, the devices taken, the boots begun. */ @@ -694,6 +740,23 @@ function planTargets( return { proposals: plan.proposals, reports }; } +/** why: at `warming-paused` a target adds nothing and, unless a boot of its own is still running, is short for memory pressure. */ +function heldByPressure(filling: boolean): { added: number; short?: TargetShort } { + return filling ? { added: 0 } : { added: 0, short: "memory-pressure" }; +} + +/** why: what stops a target from adding anything this pass (pressure, a waiter it could not serve, a retry delay), or undefined when it may add. */ +function holdFill( + plan: TargetPlan, + spec: VirtualSpec, + filling: boolean, +): { added: number; short?: TargetShort } | undefined { + if (plan.view.pressure.step !== "none") return heldByPressure(filling); + if (plan.stuck.has(spec.platform)) return { added: 0 }; + if (plan.view.retry.mayAttempt(spec, plan.view.now)) return undefined; + return filling ? { added: 0 } : { added: 0, short: "boot-failed" }; +} + /** * why: adds the boots and creations a target is missing, after the queue's. A target with a boot * already running or one proposed here is still filling, and one on a platform where a waiter @@ -706,10 +769,8 @@ function fillTarget( filling: boolean, count: "configured" | "learned", ): { added: number; short?: TargetShort } { - if (plan.stuck.has(spec.platform)) return { added: 0 }; - if (!plan.view.retry.mayAttempt(spec, plan.view.now)) { - return filling ? { added: 0 } : { added: 0, short: "boot-failed" }; - } + const held = holdFill(plan, spec, filling); + if (held !== undefined) return held; let added = 0; for (let left = missing; left > 0 && plan.started < plan.view.config.maxConcurrentBoots; left--) { const refused = addDisplacing(plan, spec, count); diff --git a/src/core/warm-pool/test-fixtures.ts b/src/core/warm-pool/test-fixtures.ts index 8baeba038..430de497b 100644 --- a/src/core/warm-pool/test-fixtures.ts +++ b/src/core/warm-pool/test-fixtures.ts @@ -4,6 +4,7 @@ import { EventBus } from "../../bus/index.js"; import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../../ports/index.js"; import type { CurrentBaseline } from "../baselines.js"; import type { RunningCapacity } from "../capacity/index.js"; +import type { MemoryPressureReader } from "../core-ports.js"; import { DeviceOperationClaims } from "../device-operation-claims.js"; import { exactRequirement, @@ -107,6 +108,28 @@ export type BaselineFixture = Partial< Pick > & { readonly version: number }; +type PressureReading = ReturnType; + +/** why: a memory pressure port the test drives: `reading` sets the state and calls every listener, as the sampler does after each reading. */ +export function fakeMemoryPressure(initial?: PressureReading) { + let current = initial; + const listeners = new Set<() => void>(); + return { + reader: { + current: () => current, + onReading: (listener: () => void) => { + listeners.add(listener); + return () => void listeners.delete(listener); + }, + } satisfies MemoryPressureReader, + reading(next: PressureReading): void { + current = next; + for (const listener of listeners) listener(); + }, + listeners: () => listeners.size, + }; +} + export function harness( initial: readonly VirtualDevice[], options: { @@ -142,6 +165,8 @@ export function harness( baselines?: Readonly>; /** why: what a platform's catalog read answers; by default a catalog that lists nothing. */ catalog?: (platform?: Platform) => Promise; + /** why: the worker's memory pressure; by default none, so no step is held. */ + memoryPressure?: MemoryPressureReader; } = {}, ) { const clock = new FakeClock(now); @@ -313,6 +338,7 @@ export function harness( }, }, logger: new JsonLinesLogger({ clock, sink }), + memoryPressure: options.memoryPressure ?? fakeMemoryPressure().reader, provisioner: { provision: async (spec, provisionOptions) => { const record: (typeof provisionCalls)[number] = { diff --git a/website/src/content/docs/docs/reference/events.mdx b/website/src/content/docs/docs/reference/events.mdx index 07727ce54..95b1327f4 100644 --- a/website/src/content/docs/docs/reference/events.mdx +++ b/website/src/content/docs/docs/reference/events.mdx @@ -125,7 +125,7 @@ release and records nothing. | --- | --- | --- | --- | | `capacity.changed` | The worker's running figures changed, and once at start. | `ios`, `android`, `global`, each with `running`, `maxRunning`, `reserved`, `warm`; `ramBudget` (`usedBytes`, `limitBytes`) under the `resource` strategy | Relayed | | `queue.changed` | A request joined or left the queue, and once at start. | `depth` (requests waiting in that line), `physical: true` when the physical line changed | Own and relayed | -| `warm-pool.target-missed` | A `warmPool.targets` entry went short and the pool could do nothing about it. Once per time it goes short. | `platform`, `model`, `osVersion`, `mode`, `origin` (always `configured`), `count`, `ready`, `reason` (`no-driver`, `runtime-missing`, `unknown-model`, `unresolvable`, `boot-failed`, `device-limit`, `running-limit`, `reserve`, `ram-budget`) | Relayed | +| `warm-pool.target-missed` | A `warmPool.targets` entry went short and the pool could do nothing about it. Once per time it goes short. | `platform`, `model`, `osVersion`, `mode`, `origin` (always `configured`), `count`, `ready`, `reason` (`no-driver`, `runtime-missing`, `unknown-model`, `unresolvable`, `boot-failed`, `device-limit`, `running-limit`, `reserve`, `ram-budget`, `memory-pressure`) | Relayed | ## Devices diff --git a/website/src/content/docs/docs/worker/capacity.mdx b/website/src/content/docs/docs/worker/capacity.mdx index 413e4f63a..075c2a1e5 100644 --- a/website/src/content/docs/docs/worker/capacity.mdx +++ b/website/src/content/docs/docs/worker/capacity.mdx @@ -178,6 +178,7 @@ What the warm pool does and does not do: - Your targets come first. To fill a target, it may shut down an idle device that only a learned kind keeps. - It never downloads a runtime or system image. A target whose runtime is missing stays short. - A booted device that nobody leases and nothing keeps warm is shut down after `idle.shutdownAfterMs` (10 minutes). See [Cleanup](/simlock/docs/worker/cleanup). +- When host memory pressure pauses warming, it starts nothing, a target left short reports `memory-pressure`, and each new memory reading it shuts down one idle device. It fills its targets again when the pause lifts. - A target that fails to boot is tried again after 1, 2, 4 and so on minutes, at most 10 minutes apart. | Key | Meaning | Default |