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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
2 changes: 1 addition & 1 deletion src/core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/core/cleanup/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>;
}

Expand Down
2 changes: 1 addition & 1 deletion src/core/reaper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReadonlySet<string>>;
readonly diskPath?: string;
readonly tickMs?: number;
Expand Down
5 changes: 4 additions & 1 deletion src/core/warm-pool/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
8 changes: 2 additions & 6 deletions src/core/warm-pool/converger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReadonlySet<string>> {
if (!this.options.config.enabled) return new Set();
if (!this.#hasResolved) await this.#resolveTargets();
Expand All @@ -301,6 +296,7 @@ export class WarmPool {
leases,
learned: this.#learnedKinds(),
targets: [...this.#resolved, ...this.#spared],
waiting: this.options.acquisition.waitingDemand(),
});
}

Expand Down
85 changes: 85 additions & 0 deletions src/core/warm-pool/policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => ({
Expand Down Expand Up @@ -1505,6 +1506,7 @@ describe("warm pool policy", () => {
leases: [leaseOn(leasedReady)],
learned: [],
targets: [target(1)],
waiting: [],
});

expect([...named]).toEqual([]);
Expand All @@ -1517,6 +1519,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", () => {
Expand Down Expand Up @@ -1564,6 +1567,88 @@ 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"]],
[
"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 }),
["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 }),
Expand Down
29 changes: 15 additions & 14 deletions src/core/warm-pool/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -518,25 +513,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<string> {
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;
}

/**
Expand All @@ -562,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;
}
Expand Down
110 changes: 109 additions & 1 deletion src/leasing/create-leasing.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import {
buildCapacityFigures,
CleanupReaper,
type ModelPreferences,
BootTimeoutError,
type ComponentInstaller,
Expand Down Expand Up @@ -28,8 +29,9 @@ import {
JsonLinesLogger,
type Logger,
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";
Expand Down Expand Up @@ -3373,6 +3375,112 @@ 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");
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");
await harness.engine.cancelPending("behind");
await Promise.all(pending);
harness.engine.dispose();
}
});
});

describe("createLeasing warm targets", () => {
const target = {
count: 2,
Expand Down
Loading