From 49182f637d208e4e5dcfee6b0b0b4453a594271a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:24:24 +0200 Subject: [PATCH 01/31] test: the warm pool creates one device per waiter behind the head under the boot cap (#774) --- src/core/domain.ts | 1 + src/core/warm-pool/policy.test.ts | 52 ++++++++++++++++++++ src/leasing/lease-acquisition-coordinator.ts | 1 + 3 files changed, 54 insertions(+) diff --git a/src/core/domain.ts b/src/core/domain.ts index 76199f8eb..bbb3a00e4 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -136,6 +136,7 @@ export interface WaitingDemand { readonly platform: Platform; readonly requirement: DeviceRequirement; readonly mode: DeviceMode; + readonly spec: VirtualSpec; readonly classOf: (model: string) => DeviceClass | undefined; } diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 01ebbea85..670cf0a0a 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -98,12 +98,14 @@ function classDemand( mode: "slim" | "full" = "full", platform: "ios" | "android" = "ios", inFlight = false, + model = "iPhone 15", ) { return { classOf, inFlight, mode, platform, + spec: spec(model, { platform, ...(mode === "slim" ? { mode } : {}) }), requirement: { imageTag: undefined, osVersion: { kind: "installed", versions: ["26.0"] }, @@ -119,6 +121,7 @@ function modelDemand(model: string): WaitingDemand { inFlight: false, mode: "full", platform: "ios", + spec: spec(model), requirement: { imageTag: undefined, osVersion: { kind: "exact", version: "26.0" }, @@ -184,6 +187,55 @@ function view( } describe("warm pool policy", () => { + it("proposes, for waiters behind the head and in queue order, one creation of each waiter's spec, up to maxConcurrentBoots, and nothing for the head", () => { + const creation = (model: string) => ({ + action: "provision", + reason: "waiting-request", + spec: spec(model), + target: spec(model), + }); + const waiter = (model: string, inFlight = false) => classDemand("full", "ios", inFlight, model); + const busy = device("busy", "leased", { spec: spec("iPad Pro") }); + const shutDown = device("shut", "shutdown", { endedAgo: 20 * minute }); + const three = [waiter("iPhone 15", true), waiter("iPhone 17"), waiter("iPhone 16")]; + + expect(evaluate(view([busy], { maxConcurrentBoots: 3, waiting: three }))).toEqual([ + creation("iPhone 17"), + creation("iPhone 16"), + ]); + expect( + evaluate( + view([busy], { + maxConcurrentBoots: 3, + waiting: [waiter("iPhone 15"), waiter("iPhone 17"), waiter("iPhone 16")], + }), + ), + ).toEqual([creation("iPhone 17"), creation("iPhone 16")]); + const refused = { + ...view([busy], { + maxConcurrentBoots: 1, + waiting: [classDemand("full", "android"), waiter("iPhone 17")], + }), + capacity: capacityOf([busy], { android: 0, global: 10 }), + }; + expect(evaluate(refused)).toEqual([creation("iPhone 17")]); + const atCap = view([busy], { + inFlight: [spec("iPhone 15")], + maxConcurrentBoots: 1, + targets: [{ count: 1, spec: spec("iPad Pro", { osVersion: "18.0" }) }], + waiting: [waiter("iPhone 15", true), waiter("iPhone 17")], + }); + expect(plan(atCap).proposals).toEqual([]); + expect(plan(atCap).targets[0]?.short).toBeUndefined(); + expect(evaluate(view([shutDown], { waiting: [waiter("iPhone 15")] }))).toEqual([ + { action: "boot", deviceId: "shut", reason: "waiting-request" }, + ]); + expect(evaluate(view([busy], { waiting: [waiter("iPhone 15")] }))).toEqual([]); + expect( + evaluate(view([shutDown], { inFlight: [spec("iPad Pro")], waiting: [waiter("iPhone 15")] })), + ).toEqual([]); + }); + it("proposes a boot, not a shutdown, for a released iPhone 15 that serves a waiting class request at the running cap", () => { const released = device("lse_15", "shutdown", { endedAgo: 1_000 }); const leased = device("busy", "leased", { spec: spec("iPhone 17") }); diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index ddf17f77f..8f1e7d326 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -643,6 +643,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { mode: specMode(waiter.spec), platform: waiter.spec.platform, requirement: waiter.requirement ?? exactRequirement(waiter.spec), + spec: waiter.spec, }, ], ); From 7a15acf7b6c572cf20986acff23ab8b047a6d915 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:25:29 +0200 Subject: [PATCH 02/31] feat(warm-pool): the pool creates a device for each waiter behind the head, within the boot cap (#774) --- src/core/warm-pool/policy.test.ts | 16 ++++- src/core/warm-pool/policy.ts | 110 +++++++++++++++++++----------- 2 files changed, 83 insertions(+), 43 deletions(-) diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 670cf0a0a..3e7ad3f08 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -849,10 +849,22 @@ describe("warm pool policy", () => { expect(evaluate(view([shut], { targets: [target(1)], waiting: [queued] }))).toEqual([]); expect( - evaluate(view([shut], { targets: [target(1)], waiting: [{ ...queued, inFlight: true }] })), + evaluate( + view([shut], { + maxConcurrentBoots: 2, + targets: [target(1)], + waiting: [{ ...queued, inFlight: true }], + }), + ), ).toEqual([{ action: "boot", deviceId: "shut", reason: "target", target: kind }]); expect( - evaluate(view([shut], { targets: [target(1)], waiting: [classDemand("full", "android")] })), + evaluate( + view([shut], { + maxConcurrentBoots: 2, + targets: [target(1)], + waiting: [classDemand("full", "android")], + }), + ), ).toHaveLength(1); }); diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 54eaa19c1..c6b9e36f7 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -34,7 +34,7 @@ export type WarmProposal = | { readonly action: "provision"; readonly spec: VirtualSpec; - readonly reason: "target"; + readonly reason: "target" | "waiting-request"; readonly target: VirtualSpec; }; @@ -164,10 +164,11 @@ export function evaluate(view: WarmPolicyView): WarmPlan { const bootable = view.devices.filter( (device) => device.state === "shutdown" && mayBeGranted(device) && idle(device), ); - const keeps = boots(view, running, bootable, room, held); + const queued = boots(view, running, bootable, room, held); + const keeps = queued.proposals; const targets = mergeTargets(view.targets); const unneeded = neverLeasedIdle(view, running, shutdowns, room); - const wanted = planTargets(view, targets, bootable, keeps, room, held, idle); + const wanted = planTargets(view, targets, bootable, queued, room, held, idle); return { proposals: [...shutdowns, ...keeps, ...unneeded, ...wanted.proposals], targets: wanted.reports, @@ -266,12 +267,18 @@ function overBudget( return proposals; } +interface QueuePass { + readonly proposals: WarmProposal[]; + readonly started: number; +} + /** - * Boots into the slots that are free: first one device for the request at the head of the queue, - * then the shut-down devices released less than `idle.shutdownAfterMs` ago, most recently released - * first. A device that does not fit the free room on its platform is passed over. Slots that a - * waiting request no idle device serves is about to take are held back from the second kind, and - * so are the slots the reserve holds: the first kind is a request's, not an idle device's. + * why: the queue is served in order, one device per waiter. A waiter behind the head gets a + * shut-down device booted or a new one created, within `maxConcurrentBoots` counting the pool's + * flights, each in-flight waiter and the head's own work; the head's creation stays leasing's. + * Then the shut-down devices released less than `idle.shutdownAfterMs` ago, most recently + * released first. Slots a waiting request no idle device serves is about to take are held back + * from the second kind, and so are the slots the reserve holds. */ function boots( view: WarmPolicyView, @@ -279,38 +286,48 @@ function boots( bootable: readonly VirtualDevice[], room: Slots, held: Slots, -): DeviceProposal[] { - const proposals: DeviceProposal[] = []; +): QueuePass { + const proposals: WarmProposal[] = []; const taken = new Set(); - const boot = (device: VirtualDevice, reason: DeviceProposal["reason"]): void => { - taken.add(device.id); - claim(room, device); - proposals.push({ action: "boot", deviceId: device.id, reason }); + let started = view.inFlight.length + view.waiting.filter((demand) => demand.inFlight).length; + const open = (): boolean => started < view.config.maxConcurrentBoots; + const hold = (platform: "ios" | "android"): void => { + room.global -= 1; + room[platform] -= 1; }; + const roomFor = (spec: VirtualSpec): boolean => room.global >= 1 && room[spec.platform] >= 1; - const unserved: WaitingDemand[] = []; view.waiting.forEach((demand, position) => { - // Only the first request in the line, the queue head, is granted a device, and not one - // already in flight (strict FIFO): a device booted for one behind it would sit idle, be shut - // down by the idle rule, and be booted again. The others still hold a slot below. - const device = - position === 0 && !demand.inFlight - ? bootable.find( - (candidate) => - !taken.has(candidate.id) && hasRoom(room, candidate) && serves(candidate, demand), - ) - : undefined; - if (device !== undefined) boot(device, "waiting-request"); - else if (demand.inFlight || !running.some((candidate) => serves(candidate, demand))) { - unserved.push(demand); + if (demand.inFlight) { + hold(demand.platform); + return; } + if (running.some((candidate) => serves(candidate, demand))) return; + const device = open() + ? bootable.find( + (candidate) => + !taken.has(candidate.id) && hasRoom(room, candidate) && serves(candidate, demand), + ) + : undefined; + if (device !== undefined) { + taken.add(device.id); + claim(room, device); + started += 1; + proposals.push({ action: "boot", deviceId: device.id, reason: "waiting-request" }); + return; + } + const creatable = view.admit.create(demand.spec) === undefined && roomFor(demand.spec); + if (position > 0 && creatable && open()) { + started += 1; + proposals.push({ + action: "provision", + reason: "waiting-request", + spec: demand.spec, + target: demand.spec, + }); + } else if (position === 0 && creatable) started += 1; + hold(demand.platform); }); - // A request no device serves will take a free slot of its own (it boots a device or creates - // one), so those slots are not the pool's to fill with a device nobody asked for. - for (const demand of unserved) { - room.global -= 1; - room[demand.platform] -= 1; - } const recent = bootable .filter( @@ -322,9 +339,13 @@ function boots( ) .sort((left, right) => compareLeastRecentlyUsed(right, left)); for (const device of recent) { - if (hasWarmRoom(room, held, device)) boot(device, "recently-released"); + if (hasWarmRoom(room, held, device)) { + claim(room, device); + started += 1; + proposals.push({ action: "boot", deviceId: device.id, reason: "recently-released" }); + } } - return proposals; + return { proposals, started }; } /** The targets with those that resolved to one spec merged into one, counts summed. */ @@ -469,25 +490,32 @@ function planTargets( view: WarmPolicyView, targets: readonly ResolvedTarget[], bootable: readonly VirtualDevice[], - keeps: readonly DeviceProposal[], + queued: QueuePass, room: Slots, held: Slots, isIdle: (device: VirtualDevice) => boolean, ): { proposals: WarmProposal[]; reports: TargetReport[] } { - const keepBoots = keeps.map((proposal) => proposal.deviceId); + const keepBoots = queued.proposals.flatMap((proposal) => + proposal.action === "boot" ? [proposal.deviceId] : [], + ); const plan: TargetPlan = { bootable, held, proposals: [], room, - started: view.inFlight.length + keepBoots.length, + started: queued.started, taken: new Set(keepBoots), view, }; const pending = (spec: VirtualSpec): number => view.inFlight.filter((flying) => sameSpec(flying, spec)).length + - keepBoots.filter((id) => - view.devices.some((device) => device.id === id && sameSpec(device.spec, spec)), + queued.proposals.filter((proposal) => + proposal.action === "provision" + ? sameSpec(proposal.spec, spec) + : proposal.action === "boot" && + view.devices.some( + (device) => device.id === proposal.deviceId && sameSpec(device.spec, spec), + ), ).length; const reports = targets.map(({ count, spec }): TargetReport => { const ready = readyOfKind(view.devices, isIdle, spec).length; From b95189598f9f2f46a9215536215c6dc59bb7aadf Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:26:22 +0200 Subject: [PATCH 03/31] test: the pool matches each device to one waiter in queue order (#774) --- src/core/warm-pool/converger.ts | 1 + src/core/warm-pool/policy.test.ts | 49 +++++++++++++++++++++++++++++++ src/core/warm-pool/policy.ts | 1 + 3 files changed, 51 insertions(+) diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index 04e8644b4..274d9ca2e 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -481,6 +481,7 @@ export class WarmPool { isClaimed: (deviceId) => this.options.claims.isClaimed(deviceId), leases, now: this.options.clock.now(), + onItsWay: [], resetDevices: new Set(this.#reset), retry: this.#schedule, spared: this.#spared, diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 3e7ad3f08..6d5c30852 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -148,6 +148,7 @@ function view( targets?: readonly ResolvedTarget[]; spared?: readonly ResolvedTarget[]; inFlight?: readonly VirtualSpec[]; + onItsWay?: WarmPolicyView["onItsWay"]; maxConcurrentBoots?: number; blocked?: readonly VirtualSpec[]; refuseProvision?: CapacityRefusalReason; @@ -160,6 +161,7 @@ function view( create: () => options.refuseProvision, }, inFlight: options.inFlight ?? [], + onItsWay: options.onItsWay ?? [], retry: { mayAttempt: (target) => !(options.blocked ?? []).some((held) => sameSpec(held, target)), }, @@ -236,6 +238,53 @@ describe("warm pool policy", () => { ).toEqual([]); }); + it("matches each device to one waiter in queue order and proposes nothing for a waiter an idle ready device or an onItsWay entry serves", () => { + const creation = (model: string) => ({ + action: "provision", + reason: "waiting-request", + spec: spec(model), + target: spec(model), + }); + const waiter = (model: string, inFlight = false) => classDemand("full", "ios", inFlight, model); + const ready = (id: string, options: Parameters[2] = {}) => + device(id, "ready", { endedAgo: 90 * minute, ...options }); + const two = [waiter("iPhone 15", true), waiter("iPhone 15"), waiter("iPhone 17")]; + const base = { maxConcurrentBoots: 5, limit: 10 }; + + expect(evaluate(view([ready("one")], { ...base, waiting: two.slice(1) }))).toEqual([ + creation("iPhone 17"), + ]); + expect( + evaluate(view([ready("one"), ready("two")], { ...base, waiting: two.slice(1) })), + ).toEqual([]); + expect( + evaluate( + view([], { + ...base, + onItsWay: [{ spec: spec("iPhone 15") }], + waiting: two.slice(1), + }), + ), + ).toEqual([creation("iPhone 17")]); + expect( + evaluate( + view([], { + ...base, + onItsWay: [{ spec: spec("iPhone 15") }, { deviceId: "other", spec: spec("iPhone 17") }], + waiting: two.slice(1), + }), + ), + ).toEqual([]); + expect( + evaluate( + view([ready("slim", { spec: spec("iPhone 15", { mode: "slim" }) })], { + ...base, + waiting: [waiter("iPhone 15", true), waiter("iPhone 17")], + }), + ), + ).toEqual([creation("iPhone 17")]); + }); + it("proposes a boot, not a shutdown, for a released iPhone 15 that serves a waiting class request at the running cap", () => { const released = device("lse_15", "shutdown", { endedAgo: 1_000 }); const leased = device("busy", "leased", { spec: spec("iPhone 17") }); diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index c6b9e36f7..849baf7c0 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -105,6 +105,7 @@ export interface WarmPolicyView { readonly spared: readonly ResolvedTarget[]; /** The spec of each target boot or creation still running: they count toward the boot cap. */ readonly inFlight: readonly VirtualSpec[]; + readonly onItsWay: readonly { readonly spec: VirtualSpec; readonly deviceId?: string }[]; /** The failure schedule: whether a spec may be tried now. */ readonly retry: { mayAttempt(spec: VirtualSpec, now: number): boolean }; /** What the capacity strategy refuses besides the running slots `capacity` already totals. */ From f4020b78b43b9de632840f1023cd63b4b783e0a3 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:26:40 +0200 Subject: [PATCH 04/31] feat(warm-pool): each ready or on-its-way device serves one waiter (#774) --- src/core/warm-pool/policy.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 849baf7c0..4343d4b9e 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -233,11 +233,11 @@ function hasWarmRoom(room: Slots, held: Slots, device: VirtualDevice): boolean { /** Whether `device` is one a waiting request would be granted: it fits and is in the pool mode. */ function serves(device: VirtualDevice, demand: WaitingDemand): boolean { - return ( - mayBeGranted(device) && - specMode(device.spec) === demand.mode && - fits(demand.requirement, device.spec, demand.classOf) - ); + return mayBeGranted(device) && servesSpec(device.spec, demand); +} + +function servesSpec(spec: VirtualSpec, demand: WaitingDemand): boolean { + return specMode(spec) === demand.mode && fits(demand.requirement, spec, demand.classOf); } /** @@ -290,6 +290,7 @@ function boots( ): QueuePass { const proposals: WarmProposal[] = []; const taken = new Set(); + const matched = new Set(); let started = view.inFlight.length + view.waiting.filter((demand) => demand.inFlight).length; const open = (): boolean => started < view.config.maxConcurrentBoots; const hold = (platform: "ios" | "android"): void => { @@ -303,7 +304,13 @@ function boots( hold(demand.platform); return; } - if (running.some((candidate) => serves(candidate, demand))) return; + const match = + running.find((candidate) => !matched.has(candidate) && serves(candidate, demand)) ?? + view.onItsWay.find((entry) => !matched.has(entry) && servesSpec(entry.spec, demand)); + if (match !== undefined) { + matched.add(match); + return; + } const device = open() ? bootable.find( (candidate) => From 4d3096aad486e087ffea34838b3f10c2e4594567 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:27:16 +0200 Subject: [PATCH 05/31] test: the pool boots a shut-down device for a waiter behind the head before creating one (#774) --- src/core/warm-pool/policy.test.ts | 46 ++++++++++++++++--------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 6d5c30852..a37bc9d25 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -454,34 +454,36 @@ describe("warm pool policy", () => { ]); }); - it("boots a device only for the head of the queue, not for a request behind it", () => { - const tablet = device("tablet", "shutdown", { endedAgo: 20 * minute, spec: spec("iPad Pro") }); - const phone = device("phone", "shutdown", { endedAgo: 20 * minute }); - // The head wants an Android device nothing serves; the iOS phone request is behind it. - const proposals = evaluate( - view([tablet, phone], { waiting: [classDemand("full", "android"), classDemand()] }), - ); - - expect(proposals).toEqual([]); - }); - - it("boots nothing for a request behind a head whose device work is in flight", () => { + it("boots a shut-down device that serves a waiter behind the head before creating one, and may boot one an operator reset shut down, for the head too", () => { + const boot = (deviceId: string) => ({ action: "boot", deviceId, reason: "waiting-request" }); const phone = device("phone", "shutdown", { endedAgo: 20 * minute }); + const tablet = device("tablet", "shutdown", { endedAgo: 20 * minute, spec: spec("iPad Pro") }); const busy = device("busy", "leased", { spec: spec("iPad Pro") }); - // The head is a tablet request being served (say by an eviction); the phone waits behind it. const tabletHead = { ...classDemand("full", "ios", true), - requirement: { - ...classDemand().requirement, - target: { class: "tablet", kind: "class" }, - }, + requirement: { ...classDemand().requirement, target: { class: "tablet", kind: "class" } }, } satisfies WaitingDemand; + const options = { maxConcurrentBoots: 3 }; - const proposals = evaluate( - view([phone, busy], { limit: 5, waiting: [tabletHead, classDemand()] }), - ); - - expect(proposals).toEqual([]); + expect( + evaluate(view([phone, busy], { ...options, waiting: [tabletHead, classDemand()] })), + ).toEqual([boot("phone")]); + expect( + evaluate( + view([phone, busy], { ...options, waiting: [tabletHead, classDemand(), classDemand()] }), + ).map((proposal) => proposal.action), + ).toEqual(["boot", "provision"]); + expect( + evaluate(view([tablet, busy], { ...options, waiting: [tabletHead, classDemand()] })), + ).toEqual([expect.objectContaining({ action: "provision" })]); + expect( + evaluate(view([phone, tablet], { ...options, reset: ["phone"], waiting: [classDemand()] })), + ).toEqual([boot("phone")]); + expect( + evaluate( + view([phone, busy], { ...options, reset: ["phone"], waiting: [tabletHead, classDemand()] }), + ), + ).toEqual([boot("phone")]); }); it("does not boot back a device an operator reset shut down, though it was released a moment ago", () => { From 6e05507903bcf3cb11027912a14107f668fc37e0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:27:41 +0200 Subject: [PATCH 06/31] test: the pool proposes no boot that the capacity strategy refuses (#774) --- src/core/warm-pool/policy.test.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index a37bc9d25..d67ebc1d2 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -486,6 +486,33 @@ describe("warm pool policy", () => { ).toEqual([boot("phone")]); }); + it("proposes no boot that admit.boot refuses for ram-budget, for a waiter or a recently released device, and holds the waiter's slot", () => { + const serving = device("serving", "shutdown", { endedAgo: 20 * minute }); + const recent = device("recent", "shutdown", { endedAgo: 1_000, spec: spec("iPad Pro") }); + const busy = device("busy", "leased", { spec: spec("iPad Pro") }); + const devices = [serving, recent, busy]; + const setup = { limit: 3, waiting: [classDemand()] }; + const refusing = (ids: readonly string[]): WarmPolicyView => { + const base = view(devices, setup); + return { + ...base, + admit: { + ...base.admit, + boot: (candidate) => (ids.includes(candidate.id) ? "ram-budget" : undefined), + }, + }; + }; + + expect(evaluate(refusing([]))).toEqual([ + { action: "boot", deviceId: "serving", reason: "waiting-request" }, + ]); + expect(evaluate(refusing(["serving"]))).toEqual([]); + expect(evaluate(view([recent], { limit: 3 }))).toEqual([ + { action: "boot", deviceId: "recent", reason: "recently-released" }, + ]); + expect(evaluate(view([recent], { limit: 3, refuseBoot: "ram-budget" }))).toEqual([]); + }); + it("does not boot back a device an operator reset shut down, though it was released a moment ago", () => { const reset = device("reset", "shutdown", { endedAgo: 1_000 }); const other = device("other", "shutdown", { endedAgo: 2_000 }); From 6722e90c761fdd75eba9067ee72e8b5d8aad25ca Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:27:52 +0200 Subject: [PATCH 07/31] test: the pool proposes no boot that the capacity strategy refuses (#774) --- src/core/warm-pool/policy.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index d67ebc1d2..0a0cab040 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -491,7 +491,7 @@ describe("warm pool policy", () => { const recent = device("recent", "shutdown", { endedAgo: 1_000, spec: spec("iPad Pro") }); const busy = device("busy", "leased", { spec: spec("iPad Pro") }); const devices = [serving, recent, busy]; - const setup = { limit: 3, waiting: [classDemand()] }; + const setup = { limit: 2, waiting: [classDemand()] }; const refusing = (ids: readonly string[]): WarmPolicyView => { const base = view(devices, setup); return { From 2f84622cb26878dff78463dcabf3a10bbf0efa58 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:28:13 +0200 Subject: [PATCH 08/31] feat(warm-pool): a boot the capacity strategy refuses is not proposed (#774) --- src/core/warm-pool/policy.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 4343d4b9e..c84feec4e 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -314,7 +314,10 @@ function boots( const device = open() ? bootable.find( (candidate) => - !taken.has(candidate.id) && hasRoom(room, candidate) && serves(candidate, demand), + !taken.has(candidate.id) && + hasRoom(room, candidate) && + serves(candidate, demand) && + view.admit.boot(candidate) === undefined, ) : undefined; if (device !== undefined) { @@ -347,7 +350,7 @@ function boots( ) .sort((left, right) => compareLeastRecentlyUsed(right, left)); for (const device of recent) { - if (hasWarmRoom(room, held, device)) { + if (hasWarmRoom(room, held, device) && view.admit.boot(device) === undefined) { claim(room, device); started += 1; proposals.push({ action: "boot", deviceId: device.id, reason: "recently-released" }); From a0d27ca1943c6620b714fe48027c49e8c7a8f29a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:28:57 +0200 Subject: [PATCH 09/31] test: the pool fills a target after the queue's devices within one cap (#774) --- src/core/warm-pool/policy.test.ts | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 0a0cab040..8d6260c58 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -946,6 +946,39 @@ describe("warm pool policy", () => { ).toHaveLength(1); }); + it("fills a target after the queue's devices within one cap, and keeps it waiting, not short, only behind a waiter the pass could not serve", () => { + const shut = ofKind("shut", "shutdown"); + const phone = device("phone", "shutdown", { endedAgo: 20 * minute, spec: spec("iPhone 15") }); + const head = modelDemand("iPad Pro"); + const filling = { targets: [target(1)], waiting: [head] }; + + expect(plan(view([shut], { ...filling, maxConcurrentBoots: 2 })).proposals).toEqual([ + { action: "boot", deviceId: "shut", reason: "target", target: kind }, + ]); + const capped = plan(view([shut], { ...filling, maxConcurrentBoots: 1 })); + expect(capped.proposals).toEqual([]); + expect(capped.targets[0]).not.toHaveProperty("short"); + + expect( + evaluate( + view([phone, shut], { + maxConcurrentBoots: 2, + targets: [target(1)], + waiting: [classDemand()], + }), + ), + ).toEqual([ + { action: "boot", deviceId: "phone", reason: "waiting-request" }, + { action: "boot", deviceId: "shut", reason: "target", target: kind }, + ]); + + const unservable = plan( + view([shut], { ...filling, maxConcurrentBoots: 3, refuseProvision: "device-limit" }), + ); + expect(unservable.proposals).toEqual([]); + expect(unservable.targets[0]).not.toHaveProperty("short"); + }); + it("proposes a shutdown for a never-leased ready device no target counts once it has been ready longer than idle.shutdownAfterMs", () => { const stale = device("stale", "ready", { readyAt: now - shutdownAfterMs - 1 }); const boundary = device("boundary", "ready", { readyAt: now - shutdownAfterMs }); From 39ddaab2f5eda62881c27820971ff8c5be0dd6e1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:29:26 +0200 Subject: [PATCH 10/31] feat(warm-pool): a target fills after the queue's devices and waits only behind a waiter the pass could not serve (#774) --- src/core/warm-pool/policy.test.ts | 8 +++++++- src/core/warm-pool/policy.ts | 13 ++++++++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 8d6260c58..8d1740f6f 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -1206,7 +1206,13 @@ describe("warm pool policy", () => { "short", ); expect( - plan(view([shut], { ...held, waiting: [modelDemand("iPad Pro")] })).targets[0], + plan( + view([shut], { + ...held, + refuseProvision: "device-limit", + waiting: [modelDemand("iPad Pro")], + }), + ).targets[0], ).not.toHaveProperty("short"); }); diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index c84feec4e..1bb5c849a 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -8,6 +8,7 @@ import { readySince, sameSpec, specMode, + type Platform, type TargetRefusal, type WaitingDemand, } from "../domain.js"; @@ -271,6 +272,7 @@ function overBudget( interface QueuePass { readonly proposals: WarmProposal[]; readonly started: number; + readonly stuck: ReadonlySet; } /** @@ -290,6 +292,7 @@ function boots( ): QueuePass { const proposals: WarmProposal[] = []; const taken = new Set(); + const stuck = new Set(); const matched = new Set(); let started = view.inFlight.length + view.waiting.filter((demand) => demand.inFlight).length; const open = (): boolean => started < view.config.maxConcurrentBoots; @@ -337,6 +340,7 @@ function boots( target: demand.spec, }); } else if (position === 0 && creatable) started += 1; + else stuck.add(demand.platform); hold(demand.platform); }); @@ -356,7 +360,7 @@ function boots( proposals.push({ action: "boot", deviceId: device.id, reason: "recently-released" }); } } - return { proposals, started }; + return { proposals, started, stuck }; } /** The targets with those that resolved to one spec merged into one, counts summed. */ @@ -485,6 +489,7 @@ interface TargetPlan { readonly room: Slots; readonly held: Slots; readonly taken: Set; + readonly stuck: ReadonlySet; readonly proposals: WarmProposal[]; /** Pool boots and creations running or proposed, which `maxConcurrentBoots` bounds. */ started: number; @@ -515,6 +520,7 @@ function planTargets( proposals: [], room, started: queued.started, + stuck: queued.stuck, taken: new Set(keepBoots), view, }; @@ -558,10 +564,7 @@ function fillTarget( missing: number, filling: boolean, ): TargetShort | undefined { - // A request queued on this platform is served first; the target waits, and is not short. - if (plan.view.waiting.some((demand) => !demand.inFlight && demand.platform === spec.platform)) { - return undefined; - } + if (plan.stuck.has(spec.platform)) return undefined; if (!plan.view.retry.mayAttempt(spec, plan.view.now)) return filling ? undefined : "boot-failed"; let added = 0; for (let left = missing; left > 0 && plan.started < plan.view.config.maxConcurrentBoots; left--) { From af7618e8af33e2e5964c200835abc5735f29d2de Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:30:09 +0200 Subject: [PATCH 11/31] test: a waiting-request creation runs under a boot claim and a throw holds its spec back (#774) --- src/core/warm-pool/converger.test.ts | 61 +++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 6 deletions(-) diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index 9890f1e45..1b8048098 100644 --- a/src/core/warm-pool/converger.test.ts +++ b/src/core/warm-pool/converger.test.ts @@ -4,12 +4,13 @@ import { EventBus } from "../../bus/index.js"; import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../../ports/index.js"; import type { RunningCapacity } from "../capacity/index.js"; import { DeviceOperationClaims } from "../device-operation-claims.js"; -import type { - VirtualDevice, - VirtualSpec, - LeaseRecord, - TargetResolution, - WaitingDemand, +import { + exactRequirement, + type VirtualDevice, + type VirtualSpec, + type LeaseRecord, + type TargetResolution, + type WaitingDemand, } from "../domain.js"; import { BootTimeoutError, type DeviceRequest } from "../driver.js"; import { SerializedDecision } from "../serialized-decision.js"; @@ -60,6 +61,17 @@ function leaseOn(deviceId: string): LeaseRecord { }; } +function waiter(spec: VirtualSpec, inFlight = false): WaitingDemand { + return { + classOf: () => undefined, + inFlight, + mode: "full", + platform: spec.platform, + requirement: exactRequirement(spec), + spec, + }; +} + function harness( initial: readonly VirtualDevice[], options: { @@ -851,6 +863,43 @@ describe("warm pool targets", () => { expect(rig.kick).toHaveBeenCalled(); }); + it("runs a waiting-request creation under an ownerless boot claim and a provisioning reservation, releases the claim once ready, kicks, and on a throw logs once and holds the spec back a minute", async () => { + const behind = { ...kind, model: "iPhone 16" }; + const waiting = [waiter({ ...kind, model: "iPhone 15" }, true), waiter(behind)]; + const ok = harness([], { maxConcurrentBoots: 2, waiting: () => waiting }); + + await ok.pool.pass(); + await ok.pool.settle(); + + expect(ok.provisionCalls).toHaveLength(1); + expect(ok.provisionCalls[0]?.spec).toEqual(behind); + expect(ok.provisionCalls[0]?.claim).toEqual({ kind: "boot" }); + expect(ok.provisionReservations).toHaveLength(1); + expect(ok.claims.isClaimed("new-1")).toBe(false); + expect(ok.kick).toHaveBeenCalled(); + + const failing = harness([], { + maxConcurrentBoots: 2, + provision: async () => { + throw new Error("the runtime would not boot"); + }, + waiting: () => waiting, + }); + await failing.pool.pass(); + await failing.pool.settle(); + failing.clock.advance(WARM_POOL_TICK_MS); + await failing.pool.settle(); + + expect(failing.provisionCalls).toHaveLength(1); + const warnings = failing.sink.records.filter( + (record) => record.message === "warm pool creation of a device failed", + ); + expect(warnings).toHaveLength(1); + failing.clock.advance(minute); + await failing.pool.settle(); + expect(failing.provisionCalls).toHaveLength(2); + }); + it("boots a shut-down device of the target's kind before creating one, and counts the target filled", async () => { const rig = harness([ofKind("shut", "shutdown")], { targets: [iphone17] }); From 9f767abdbe80108d7e155b4d882695e5226e2aa8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:30:37 +0200 Subject: [PATCH 12/31] feat(warm-pool): a spec held back after a failed creation is not created again for a waiter (#774) --- src/core/warm-pool/policy.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 1bb5c849a..1f6f9512f 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -331,7 +331,7 @@ function boots( return; } const creatable = view.admit.create(demand.spec) === undefined && roomFor(demand.spec); - if (position > 0 && creatable && open()) { + if (position > 0 && creatable && open() && view.retry.mayAttempt(demand.spec, view.now)) { started += 1; proposals.push({ action: "provision", From 00326608c8749ae494543e4e45fa535894e6b9c3 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:31:19 +0200 Subject: [PATCH 13/31] test: the pool runs waiting-request boots beside the pass under the boot cap (#774) --- src/core/warm-pool/converger.test.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index 1b8048098..e0dc3702b 100644 --- a/src/core/warm-pool/converger.test.ts +++ b/src/core/warm-pool/converger.test.ts @@ -1011,6 +1011,32 @@ describe("warm pool targets", () => { expect(rig.provisionCalls).toHaveLength(3); }); + it("runs waiting-request boots beside the pass, three at once under maxConcurrentBoots 3, and counts them in the next pass's inFlight", async () => { + const gate = held(); + const shutDown = ["a", "b", "c", "d"].map((id) => device(id, "shutdown", 20 * minute)); + const rig = harness(shutDown, { + boot: async (target) => { + await gate.gate; + return { ...target, state: "ready" }; + }, + maxConcurrentBoots: 3, + waiting: () => shutDown.map((item) => waiter(item.spec)), + }); + + const first = rig.pool.pass(); + await flush(); + expect(rig.bootCalls).toEqual(["a", "b", "c"]); + + const second = rig.pool.pass(); + await flush(); + expect(rig.bootCalls).toEqual(["a", "b", "c"]); + + gate.finish(); + await Promise.all([first, second]); + await rig.pool.settle(); + expect(rig.bootCalls).toContain("d"); + }); + it("does not return from a pass for a creation it started, and settle waits for it", async () => { const gate = held(); const rig = harness([], { provision: async () => gate.gate, targets: [iphone17] }); From 8b3b7dd77cbff7a9be855731f95eb420f7d08e16 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:31:54 +0200 Subject: [PATCH 14/31] feat(warm-pool): waiting-request boots run beside the pass and count toward the boot cap (#774) --- src/core/warm-pool/converger.test.ts | 4 +++- src/core/warm-pool/converger.ts | 24 +++++++++++++++--------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index e0dc3702b..672875d35 100644 --- a/src/core/warm-pool/converger.test.ts +++ b/src/core/warm-pool/converger.test.ts @@ -1017,7 +1017,9 @@ describe("warm pool targets", () => { const rig = harness(shutDown, { boot: async (target) => { await gate.gate; - return { ...target, state: "ready" }; + const ready = { ...target, state: "ready" as const }; + rig.state.devices = rig.state.devices.map((item) => (item.id === target.id ? ready : item)); + return ready; }, maxConcurrentBoots: 3, waiting: () => shutDown.map((item) => waiter(item.spec)), diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index 274d9ca2e..d1823fec1 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -496,23 +496,29 @@ export class WarmPool { this.#launch(proposal.target, () => this.#provision(proposal.spec, proposal.target)); return; } - // A failed keep boot releases its reservation, which changes capacity and so triggers the next + // why: a failed keep boot releases its reservation, which changes capacity and so triggers the next // pass at once; without a pause that would retry a broken one in a loop. A failed shutdown // frees nothing, but any other trigger that comes soon would propose it again, so it is held - // back the same way. A target's boot is held back by the retry schedule instead, which the - // policy reads before it proposes one. + // back the same way. A target's or a waiter's boot is held back by the retry schedule instead, + // which the policy reads before it proposes one. + const owner = + proposal.action === "boot" && proposal.reason === "waiting-request" + ? this.#specOf(proposal.deviceId) + : proposal.target; if ( - proposal.target === undefined && + owner === undefined && (this.#retryAfter.get(proposal.deviceId) ?? 0) > this.options.clock.now() ) { return; } if (proposal.action === "shutdown") await this.#shutdown(proposal.deviceId); - else if (proposal.target === undefined) await this.#boot(proposal.deviceId, undefined); - else { - const target = proposal.target; - this.#launch(target, () => this.#boot(proposal.deviceId, target)); - } + else if (owner === undefined) await this.#boot(proposal.deviceId, undefined); + else this.#launch(owner, () => this.#boot(proposal.deviceId, owner)); + } + + #specOf(deviceId: string): VirtualSpec | undefined { + return this.options.registry.snapshot.virtualDevices.find((device) => device.id === deviceId) + ?.spec; } /** From 7d7e9fe7718ee491f8bf6419680e793ec0d12c97 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:33:00 +0200 Subject: [PATCH 15/31] test: the pool tells the policy which devices and creations are on their way (#774) --- src/core/warm-pool/converger.test.ts | 53 +++++++++++++++++++++++++++- src/core/warm-pool/converger.ts | 2 +- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index 672875d35..e4e4c3682 100644 --- a/src/core/warm-pool/converger.test.ts +++ b/src/core/warm-pool/converger.test.ts @@ -97,6 +97,7 @@ function harness( /** The budget's reservation call throws, which no refusal does. */ reserveThrows?: boolean; refusedPlatforms?: readonly ("ios" | "android")[]; + provisioning?: Promise; } = {}, ) { const clock = new FakeClock(now); @@ -207,6 +208,7 @@ function harness( }, }, claims: { + claim: (id) => claims.claim(id), isClaimed: (id) => claims.isClaimed(id), operationFor: (id) => claims.operationFor(id), tryClaim: (id, operation) => @@ -269,7 +271,7 @@ function harness( mode: "full", readyAt: clock.now(), spec, - state: "ready", + state: options.provisioning === undefined ? "ready" : "provisioning", }; state.devices = [...state.devices, created]; const claim = claims.tryClaim( @@ -280,6 +282,12 @@ function harness( if (claim === undefined) throw new Error("the new device is already claimed"); provisionOptions.reservation.release(); record.deviceId = id; + if (options.provisioning !== undefined) { + await options.provisioning; + state.devices = state.devices.map((item) => + item.id === id ? { ...item, state: "ready" } : item, + ); + } return { claim, device: created }; }, }, @@ -1039,6 +1047,49 @@ describe("warm pool targets", () => { expect(rig.bootCalls).toContain("d"); }); + it("builds onItsWay with one entry per on-its-way device and one per creation flight not yet registered, never two for one creation and never one short", async () => { + const x = device("shut-x", "shutdown", 20 * minute).spec; + const head = waiter({ ...kind, model: "iPad Pro" }, true); + const x2 = waiter(x); + const x3 = waiter(x); + const x4 = waiter(x); + const run = async ( + devices: readonly VirtualDevice[], + first: readonly WaitingDemand[], + provisioning?: Promise, + ) => { + let waiting: readonly WaitingDemand[] = first; + const gate = held(); + const rig = harness(devices, { + boot: async () => gate.gate.then(() => undefined), + maxConcurrentBoots: 10, + provision: async () => gate.gate, + ...(provisioning === undefined ? {} : { provisioning }), + waiting: () => waiting, + }); + const counts = () => [rig.bootCalls.length, rig.provisionCalls.length]; + void rig.pool.pass(); + await flush(); + const started = counts(); + void rig.pool.pass(); + await flush(); + const again = counts(); + waiting = [...first, x4]; + void rig.pool.pass(); + await flush(); + return { again, later: counts(), started }; + }; + + const unregistered = await run([], [head, x2]); + expect(unregistered).toEqual({ again: [0, 1], later: [0, 2], started: [0, 1] }); + + const registered = await run([], [head, x2], new Promise(() => undefined)); + expect(registered).toEqual({ again: [0, 1], later: [0, 2], started: [0, 1] }); + + const bootAndCreation = await run([device("shut-x", "shutdown", 20 * minute)], [head, x2, x3]); + expect(bootAndCreation).toEqual({ again: [1, 1], later: [1, 2], started: [1, 1] }); + }); + it("does not return from a pass for a creation it started, and settle waits for it", async () => { const gate = held(); const rig = harness([], { provision: async () => gate.gate, targets: [iphone17] }); diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index d1823fec1..61c21e15a 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -54,7 +54,7 @@ export interface WarmPoolOptions { CapacityCoordinator, "canBoot" | "canProvision" | "runningCapacity" | "tryReserveBoot" | "tryReserveProvisioning" >; - readonly claims: Pick; + readonly claims: Pick; readonly clock: Clock; readonly config: WarmPoolConfig; readonly decisions: Pick; From 3fd9ca7b196ba2d1dd64cf399812754ade9ee02a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:33:27 +0200 Subject: [PATCH 16/31] feat(warm-pool): the pool reports devices and creations on their way to the policy (#774) --- src/core/warm-pool/converger.ts | 40 ++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index 61c21e15a..21c032fc1 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -77,6 +77,7 @@ export const WARM_POOL_TICK_MS = 30_000; /** A target boot or creation that runs beside the pass: the target's spec, and its end. */ interface Flight { + readonly creation: boolean; readonly spec: VirtualSpec; done: Promise; } @@ -481,7 +482,7 @@ export class WarmPool { isClaimed: (deviceId) => this.options.claims.isClaimed(deviceId), leases, now: this.options.clock.now(), - onItsWay: [], + onItsWay: this.#onItsWay(devices), resetDevices: new Set(this.#reset), retry: this.#schedule, spared: this.#spared, @@ -490,10 +491,39 @@ export class WarmPool { }; } + /** + * why: a request waits for a device that is `provisioning`, or shut down under an ownerless + * `boot` claim, so the policy matches those to waiters. A creation in flight has no device until + * it registers, and counts once: only the flights beyond the spec's `provisioning` devices. + */ + #onItsWay(devices: readonly VirtualDevice[]): { spec: VirtualSpec; deviceId?: string }[] { + const entries: { spec: VirtualSpec; deviceId?: string }[] = devices.flatMap((device) => { + const claim = this.options.claims.claim(device.id); + const onItsWay = + (device.state === "provisioning" || device.state === "shutdown") && + claim?.kind === "boot" && + claim.owner === undefined; + return onItsWay ? [{ deviceId: device.id, spec: device.spec }] : []; + }); + const creations = [...this.#flights].filter((flight) => flight.creation); + for (const [index, flight] of creations.entries()) { + const earlier = creations + .slice(0, index) + .filter((other) => sameSpec(other.spec, flight.spec)); + const registered = entries.filter( + (entry) => + sameSpec(entry.spec, flight.spec) && + devices.some((device) => device.id === entry.deviceId && device.state === "provisioning"), + ); + if (earlier.length >= registered.length) entries.push({ spec: flight.spec }); + } + return entries; + } + async #act(proposal: WarmProposal): Promise { if (this.options.acquisition.maintenanceActive) return; if (proposal.action === "provision") { - this.#launch(proposal.target, () => this.#provision(proposal.spec, proposal.target)); + this.#launch(proposal.target, true, () => this.#provision(proposal.spec, proposal.target)); return; } // why: a failed keep boot releases its reservation, which changes capacity and so triggers the next @@ -513,7 +543,7 @@ export class WarmPool { } if (proposal.action === "shutdown") await this.#shutdown(proposal.deviceId); else if (owner === undefined) await this.#boot(proposal.deviceId, undefined); - else this.#launch(owner, () => this.#boot(proposal.deviceId, owner)); + else this.#launch(owner, false, () => this.#boot(proposal.deviceId, owner)); } #specOf(deviceId: string): VirtualSpec | undefined { @@ -527,8 +557,8 @@ export class WarmPool { * an attempt was made. One that was declined (the device or the budget was gone by then) asks * for none: the same view would propose it again at once, and the pool would spin. */ - #launch(spec: VirtualSpec, run: () => Promise): void { - const flight: Flight = { done: Promise.resolve(), spec }; + #launch(spec: VirtualSpec, creation: boolean, run: () => Promise): void { + const flight: Flight = { creation, done: Promise.resolve(), spec }; this.#flights.add(flight); flight.done = run() .catch((error: unknown) => { From 3531a4582c50ba231b2b8e38d2c8c04ccd057e7c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:33:42 +0200 Subject: [PATCH 17/31] test: the pool runs a pass when a request is queued (#774) --- src/core/warm-pool/converger.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index e4e4c3682..15b27453e 100644 --- a/src/core/warm-pool/converger.test.ts +++ b/src/core/warm-pool/converger.test.ts @@ -797,6 +797,7 @@ describe("warm pool converger", () => { ["device.shutdown", { deviceId: "d", initiator: "test" }], ["device.deleted", { deviceId: "d", initiator: "test", physical: false }], ["cleanup.executed", { action: "shutdown", reason: "r", ruleName: "n", target: "d" }], + ["lease.queued", { queuePosition: 2, requestId: "r" }], ] as const; const rig = harness([]); rig.pool.start(); From c425a7766de29e6438468ceb3ff5dd22b85f750d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:33:54 +0200 Subject: [PATCH 18/31] feat(warm-pool): a queued request triggers a pass (#774) --- src/core/warm-pool/converger.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index 21c032fc1..739397011 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -729,4 +729,5 @@ const TRIGGERS = [ "device.deleted", "cleanup.executed", "capacity.changed", + "lease.queued", ] as const; From 1e96f1236df49f87a28cfa6a06d5d97f0618018e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:34:30 +0200 Subject: [PATCH 19/31] test: warmPool.maxConcurrentBoots defaults from the CPU count (#774) --- src/core/config.test.ts | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 145c6899d..33e271932 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -122,7 +122,7 @@ describe("loadConfig", () => { http: { enabled: false, host: "127.0.0.1", port: 4701 }, warmPool: { enabled: true, - maxConcurrentBoots: 1, + maxConcurrentBoots: 2, reserveRunning: { android: 0, ios: 0 }, targets: [], quarantine: { @@ -411,20 +411,29 @@ describe("loadConfig", () => { ); describe("warmPool.targets and warmPool.maxConcurrentBoots", () => { - async function load(warmPool?: unknown) { + async function load(warmPool?: unknown, cpuCount = 8) { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); if (warmPool !== undefined) { await filesystem.writeFileAtomic(configPath, JSON.stringify({ warmPool })); } - return loadConfig({ configPath, filesystem, systemStats: createStats() }); + const systemStats = new FakeSystemStats({ cpuCount, totalRamBytes: 32 * gibibyte }); + return loadConfig({ configPath, filesystem, systemStats }); } - it("defaults to no targets and one concurrent boot", async () => { - const config = await load(); - - expect(config.warmPool.targets).toEqual([]); - expect(config.warmPool.maxConcurrentBoots).toBe(1); + it("defaults to no targets and max(1, floor(cpuCount / 4)) concurrent boots, and a file value wins", async () => { + expect((await load()).warmPool.targets).toEqual([]); + for (const [cpuCount, boots] of [ + [2, 1], + [8, 2], + [12, 3], + ] as const) { + expect( + (await load(undefined, cpuCount)).warmPool.maxConcurrentBoots, + `${cpuCount} CPUs`, + ).toBe(boots); + } + expect((await load({ maxConcurrentBoots: 5 }, 2)).warmPool.maxConcurrentBoots).toBe(5); }); it("loads a target with a model, an OS range, a mode and a count, and a boot cap of two", async () => { From 24f8943a9ddfdcfc8d84d16475fa43ea7ac3ff02 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:34:46 +0200 Subject: [PATCH 20/31] feat(config): warmPool.maxConcurrentBoots defaults from the CPU count (#774) --- src/core/config.ts | 2 +- src/core/warm-pool/config.ts | 17 ++++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/core/config.ts b/src/core/config.ts index cd248f0bf..2bc495f19 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -892,7 +892,7 @@ function defaultConfig( deleteAfterMs: 60 * 60_000, }, warmPool: { - ...defaultWarmPoolConfig, + ...defaultWarmPoolConfig(systemStats), quarantine: { maxRetries: 3, retryBackoffMs: 30_000, diff --git a/src/core/warm-pool/config.ts b/src/core/warm-pool/config.ts index dbf6524c0..de8eef7a2 100644 --- a/src/core/warm-pool/config.ts +++ b/src/core/warm-pool/config.ts @@ -1,4 +1,5 @@ import { parseOsConstraint } from "../../contract/index.js"; +import type { SystemStats } from "../../ports/index.js"; import { WARM_POOL_NAME_MAX, WARM_POOL_TARGETS_MAX } from "../../contract/schemas.js"; import { booleanValue, @@ -34,16 +35,18 @@ export interface WarmPoolConfig { readonly reserveRunning: { readonly ios: number; readonly android: number }; /** Kinds of device kept booted ahead of demand. */ readonly targets: readonly WarmTarget[]; - /** The most target boots and creations that run at once. */ + /** why: the most boots and creations in flight at once: the pool's own, for waiters and targets, and each waiting request's own. */ readonly maxConcurrentBoots: number; } -export const defaultWarmPoolConfig: WarmPoolConfig = { - enabled: true, - maxConcurrentBoots: 1, - reserveRunning: { android: 0, ios: 0 }, - targets: [], -}; +export function defaultWarmPoolConfig(systemStats: SystemStats): WarmPoolConfig { + return { + enabled: true, + maxConcurrentBoots: Math.max(1, Math.floor(systemStats.cpuCount() / 4)), + reserveRunning: { android: 0, ios: 0 }, + targets: [], + }; +} /** A non-empty string no longer than the bound the status answer carries. */ function boundedName(value: unknown, path: string): string { From 8f923f0f5fcf6df7ced74ad11911b926da8c72fb Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:36:00 +0200 Subject: [PATCH 21/31] test: a request behind an in-flight head is granted the device the pool created for it (#774) --- .../lease-acquisition-coordinator.test.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/leasing/lease-acquisition-coordinator.test.ts b/src/leasing/lease-acquisition-coordinator.test.ts index 46d5f17ef..8156f3516 100644 --- a/src/leasing/lease-acquisition-coordinator.test.ts +++ b/src/leasing/lease-acquisition-coordinator.test.ts @@ -301,6 +301,7 @@ async function createHarness( components, coordinator, driver, + provisioner, queue, registry, requestIds, @@ -903,6 +904,40 @@ describe("LeaseAcquisitionCoordinator", () => { }).toEqual({ queueDepth: 0, secondGranted: true, sameDevice: false }); }); + it("grants a request queued behind an in-flight head the device the pool created for it, with no provision of its own", async () => { + const harness = await createHarness({ maxDevices: 2, maxRunning: 2 }); + harness.driver.hangMakeReady(); + const first = harness.coordinator.request(request, { ownerId: "a", requesterId: "a" }); + await settle(); + const second = harness.coordinator.request(request, { ownerId: "b", requesterId: "b" }); + let secondDeviceId: string | undefined; + void second.then((grant) => { + secondDeviceId = grant.device.id; + }); + await settle(); + expect(harness.coordinator.waitingDemand()).toMatchObject([ + { inFlight: true, spec: request }, + { inFlight: false, spec: request }, + ]); + + const created = harness.provisioner.provision(request, { + claim: { kind: "boot" }, + reservation: { release: () => undefined }, + }); + await settle(); + harness.driver.releaseMakeReady(); + const [firstGrant, handoff] = await Promise.all([first, created]); + handoff.claim.release(); + harness.coordinator.kick(); + await settle(); + + expect({ + provisioned: harness.driver.calls.filter((call) => call.operation === "provision").length, + sameDevice: secondDeviceId === firstGrant.device.id, + secondGotPoolDevice: secondDeviceId === handoff.device.id, + }).toEqual({ provisioned: 2, sameDevice: false, secondGotPoolDevice: true }); + }); + it("grants a request queued behind another request booting a shut-down device once that device is granted, with no release", async () => { const harness = await createHarness({ maxDevices: 2, maxRunning: 2 }); const held = await Promise.all([ @@ -3398,6 +3433,7 @@ describe("LeaseAcquisitionCoordinator waiting demand", () => { platform: "ios", target: { kind: "model", model: "iPhone 16" }, }, + spec: request, }, ]); From 13bdf2c2f0d518ba51ce19f300f22e59483517f4 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:46:46 +0200 Subject: [PATCH 22/31] test: requests behind an in-flight head are each granted the device the pool created for them (#774) --- e2e/warm-pool-reserve.test.ts | 32 +++++++++++++++++ e2e/warm-targets.test.ts | 4 ++- .../lease-acquisition-coordinator.test.ts | 36 +++++++++++-------- 3 files changed, 57 insertions(+), 15 deletions(-) diff --git a/e2e/warm-pool-reserve.test.ts b/e2e/warm-pool-reserve.test.ts index edfddbd81..ee9e510ba 100644 --- a/e2e/warm-pool-reserve.test.ts +++ b/e2e/warm-pool-reserve.test.ts @@ -104,6 +104,38 @@ describe("warm pool reserve and requests that wait for a booting device", () => expect(status.json).toMatchObject({ capacity: { ios: { warm: 2 } } }); }); + it("five detached leases of one kind queued behind a booting device, with maxConcurrentBoots 3, start three makeReady calls at once, not four, then the fourth once one is ready, and every lease is granted with no device left idle", async () => { + const env = await withDaemon({ + configOverrides: { + limits: { maxRunning: 10, ios: { maxDevices: 10, maxRunning: 10 } }, + warmPool: { maxConcurrentBoots: 3 }, + }, + driverScript: { ios: { ...IOS, reclaimResult: "shutdown" } }, + }); + const warm = await lease(env, "warm"); + await env.driverScript.merge({ ios: { latencyMs: { makeReady: 4_000 } } }); + expect((await env.cli(["release", warm.lease.id])).code).toBe(0); + await waitFor(async () => (await makeReadyCalls(env)) === 2, { + label: "the warm pool's boot of the released device has started", + }); + + const grants = ["a1", "a2", "a3", "a4", "a5"].map((agent) => + lease(env, agent, ["--timeout", "60s"]), + ); + await waitFor(async () => (await makeReadyCalls(env)) === 5, { + label: "three more boots are running", + }); + await new Promise((resolve) => setTimeout(resolve, 1_500)); + expect(await makeReadyCalls(env)).toBe(5); + + const granted = await Promise.all(grants); + await untilQuiet(env); + + expect(new Set(granted.map((grant) => grant.device.id)).size).toBe(5); + expect(await makeReadyCalls(env)).toBe(6); + expect(await deviceStates(env)).toEqual(["leased", "leased", "leased", "leased", "leased"]); + }); + describe("while the warm pool boots a released device", () => { async function releasedAndBooting(env: TestEnv): Promise { const first = await lease(env, "holder"); diff --git a/e2e/warm-targets.test.ts b/e2e/warm-targets.test.ts index 88928884b..6823e0f7d 100644 --- a/e2e/warm-targets.test.ts +++ b/e2e/warm-targets.test.ts @@ -69,7 +69,9 @@ async function named(env: TestEnv, ...names: string[]) { describe("warm pool targets", () => { it("with a target of two iPhone 17 and no devices, keeps two ready one boot after the other, and grants the first lease without a boot", async () => { const env = await withDaemon({ - configOverrides: { warmPool: { targets: [{ ...IPHONE_17, count: 2 }] } }, + configOverrides: { + warmPool: { maxConcurrentBoots: 1, targets: [{ ...IPHONE_17, count: 2 }] }, + }, driverScript: { ios: { ...IOS, latencyMs: { makeReady: 300 } } }, }); diff --git a/src/leasing/lease-acquisition-coordinator.test.ts b/src/leasing/lease-acquisition-coordinator.test.ts index 8156f3516..9393410a6 100644 --- a/src/leasing/lease-acquisition-coordinator.test.ts +++ b/src/leasing/lease-acquisition-coordinator.test.ts @@ -909,33 +909,41 @@ describe("LeaseAcquisitionCoordinator", () => { harness.driver.hangMakeReady(); const first = harness.coordinator.request(request, { ownerId: "a", requesterId: "a" }); await settle(); - const second = harness.coordinator.request(request, { ownerId: "b", requesterId: "b" }); - let secondDeviceId: string | undefined; - void second.then((grant) => { - secondDeviceId = grant.device.id; - }); + const granted: Record = {}; + for (const agent of ["b", "c"]) { + void harness.coordinator + .request(request, { ownerId: agent, requesterId: agent }) + .then((grant) => { + granted[agent] = grant.device.id; + }); + } await settle(); expect(harness.coordinator.waitingDemand()).toMatchObject([ { inFlight: true, spec: request }, { inFlight: false, spec: request }, + { inFlight: false, spec: request }, ]); - const created = harness.provisioner.provision(request, { - claim: { kind: "boot" }, - reservation: { release: () => undefined }, - }); + const reservation = { release: () => undefined }; + const created = [ + harness.provisioner.provision(request, { claim: { kind: "boot" }, reservation }), + harness.provisioner.provision(request, { claim: { kind: "boot" }, reservation }), + ]; await settle(); harness.driver.releaseMakeReady(); - const [firstGrant, handoff] = await Promise.all([first, created]); - handoff.claim.release(); + const [firstGrant, ...handoffs] = await Promise.all([first, ...created]); + for (const handoff of handoffs) handoff.claim.release(); harness.coordinator.kick(); await settle(); expect({ + distinct: new Set([firstGrant.device.id, ...Object.values(granted)]).size, + granted: Object.keys(granted).sort(), provisioned: harness.driver.calls.filter((call) => call.operation === "provision").length, - sameDevice: secondDeviceId === firstGrant.device.id, - secondGotPoolDevice: secondDeviceId === handoff.device.id, - }).toEqual({ provisioned: 2, sameDevice: false, secondGotPoolDevice: true }); + }).toEqual({ distinct: 3, granted: ["b", "c"], provisioned: 3 }); + expect(Object.values(granted).sort()).toEqual( + handoffs.map((handoff) => handoff.device.id).sort(), + ); }); it("grants a request queued behind another request booting a shut-down device once that device is granted, with no release", async () => { From 17e64a16611bf5ede66f9832efc446fda420b9a5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:47:08 +0200 Subject: [PATCH 23/31] fix(leasing): a request granted a ready device wakes the next one in line (#774) --- src/leasing/lease-acquisition-coordinator.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index 8f1e7d326..378b23b9f 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -899,6 +899,9 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { if (!this.options.queue.markProcessing(waiter)) return undefined; try { await this.#grant(waiter, plan.device, plan.kind); + // why: the next request in line may already have a ready device waiting for it, and no + // other event will wake it. + this.#wakeQueue(); } catch (error: unknown) { this.#logFailure("granting a ready device failed", waiter, plan.device, "grant", error); this.#defer(waiter, "waiting-for-device"); From 2d658937805e684284739a3ebe67d2e128cab586 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:52:49 +0200 Subject: [PATCH 24/31] fix(warm-pool): the pool leaves the waiter the queue reaches at once to leasing's own creation (#774) --- src/core/warm-pool/policy.test.ts | 11 +++++++---- src/core/warm-pool/policy.ts | 23 ++++++++++++++--------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 8d1740f6f..dc2f5b407 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -251,18 +251,21 @@ describe("warm pool policy", () => { const two = [waiter("iPhone 15", true), waiter("iPhone 15"), waiter("iPhone 17")]; const base = { maxConcurrentBoots: 5, limit: 10 }; - expect(evaluate(view([ready("one")], { ...base, waiting: two.slice(1) }))).toEqual([ + expect(evaluate(view([ready("one")], { ...base, waiting: two }))).toEqual([ creation("iPhone 17"), ]); expect( - evaluate(view([ready("one"), ready("two")], { ...base, waiting: two.slice(1) })), + evaluate( + view([ready("one")], { ...base, waiting: [waiter("iPhone 15"), waiter("iPhone 17")] }), + ), ).toEqual([]); + expect(evaluate(view([ready("one"), ready("two")], { ...base, waiting: two }))).toEqual([]); expect( evaluate( view([], { ...base, onItsWay: [{ spec: spec("iPhone 15") }], - waiting: two.slice(1), + waiting: two, }), ), ).toEqual([creation("iPhone 17")]); @@ -271,7 +274,7 @@ describe("warm pool policy", () => { view([], { ...base, onItsWay: [{ spec: spec("iPhone 15") }, { deviceId: "other", spec: spec("iPhone 17") }], - waiting: two.slice(1), + waiting: two, }), ), ).toEqual([]); diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 1f6f9512f..d83d31115 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -302,18 +302,23 @@ function boots( }; const roomFor = (spec: VirtualSpec): boolean => room.global >= 1 && room[spec.platform] >= 1; - view.waiting.forEach((demand, position) => { + let atHead = true; + for (const demand of view.waiting) { + const head: boolean = atHead; if (demand.inFlight) { + atHead = false; hold(demand.platform); - return; + continue; } + const ready = running.find((candidate) => !matched.has(candidate) && serves(candidate, demand)); const match = - running.find((candidate) => !matched.has(candidate) && serves(candidate, demand)) ?? - view.onItsWay.find((entry) => !matched.has(entry) && servesSpec(entry.spec, demand)); + ready ?? view.onItsWay.find((entry) => !matched.has(entry) && servesSpec(entry.spec, demand)); if (match !== undefined) { matched.add(match); - return; + atHead = head && ready !== undefined; + continue; } + atHead = false; const device = open() ? bootable.find( (candidate) => @@ -328,10 +333,10 @@ function boots( claim(room, device); started += 1; proposals.push({ action: "boot", deviceId: device.id, reason: "waiting-request" }); - return; + continue; } const creatable = view.admit.create(demand.spec) === undefined && roomFor(demand.spec); - if (position > 0 && creatable && open() && view.retry.mayAttempt(demand.spec, view.now)) { + if (!head && creatable && open() && view.retry.mayAttempt(demand.spec, view.now)) { started += 1; proposals.push({ action: "provision", @@ -339,10 +344,10 @@ function boots( spec: demand.spec, target: demand.spec, }); - } else if (position === 0 && creatable) started += 1; + } else if (head && creatable) started += 1; else stuck.add(demand.platform); hold(demand.platform); - }); + } const recent = bootable .filter( From 9785494ac589e09ad8e94259ca4025d29bf2f88e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 20:54:00 +0200 Subject: [PATCH 25/31] docs(warm-pool): the pool serves the whole queue; the boot cap defaults from the CPU (#774) --- docs/CLI.md | 9 +++++--- docs/CONFIGURATION.md | 4 ++-- docs/EVENTS.md | 2 +- docs/internal/EVENTS.md | 2 +- docs/internal/flows/device-selection.md | 2 +- src/core/warm-pool/AGENTS.md | 29 ++++++++++++++++--------- src/core/warm-pool/converger.ts | 11 +++++----- src/core/warm-pool/policy.test.ts | 3 ++- src/core/warm-pool/policy.ts | 14 ++++++------ src/leasing/AGENTS.md | 3 ++- 10 files changed, 47 insertions(+), 32 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 2f9efc7b6..a9ae268cb 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -593,8 +593,11 @@ A lease names its device in one of three ways: A class lease is served by the first of these that applies: an idle device that is already running and fits, then (unless `--no-wait`) a device the warm -pool is already booting that fits, which it waits for, then an idle device that -is shut down and fits (it is booted), then a new device. A device fits when its platform, +pool is already booting or creating that fits, which it waits for, then an idle device that +is shut down and fits (it is booted), then a new device. A request queued behind +another is not left idle meanwhile: the warm pool boots a shut-down device that fits it or +creates a new one for it, within `warmPool.maxConcurrentBoots`, and the request is granted that +device once it is ready and the request is next in line. A device fits when its platform, class, OS, mode and image tag all satisfy the request: with no `--os` a class lease fits a device on any installed runtime, with `--os` a device whose OS satisfies it, `--mode full` and `--image-tag` @@ -1520,7 +1523,7 @@ warm pool: enabled, reserve ios 1 android 0 `no-driver`, `runtime-missing`, `unknown-model`, `unresolvable`, `boot-failed`, `device-limit`, `running-limit`, `reserve` or `ram-budget`; when several apply, the first of that list is shown. A target that is filling, held back by -`warmPool.maxConcurrentBoots` or waiting behind a queued request is not short. +`warmPool.maxConcurrentBoots` or waiting behind a queued request the pool could not serve is not short. In `--json` the block is `warmPool`: `enabled`, `reserveRunning` (`ios`, `android`) and `targets`, each with `platform`, `model`, `osVersion` (the one the target resolved to, or the one it names when it did not resolve; absent diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 45a7ea73b..4d91110b7 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -18,8 +18,8 @@ edit yourself keeps the mode you give it until the next `config set`; run | `idle.deleteAfterMs` | How long a shut-down device sits idle before Simlock deletes it (tier 2, reclaims disk). Idle counts from the end of the device's last lease, or, for a device that never served one (one the pool created for a `warmPool.targets` entry that was later lowered or removed, say), from when it was shut down. | `1 hour` | | `warmPool.enabled` | Whether released devices are kept warm. `true` keeps a released device running or boots it back when the running limit has room, and shuts down the least recently used idle devices when the machine is over its running limit. `false` keeps nothing warm: every idle running device is shut down. | `true` | | `warmPool.reserveRunning.ios` / `warmPool.reserveRunning.android` | Running slots per platform that idle warm devices may not fill, so a request for a model nobody predicted boots at once instead of shutting a warm device down first. With a running limit of 3 for the platform and a reserve of 1, at most 2 idle devices stay warm. The global running limit loses the sum of the two reserves, each counted at most up to its platform's running limit. A non-negative integer; a reserve at or above the platform's running limit keeps no device of that platform warm. | `0` | -| `warmPool.targets` | Kinds of device Simlock keeps booted, clean and unleased ahead of demand. Each entry is written like a lease request: `platform` (`ios` or `android`), `model` (the exact model name), optionally `osVersion` (a version or an OS range such as `">=18"`) and `mode` (`slim` or `full`), and a `count`. Every pass Simlock resolves each entry the way a lease request is resolved, so the newest installed runtime in range is used and the platform's default mode applies when `mode` is left out, then boots a shut-down device of that kind or creates one until `count` are ready. The first lease for that kind is granted without a boot, including under `lease.identity` `fresh`, where every lease then costs one new device. A target never shuts a device down to make room and never downloads a runtime: one whose runtime or model is not available stays short and is logged. `simlock status` shows each kind of device the targets name (entries that resolve to the same device are one line; an entry that could not be resolved, and every entry while the pool is off or before its first pass, is a line of its own) with how many are ready and booting and, when the last pass could do nothing for it, why it is short (`runtime-missing`, `unknown-model`, `running-limit`, `reserve`, `ram-budget` and the others listed under [`simlock status`](CLI.md#simlock-status)), and with `warmPool.enabled` `false` shows every target as `disabled`; a target that is filling or waiting behind a queued request is not short. `simlock doctor` reports a target whose runtime or model does not exist, and targets whose counts add up to more than the running limit leaves after the reserve. A device that fails to boot is tried again after 1, 2, 4 and so on minutes, at most 10 apart. Unknown keys, a `count` below 1, an unknown platform, more than 256 entries and a `model` or `osVersion` longer than 256 characters fail the load, naming the key. Changes take effect on daemon restart; with `warmPool.enabled` `false` no target is kept. | `[]` | -| `warmPool.maxConcurrentBoots` | The most target devices booted or created at once. A positive integer. | `1` | +| `warmPool.targets` | Kinds of device Simlock keeps booted, clean and unleased ahead of demand. Each entry is written like a lease request: `platform` (`ios` or `android`), `model` (the exact model name), optionally `osVersion` (a version or an OS range such as `">=18"`) and `mode` (`slim` or `full`), and a `count`. Every pass Simlock resolves each entry the way a lease request is resolved, so the newest installed runtime in range is used and the platform's default mode applies when `mode` is left out, then boots a shut-down device of that kind or creates one until `count` are ready. The first lease for that kind is granted without a boot, including under `lease.identity` `fresh`, where every lease then costs one new device. A target never shuts a device down to make room and never downloads a runtime: one whose runtime or model is not available stays short and is logged. `simlock status` shows each kind of device the targets name (entries that resolve to the same device are one line; an entry that could not be resolved, and every entry while the pool is off or before its first pass, is a line of its own) with how many are ready and booting and, when the last pass could do nothing for it, why it is short (`runtime-missing`, `unknown-model`, `running-limit`, `reserve`, `ram-budget` and the others listed under [`simlock status`](CLI.md#simlock-status)), and with `warmPool.enabled` `false` shows every target as `disabled`; a target that is filling or waiting behind a queued request the pool could not serve is not short. `simlock doctor` reports a target whose runtime or model does not exist, and targets whose counts add up to more than the running limit leaves after the reserve. A device that fails to boot is tried again after 1, 2, 4 and so on minutes, at most 10 apart. Unknown keys, a `count` below 1, an unknown platform, more than 256 entries and a `model` or `osVersion` longer than 256 characters fail the load, naming the key. Changes take effect on daemon restart; with `warmPool.enabled` `false` no target is kept. | `[]` | +| `warmPool.maxConcurrentBoots` | The most boots and creations in flight at once. The warm pool starts a boot or a creation for every queued request, oldest first, and then for the targets, up to this many together with the boots and creations queued requests are running themselves. A positive integer. | `max(1, floor(cpuCount / 4))` over the host's CPUs, so `3` on a 12-CPU Mac | | `warmPool.quarantine.maxRetries` | Failed purge retries allowed on a quarantined device (after the triggering failure) before Simlock gives up and destroys it. A device created under `lease.identity` `fresh` retries its delete instead of a purge. A physical device is never destroyed: its retries are uninstall retries, and when they run out it is unenrolled. | `3` | | `warmPool.quarantine.retryBackoffMs` | Delay before the first quarantine purge retry. | `30 seconds` | | `warmPool.quarantine.retryBackoffMultiplier` | Growth factor applied to the backoff after each failed retry. | `2` | diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 43b1c52df..d67affb22 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -32,7 +32,7 @@ the gateway's own lease index before any worker is ever contacted. `lease-id-tak |---|---|---|---|---| | `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 change is to the physical line | the number of requests waiting in a queue changed: a request joined it or left it. A queue has two lines, simulator and emulator requests and physical requests: `depth` counts the line that changed, and `physical` says which. 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, OS version (the one the target resolved to, or the one it names when it did not resolve; absent when it names none and did not resolve), mode, count, ready, reason (the one reason `simlock status` shows as the target's `short`: `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. Once on that edge for each kind of device the targets name (targets that resolve to the same device emit one event between them, with their counts added), not on each short pass after, nor when a retry or a boot fills it and it is short again; only a target whose ready devices reach its count and that is then missed again emits again. A target that is filling, held by `warmPool.maxConcurrentBoots` or waiting behind a queued request is not short | WarmPool (worker) | implemented | +| `warm-pool.target-missed` | platform, model, OS version (the one the target resolved to, or the one it names when it did not resolve; absent when it names none and did not resolve), mode, count, ready, reason (the one reason `simlock status` shows as the target's `short`: `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. Once on that edge for each kind of device the targets name (targets that resolve to the same device emit one event between them, with their counts added), not on each short pass after, nor when a retry or a boot fills it and it is short again; only a target whose ready devices reach its count and that is then 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/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 675e73a4b..eb3f8289e 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, count, ready, reason }` — `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 is not short | WarmPool (worker) | implemented | +| `warm-pool.target-missed` | `{ platform, model, osVersion?, mode, count, ready, reason }` — `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 | ## Device lifecycle diff --git a/docs/internal/flows/device-selection.md b/docs/internal/flows/device-selection.md index 253c07e80..68cdb2e4c 100644 --- a/docs/internal/flows/device-selection.md +++ b/docs/internal/flows/device-selection.md @@ -81,7 +81,7 @@ same platform, same image tag, model equal or `classOf(model)` equal to the clas `classOf` reads the catalog entry read during resolution; a device record stores no class. 1. A `ready`, unclaimed device that serves → grant. -2. Unless `noWait`: one the warm pool is booting or creating for nobody → wait. +2. Unless `noWait`: one the warm pool is booting or creating under an ownerless claim (for a target, a released device or a request queued behind) → wait. 3. A `shutdown` device that serves → boot it. 4. Else provision the spec, evict an idle device, wait, or `NO_CAPACITY`. diff --git a/src/core/warm-pool/AGENTS.md b/src/core/warm-pool/AGENTS.md index 4fc1c5fdb..8bc560189 100644 --- a/src/core/warm-pool/AGENTS.md +++ b/src/core/warm-pool/AGENTS.md @@ -13,7 +13,7 @@ Flows: [startup](../../../docs/internal/flows/startup.md). Parent: [core](../AGE | `converger.ts` | `WarmPool`: triggers, one pass at a time, acts, `figures()`, `warm-pool.target-missed` | | `policy.ts` | `evaluate`: pure; proposals and per-target reports; `targetedDevices`, `reservedRunning` | | `retry.ts` | `RetrySchedule`: a target's failed boot or creation, keyed by resolved spec | -| `config.ts` | `WarmPoolConfig`, `defaultWarmPoolConfig`, validators | +| `config.ts` | `WarmPoolConfig`, `defaultWarmPoolConfig(systemStats)`, validators | | `figures.ts` | `WarmPoolFigures`, `WarmTargetFigures` | ## How it works @@ -22,8 +22,8 @@ Warm = virtual, `ready`, unleased. Budget = running limit minus every slot a lea quarantined or reserved device holds (`RunningCapacity`), per platform and global. 1. **Trigger** — bus facts `daemon.started`, `device.reclaimed`, `device.quarantine-recovered`, - `lease.granted`, `lease.released`, `device.shutdown`, `device.deleted`, `cleanup.executed`, - `capacity.changed`; a 30 s tick; the retry timer; `core.passWarmPool()` (leasing, once a + `lease.granted`, `lease.released`, `lease.queued`, `device.shutdown`, `device.deleted`, + `cleanup.executed`, `capacity.changed`; a 30 s tick; the retry timer; `core.passWarmPool()` (leasing, once a background reclaim drops its claim). A trigger during a pass asks for one more pass. 2. **Fence** — while nuke holds acquisition closed: do nothing, and remember each `shutdown` device; it is never booted back unasked. @@ -35,18 +35,27 @@ quarantined or reserved device holds (`RunningCapacity`), per platform and globa - pool off: shut down every idle `ready` device (`disabled`); - over budget: shut down idle devices, LRU first, never one a waiting request would take; none while a booted device is on its way to a lease; - - boot one shut-down device for the queue head; then devices released less than - `idle.shutdownAfterMs` ago, newest first, while room beyond the reserve is left; + - the queue, oldest first, one device per waiter and one waiter per device: an idle ready device or + one on its way (`onItsWay`: `provisioning` or shut down under an ownerless `boot` claim) that + serves it, else a shut-down device that serves it is booted, else a device of its spec is + created (`waiting-request`), under `maxConcurrentBoots` counting the pool's flights, each + in-flight waiter and the head's own work. No creation for the head or for a waiter every + earlier waiter of which is matched to a ready device: leasing creates for those. A boot or + creation the capacity strategy or the retry schedule refuses is not proposed; + - then devices released less than `idle.shutdownAfterMs` ago, newest first, while room beyond + the reserve is left; - shut down a device never leased, `ready` longer than `idle.shutdownAfterMs`, no target keeps; - targets: merge those of one spec (counts summed); boot a shut-down device of the kind, else - create one. Not while a request is queued on its platform, not while `RetrySchedule` holds the - spec, not past running slots, reserve, device limit, RAM or `maxConcurrentBoots`. + create one, after the queue's devices. Not while a waiter on its platform is one the pass could not + serve, not while `RetrySchedule` holds the spec, not past running slots, reserve, device limit, + RAM or `maxConcurrentBoots`. 5. **Act** — each proposal revalidated (same state, no lease, no claim): - shutdown: `lifecycle.shutdown`, initiator `warm-pool`, `cleanup` claim; - boot (lock: `tryReserveBoot` + `boot` claim) → `bootWarm` → release both; - creation (lock: `tryReserveProvisioning`) → `provisioner.provision` with an ownerless `boot` claim, dropped once ready, so a request may wait on it. - Target boots and creations run beside the pass. Every attempted action ends in `kick()`. + Target and `waiting-request` boots and creations run beside the pass. Every attempted action + ends in `kick()`. 6. **Report** — emit `warm-pool.target-missed`, arm the retry timer. `targeted()`: per target, its ready unleased unclaimed devices, oldest first, up to its count. @@ -58,7 +67,7 @@ Figures (`figures()`, read by `status.get`, doctor's `warm-pool-target-unreachab `short`, the first that applies: `disabled`; set in the converger `no-driver`, `runtime-missing`, `unknown-model`, `unresolvable`; set in the policy `boot-failed`, `device-limit`, `running-limit`, -`reserve`, `ram-budget`. None while filling or waiting behind a queued request. +`reserve`, `ram-budget`. None while filling or waiting behind a queued request the pass could not serve. `warm-pool.target-missed`: once per report that is short now and whose configured targets have not missed since they were last met (ready ≥ count). Payload: platform, model, osVersion, mode, count, @@ -74,7 +83,7 @@ Stop: `close()` at stop start; `drain()` finishes the pass and running boots, st | Pool on | `true` | `warmPool.enabled` | | Running slots idle devices may not fill | 0 per platform, capped at its limit | `warmPool.reserveRunning` | | Targets | none, at most 256 | `warmPool.targets` | -| Target boots and creations at once | 1 | `warmPool.maxConcurrentBoots` | +| Boots and creations in flight at once | `max(1, floor(cpuCount / 4))` | `warmPool.maxConcurrentBoots` | | Recently released, never-leased idle | 10 min | `idle.shutdownAfterMs` | | Tick; pause after a failed keep boot or shutdown | 30 s | `WARM_POOL_TICK_MS` | | Target retry | 60 s, doubling, cap 10 min | `RETRY_FIRST_MS`, `RETRY_MAX_MS` | diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index 739397011..c2e2be98a 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -75,7 +75,7 @@ export interface WarmPoolOptions { /** The tick that re-runs a pass when no event does, so a slot freed silently is still used. */ export const WARM_POOL_TICK_MS = 30_000; -/** A target boot or creation that runs beside the pass: the target's spec, and its end. */ +/** why: a boot or creation of the pool that runs beside the pass, for a target or a waiter: its spec, and its end. */ interface Flight { readonly creation: boolean; readonly spec: VirtualSpec; @@ -83,15 +83,16 @@ interface Flight { } /** - * Observes the bus and runs one pass at a time over the pool: it resolves the operator's targets, + * why: observes the bus and runs one pass at a time over the pool: it resolves the operator's targets, * reads a snapshot, asks the policy what to shut down, boot and create, and does each through the * device lifecycle and the provisioner, revalidating the device first (safety rule 2). A trigger * that arrives during a pass asks for one more, not one each. * * Every action that is attempted ends in `kick()`, whether it worked or not, so a request waiting * on a boot the pool started plans again either way; one declined before it began does not. A - * boot or creation for a target runs beside the pass, up to `maxConcurrentBoots` at a time, and - * asks for the next pass when it ends. + * boot or creation for a target or for a waiting request runs beside the pass, up to + * `maxConcurrentBoots` at a time with the waiting requests' own, and asks for the next pass when + * it ends. */ export class WarmPool { readonly #logger: Logger; @@ -552,7 +553,7 @@ export class WarmPool { } /** - * Starts a target's boot or creation beside the pass, which does not wait for it: the policy + * why: starts a boot or creation for a target or a waiter beside the pass, which does not wait for it: the policy * counts it toward `maxConcurrentBoots` until it ends, and its end asks for the next pass when * an attempt was made. One that was declined (the device or the budget was gone by then) asks * for none: the same view would propose it again at once, and the pool would spin. diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index dc2f5b407..903cebd32 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -1121,13 +1121,14 @@ describe("warm pool policy", () => { expect(result.targets.map((report) => report.booting)).toEqual([1, 0]); }); - it("reports a target held by the boot cap, or behind a queued request, with no reason", () => { + it("reports a target held by the boot cap, or behind a waiter the pass could not serve, with no reason", () => { const capped = plan(view([], { inFlight: [spec("iPad Pro")], targets: [target(1)] })); expect(capped.targets[0]).toMatchObject({ booting: 0, count: 1, ready: 0 }); expect(capped.targets[0]).not.toHaveProperty("short"); const queued = plan( view([], { + refuseProvision: "device-limit", targets: [target(1)], waiting: [classDemand()], }), diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index d83d31115..f22e75d88 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -104,7 +104,7 @@ export interface WarmPolicyView { readonly targets: readonly ResolvedTarget[]; /** Targets whose resolution failed and that keep a stale spec: their devices are spared. */ readonly spared: readonly ResolvedTarget[]; - /** The spec of each target boot or creation still running: they count toward the boot cap. */ + /** why: the spec of each boot or creation of the pool still running, for a target or a waiter; they count toward the boot cap. */ readonly inFlight: readonly VirtualSpec[]; readonly onItsWay: readonly { readonly spec: VirtualSpec; readonly deviceId?: string }[]; /** The failure schedule: whether a spec may be tried now. */ @@ -501,9 +501,9 @@ interface TargetPlan { } /** - * What each target still needs, and the boots and creations that fill it: a shut-down device of - * its kind is booted before a new one is created, never while a request is queued on its - * platform, never while its spec is held back after a failure, and never past the slots, the + * why: what each target still needs, and the boots and creations that fill it: a shut-down device + * of its kind is booted before a new one is created, never while a waiter on its platform is one + * the queue pass could not serve, never while its spec is held back after a failure, and never past the slots, the * device limit and RAM the capacity allows, nor past `maxConcurrentBoots` pool boots at once. A * target never shuts a device down: what it cannot fit it reports short. */ @@ -559,9 +559,9 @@ function planTargets( } /** - * Adds the boots and creations a target is missing. The reason it is short, when a pass could do - * nothing for it: a target with a boot already running or one proposed here is still filling, and - * one waiting behind a queued request is waiting, and neither is short, whatever stopped the rest. + * 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 + * could not be served is waiting; neither is short, whatever stopped the rest. */ function fillTarget( plan: TargetPlan, diff --git a/src/leasing/AGENTS.md b/src/leasing/AGENTS.md index 3472189ab..c438536cf 100644 --- a/src/leasing/AGENTS.md +++ b/src/leasing/AGENTS.md @@ -56,7 +56,8 @@ and registry writers. Read-decide-commit runs under it; driver I/O never does. that fails hands the device to core's quarantine through a port leasing declares, and the waiter's slot is freed either way. 5. **Grant** (lock) — `LeaseLifecycle.grant` → one registry commit: device - `leased` + lease + request granted. Emits `lease.granted`. Arms the TTL. + `leased` + lease + request granted. Emits `lease.granted`. Arms the TTL. A grant of a ready + device wakes the queue, so the next waiter plans without another event. 6. **Renew** — moves `ttlDeadline`; emits `lease.renewed`. The gateway forwards renews; it runs no timers of its own. 7. **End** — explicit release, TTL expiry, `device-lost` (health monitor or From 628c4e729cf748afd47a5650365a066f8815059f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 21:00:49 +0200 Subject: [PATCH 26/31] test: the stop test pins the boot cap it relies on (#774) --- src/daemon/main.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 6c6a76f3b..3bf62f20d 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -1401,6 +1401,7 @@ describe("startDaemon stop with a warm target", () => { capacity: { config: { maxRunning: 8 }, strategy: "fixed" }, http: { enabled: true, host: "127.0.0.1", port: await freeLoopbackPort() }, warmPool: { + maxConcurrentBoots: 1, targets: [{ count: 2, model: "iPhone 16", osVersion: "26.5", platform: "ios" }], }, }, From 062dbe17352c77fdcabdfc29ee5162bcb07ae214 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 21:02:07 +0200 Subject: [PATCH 27/31] refactor(warm-pool): split the queue pass into steps (#774) --- src/core/warm-pool/converger.test.ts | 14 +-- src/core/warm-pool/converger.ts | 13 ++- src/core/warm-pool/policy.ts | 125 +++++++++++++++++---------- 3 files changed, 95 insertions(+), 57 deletions(-) diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index 15b27453e..8d5a57d1f 100644 --- a/src/core/warm-pool/converger.test.ts +++ b/src/core/warm-pool/converger.test.ts @@ -138,6 +138,13 @@ function harness( }[] = []; const provisionReservations: { released: number }[] = []; const reserveAttempts = { count: 0 }; + const finishProvisioning = async (id: string): Promise => { + if (options.provisioning === undefined) return; + await options.provisioning; + state.devices = state.devices.map((item) => + item.id === id ? { ...item, state: "ready" } : item, + ); + }; const poolOptions: WarmPoolOptions = { acquisition: { kick, @@ -282,12 +289,7 @@ function harness( if (claim === undefined) throw new Error("the new device is already claimed"); provisionOptions.reservation.release(); record.deviceId = id; - if (options.provisioning !== undefined) { - await options.provisioning; - state.devices = state.devices.map((item) => - item.id === id ? { ...item, state: "ready" } : item, - ); - } + await finishProvisioning(id); return { claim, device: created }; }, }, diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index c2e2be98a..f71a6d183 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -532,10 +532,7 @@ export class WarmPool { // frees nothing, but any other trigger that comes soon would propose it again, so it is held // back the same way. A target's or a waiter's boot is held back by the retry schedule instead, // which the policy reads before it proposes one. - const owner = - proposal.action === "boot" && proposal.reason === "waiting-request" - ? this.#specOf(proposal.deviceId) - : proposal.target; + const owner = this.#ownerOf(proposal); if ( owner === undefined && (this.#retryAfter.get(proposal.deviceId) ?? 0) > this.options.clock.now() @@ -547,6 +544,14 @@ export class WarmPool { else this.#launch(owner, false, () => this.#boot(proposal.deviceId, owner)); } + /** why: the spec a boot or creation is held back by, when it is one of a target's or a waiter's. */ + #ownerOf(proposal: Exclude): VirtualSpec | undefined { + if (proposal.action === "boot" && proposal.reason === "waiting-request") { + return this.#specOf(proposal.deviceId); + } + return proposal.target; + } + #specOf(deviceId: string): VirtualSpec | undefined { return this.options.registry.snapshot.virtualDevices.find((device) => device.id === deviceId) ?.spec; diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index f22e75d88..185b706ef 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -275,6 +275,16 @@ interface QueuePass { readonly stuck: ReadonlySet; } +interface QueueState { + readonly view: WarmPolicyView; + readonly bootable: readonly VirtualDevice[]; + readonly room: Slots; + readonly proposals: WarmProposal[]; + readonly taken: Set; + readonly stuck: Set; + started: number; +} + /** * why: the queue is served in order, one device per waiter. A waiter behind the head gets a * shut-down device booted or a new one created, within `maxConcurrentBoots` counting the pool's @@ -290,24 +300,22 @@ function boots( room: Slots, held: Slots, ): QueuePass { - const proposals: WarmProposal[] = []; - const taken = new Set(); - const stuck = new Set(); - const matched = new Set(); - let started = view.inFlight.length + view.waiting.filter((demand) => demand.inFlight).length; - const open = (): boolean => started < view.config.maxConcurrentBoots; - const hold = (platform: "ios" | "android"): void => { - room.global -= 1; - room[platform] -= 1; + const state: QueueState = { + bootable, + proposals: [], + room, + started: view.inFlight.length + view.waiting.filter((demand) => demand.inFlight).length, + stuck: new Set(), + taken: new Set(), + view, }; - const roomFor = (spec: VirtualSpec): boolean => room.global >= 1 && room[spec.platform] >= 1; - + const matched = new Set(); let atHead = true; for (const demand of view.waiting) { const head: boolean = atHead; + atHead = false; if (demand.inFlight) { - atHead = false; - hold(demand.platform); + holdSlot(room, demand.platform); continue; } const ready = running.find((candidate) => !matched.has(candidate) && serves(candidate, demand)); @@ -316,43 +324,16 @@ function boots( if (match !== undefined) { matched.add(match); atHead = head && ready !== undefined; - continue; + } else if (!bootForWaiter(state, demand)) { + createForWaiter(state, demand, head); + holdSlot(room, demand.platform); } - atHead = false; - const device = open() - ? bootable.find( - (candidate) => - !taken.has(candidate.id) && - hasRoom(room, candidate) && - serves(candidate, demand) && - view.admit.boot(candidate) === undefined, - ) - : undefined; - if (device !== undefined) { - taken.add(device.id); - claim(room, device); - started += 1; - proposals.push({ action: "boot", deviceId: device.id, reason: "waiting-request" }); - continue; - } - const creatable = view.admit.create(demand.spec) === undefined && roomFor(demand.spec); - if (!head && creatable && open() && view.retry.mayAttempt(demand.spec, view.now)) { - started += 1; - proposals.push({ - action: "provision", - reason: "waiting-request", - spec: demand.spec, - target: demand.spec, - }); - } else if (head && creatable) started += 1; - else stuck.add(demand.platform); - hold(demand.platform); } const recent = bootable .filter( (device) => - !taken.has(device.id) && + !state.taken.has(device.id) && !view.resetDevices.has(device.id) && view.now - (device.lastLeaseEndedAt ?? Number.NEGATIVE_INFINITY) < view.config.shutdownAfterMs, @@ -361,11 +342,61 @@ function boots( for (const device of recent) { if (hasWarmRoom(room, held, device) && view.admit.boot(device) === undefined) { claim(room, device); - started += 1; - proposals.push({ action: "boot", deviceId: device.id, reason: "recently-released" }); + state.started += 1; + state.proposals.push({ action: "boot", deviceId: device.id, reason: "recently-released" }); } } - return { proposals, started, stuck }; + return { proposals: state.proposals, started: state.started, stuck: state.stuck }; +} + +function holdSlot(room: Slots, platform: Platform): void { + room.global -= 1; + room[platform] -= 1; +} + +function bootsOpen(state: QueueState): boolean { + return state.started < state.view.config.maxConcurrentBoots; +} + +function bootForWaiter(state: QueueState, demand: WaitingDemand): boolean { + if (!bootsOpen(state)) return false; + const device = state.bootable.find( + (candidate) => + !state.taken.has(candidate.id) && + hasRoom(state.room, candidate) && + serves(candidate, demand) && + state.view.admit.boot(candidate) === undefined, + ); + if (device === undefined) return false; + state.taken.add(device.id); + claim(state.room, device); + state.started += 1; + state.proposals.push({ action: "boot", deviceId: device.id, reason: "waiting-request" }); + return true; +} + +function createForWaiter(state: QueueState, demand: WaitingDemand, head: boolean): void { + const { room, view } = state; + const creatable = + view.admit.create(demand.spec) === undefined && + room.global >= 1 && + room[demand.spec.platform] >= 1; + if (head && creatable) { + state.started += 1; + } else if ( + !head && + creatable && + bootsOpen(state) && + view.retry.mayAttempt(demand.spec, view.now) + ) { + state.started += 1; + state.proposals.push({ + action: "provision", + reason: "waiting-request", + spec: demand.spec, + target: demand.spec, + }); + } else state.stuck.add(demand.platform); } /** The targets with those that resolved to one spec merged into one, counts summed. */ From c3bdc247dc6e0bf6404df3a1a7539ed102ad1bd4 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 21:02:28 +0200 Subject: [PATCH 28/31] refactor(warm-pool): split the queue pass further (#774) --- src/core/warm-pool/policy.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 185b706ef..6bddfe423 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -319,8 +319,7 @@ function boots( continue; } const ready = running.find((candidate) => !matched.has(candidate) && serves(candidate, demand)); - const match = - ready ?? view.onItsWay.find((entry) => !matched.has(entry) && servesSpec(entry.spec, demand)); + const match = ready ?? onItsWayFor(view, matched, demand); if (match !== undefined) { matched.add(match); atHead = head && ready !== undefined; @@ -329,8 +328,21 @@ function boots( holdSlot(room, demand.platform); } } + bootRecentlyReleased(state, held); + return { proposals: state.proposals, started: state.started, stuck: state.stuck }; +} - const recent = bootable +function onItsWayFor( + view: WarmPolicyView, + matched: ReadonlySet, + demand: WaitingDemand, +): WarmPolicyView["onItsWay"][number] | undefined { + return view.onItsWay.find((entry) => !matched.has(entry) && servesSpec(entry.spec, demand)); +} + +function bootRecentlyReleased(state: QueueState, held: Slots): void { + const { room, view } = state; + const recent = state.bootable .filter( (device) => !state.taken.has(device.id) && @@ -346,7 +358,6 @@ function boots( state.proposals.push({ action: "boot", deviceId: device.id, reason: "recently-released" }); } } - return { proposals: state.proposals, started: state.started, stuck: state.stuck }; } function holdSlot(room: Slots, platform: Platform): void { From ab4a788ac50cf07bdf801bcd77dfd2d757e546d1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 21:09:22 +0200 Subject: [PATCH 29/31] test: audit probes pin the in-flight waiter count, an owned claim, a registered creation and a floor CPU case (#774) --- src/core/config.test.ts | 2 ++ src/core/warm-pool/converger.test.ts | 18 +++++++++++++++++- src/core/warm-pool/policy.test.ts | 3 +++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 33e271932..ca295a1e3 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -425,7 +425,9 @@ describe("loadConfig", () => { expect((await load()).warmPool.targets).toEqual([]); for (const [cpuCount, boots] of [ [2, 1], + [6, 1], [8, 2], + [10, 2], [12, 3], ] as const) { expect( diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index 8d5a57d1f..22075921f 100644 --- a/src/core/warm-pool/converger.test.ts +++ b/src/core/warm-pool/converger.test.ts @@ -1060,6 +1060,8 @@ describe("warm pool targets", () => { devices: readonly VirtualDevice[], first: readonly WaitingDemand[], provisioning?: Promise, + registers = false, + owner?: string, ) => { let waiting: readonly WaitingDemand[] = first; const gate = held(); @@ -1071,9 +1073,14 @@ describe("warm pool targets", () => { waiting: () => waiting, }); const counts = () => [rig.bootCalls.length, rig.provisionCalls.length]; + if (owner !== undefined) rig.claims.tryClaim("shut-x", "boot", owner); void rig.pool.pass(); await flush(); const started = counts(); + if (registers) { + gate.finish(); + await flush(); + } void rig.pool.pass(); await flush(); const again = counts(); @@ -1086,11 +1093,20 @@ describe("warm pool targets", () => { const unregistered = await run([], [head, x2]); expect(unregistered).toEqual({ again: [0, 1], later: [0, 2], started: [0, 1] }); - const registered = await run([], [head, x2], new Promise(() => undefined)); + const registered = await run([], [head, x2], new Promise(() => undefined), true); expect(registered).toEqual({ again: [0, 1], later: [0, 2], started: [0, 1] }); const bootAndCreation = await run([device("shut-x", "shutdown", 20 * minute)], [head, x2, x3]); expect(bootAndCreation).toEqual({ again: [1, 1], later: [1, 2], started: [1, 1] }); + + const owned = await run( + [device("shut-x", "shutdown", 20 * minute)], + [head, x2], + undefined, + false, + "an-agent", + ); + expect(owned).toEqual({ again: [0, 1], later: [0, 2], started: [0, 1] }); }); it("does not return from a pass for a creation it started, and settle waits for it", async () => { diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 903cebd32..e786756c4 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -205,6 +205,9 @@ describe("warm pool policy", () => { creation("iPhone 17"), creation("iPhone 16"), ]); + expect(evaluate(view([busy], { maxConcurrentBoots: 2, waiting: three }))).toEqual([ + creation("iPhone 17"), + ]); expect( evaluate( view([busy], { From f3ec4a9aee5d568c10e8090b8d428a383c27688f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 21:23:34 +0200 Subject: [PATCH 30/31] fix(warm-pool): a waiter's boot respects the retry schedule (#774) --- docs/CONFIGURATION.md | 2 +- src/core/warm-pool/policy.test.ts | 17 +++++++++++++++++ src/core/warm-pool/policy.ts | 2 +- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 4d91110b7..0da265a8f 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -19,7 +19,7 @@ edit yourself keeps the mode you give it until the next `config set`; run | `warmPool.enabled` | Whether released devices are kept warm. `true` keeps a released device running or boots it back when the running limit has room, and shuts down the least recently used idle devices when the machine is over its running limit. `false` keeps nothing warm: every idle running device is shut down. | `true` | | `warmPool.reserveRunning.ios` / `warmPool.reserveRunning.android` | Running slots per platform that idle warm devices may not fill, so a request for a model nobody predicted boots at once instead of shutting a warm device down first. With a running limit of 3 for the platform and a reserve of 1, at most 2 idle devices stay warm. The global running limit loses the sum of the two reserves, each counted at most up to its platform's running limit. A non-negative integer; a reserve at or above the platform's running limit keeps no device of that platform warm. | `0` | | `warmPool.targets` | Kinds of device Simlock keeps booted, clean and unleased ahead of demand. Each entry is written like a lease request: `platform` (`ios` or `android`), `model` (the exact model name), optionally `osVersion` (a version or an OS range such as `">=18"`) and `mode` (`slim` or `full`), and a `count`. Every pass Simlock resolves each entry the way a lease request is resolved, so the newest installed runtime in range is used and the platform's default mode applies when `mode` is left out, then boots a shut-down device of that kind or creates one until `count` are ready. The first lease for that kind is granted without a boot, including under `lease.identity` `fresh`, where every lease then costs one new device. A target never shuts a device down to make room and never downloads a runtime: one whose runtime or model is not available stays short and is logged. `simlock status` shows each kind of device the targets name (entries that resolve to the same device are one line; an entry that could not be resolved, and every entry while the pool is off or before its first pass, is a line of its own) with how many are ready and booting and, when the last pass could do nothing for it, why it is short (`runtime-missing`, `unknown-model`, `running-limit`, `reserve`, `ram-budget` and the others listed under [`simlock status`](CLI.md#simlock-status)), and with `warmPool.enabled` `false` shows every target as `disabled`; a target that is filling or waiting behind a queued request the pool could not serve is not short. `simlock doctor` reports a target whose runtime or model does not exist, and targets whose counts add up to more than the running limit leaves after the reserve. A device that fails to boot is tried again after 1, 2, 4 and so on minutes, at most 10 apart. Unknown keys, a `count` below 1, an unknown platform, more than 256 entries and a `model` or `osVersion` longer than 256 characters fail the load, naming the key. Changes take effect on daemon restart; with `warmPool.enabled` `false` no target is kept. | `[]` | -| `warmPool.maxConcurrentBoots` | The most boots and creations in flight at once. The warm pool starts a boot or a creation for every queued request, oldest first, and then for the targets, up to this many together with the boots and creations queued requests are running themselves. A positive integer. | `max(1, floor(cpuCount / 4))` over the host's CPUs, so `3` on a 12-CPU Mac | +| `warmPool.maxConcurrentBoots` | The most boots and creations in flight at once. The warm pool starts a boot, or a creation for a request behind the head, for every queued request no ready device serves, oldest first (the head's creation and requests a ready device serves are the lease's own), and then for the targets, up to this many together with the boots and creations queued requests are running themselves. A positive integer. | `max(1, floor(cpuCount / 4))` over the host's CPUs, so `3` on a 12-CPU Mac | | `warmPool.quarantine.maxRetries` | Failed purge retries allowed on a quarantined device (after the triggering failure) before Simlock gives up and destroys it. A device created under `lease.identity` `fresh` retries its delete instead of a purge. A physical device is never destroyed: its retries are uninstall retries, and when they run out it is unenrolled. | `3` | | `warmPool.quarantine.retryBackoffMs` | Delay before the first quarantine purge retry. | `30 seconds` | | `warmPool.quarantine.retryBackoffMultiplier` | Growth factor applied to the backoff after each failed retry. | `2` | diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index e786756c4..b718cdff7 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -289,6 +289,23 @@ describe("warm pool policy", () => { }), ), ).toEqual([creation("iPhone 17")]); + // why: the head is the first waiter no ready idle device takes: with one ready device and two + // waiters it serves, the second is the head and leasing creates for it. + expect( + evaluate( + view([ready("one")], { ...base, waiting: [waiter("iPhone 15"), waiter("iPhone 15")] }), + ), + ).toEqual([]); + }); + + it("proposes no boot for a waiter whose spec the retry schedule holds back after a failed boot", () => { + const released = device("lse_15", "shutdown", { endedAgo: 90 * minute }); + const waiting = [classDemand(), classDemand()]; + + expect(evaluate(view([released], { waiting }))).toEqual([ + { action: "boot", deviceId: "lse_15", reason: "waiting-request" }, + ]); + expect(evaluate(view([released], { waiting, blocked: [spec("iPhone 15")] }))).toEqual([]); }); it("proposes a boot, not a shutdown, for a released iPhone 15 that serves a waiting class request at the running cap", () => { diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 6bddfe423..991878938 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -370,7 +370,7 @@ function bootsOpen(state: QueueState): boolean { } function bootForWaiter(state: QueueState, demand: WaitingDemand): boolean { - if (!bootsOpen(state)) return false; + if (!bootsOpen(state) || !state.view.retry.mayAttempt(demand.spec, state.view.now)) return false; const device = state.bootable.find( (candidate) => !state.taken.has(candidate.id) && From 3aca357d027c1ac1f32fc8d15b8b8723f7fb4e4e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 21:57:08 +0200 Subject: [PATCH 31/31] fix(warm-pool): a waiter's boot is held back under the device's spec (#774) --- src/core/warm-pool/policy.test.ts | 10 ++++++++++ src/core/warm-pool/policy.ts | 4 +++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index b718cdff7..af1e63560 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -306,6 +306,16 @@ describe("warm pool policy", () => { { action: "boot", deviceId: "lse_15", reason: "waiting-request" }, ]); expect(evaluate(view([released], { waiting, blocked: [spec("iPhone 15")] }))).toEqual([]); + + // why: the converger records the failure under the device's spec, which a class waiter's may differ from. + const other = device("lse_17", "shutdown", { + endedAgo: 90 * minute, + spec: spec("iPhone 17"), + }); + expect(evaluate(view([other], { waiting }))).toEqual([ + { action: "boot", deviceId: "lse_17", reason: "waiting-request" }, + ]); + expect(evaluate(view([other], { waiting, blocked: [spec("iPhone 17")] }))).toEqual([]); }); it("proposes a boot, not a shutdown, for a released iPhone 15 that serves a waiting class request at the running cap", () => { diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 991878938..644d235c4 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -370,12 +370,14 @@ function bootsOpen(state: QueueState): boolean { } function bootForWaiter(state: QueueState, demand: WaitingDemand): boolean { - if (!bootsOpen(state) || !state.view.retry.mayAttempt(demand.spec, state.view.now)) return false; + if (!bootsOpen(state)) return false; const device = state.bootable.find( (candidate) => !state.taken.has(candidate.id) && hasRoom(state.room, candidate) && serves(candidate, demand) && + // why: the converger records a failed boot under the device's spec, not the waiter's. + state.view.retry.mayAttempt(candidate.spec, state.view.now) && state.view.admit.boot(candidate) === undefined, ); if (device === undefined) return false;