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..0da265a8f 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 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/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/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/core/config.test.ts b/src/core/config.test.ts index 145c6899d..ca295a1e3 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,31 @@ 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], + [6, 1], + [8, 2], + [10, 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 () => { 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/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/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/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 { diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index 9890f1e45..22075921f 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: { @@ -85,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); @@ -125,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, @@ -195,6 +215,7 @@ function harness( }, }, claims: { + claim: (id) => claims.claim(id), isClaimed: (id) => claims.isClaimed(id), operationFor: (id) => claims.operationFor(id), tryClaim: (id, operation) => @@ -257,7 +278,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( @@ -268,6 +289,7 @@ function harness( if (claim === undefined) throw new Error("the new device is already claimed"); provisionOptions.reservation.release(); record.deviceId = id; + await finishProvisioning(id); return { claim, device: created }; }, }, @@ -777,6 +799,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(); @@ -851,6 +874,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] }); @@ -962,6 +1022,93 @@ 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; + 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)), + }); + + 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("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, + registers = false, + owner?: string, + ) => { + 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]; + 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(); + 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), 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 () => { 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 04e8644b4..f71a6d183 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; @@ -75,22 +75,24 @@ 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; done: Promise; } /** - * 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; @@ -481,6 +483,7 @@ export class WarmPool { isClaimed: (deviceId) => this.options.claims.isClaimed(deviceId), leases, now: this.options.clock.now(), + onItsWay: this.#onItsWay(devices), resetDevices: new Set(this.#reset), retry: this.#schedule, spared: this.#spared, @@ -489,39 +492,79 @@ 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; } - // 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 = this.#ownerOf(proposal); 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, 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; } /** - * 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. */ - #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) => { @@ -692,4 +735,5 @@ const TRIGGERS = [ "device.deleted", "cleanup.executed", "capacity.changed", + "lease.queued", ] as const; diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index 01ebbea85..af1e63560 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" }, @@ -145,6 +148,7 @@ function view( targets?: readonly ResolvedTarget[]; spared?: readonly ResolvedTarget[]; inFlight?: readonly VirtualSpec[]; + onItsWay?: WarmPolicyView["onItsWay"]; maxConcurrentBoots?: number; blocked?: readonly VirtualSpec[]; refuseProvision?: CapacityRefusalReason; @@ -157,6 +161,7 @@ function view( create: () => options.refuseProvision, }, inFlight: options.inFlight ?? [], + onItsWay: options.onItsWay ?? [], retry: { mayAttempt: (target) => !(options.blocked ?? []).some((held) => sameSpec(held, target)), }, @@ -184,6 +189,135 @@ 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: 2, waiting: three }))).toEqual([ + creation("iPhone 17"), + ]); + 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("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 }))).toEqual([ + creation("iPhone 17"), + ]); + expect( + 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, + }), + ), + ).toEqual([creation("iPhone 17")]); + expect( + evaluate( + view([], { + ...base, + onItsWay: [{ spec: spec("iPhone 15") }, { deviceId: "other", spec: spec("iPhone 17") }], + waiting: two, + }), + ), + ).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")]); + // 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([]); + + // 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", () => { const released = device("lse_15", "shutdown", { endedAgo: 1_000 }); const leased = device("busy", "leased", { spec: spec("iPhone 17") }); @@ -353,34 +487,63 @@ 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( + 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")]); + }); - expect(proposals).toEqual([]); + 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: 2, 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", () => { @@ -797,13 +960,58 @@ 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); }); + 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 }); @@ -943,13 +1151,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()], }), @@ -1031,7 +1240,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 54eaa19c1..644d235c4 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"; @@ -34,7 +35,7 @@ export type WarmProposal = | { readonly action: "provision"; readonly spec: VirtualSpec; - readonly reason: "target"; + readonly reason: "target" | "waiting-request"; readonly target: VirtualSpec; }; @@ -103,8 +104,9 @@ 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. */ readonly retry: { mayAttempt(spec: VirtualSpec, now: number): boolean }; /** What the capacity strategy refuses besides the running slots `capacity` already totals. */ @@ -164,10 +166,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, @@ -231,11 +234,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); } /** @@ -266,12 +269,29 @@ function overBudget( return proposals; } +interface QueuePass { + readonly proposals: WarmProposal[]; + readonly started: number; + 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; +} + /** - * 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,52 +299,117 @@ function boots( bootable: readonly VirtualDevice[], room: Slots, held: Slots, -): DeviceProposal[] { - const proposals: DeviceProposal[] = []; - 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 }); +): QueuePass { + 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 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); + const matched = new Set(); + let atHead = true; + for (const demand of view.waiting) { + const head: boolean = atHead; + atHead = false; + if (demand.inFlight) { + holdSlot(room, demand.platform); + continue; + } + const ready = running.find((candidate) => !matched.has(candidate) && serves(candidate, demand)); + const match = ready ?? onItsWayFor(view, matched, demand); + if (match !== undefined) { + matched.add(match); + atHead = head && ready !== undefined; + } else if (!bootForWaiter(state, demand)) { + createForWaiter(state, demand, head); + holdSlot(room, 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; } + bootRecentlyReleased(state, held); + return { proposals: state.proposals, started: state.started, stuck: state.stuck }; +} + +function onItsWayFor( + view: WarmPolicyView, + matched: ReadonlySet, + demand: WaitingDemand, +): WarmPolicyView["onItsWay"][number] | undefined { + return view.onItsWay.find((entry) => !matched.has(entry) && servesSpec(entry.spec, demand)); +} - const recent = bootable +function bootRecentlyReleased(state: QueueState, held: Slots): void { + const { room, view } = state; + const recent = state.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, ) .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) && view.admit.boot(device) === undefined) { + claim(room, device); + state.started += 1; + state.proposals.push({ action: "boot", deviceId: device.id, reason: "recently-released" }); + } } - return proposals; +} + +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) && + // 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; + 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. */ @@ -453,15 +538,16 @@ 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; } /** - * 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. */ @@ -469,25 +555,33 @@ 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, + stuck: queued.stuck, 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; @@ -509,9 +603,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, @@ -519,10 +613,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--) { 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" }], }, }, 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 diff --git a/src/leasing/lease-acquisition-coordinator.test.ts b/src/leasing/lease-acquisition-coordinator.test.ts index 46d5f17ef..9393410a6 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,48 @@ 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 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 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, ...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, + }).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 () => { const harness = await createHarness({ maxDevices: 2, maxRunning: 2 }); const held = await Promise.all([ @@ -3398,6 +3441,7 @@ describe("LeaseAcquisitionCoordinator waiting demand", () => { platform: "ios", target: { kind: "model", model: "iPhone 16" }, }, + spec: request, }, ]); diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index ddf17f77f..378b23b9f 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, }, ], ); @@ -898,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");