From ba79c0b59024e815cd7956acf6eb14edb159c34f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 11:39:37 +0200 Subject: [PATCH 1/5] =?UTF-8?q?test:=20reproduce=20#802=20=E2=80=94=20reap?= =?UTF-8?q?er=20shuts=20down=20a=20queued=20request=20device?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/leasing/create-leasing.test.ts | 94 ++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/src/leasing/create-leasing.test.ts b/src/leasing/create-leasing.test.ts index 26639c96c..76aa369d6 100644 --- a/src/leasing/create-leasing.test.ts +++ b/src/leasing/create-leasing.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import { buildCapacityFigures, + CleanupReaper, type ModelPreferences, BootTimeoutError, type ComponentInstaller, @@ -28,6 +29,7 @@ import { JsonLinesLogger, type Logger, MemoryLogSink, + MemoryFilesystem, } from "../ports/index.js"; import { createLeasing } from "./create-leasing.js"; import { NoCapacityError, ProvisionFailedError } from "./lease-acquisition-coordinator.js"; @@ -3373,6 +3375,98 @@ describe("createLeasing warm pool", () => { }); }); +describe("createLeasing queued device cleanup", () => { + it("keeps an old released device ready across reaper passes while its requester waits behind the queue head", async () => { + const driver = new FakeDriver({ + availableOsVersions: ["26.5"], + clock: new FakeClock(1_000), + knownModels: ["iPhone 16"], + platform: "ios", + reclaimResult: "shutdown", + }); + const android = new FakeDriver({ + availableOsVersions: ["35"], + clock: new FakeClock(1_000), + platform: "android", + reclaimResult: "shutdown", + }); + const harness = await createHarness({ + driver, + drivers: [driver, android], + limits: { + android: { maxDevices: 1, maxRunning: 1 }, + ios: { maxDevices: 1, maxRunning: 1 }, + maxRunning: 3, + }, + }); + const other = { model: "Pixel 9", osVersion: "35", platform: "android" } as const; + await harness.engine.request(request, { + ownerId: "holder", + requesterId: "holder", + ttlMs: 3_600_000, + }); + const previous = await harness.engine.request(other, { + ownerId: "previous", + requesterId: "previous", + }); + await harness.engine.release(previous.lease.id, "explicit"); + await harness.engine.settle(); + harness.clock.advance(10_001); + await harness.engine.convergeRunningCapacity(); + const pending = ["head", "behind"].map((requesterId, index) => + harness.engine + .request(index === 0 ? request : other, { + ownerId: requesterId, + requesterId, + }) + .catch((error: unknown) => error), + ); + await flush(); + await harness.engine.core.passWarmPool(); + await harness.engine.settle(); + const state = () => + harness.registry.snapshot.devices.find((device) => device.id === previous.device.id)?.state; + expect(harness.engine.waitingRequests().map((entry) => entry.requesterId)).toEqual([ + "head", + "behind", + ]); + expect(state()).toBe("ready"); + const reaper = new CleanupReaper({ + clock: harness.clock, + config: config(), + eventBus: harness.bus, + executor: harness.engine.cleanup, + filesystem: new MemoryFilesystem(), + registry: harness.registry, + targetedDevices: () => harness.engine.core.targetedDevices(), + }); + try { + for (let pass = 0; pass < 2; pass += 1) { + await reaper.run(); + await harness.engine.settle(); + } + expect( + harness.bus + .replay() + .filter( + (event) => + event.event === "device.shutdown" && + event.payload.deviceId === previous.device.id && + event.payload.initiator === "cleanup-reaper", + ), + "a device booted for a queued requester must not be reaped", + ).toEqual([]); + expect(state()).toBe("ready"); + } finally { + reaper.dispose(); + await harness.engine.cancelPending("head"); + await harness.engine.cancelPending("behind"); + await Promise.all(pending); + harness.engine.dispose(); + } + }); +}); + describe("createLeasing warm targets", () => { const target = { count: 2, From 03ee84e148139db2be176b06c796f3c15a3b6032 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 11:53:10 +0200 Subject: [PATCH 2/5] fix(warm-pool): protect ready devices serving queued requests (#802) --- docs/CONFIGURATION.md | 2 +- src/core/AGENTS.md | 2 +- src/core/warm-pool/AGENTS.md | 5 ++++- src/core/warm-pool/converger.ts | 8 ++------ src/core/warm-pool/policy.test.ts | 2 ++ src/core/warm-pool/policy.ts | 19 +++++++++++++------ 6 files changed, 23 insertions(+), 15 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 056ef01ef..487234094 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -14,7 +14,7 @@ edit yourself keeps the mode you give it until the next `config set`; run | Property | Description | Default | | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | | `capacity.strategy` | Which policy decides how many devices may exist and run at once: `resource` or `fixed`. The options under `capacity.config` are that strategy's own -- see [Capacity strategies](#capacity-strategies). | `resource` | -| `idle.shutdownAfterMs` | How long an unused device sits idle before Simlock shuts it down (tier 1, reclaims RAM). Devices that a `warmPool.targets` entry keeps ready, or that the pool keeps for a kind it has leased, ignore it; a device that never served a lease and that no target or leased kind keeps is shut down once it has been ready this long. | `10 minutes` | +| `idle.shutdownAfterMs` | How long an unused device sits idle before Simlock shuts it down (tier 1, reclaims RAM). Devices that a `warmPool.targets` entry keeps ready, that the pool keeps for a kind it has leased, or that can serve a queued request while the pool is enabled, ignore it; a device that never served a lease and that no target or leased kind keeps is shut down once it has been ready this long. | `10 minutes` | | `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` boots a released device back and keeps it ready, when the running limit has room: the pool remembers every kind of device it has leased (model, OS, mode, image tag) and keeps as many ready as were leased at once in the last 24 hours, at least one, across daemon restarts, until the model or runtime is gone, three boots in a row fail, or `simlock nuke` clears it. It also shuts down the least recently used idle devices when the machine is over its running limit. `false` keeps nothing warm and learns nothing: 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` | diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index 3341336e1..c3f3c2ca3 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -92,7 +92,7 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic physical one. Physical not present: wait `health.probeIntervalMs`, not counted. Entry writes `quarantineCause` (kind, message cut to 300 characters, or `stalledState`); retries keep it, every exit drops it. 5. **Cleanup** — `CleanupReaper` on `lease.released`, `daemon.started`, `disk.pressure-detected`, a - tick. `idle-shutdown`: leased once, `ready`, idle past T1, not warm-targeted. `idle-destroy`: + tick. `idle-shutdown`: leased once, `ready`, idle past T1, neither warm-targeted nor serving a queued request with the pool enabled. `idle-destroy`: `shutdown`, idle (lease end, else `shutdownAt`) past T2, or T1 under pressure. `CleanupExecutor` revalidates, acts, emits `cleanup.executed`; a throwing action is logged, the run goes on. 6. **Nuke** — one at a time: close acquisition, settle reclaim and warm pool → release all leases diff --git a/src/core/warm-pool/AGENTS.md b/src/core/warm-pool/AGENTS.md index c582abd40..25ac27e1f 100644 --- a/src/core/warm-pool/AGENTS.md +++ b/src/core/warm-pool/AGENTS.md @@ -70,7 +70,10 @@ quarantined or reserved device holds (`RunningCapacity`), per platform and globa 6. **Report** — emit `warm-pool.target-missed`, arm the retry timer. `targeted()`: per target and learned kind, its ready unleased unclaimed devices, oldest first, up to its count. -The reaper's `idle-shutdown` spares them. With no pass yet, it resolves the targets first. +It also includes every ready unleased unclaimed device a current non-in-flight waiter could +be granted, using the pool's requirement, mode and fresh-identity checks. Demand is read on +every call, so cancellation removes this protection. The reaper's `idle-shutdown` spares +these devices. With no pass yet, it resolves the targets first. With the pool off it returns none. Figures (`figures()`, read by `status.get`, doctor's `warm-pool-target-unreachable`, the console): `enabled`, `reserveRunning`, and per kind `platform`, `model`, `osVersion`, `mode`, `count`, `ready`, diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index 6cc573f47..3aa93f018 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -285,12 +285,7 @@ export class WarmPool { this.#draining = true; } - /** - * The devices the idle shutdown timer leaves alone: for each target, its ready unleased devices - * of that kind, oldest first, up to its count. Targets not yet resolved by any pass are resolved - * first, so the reaper's first run after a start does not read an empty set; none with the - * pool off. - */ + /** why: resolve before the first reaper run, and read live demand so cancellation drops queue protection. */ async targeted(): Promise> { if (!this.options.config.enabled) return new Set(); if (!this.#hasResolved) await this.#resolveTargets(); @@ -301,6 +296,7 @@ export class WarmPool { leases, learned: this.#learnedKinds(), targets: [...this.#resolved, ...this.#spared], + waiting: this.options.acquisition.waitingDemand(), }); } diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 017374d69..606978a28 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -1505,6 +1505,7 @@ describe("warm pool policy", () => { leases: [leaseOn(leasedReady)], learned: [], targets: [target(1)], + waiting: [], }); expect([...named]).toEqual([]); @@ -1517,6 +1518,7 @@ describe("warm pool policy", () => { leases: devices.filter((item) => item.state === "leased").map(leaseOn), learned: [] as WarmPolicyView["learned"], targets, + waiting: [] as readonly WaitingDemand[], }); it("names, for each target, its ready unleased devices of that kind, oldest first, up to the count", () => { diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 29395cf0a..0d782a429 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -518,25 +518,32 @@ export function readyCount(input: DeviceCounts, spec: VirtualSpec): number { return readyOfKind(input.devices, idlePredicate(input.leases, input.isClaimed), spec).length; } -/** - * The devices a target keeps: for each target, its ready unleased devices of that kind, oldest - * first, up to its count. The one place the pool and the idle shutdown timer agree on which - * devices a target counts. - */ +/** why: the reaper and pool must spare the same devices while queue FIFO delays their grant. */ export function targetedDevices( input: DeviceCounts & { readonly targets: readonly ResolvedTarget[]; readonly learned: readonly LearnedKind[]; + readonly waiting: readonly WaitingDemand[]; }, ): ReadonlySet { const isIdle = idlePredicate(input.leases, input.isClaimed); - return new Set( + const kept = new Set( plannedKinds(mergeTargets(input.targets), input.learned).flatMap((kind) => readyOfKind(input.devices, isIdle, kind.spec) .slice(0, Math.max(kind.configuredCount, kind.learnedCount)) .map((device) => device.id), ), ); + for (const device of input.devices) { + if ( + device.state === "ready" && + isIdle(device) && + input.waiting.some((demand) => !demand.inFlight && serves(device, demand)) + ) { + kept.add(device.id); + } + } + return kept; } /** From c40d90bf02dc214d2af3aac2de5e545f6cbb2c8a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 11:54:20 +0200 Subject: [PATCH 3/5] test: cancellation restores idle cleanup for queued devices (#802) --- src/leasing/create-leasing.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/leasing/create-leasing.test.ts b/src/leasing/create-leasing.test.ts index 76aa369d6..4856ca254 100644 --- a/src/leasing/create-leasing.test.ts +++ b/src/leasing/create-leasing.test.ts @@ -3457,6 +3457,20 @@ describe("createLeasing queued device cleanup", () => { "a device booted for a queued requester must not be reaped", ).toEqual([]); expect(state()).toBe("ready"); + await harness.engine.cancelPending("behind"); + expect( + [...(await harness.engine.core.targetedDevices())], + "cancelling the waiter removes cleanup protection immediately", + ).not.toContain(previous.device.id); + await reaper.run(); + await harness.engine.settle(); + expect(state(), "ordinary idle cleanup resumes after cancellation").toBe("shutdown"); + expect(harness.bus.replay()).toContainEqual( + expect.objectContaining({ + event: "device.shutdown", + payload: { deviceId: previous.device.id, initiator: "cleanup-reaper" }, + }), + ); } finally { reaper.dispose(); await harness.engine.cancelPending("head"); From 5a809a18967d5934d0e287e6b5d7866f94158646 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 11:55:13 +0200 Subject: [PATCH 4/5] test: queue cleanup protection preserves grantability checks (#802) --- src/core/warm-pool/policy.test.ts | 53 +++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 606978a28..9d74d9abd 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -1566,6 +1566,59 @@ describe("warm pool policy", () => { expect([...targetedDevices(input(devices, [target(5)]))]).toEqual(["good"]); }); + it("protects queued demand only for ready idle grantable devices matching its requirement and mode", () => { + const ready = device("ready", "ready"); + const waiting = [classDemand()]; + const cases = [ + ["matching class", view([ready], { waiting }), ["ready"]], + [ + "another matching model", + view([{ ...ready, spec: spec("iPhone 17") }], { waiting }), + ["ready"], + ], + ["no demand", view([ready]), []], + ["in flight", view([ready], { waiting: [classDemand("full", "ios", true)] }), []], + ["claimed", view([ready], { claimed: [ready.id], waiting }), []], + ["leased record", view([ready], { leased: [ready], waiting }), []], + ["shutdown", view([{ ...ready, state: "shutdown" }], { waiting }), []], + [ + "spent fresh", + view([device("ready", "ready", { endedAgo: 1, leaseIdentity: "fresh" })], { waiting }), + [], + ], + [ + "unused fresh", + view([device("ready", "ready", { leaseIdentity: "fresh" })], { waiting }), + ["ready"], + ], + ["mode", view([ready], { waiting: [classDemand("slim")] }), []], + ["platform", view([ready], { waiting: [classDemand("full", "android")] }), []], + ["model", view([ready], { waiting: [modelDemand("iPhone 17")] }), []], + ["class", view([{ ...ready, spec: spec("iPad Pro") }], { waiting }), []], + [ + "OS", + view([{ ...ready, spec: spec("iPhone 15", { osVersion: "25.0" }) }], { waiting }), + [], + ], + [ + "image", + view([ready], { + waiting: [ + { + ...classDemand(), + requirement: { ...classDemand().requirement, imageTag: "google_apis" }, + }, + ], + }), + [], + ], + ] as const; + + for (const [name, policyView, expected] of cases) { + expect([...targetedDevices(policyView)], name).toEqual(expected); + } + }); + it("sums the counts of targets of one spec and keeps a different spec apart", () => { const devices = [ ofKind("a", "ready", { createdAt: 1 }), From ddf2da8098cfa11162b221c6a68cb45b10209b00 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 21 Oct 2026 12:08:34 +0200 Subject: [PATCH 5/5] fix(warm-pool): consolidate audited queue protection (#802) --- src/core/cleanup/types.ts | 2 +- src/core/reaper.ts | 2 +- src/core/warm-pool/policy.test.ts | 30 ++++++++++++++++++++++++++++++ src/core/warm-pool/policy.ts | 10 ++-------- src/leasing/create-leasing.test.ts | 2 +- 5 files changed, 35 insertions(+), 11 deletions(-) diff --git a/src/core/cleanup/types.ts b/src/core/cleanup/types.ts index deac8a036..fd6239086 100644 --- a/src/core/cleanup/types.ts +++ b/src/core/cleanup/types.ts @@ -9,7 +9,7 @@ export interface RegistryView { readonly diskFreeBytes: number; readonly leases: readonly LeaseRecord[]; readonly now: number; - /** Devices a warm target keeps: the idle shutdown timer leaves them alone. */ + /** why: idle shutdown must spare warm targets, learned kinds and devices serving queued demand. */ readonly targeted: ReadonlySet; } diff --git a/src/core/reaper.ts b/src/core/reaper.ts index 84b933a1e..493e322ae 100644 --- a/src/core/reaper.ts +++ b/src/core/reaper.ts @@ -26,7 +26,7 @@ export interface CleanupReaperOptions { readonly logger?: Logger; readonly registry: Registry; readonly rules?: readonly CleanupRule[]; - /** The devices a warm target keeps, read at each run; none when omitted. */ + /** why: read target, learned-kind and live queue protection on every cleanup pass. */ readonly targetedDevices?: () => Promise>; readonly diskPath?: string; readonly tickMs?: number; diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 9d74d9abd..189156f5c 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -204,6 +204,7 @@ function view( }; } +// why: the pure planner needs many capacity, matching and ordering cases through its policy seam. 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) => ({ @@ -1571,6 +1572,35 @@ describe("warm pool policy", () => { const waiting = [classDemand()]; const cases = [ ["matching class", view([ready], { waiting }), ["ready"]], + [ + "matching exact model", + view([ready], { waiting: [modelDemand("iPhone 15")] }), + ["ready"], + ], + ["no devices", view([], { waiting }), []], + [ + "later active waiter", + view([ready], { + waiting: [classDemand("slim"), classDemand("full", "ios", true), ...waiting], + }), + ["ready"], + ], + [ + "union with configured and learned kinds", + view( + [ + ofKind("targeted", "ready"), + device("learned", "ready", { spec: spec("iPad Pro") }), + ready, + ], + { + targets: [target(1)], + learned: [learnedOf(spec("iPad Pro"))], + waiting, + }, + ), + ["targeted", "learned", "ready"], + ], [ "another matching model", view([{ ...ready, spec: spec("iPhone 17") }], { waiting }), diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 0d782a429..decce40de 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -192,12 +192,7 @@ export function evaluate(view: WarmPolicyView): WarmPlan { idle, view.handoffInFlight ? [] - : running.filter( - (device) => - !proposed.has(device.id) && - !sparedDevices.has(device.id) && - !view.waiting.some((demand) => !demand.inFlight && serves(device, demand)), - ), + : running.filter((device) => !proposed.has(device.id) && !sparedDevices.has(device.id)), ); return { proposals: [...shutdowns, ...keeps, ...unneeded, ...wanted.proposals], @@ -569,8 +564,7 @@ function neverLeasedIdle( device.lastLeaseEndedAt !== undefined || kept.has(device.id) || already.has(device.id) || - view.now - readySince(device) <= view.config.shutdownAfterMs || - view.waiting.some((demand) => !demand.inFlight && serves(device, demand)) + view.now - readySince(device) <= view.config.shutdownAfterMs ) { continue; } diff --git a/src/leasing/create-leasing.test.ts b/src/leasing/create-leasing.test.ts index 4856ca254..81cb1f8ed 100644 --- a/src/leasing/create-leasing.test.ts +++ b/src/leasing/create-leasing.test.ts @@ -31,7 +31,7 @@ import { MemoryLogSink, MemoryFilesystem, } from "../ports/index.js"; -import { createLeasing } from "./create-leasing.js"; +import { createLeasing } from "./index.js"; import { NoCapacityError, ProvisionFailedError } from "./lease-acquisition-coordinator.js"; import { LeaseHealthMonitor } from "./lease-health-monitor.js"; import { createTestEngine } from "./testing.js";