diff --git a/docs/CLI.md b/docs/CLI.md index a9ae268cb..b8f18c63b 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -2408,7 +2408,7 @@ never acts on it. Emergency reset: force-release all leases, kill emulator/simulator processes simlock started, clear the queue. With `--delete-devices`, also destroy every -registry-managed device. Never touches devices outside the registry. A lease on +registry-managed device. It also clears what the warm pool has learned from past leases, so no device is booted back unasked afterwards. Never touches devices outside the registry. A lease on an enrolled physical device ends like any other, and its apps are uninstalled; the device stays enrolled, and `--delete-devices` never deletes one. It stays a per-machine command: a gateway answers `UNSUPPORTED_IN_GATEWAY_MODE` (exit diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 0da265a8f..056ef01ef 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -14,9 +14,9 @@ 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 ignore it; a device that never served a lease and that no target 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, 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.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.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` | | `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 | @@ -26,7 +26,7 @@ edit yourself keeps the mode you give it until the next `config set`; run | `warmPool.quarantine.maxRetryBackoffMs` | Cap on the quarantine retry backoff. | `5 minutes` | | `lease.defaultTtlMs` | TTL applied to a lease whose `lease.request` carried no `ttlMs` — **that request only**. It is *not* the renew fallback: a renew given no explicit TTL re-applies the lease's own stored width, so a lease granted for longer keeps it. A lease not renewed before its deadline expires and its device is reclaimed. | `15 minutes` | | `lease.maxTtlMs` | Largest TTL a request or a renew may ask for. A larger `ttlMs` is rejected with `BAD_REQUEST` rather than silently clamped, so a caller is never left believing it has more time than it does. | `4 hours` | -| `lease.identity.ios` | Whether iOS leases reuse simulators. `reusable` erases a released simulator, shuts it down and keeps it for a later lease. `fresh` creates a simulator for each lease and deletes it when the lease ends — by release, by expiry, or because the device was lost — so no simulator serves two leases. If the delete fails, the simulator is quarantined, never leased again, and the delete is retried. **Boot cost:** under `fresh` no simulator stays warm after a release, so every iOS lease pays a full boot (about 30 seconds on an Apple silicon Mac), unless a `warmPool.targets` entry has already created and booted a device of that kind, which the lease is then granted at once. Under `reusable` a released simulator is booted back when the running limit has room (see `warmPool.enabled`), so a lease that arrives afterwards often finds it ready; one that arrives while it boots waits for it and is granted it when it is ready (not with `--no-wait`, which plans as if the device were not there and so gets what any lease gets at that moment: a device of its own, an idle device made room for, or `NO_CAPACITY`); one that arrives first, or when there is no room, pays the boot. Each device keeps the setting it was created with, even if you change this value later. | `reusable` | +| `lease.identity.ios` | Whether iOS leases reuse simulators. `reusable` erases a released simulator, shuts it down and keeps it for a later lease. `fresh` creates a simulator for each lease and deletes it when the lease ends — by release, by expiry, or because the device was lost — so no simulator serves two leases. If the delete fails, the simulator is quarantined, never leased again, and the delete is retried. **Boot cost:** under `fresh` no simulator stays warm after a release, so every iOS lease pays a full boot (about 30 seconds on an Apple silicon Mac), unless a `warmPool.targets` entry, or a kind the pool learned from earlier leases, has already created and booted a device of that kind, which the lease is then granted at once. Under `reusable` a released simulator is booted back and kept ready when the running limit has room (see `warmPool.enabled`), so a lease that arrives afterwards often finds it ready; one that arrives while it boots waits for it and is granted it when it is ready (not with `--no-wait`, which plans as if the device were not there and so gets what any lease gets at that moment: a device of its own, an idle device made room for, or `NO_CAPACITY`); one that arrives first, or when there is no room, pays the boot. Each device keeps the setting it was created with, even if you change this value later. | `reusable` | | `lease.identity.android` | The same setting for Android emulators. `fresh` is accepted, but it is designed for iOS. | `reusable` | | `lease.requestRetentionMs` | How long a settled lease request stays stored, counted from when it settled. A client that repeats a request with the same `idempotencyKey` inside this window gets the stored result back; after it, the record is removed and the same key starts a new request. | `10 minutes` | | `lease.maxRequestRecords` | The most lease-request records Simlock keeps. When a new request would go over it, the oldest settled record is removed. A request that is still open is never removed. | `10000` | diff --git a/docs/EVENTS.md b/docs/EVENTS.md index d67affb22..b1321f8c1 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -46,7 +46,7 @@ the gateway's own lease index before any worker is ever contacted. `lease-id-tak | `device.quarantine-recovered` | device id, attempts, reclaim strategy (erase/snapshot/wipe/uninstall), `missingApps` for a physical device, the device's `platform` (`ios` or `android`) | a quarantined device's retried purge succeeded; it returned to `ready`/`shutdown` and rejoined the warm pool. Never emitted for a `fresh` device: its retry is a delete, and a successful one emits `device.deleted` | QuarantineCoordinator | implemented | | `device.quarantine-abandoned` | device id, attempts, the device's `platform` (`ios` or `android`) | a quarantined device exhausted its configured retry budget (`warmPool.quarantine.maxRetries`) — purge retries, or delete retries for a `fresh` device — and was destroyed, or, for a physical device, unenrolled: Simlock never destroys a physical device | QuarantineCoordinator | implemented | | `device.quarantine-stranded` | device id, attempts, stable error summary, the device's `platform` (`ios` or `android`) | a quarantined device exhausted its retry budget (purge or delete retries) and the destroy that should have retired it also failed; it stays `quarantined` with no further retry until an operator intervenes | QuarantineCoordinator | implemented | -| `device.shutdown` | device id, initiator (rule/command; `warm-pool` when the warm pool shut an idle device down, over the running limit, with `warmPool.enabled: false`, to keep `warmPool.reserveRunning` running slots free, or because a ready device that never served a lease and that no `warmPool.targets` entry keeps has been idle past `idle.shutdownAfterMs`) | device stopped, still on disk | Registry; the reclaim coordinator for interrupted reclaim recovery | implemented | +| `device.shutdown` | device id, initiator (rule/command; `warm-pool` when the warm pool shut an idle device down, over the running limit, with `warmPool.enabled: false`, to keep `warmPool.reserveRunning` running slots free, or because a ready device that never served a lease and that no `warmPool.targets` entry and no kind the pool learned from a lease keeps has been idle past `idle.shutdownAfterMs`, or to displace it: an older leased kind's idle device shut down so a newer kind can boot into its running slot) | device stopped, still on disk | Registry; the reclaim coordinator for interrupted reclaim recovery | implemented | | `device.deleted` | device id, initiator (`lease-end` when a `fresh` device's lease ended and its delete completed, including a delete retried from quarantine; `doctor` when `doctor --fix`, or a daemon start that found a leased device gone from its platform, marked it missing; `operator` when `device remove` unenrolled a physical device; `quarantine` when a physical device's retries ran out and it was unenrolled; `lease-engine` when a device that failed to boot for a lease was destroyed in cleanup; `cleanup-reaper` when the cleanup reaper destroyed a device; `nuke` when `nuke` destroyed it), physical (`true` for an enrolled physical device, `false` for a simulator or emulator) | device removed from the registry, and from disk for a simulator or emulator; a physical device is only forgotten, nothing on it changes | Registry | implemented | | `device.enrolled` | device id, platform, driver device id (the canonical ID), model, OS version, class (phone/tablet), app count, reenrolled | `device add` wrote a physical device `ready`; `reenrolled` is `true` when the device already had a record, which kept its device id and took a fresh read of its model, OS version, class and apps | Registry | implemented | | `device.absence-detected` | device id, previous state (ready/leased/reclaiming), absent reason (locked/untrusted/not-present) | an enrolled physical device became `absent`: it was not present for the grace period (`health.stableObservations` reads in a row, `health.probeIntervalMs` apart), or its reclaim failed while it was not present. For a leased device `lease.released` (device-lost) comes first | Registry; ReclaimCoordinator | implemented | diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 03ef76e6d..dc0efe45f 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -27,7 +27,7 @@ worker daemon ── uplink (WebSocket to /v1/uplink, worker dials) ──┘ - A gateway is a second set of handlers for the same contract. Every frontend works against either mode unchanged. - State lives on the worker (`state.db`, its registry tables written only by core's - `Registry`). A gateway keeps only its tokens, its instance id and its drained-worker set on + `Registry`; the warm pool's learned kinds in its own tables). A gateway keeps only its tokens, its instance id and its drained-worker set on disk (`state.db`); everything else is rebuilt from the workers that reconnect. ## Modules diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index eb3f8289e..c5e7a8f72 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -84,7 +84,7 @@ worker is ever contacted. `lease-id-taken` (ADR 0020; widens a published vocabul | `device.quarantine-recovered` | device id, attempts, reclaim strategy (erase/snapshot/wipe/uninstall), `missingApps` for a physical device (additive), the device's `platform` (`ios` or `android`) | a quarantined device's retried purge succeeded; it returned to `ready`/`shutdown` and rejoined the warm pool. Never emitted for a spent `fresh` device (`mayBeGranted` false): its retry is a delete, and a successful one emits `device.deleted` with initiator `lease-end` | QuarantineCoordinator | implemented | | `device.quarantine-abandoned` | device id, attempts, the device's `platform` (`ios` or `android`) | a quarantined device exhausted its configured retry budget (`warmPool.quarantine.maxRetries`) — purge retries, or delete retries for a spent `fresh` device — and was destroyed, or, for a physical device, unenrolled: Simlock never destroys one (safety rule 2, ADR 0022 §4) | QuarantineCoordinator | implemented | | `device.quarantine-stranded` | device id, attempts, stable error summary, the device's `platform` (`ios` or `android`) | a quarantined device exhausted its retry budget (purge or delete retries) and the destroy that should have retired it also failed; it stays `quarantined` with no further retry until an operator intervenes | QuarantineCoordinator | implemented | -| `device.shutdown` | device id, initiator (rule/command; `warm-pool` when the warm pool shut an idle device down, over the running limit, with `warmPool.enabled: false`, to keep `warmPool.reserveRunning` running slots free, or because a ready device that never served a lease and that no `warmPool.targets` entry keeps has been idle past `idle.shutdownAfterMs`) | device stopped, still on disk | Registry; ReclaimCoordinator for interrupted reclaim recovery | implemented | +| `device.shutdown` | device id, initiator (rule/command; `warm-pool` when the warm pool shut an idle device down, over the running limit, with `warmPool.enabled: false`, to keep `warmPool.reserveRunning` running slots free, or because a ready device that never served a lease and that no `warmPool.targets` entry and no kind the pool learned from a lease keeps has been idle past `idle.shutdownAfterMs`, or to displace it: an older leased kind's idle device shut down so a newer kind can boot into its running slot) | device stopped, still on disk | Registry; ReclaimCoordinator for interrupted reclaim recovery | implemented | | `device.deleted` | device id, initiator (`lease-end` when a `fresh` device's lease ended and its delete completed — from ReclaimCoordinator, at startup convergence, or retried from quarantine; #75. `doctor` when `doctor --fix` marked a missing device, or startup's lease reconciler found a leased device absent from a platform it could read and ended the lease in the same write, ADR 0019 §2. `operator` when `device remove` unenrolled a physical device, ADR 0022 §2. `quarantine` when a physical device's quarantine retries ran out and it was unenrolled, ADR 0022 §4; `lease-engine` when a device that failed to boot for a lease was destroyed in cleanup; `cleanup-reaper` when the cleanup reaper destroyed a device; `nuke` when `nuke` destroyed it), physical (the record's own flag: `true` for an enrolled physical device, `false` for a simulator or emulator; additive, events rule 6) | device removed from the registry, and from disk for a virtual device; a physical device is only forgotten and nothing is sent to it | Registry | implemented | | `device.enrolled` | device id, platform, driver device id (the canonical ID), model, OS version, class (phone/tablet), app count, reenrolled | an admin's `device add` wrote a physical device `ready` (ADR 0022 §2). `reenrolled` is `true` when the device already had a `ready`, `quarantined` or `absent` record, which kept its registry ID and took a fresh read of model, OS version, class and apps | Registry | implemented | | `device.absence-detected` | device id, previous state (ready/leased/reclaiming), absent reason (locked/untrusted/not-present) | an enrolled physical device became `absent` (ADR 0022 §2, §7, §8): the `PhysicalDeviceWatcher` read it not present `health.stableObservations` times in a row (a leased device's lease ends first, `lease.released` device-lost, in the same write), or `ReclaimCoordinator` found it not present after a failed reclaim (`reclaiming → absent`, no `device.purge-failed`, no `device.quarantined`). Emitted after the commit | Registry (the watcher's writes, the reclaim's failure path) | implemented | diff --git a/docs/internal/flows/device-selection.md b/docs/internal/flows/device-selection.md index 68cdb2e4c..95482f9ae 100644 --- a/docs/internal/flows/device-selection.md +++ b/docs/internal/flows/device-selection.md @@ -24,7 +24,7 @@ How one lease request becomes one concrete device, virtual or physical. | iOS device types and runtimes | `simctl list -j devicetypes runtimes` | Each resolve, catalog | | Existing devices | registry snapshot | Each plan | | Enrolled physical devices | registry snapshot; presence from `Driver.listPresentPhysical` | Each physical plan; presence before each grant | -| Warm targets | `warmPool.targets` (`core/warm-pool/config.ts`) | Every warm-pool pass, downloads off | +| Warm targets | `warmPool.targets` (`core/warm-pool/config.ts`), and the kinds the pool learned from leases (`core/warm-pool/learned.ts`, `state.db`) | Every warm-pool pass, downloads off | Never read: the sdkmanager catalog. A preference list is merged in `daemon/main.ts` `modelPreferenceWiring`; nothing else builds it. @@ -50,7 +50,7 @@ In `LeaseAcquisitionCoordinator` (`leasing/lease-acquisition-coordinator.ts`), n 9. Requirement: class or model target, OS (`range`, `exact`, or `installed` for a class with no OS), image tag. An exact model gets `exactRequirement(spec)`. -Warm targets go through the same steps (`resolve`) with `allowDownload: false`; a target names no class. +Warm targets go through the same steps (`resolve`) with `allowDownload: false`; a target names no class. A learned kind is already a resolved spec and is kept ready like a target. ## Android `resolveSpec` @@ -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 under an ownerless claim (for a target, a released device or a request queued behind) → wait. +2. Unless `noWait`: one the warm pool is booting or creating under an ownerless claim (for a target or learned kind, 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/docs/internal/flows/startup.md b/docs/internal/flows/startup.md index 8b2da1dfa..9a94fb8e9 100644 --- a/docs/internal/flows/startup.md +++ b/docs/internal/flows/startup.md @@ -71,7 +71,8 @@ the data directory (`sweepWriteLeftovers`). `device.shutdown` (initiator `startup-interrupted-reclaim`). 3. Spent deletes: `shutdown` devices that may not be granted again are deleted inline. A failed delete is logged; the device stays `shutdown`. - 4. Warm pool and capacity observer start. + 4. Warm pool and capacity observer start. The pool closes the lease rows of its learned-kind + record whose lease the registry no longer holds, and its first pass boots the recorded kinds. 22. `queue.changed` with the first depth. Converge done → health `running`. Arm (skipped when a stop already ran): diff --git a/e2e/capacity-cleanup-nuke.test.ts b/e2e/capacity-cleanup-nuke.test.ts index 64d2d279e..a19f1d25c 100644 --- a/e2e/capacity-cleanup-nuke.test.ts +++ b/e2e/capacity-cleanup-nuke.test.ts @@ -71,29 +71,6 @@ async function releaseAndForget( return grant.device.driverDeviceId; } -/** - * Forces an immediate, synchronous reaper evaluation (rather than waiting on the slow - * 60s periodic tick or hoping an unrelated `lease.released` retriggers it) by polling - * `simlock cleanup` itself until the target reaches `state` -- this is what lets an - * idle-threshold test converge in milliseconds without a fixed sleep: each poll tick - * both re-checks real elapsed time *and* forces the daemon to act on it. - */ -async function waitForCleanupToReach( - env: Awaited>, - driverDeviceId: string, - state: string, - timeout = 10_000, -): Promise { - await waitFor( - async () => { - await env.cli(["cleanup"]); - const rows = await deviceRows(env); - return rows.some((row) => row.driverDeviceId === driverDeviceId && row.state === state); - }, - { timeout, interval: 50, label: `cleanup demotes ${driverDeviceId} to ${state}` }, - ); -} - describe("capacity, warm pool, cleanup, and nuke", () => { it("distinguishes the managed-device limit from the running limit, and counts reclaiming as running, never warm", async () => { const env = await withDaemon({ @@ -157,7 +134,7 @@ describe("capacity, warm pool, cleanup, and nuke", () => { await waitForLeaseCount(env, 0); }); - it("demotes an idle device, previews cleanup without executing on --dry-run, and nuke touches only registry devices", async () => { + it("keeps an idle device of a leased kind out of cleanup and its --dry-run preview, and nuke touches only registry devices", async () => { const env = await withDaemon({ configOverrides: { // Tight on purpose: by the nuke phase this forces a real queued waiter @@ -181,9 +158,16 @@ describe("capacity, warm pool, cleanup, and nuke", () => { await holderX.waitForExit(15_000).catch(() => undefined); await waitForDeviceState(env, grantX.device.driverDeviceId, "ready"); - await waitForCleanupToReach(env, grantX.device.driverDeviceId, "shutdown"); + // why: the pool learned the kind from the lease and keeps its device ready past idle.shutdownAfterMs. + expect((await env.cli(["cleanup"])).code).toBe(0); + await new Promise((resolve) => setTimeout(resolve, 500)); + expect((await env.cli(["cleanup"])).code).toBe(0); + expect( + (await deviceRows(env)).find((row) => row.driverDeviceId === grantX.device.driverDeviceId) + ?.state, + ).toBe("ready"); - // cleanup --dry-run must report proposals without acting on them. + // why: a dry run lists what a real run would do, and the device the pool keeps is not in it. That it executes nothing is the reaper unit test's: no device here is one a rule acts on. await env.driverScript.merge({ ios: { latencyMs: { reclaim: 5_000 } } }); const dryRunDeviceId = await releaseAndForget(env, "dryrun-z"); await waitForDeviceState(env, dryRunDeviceId, "ready"); @@ -193,26 +177,12 @@ describe("capacity, warm pool, cleanup, and nuke", () => { ); expect(readyDevice, "expected a ready (warm) device for the dry-run preview").toBeDefined(); - await waitFor( - async () => { - const preview = await env.cli(["cleanup", "--dry-run"]); - const proposals = preview.json as { rule: string; target: string }[]; - return proposals.some((proposal) => proposal.target === readyDevice?.id); - }, - { - timeout: 10_000, - interval: 50, - label: "dry-run eventually proposes shutting the idle device down", - }, - ); - - await env.driverLog.clear(); - const dryRun = await env.cli(["cleanup", "--dry-run"]); - expect(dryRun.code).toBe(0); - const dryRunCalls = await env.driverLog.calls(); + const preview = await env.cli(["cleanup", "--dry-run"]); expect( - dryRunCalls.filter((call) => call.operation === "shutdown" || call.operation === "destroy"), - "--dry-run must never call a destructive/state-changing driver verb", + (preview.json as { target: string }[]).filter( + (proposal) => proposal.target === readyDevice?.id, + ), + "the kept device of a leased kind is not proposed", ).toEqual([]); // nuke: force-releases every lease, clears the queue, destroys registry devices, diff --git a/e2e/console/attention.spec.ts b/e2e/console/attention.spec.ts index 6aa415713..559178763 100644 --- a/e2e/console/attention.spec.ts +++ b/e2e/console/attention.spec.ts @@ -36,11 +36,15 @@ const FAILING_RECLAIM = { }; /** - * A worker whose stall threshold is one second: a device left `provisioning` with nothing - * working on it is stalled a second after it entered that state. + * why: a worker whose stall threshold is one second: a device left `provisioning` with nothing + * working on it is stalled a second after it entered that state. The pool is off: a kind it + * learned from the first lease would be refilled with a ready device the stranded lease takes. */ const STALLING = { - config: { stalledTransition: { minimumThresholdMs: 1_000, thresholdMultiplier: 1 } }, + config: { + stalledTransition: { minimumThresholdMs: 1_000, thresholdMultiplier: 1 }, + warmPool: { enabled: false }, + }, driverScript: { ios: IOS }, } as const; diff --git a/e2e/doctor-drift.test.ts b/e2e/doctor-drift.test.ts index 414f9f08c..a9b105a94 100644 --- a/e2e/doctor-drift.test.ts +++ b/e2e/doctor-drift.test.ts @@ -178,22 +178,23 @@ describe("doctor and drift", () => { const fixed = await env.cli(["doctor", "--fix"]); expect(fixed.code).toBe(0); - // Registry-only destruction (safety.md #1/#3): --fix must never call a destructive - // or state-changing driver verb. Every correction above is pure registry bookkeeping. - // The one call that is not --fix's is the warm pool booting back the device --fix just - // marked shut down, which was released a moment ago and has room: a `makeReady`, and only - // for that device. + // why: registry-only destruction (safety.md #1/#3): --fix must never call a destructive + // or state-changing driver verb. Every correction above is pure registry bookkeeping. The calls that are not --fix's are the warm pool's: booting back the device --fix just + // marked shut down, and creating and booting one device to refill the leased kind that lost + // device C from the registry. const calls = await env.driverLog.calls(); - const destructiveOps = new Set(["destroy", "shutdown", "reclaim", "provision"]); + const destructiveOps = new Set(["destroy", "shutdown", "reclaim"]); expect( calls.filter((call) => destructiveOps.has(call.operation)), `--fix must be registry-only; saw: ${JSON.stringify(calls.map((call) => call.operation))}`, ).toEqual([]); for (const call of calls.filter((entry) => entry.operation === "makeReady")) { + const booted = JSON.stringify(call.arguments); expect( - JSON.stringify(call.arguments), - "only the corrected device may be booted by the warm pool", - ).toContain(deviceA.device.driverDeviceId); + booted.includes(deviceA.device.driverDeviceId) || + ![...distinctUdids].some((udid) => booted.includes(udid)), + "the warm pool boots only the corrected device or a device it created", + ).toBe(true); } const rowsAfterFix = await deviceRows(env); diff --git a/e2e/ram-budget-by-mode.test.ts b/e2e/ram-budget-by-mode.test.ts index 686e64a75..d200eb930 100644 --- a/e2e/ram-budget-by-mode.test.ts +++ b/e2e/ram-budget-by-mode.test.ts @@ -69,7 +69,7 @@ describe("RAM budget by device mode", () => { it("counts each device by its mode once booted, needs full-size room for every new one, and goes over after a restart with larger sizes", async () => { const env = await withDaemon({ // Fresh devices are deleted on release, so each pass below starts from an empty budget. - configOverrides: { lease: { identity: { ios: "fresh" } } }, + configOverrides: { lease: { identity: { ios: "fresh" } }, warmPool: { enabled: false } }, driverScript: { ios: { availableOsVersions: [UNSLIMMABLE, SLIMMABLE], diff --git a/e2e/slow-warm-pool.test.ts b/e2e/slow-warm-pool.test.ts index f10ab75e6..bc88c3693 100644 --- a/e2e/slow-warm-pool.test.ts +++ b/e2e/slow-warm-pool.test.ts @@ -199,11 +199,14 @@ interface Lane { } /** - * A real-driver daemon whose pool targets one device of the newest runtime of each platform; with + * why: a real-driver daemon whose pool targets one device of the newest runtime of each platform; with * `enabled: false` the config is rewritten and the daemon restarted with the pool off, so no - * device exists until a lease asks. + * device exists until a lease asks. With `noTargets` the pool has none to fill: only the kinds it + * learns from leases. */ -async function warmDaemon(options: { readonly enabled?: boolean } = {}): Promise { +async function warmDaemon( + options: { readonly enabled?: boolean; readonly noTargets?: boolean } = {}, +): Promise { await sweepStaleDeviceSets(); const env = await withDaemon({ driver: "real" }); const adbServerPort = env.adbServerPort; @@ -222,7 +225,7 @@ async function warmDaemon(options: { readonly enabled?: boolean } = {}): Promise }; await writeWarmPool(env, { maxConcurrentBoots: 2, - targets: [targets.ios, targets.android], + targets: options.noTargets === true ? [] : [targets.ios, targets.android], ...(options.enabled === undefined ? {} : { enabled: options.enabled }), }); return { adbServerPort, deviceSet: iosDeviceSet(env.home), env, targets }; @@ -307,6 +310,40 @@ async function holdsState( }); } +async function untilSettled(env: TestEnv, driverDeviceId: string): Promise { + let last: Row[] = []; + await waitFor( + async () => { + last = await devices(env); + const row = last.find((entry) => entry.driverDeviceId === driverDeviceId); + return row !== undefined && (row.state === "ready" || row.state === "shutdown"); + }, + { + interval: 1000, + label: () => + `${driverDeviceId} is reclaimed; last saw ${JSON.stringify(last.map((r) => [r.driverDeviceId, r.state]))}`, + timeout: READY_TIMEOUT, + }, + ); +} + +async function untilEachPlatformHasReady(env: TestEnv): Promise { + let last: Row[] = []; + await waitFor( + async () => { + last = await devices(env); + return (["ios", "android"] as const).every((platform) => + last.some((row) => row.spec.platform === platform && row.state === "ready"), + ); + }, + { + interval: 1000, + label: () => `a ready device on each platform; last saw ${JSON.stringify(last)}`, + timeout: READY_TIMEOUT, + }, + ); +} + /** Per platform, exactly one device, and it is ready. */ function expectOneReadyPerPlatform(rows: readonly Row[]): void { for (const platform of ["ios", "android"] as const) { @@ -543,7 +580,7 @@ describe( ); it( - "grants the first lease of each targeted model warm with no booting progress, and after release each device is ready again", + "grants the first lease of each targeted model warm with no booting progress, and after release each platform still has a ready device", { timeout: WARM_ROUND_TIMEOUT }, async (context) => { const missing = await missingPlatform(); @@ -571,10 +608,13 @@ describe( await expectGrantedWarm(env, granted, readyEvents); for (const grant of granted) await release(env, grant); - // iOS is shut down, erased and booted again by the pool; Android restores its snapshot. + // why: the pool booted a second device of each kind while the first was leased (a target counts + // ready devices only), so once the released one is reclaimed the kind already has its + // ready device: the pool owes the released one nothing, and it may stay down. for (const grant of granted) { - await untilState(env, grant.device.driverDeviceId, "ready"); + await untilSettled(env, grant.device.driverDeviceId); } + await untilEachPlatformHasReady(env); // A failed snapshot load falls back to a wipe and the pool boots the device back to ready, // so the state alone cannot tell the two apart: the reclaim's own strategy does. const android = granted.find((grant) => grant.device.spec.platform === "android"); @@ -701,5 +741,65 @@ describe( } }, ); + + it( + "with no target, a released simulator and a released emulator are ready again before the next lease, are shut down with the pool off, and are booted again from the record with it on", + { timeout: COLD_TEST_TIMEOUT }, + async (context) => { + const missing = await missingPlatform(); + if (missing !== undefined) context.skip(missing); + let lane: Lane | undefined; + try { + lane = await step("start the daemon with no target", DAEMON_START_BUDGET, () => + warmDaemon({ noTargets: true }), + ); + const { env, targets } = lane; + const first = { + android: await step("lease the emulator", LEASE_TIMEOUT + MINUTE, () => + lease(env, targets.android, "learn-android"), + ), + ios: await step("lease the simulator", LEASE_TIMEOUT + MINUTE, () => + lease(env, targets.ios, "learn-ios"), + ), + }; + await step("release the simulator", RELEASE_TIMEOUT + MINUTE, () => + release(env, first.ios.grant), + ); + await step("release the emulator", RELEASE_TIMEOUT + MINUTE, () => + release(env, first.android.grant), + ); + const iosUdid = first.ios.grant.device.driverDeviceId; + const androidId = first.android.grant.device.driverDeviceId; + await step("both devices are ready again", 2 * READY_TIMEOUT, async () => { + await untilState(env, iosUdid, "ready"); + await untilState(env, androidId, "ready"); + }); + await step("both stay ready", HOLD + 2 * MINUTE, async () => { + await holdsState(env, iosUdid, "ready", HOLD); + await holdsState(env, androidId, "ready", HOLD); + }); + + await step("the pool off shuts both down", 12 * MINUTE, async () => { + await writeWarmPool(env, { enabled: false }); + await untilState(env, iosUdid, "shutdown", 5 * MINUTE); + await untilState(env, androidId, "shutdown", 5 * MINUTE); + }); + await step( + "the pool on boots both from the record, before any lease", + 2 * READY_TIMEOUT, + async () => { + await writeWarmPool(env, { enabled: true }); + await untilState(env, iosUdid, "ready"); + await untilState(env, androidId, "ready"); + }, + ); + } catch (error: unknown) { + if (lane !== undefined) await diagnose(lane.env); + throw error; + } finally { + if (lane !== undefined) await nuke(lane.env); + } + }, + ); }, ); diff --git a/e2e/warm-pool-learned.test.ts b/e2e/warm-pool-learned.test.ts new file mode 100644 index 000000000..42b3873d4 --- /dev/null +++ b/e2e/warm-pool-learned.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it } from "vitest"; + +import { events, waitFor, withDaemon, type TestEnv } from "./helpers/index.js"; + +const IOS = { + availableOsVersions: ["18.4"], + knownModels: ["iPhone 16"], + reclaimResult: "shutdown", +} as const; + +interface Device { + readonly id: string; + readonly state: string; +} + +interface Grant { + readonly lease: { readonly id: string }; + readonly device: Device; +} + +async function devices(env: TestEnv): Promise { + const listed = await env.cli(["list", "--devices"]); + expect(listed.code, listed.stderr).toBe(0); + return listed.json as Device[]; +} + +async function lease(env: TestEnv, agent: string): Promise { + const result = await env.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--agent-id", + agent, + "--detach", + ]); + expect(result.code, result.stderr).toBe(0); + return result.json as Grant; +} + +async function grants(env: TestEnv): Promise { + return (await events(env.env)).filter((entry) => entry.event === "lease.granted") as never; +} + +describe("a worker with no targets keeps the kinds it has leased", () => { + it("creates nothing while the first lease is held, boots the released device back and keeps it ready past idle.shutdownAfterMs, and grants the next lease of its kind warm", async () => { + const env = await withDaemon({ + configOverrides: { + idle: { shutdownAfterMs: 500 }, + limits: { maxRunning: 2, ios: { maxDevices: 2, maxRunning: 2 } }, + }, + driverScript: { ios: IOS }, + }); + const first = await lease(env, "a1"); + await new Promise((resolve) => setTimeout(resolve, 1_500)); + expect(await devices(env)).toHaveLength(1); + + expect((await env.cli(["release", first.lease.id])).code).toBe(0); + await waitFor(async () => (await devices(env)).every((device) => device.state === "ready"), { + label: "the released device is booted back", + }); + await new Promise((resolve) => setTimeout(resolve, 1_500)); + expect((await env.cli(["cleanup"])).code).toBe(0); + await new Promise((resolve) => setTimeout(resolve, 500)); + + expect((await devices(env)).map((device) => device.state)).toEqual(["ready"]); + const second = await lease(env, "a2"); + expect(second.device.id).toBe(first.device.id); + expect((await grants(env)).map((entry) => entry.payload.source)).toEqual([ + "provisioned", + "warm", + ]); + }); + it("shuts the device down when the pool is off and boots it again from the record when the pool is back on, before any lease", async () => { + const env = await withDaemon({ + configOverrides: { limits: { maxRunning: 2, ios: { maxDevices: 2, maxRunning: 2 } } }, + driverScript: { ios: IOS }, + }); + const first = await lease(env, "a1"); + expect((await env.cli(["release", first.lease.id])).code).toBe(0); + await waitFor(async () => (await devices(env)).every((device) => device.state === "ready"), { + label: "the released device is booted back", + }); + + await env.withConfig({ warmPool: { enabled: false } }, async () => { + await waitFor( + async () => (await devices(env)).every((device) => device.state === "shutdown"), + { label: "the pool being off shuts the device down" }, + ); + }); + + await waitFor( + async () => (await devices(env)).map((device) => device.state).join() === "ready", + { + label: "the record boots the device again before any lease", + }, + ); + expect((await grants(env)).map((entry) => entry.payload.source)).toEqual(["provisioned"]); + }); + + it("boots nothing after simlock nuke --yes and a restart", async () => { + const env = await withDaemon({ + configOverrides: { limits: { maxRunning: 2, ios: { maxDevices: 2, maxRunning: 2 } } }, + driverScript: { ios: IOS }, + }); + const first = await lease(env, "a1"); + expect((await env.cli(["release", first.lease.id])).code).toBe(0); + await waitFor(async () => (await devices(env)).every((device) => device.state === "ready"), { + label: "the released device is booted back", + }); + + const nuked = await env.cli(["nuke", "--yes"]); + expect(nuked.code, nuked.stderr).toBe(0); + await env.restartDaemon(); + await new Promise((resolve) => setTimeout(resolve, 3_000)); + + expect((await devices(env)).filter((device) => device.state !== "shutdown")).toEqual([]); + }); +}); diff --git a/e2e/warm-pool-reserve.test.ts b/e2e/warm-pool-reserve.test.ts index ee9e510ba..bef216e0c 100644 --- a/e2e/warm-pool-reserve.test.ts +++ b/e2e/warm-pool-reserve.test.ts @@ -122,11 +122,12 @@ describe("warm pool reserve and requests that wait for a booting device", () => 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", + // why: the warm pool's boot of the released device counts among the three. + await waitFor(async () => (await makeReadyCalls(env)) === 4, { + label: "two more boots are running beside the warm pool's", }); await new Promise((resolve) => setTimeout(resolve, 1_500)); - expect(await makeReadyCalls(env)).toBe(5); + expect(await makeReadyCalls(env)).toBe(4); const granted = await Promise.all(grants); await untilQuiet(env); diff --git a/e2e/warm-targets.test.ts b/e2e/warm-targets.test.ts index 6823e0f7d..d7ead9166 100644 --- a/e2e/warm-targets.test.ts +++ b/e2e/warm-targets.test.ts @@ -128,7 +128,7 @@ describe("warm pool targets", () => { ).toEqual([]); }); - it("keeps a targeted device ready past idle.shutdownAfterMs, shuts a leased non-targeted one down through cleanup-reaper and a never-leased non-targeted one down as warm-pool", async () => { + it("keeps a targeted device and a leased non-targeted kind ready past idle.shutdownAfterMs, and shuts a never-leased non-targeted one down as warm-pool", async () => { const env = await withDaemon({ configOverrides: { idle: { shutdownAfterMs: 500 }, warmPool: { targets: [IPHONE_17] } }, driverScript: { ios: IOS }, @@ -149,27 +149,6 @@ describe("warm pool targets", () => { const other = await lease(env, "other", "iPhone 16"); expect((await env.cli(["release", other.lease.id])).code).toBe(0); - await waitFor( - async () => { - await env.cli(["cleanup"]); - return (await devices(env)).some( - (row) => row.driverDeviceId === other.device.driverDeviceId && row.state === "shutdown", - ); - }, - { interval: 50, label: "cleanup shuts the idle iPhone 16 down", timeout: 20_000 }, - ); - - const after = await devices(env); - expect(after.find((row) => row.id === targeted.device.id)?.state).toBe("ready"); - const shutdowns = await named(env, "device.shutdown"); - expect(shutdowns).toContainEqual( - expect.objectContaining({ - payload: expect.objectContaining({ - deviceId: other.device.id, - initiator: "cleanup-reaper", - }), - }), - ); // The extra iPhone 17 was never leased and no target counts it: the pool shuts that one down. await waitFor( async () => @@ -180,7 +159,15 @@ describe("warm pool targets", () => { ), { label: "the pool shuts the never-leased replacement down", timeout: 45_000 }, ); - expect((await devices(env)).find((row) => row.id === targeted.device.id)?.state).toBe("ready"); + expect((await env.cli(["cleanup"])).code).toBe(0); + const kept = await devices(env); + expect(kept.find((row) => row.id === targeted.device.id)?.state).toBe("ready"); + expect(kept.find((row) => row.id === other.device.id)?.state).toBe("ready"); + expect( + (await named(env, "device.shutdown")).filter( + (entry) => (entry.payload as { deviceId: string }).deviceId === other.device.id, + ), + ).toEqual([]); }); it("with a driver that fails every boot, logs the target short with boot-failed after the first creation and holds the next one back", async () => { diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 3b5dfff03..95d1f216f 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6,7 +6,7 @@ import { createServer, type Socket } from "node:net"; import { Readable } from "node:stream"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { testComponentWiring } from "../core/testing.js"; +import { testComponentWiring, testStateOf } from "../core/testing.js"; import { EventBus } from "../bus/index.js"; import { ringEventHistory, seedHistory } from "../history/testing.js"; @@ -7291,6 +7291,7 @@ async function startTestDaemon(): Promise<{ socketPath: string; daemon: DaemonSe eventBus, idGenerator: sequence(), registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte, @@ -7403,6 +7404,7 @@ async function startInMemoryDaemon(options: { eventBus, idGenerator: sequence(), registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte, diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index 6c16ae5d7..3341336e1 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -96,7 +96,7 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic `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 - `killed` → shut down each unleased `ready` virtual device; with delete, destroy each `shutdown` one; a device it cannot reset is logged, the rest go on. + `killed` → clear the warm pool's learned kinds → shut down each unleased `ready` virtual device; with delete, destroy each `shutdown` one; a device it cannot reset is logged, the rest go on. 7. **Startup** — `readStartup` (`listManaged` per driver, parallel) → `doctor.reconcile({ read })` → leasing's reconcile → `core.converge`: re-arm quarantine → recover interrupted reclaims → delete spent devices → start warm pool and `CapacityObserver`. Skips unreadable, leased, claimed. diff --git a/src/core/create-core.test.ts b/src/core/create-core.test.ts index c4f818d09..c0990be85 100644 --- a/src/core/create-core.test.ts +++ b/src/core/create-core.test.ts @@ -21,7 +21,7 @@ import { } from "./index.js"; import { type FakePhysicalDevice } from "./fake-driver.js"; import { ReclaimCoordinator } from "./reclaim-coordinator.js"; -import { FakeDriver, loadTestRegistry, testComponentWiring } from "./testing.js"; +import { FakeDriver, loadTestRegistry, testComponentWiring, testStateOf } from "./testing.js"; import { WarmPool } from "./warm-pool/index.js"; async function build( @@ -78,6 +78,7 @@ async function build( logger, prerequisiteChecks: options.prerequisiteChecks, registry, + state: testStateOf(registry), systemStats, ...testComponentWiring({ clock, drivers: [driver], eventBus, registry }), }); diff --git a/src/core/create-core.ts b/src/core/create-core.ts index c88cbcdab..22208c6e6 100644 --- a/src/core/create-core.ts +++ b/src/core/create-core.ts @@ -1,5 +1,6 @@ import type { EventBus } from "../bus/index.js"; import type { Clock, Logger, SystemStats } from "../ports/index.js"; +import type { StateDatabase } from "../state/index.js"; import { buildCapacityFigures, CapacityCoordinator, @@ -65,6 +66,7 @@ interface CoreOptions { /** The checks `doctor` runs per platform this host could run. None if omitted. */ readonly prerequisiteChecks?: readonly PrerequisiteCheck[] | undefined; readonly registry: Registry; + readonly state: StateDatabase; readonly systemStats: SystemStats; } @@ -244,6 +246,7 @@ export function createCore(options: CoreOptions): Core { defaultMode: (platform) => port("warmPoolDemand").defaultMode(platform), }, capacity, + catalog: drivers, claims, clock: options.clock, config: options.config.warmPool, @@ -255,6 +258,7 @@ export function createCore(options: CoreOptions): Core { ...(options.logger === undefined ? {} : { logger: options.logger }), provisioner, registry, + state: options.state, }); const nuke = new NukeService({ acquisition: { @@ -273,6 +277,7 @@ export function createCore(options: CoreOptions): Core { leases: leaseMaintenance.leases, ...(options.logger === undefined ? {} : { logger: options.logger }), registry, + warmPool: { forget: () => warmPool.forget() }, }); const doctor = new Doctor({ // Without this, a backgrounded reclaim -- which holds its device in `reclaiming` for a full diff --git a/src/core/doctor.test.ts b/src/core/doctor.test.ts index 9626432b3..48affb235 100644 --- a/src/core/doctor.test.ts +++ b/src/core/doctor.test.ts @@ -19,7 +19,7 @@ import { QuarantineCoordinator } from "./quarantine-coordinator.js"; import type { Registry } from "./registry.js"; import { SerializedDecision } from "./serialized-decision.js"; import { StartupRead } from "./startup-read.js"; -import { loadTestRegistry, openTestState, testComponentWiring } from "./testing.js"; +import { loadTestRegistry, openTestState, testComponentWiring, testStateOf } from "./testing.js"; import { createTestEngine } from "../leasing/testing.js"; describe("Doctor", () => { @@ -549,6 +549,7 @@ describe("Doctor", () => { eventBus, idGenerator: sequence(), registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 }), }); diff --git a/src/core/index.ts b/src/core/index.ts index fc0301501..aebbef72d 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -133,6 +133,7 @@ export type { InstanceIdentityOptions } from "./instance-identity.js"; export { Nuke } from "./nuke.js"; export { type NukeExecutor } from "./core-ports.js"; export { registryOwner } from "./registry-schema.js"; +export { warmPoolOwner } from "./warm-pool/index.js"; export { RegistryLoadError } from "./registry-rows.js"; export { Registry, RegistryEventError, UnknownDeviceError, UnknownLeaseError } from "./registry.js"; export { diff --git a/src/core/nuke-service.test.ts b/src/core/nuke-service.test.ts index 3038cd318..589caf0c7 100644 --- a/src/core/nuke-service.test.ts +++ b/src/core/nuke-service.test.ts @@ -35,7 +35,7 @@ class MutableRegistry implements NukeRegistryView { } } -function createHarness(devices: VirtualDevice[]) { +function createHarness(devices: VirtualDevice[], onForget: () => void = () => undefined) { const registry = new MutableRegistry(devices); const calls: string[] = []; const lifecycle: NukeDeviceLifecycle = { @@ -79,6 +79,7 @@ function createHarness(devices: VirtualDevice[]) { }, }, registry, + warmPool: { forget: onForget }, }); return { calls, lifecycle, registry, service }; } @@ -100,6 +101,32 @@ describe("NukeService", () => { ]); }); + it("clears the warm pool's record before it resets devices, and still resets them when forget throws", async () => { + const clearing = createHarness([device("ready", "ready")], () => { + clearing.calls.push("forget"); + }); + const throwing = createHarness([device("ready", "ready")], () => { + throwing.calls.push("forget"); + throw new Error("disk I/O error"); + }); + + await clearing.service.nuke(false); + await throwing.service.nuke(false); + + for (const run of [clearing, throwing]) { + expect(run.calls).toEqual([ + "maintenance:begin", + "release-maintenance:begin", + "release:killed", + "forget", + "shutdown:ready", + "release-maintenance:end", + "maintenance:end", + ]); + expect(run.registry.devices).toMatchObject([{ id: "ready", state: "shutdown" }]); + } + }); + it("targets only non-deleted registry records and supports shutdown-only mode", async () => { const ready = device("registered", "ready"); const harness = createHarness([ready, device("already-deleted", "deleted")]); @@ -227,6 +254,8 @@ describe("NukeService", () => { }, }, registry: harness.registry, + + warmPool: { forget() {} }, }); await expect(harness.service.nuke(false)).rejects.toThrow("release failed"); @@ -281,6 +310,8 @@ describe("NukeService", () => { async endMaintenance() {}, }, registry, + + warmPool: { forget() {} }, }); async function register( @@ -381,6 +412,8 @@ describe("NukeService", () => { }, logger: new JsonLinesLogger({ clock: new FakeClock(1_000), sink }), registry: harness.registry, + + warmPool: { forget() {} }, }); await service.nuke(false); diff --git a/src/core/nuke-service.ts b/src/core/nuke-service.ts index 32ba3f947..73804b59b 100644 --- a/src/core/nuke-service.ts +++ b/src/core/nuke-service.ts @@ -44,6 +44,8 @@ export interface NukeServiceOptions { readonly leases: LeaseMaintenance; readonly registry: NukeRegistryView; readonly logger?: Logger; + /** why: nuke starts the warm pool over, so the kinds it learned are not booted back. */ + readonly warmPool: { forget(): void }; } /** @@ -83,6 +85,13 @@ export class NukeService implements NukeExecutor { await this.options.leases.beginMaintenance(); releaseMaintenanceStarted = true; const releasedLeaseIds = await this.options.leases.releaseAllDuringMaintenance("killed"); + try { + this.options.warmPool.forget(); + } catch (error: unknown) { + this.#logger.error("nuke could not clear the warm pool's record", { + error: stableError(error), + }); + } for (const device of this.options.registry.snapshot.virtualDevices) { try { diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index c748cad92..bc2983122 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { loadTestRegistry, testComponentWiring } from "./testing.js"; +import { loadTestRegistry, testComponentWiring, testStateOf } from "./testing.js"; import { EventBus } from "../bus/index.js"; import { FakeClock, FakeSystemStats } from "../ports/index.js"; @@ -58,6 +58,7 @@ describe("Nuke", () => { eventBus, idGenerator: sequence(), registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * 1024 ** 3, @@ -102,6 +103,7 @@ describe("Nuke", () => { eventBus, idGenerator: sequence(), registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * 1024 ** 3, diff --git a/src/core/physical-enrollment.test.ts b/src/core/physical-enrollment.test.ts index 49af0b412..2765ff08b 100644 --- a/src/core/physical-enrollment.test.ts +++ b/src/core/physical-enrollment.test.ts @@ -6,7 +6,7 @@ import { type FakePhysicalDevice } from "./fake-driver.js"; import type { PhysicalDevice } from "./domain.js"; import { createCore, loadConfig } from "./index.js"; import { PhysicalEnrollment } from "./physical-enrollment.js"; -import { FakeDriver, loadTestRegistry, testComponentWiring } from "./testing.js"; +import { FakeDriver, loadTestRegistry, testComponentWiring, testStateOf } from "./testing.js"; const UDID = "00008110-001A2B3C4D5E"; const ALIAS = "7A1C0E52-6B7D-4F1E-9C1A-2D3E4F5A6B7C"; @@ -37,6 +37,7 @@ async function build(physicalDevices: readonly FakePhysicalDevice[] = [IPHONE]) drivers: [driver], eventBus, registry, + state: testStateOf(registry), systemStats, ...testComponentWiring({ clock, drivers: [driver], eventBus, registry }), }); @@ -400,6 +401,7 @@ describe("PhysicalEnrollment", () => { drivers: [harness.driver, android], eventBus: harness.eventBus, registry: harness.registry, + state: testStateOf(harness.registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * 1024 ** 3 }), ...testComponentWiring({ clock: harness.clock, diff --git a/src/core/quarantine-coordinator.test.ts b/src/core/quarantine-coordinator.test.ts index 8c0a883ec..8f06fcdb0 100644 --- a/src/core/quarantine-coordinator.test.ts +++ b/src/core/quarantine-coordinator.test.ts @@ -13,7 +13,13 @@ import { DeviceOperationClaims } from "./device-operation-claims.js"; import { DriverCatalog } from "./driver-catalog.js"; import type { VirtualDevice, VirtualSpec } from "./domain.js"; import { type FakePhysicalDevice } from "./fake-driver.js"; -import { FakeDriver, loadTestRegistry, openTestState, testComponentWiring } from "./testing.js"; +import { + FakeDriver, + loadTestRegistry, + openTestState, + testComponentWiring, + testStateOf, +} from "./testing.js"; import { createCore, loadConfig } from "./index.js"; import { QuarantineCoordinator, @@ -1025,6 +1031,7 @@ describe("QuarantineCoordinator and enrollment of a quarantined physical device drivers: [driver], eventBus, registry, + state: testStateOf(registry), systemStats, ...testComponentWiring({ clock, drivers: [driver], eventBus, registry }), }); @@ -1198,6 +1205,7 @@ describe("QuarantineCoordinator retry of a physical device that is not present ( eventBus, ...(logger === undefined ? {} : { logger }), registry, + state: testStateOf(registry), systemStats, ...testComponentWiring({ clock, drivers: [driver], eventBus, registry }), }); diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index 986883791..40e90342d 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { loadTestRegistry, testComponentWiring } from "./testing.js"; +import { loadTestRegistry, testComponentWiring, testStateOf } from "./testing.js"; import { EventBus } from "../bus/index.js"; import { @@ -157,6 +157,7 @@ async function createHarness( eventBus, idGenerator: { generate: () => `request-${nextId++}` }, registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte, diff --git a/src/core/testing.ts b/src/core/testing.ts index 080e896d8..3e7aec9a8 100644 --- a/src/core/testing.ts +++ b/src/core/testing.ts @@ -17,6 +17,7 @@ import { DriverCatalog } from "./driver-catalog.js"; import type { Platform } from "./domain.js"; import { Registry, type RegistryOptions } from "./registry.js"; import { registryOwner } from "./registry-schema.js"; +import { warmPoolOwner } from "./warm-pool/index.js"; import { SerializedDecision } from "./serialized-decision.js"; /** @@ -95,7 +96,7 @@ export function openMemoryState(owners: readonly SqliteSchemaOwner[]): Promise { - return openMemoryState([registryOwner, fakeDeviceDataTable]); + return openMemoryState([registryOwner, warmPoolOwner, fakeDeviceDataTable]); } export function describeDeviceDataTable( @@ -122,14 +123,22 @@ export function describeDeviceDataTable( }); } +const registryStates = new WeakMap(); + +// why: the daemon hands the registry and the warm pool one `state.db` handle, so a test engine takes the registry's. +export function testStateOf(registry: Registry): StateDatabase { + const state = registryStates.get(registry); + if (state === undefined) throw new Error("this registry was not loaded by loadTestRegistry"); + return state; +} + export async function loadTestRegistry( options: Omit & { readonly state?: StateDatabase | undefined; }, ): Promise { - return Registry.load({ - ...options, - deviceData: fakeDeviceDataTables, - state: options.state ?? (await openTestState()), - }); + const state = options.state ?? (await openTestState()); + const registry = await Registry.load({ ...options, deviceData: fakeDeviceDataTables, state }); + registryStates.set(registry, state); + return registry; } diff --git a/src/core/warm-pool/AGENTS.md b/src/core/warm-pool/AGENTS.md index 8bc560189..c582abd40 100644 --- a/src/core/warm-pool/AGENTS.md +++ b/src/core/warm-pool/AGENTS.md @@ -1,6 +1,6 @@ # Warm pool -Does: decides which idle virtual devices stay booted, and keeps `warmPool.targets` filled. +Does: decides which idle virtual devices stay booted, and keeps `warmPool.targets` and the kinds it learned from leases filled. Entry: `index.ts` → `WarmPool`, built by `createCore`; `start()` runs at the end of `core.converge`. Uses: core (capacity, lifecycle, provisioner, claims, registry, lock), bus, ports, contract. Leasing reaches it only through `CorePorts.warmPoolDemand` and `core.passWarmPool()`. @@ -8,13 +8,15 @@ Flows: [startup](../../../docs/internal/flows/startup.md). Parent: [core](../AGE ## Files -| File | Role | -| -------------- | ---------------------------------------------------------------------------------------- | -| `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(systemStats)`, validators | -| `figures.ts` | `WarmPoolFigures`, `WarmTargetFigures` | +| File | Role | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------ | +| `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` | +| `learned.ts` | `warmPoolOwner` (`state.db` tables `warm_kinds`, `warm_kind_leases`), `LearnedKinds`: the kinds leased, their 24 h peak | +| `catalog-check.ts` | `CatalogCheck`: one catalog read per platform beside a pass, 30 s limit; says which learned kinds are gone or unanswered | +| `retry.ts` | `RetrySchedule`: a target's failed boot or creation, keyed by resolved spec | +| `config.ts` | `WarmPoolConfig`, `defaultWarmPoolConfig(systemStats)`, validators | +| `figures.ts` | `WarmPoolFigures`, `WarmTargetFigures` | ## How it works @@ -26,8 +28,14 @@ quarantined or reserved device holds (`RunningCapacity`), per platform and globa `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. -3. **Resolve** — each target through `warmPoolDemand.resolve`, downloads off, every pass. + device; it is never booted back unasked. Nuke also clears the learned record (`forget()`). + **Learn** — on `lease.granted` the leased device's kind is recorded (not a physical device, not + with the pool off); `lease.released` and `lease.expired` close its lease row; `start()` closes + rows whose lease the registry no longer holds. Each kind's count is its peak of leases held at + once in the last 24 h, at least 1; 32 kinds per platform, the oldest dropped. +3. **Resolve** — each target (a learned kind needs none; the catalog check forgets one whose model, + OS, image tag or driver is gone, and a third failed boot in a row forgets it too) through `warmPoolDemand.resolve`, downloads off, every pass. + A kind whose platform has no catalog answer yet (read pending, failed or timed out) is kept and planned for nothing that pass. A refusal is a report. An `unresolvable` target keeps its last spec, so its devices stay spared. A device of a platform whose driver was refused at discovery is never proposed — boot or shutdown — but still holds its capacity slot, and `targeted()` still lists it to the reaper. @@ -42,13 +50,16 @@ quarantined or reserved device holds (`RunningCapacity`), per platform and globa 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; + - shut down a device never leased, `ready` longer than `idle.shutdownAfterMs`, no target or + learned kind keeps; - targets: merge those of one spec (counts summed); boot a shut-down device of the kind, else 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`. + - learned kinds, newest first, after the configured targets: the same fill, a kind having its + ready idle, leased and reclaiming devices. One short for a running slot displaces the least + recently used idle ready device of an older learned kind (`displaced`; never a configured + target's device, a spared target's, or when the capacity strategy would still refuse the kind after the shutdown). 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; @@ -58,7 +69,7 @@ quarantined or reserved device holds (`RunningCapacity`), per platform and globa 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. +`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. Figures (`figures()`, read by `status.get`, doctor's `warm-pool-target-unreachable`, the console): @@ -78,18 +89,19 @@ Stop: `close()` at stop start; `drain()` finishes the pass and running boots, st ## State and timers -| What | Default | Key | -| ------------------------------------------------ | ----------------------------------- | -------------------------------- | -| 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` | -| 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` | +| What | Default | Key | +| --------------------------------------- | ----------------------------------- | -------------------------------- | +| 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` | +| Boots and creations in flight at once | `max(1, floor(cpuCount / 4))` | `warmPool.maxConcurrentBoots` | +| Never-leased idle | 10 min | `idle.shutdownAfterMs` | +| Tick; pause after a failed shutdown | 30 s | `WARM_POOL_TICK_MS` | +| Target retry | 60 s, doubling, cap 10 min | `RETRY_FIRST_MS`, `RETRY_MAX_MS` | Target keys: `platform`, `model`, `count` required; `osVersion` (version or range), `mode`. -Any other key, a class included, fails the load. Memory only: nothing is persisted. +Any other key, a class included, fails the load. Targets are config; the learned kinds are the +pool's own `state.db` tables, kept across restarts and cleared by nuke. ## Rules @@ -97,7 +109,7 @@ Any other key, a class included, fails the load. Memory only: nothing is persist - Acts only through `ManagedDeviceLifecycle` and `DeviceProvisioner`, never on a leased or claimed device. - Never installs: a missing runtime is a report, not a download. -- A target never shuts a device down; what does not fit is reported short. +- A target never shuts a device down (a learned kind may displace an older learned kind's idle one); what does not fit is reported short. - `reserveRunning` holds slots from idle devices only; it never holds back a request. - Reclaim commits the driver's state and decides nothing; keep or shut down is decided here. @@ -108,3 +120,5 @@ Any other key, a class included, fails the load. Memory only: nothing is persist it waits; a burst larger than `count` pays the boot. - **A failing target retries forever.** 1, 2, 4 … minutes, at most 10 apart, no attempt limit; each try boots or creates a device. `retry.ts` is the one place to add a limit. +- **A hung `avdmanager` leaves one stuck process per 30 s.** The catalog check abandons a read + after 30 s, but the driver's call has no timeout of its own. diff --git a/src/core/warm-pool/catalog-check.ts b/src/core/warm-pool/catalog-check.ts new file mode 100644 index 000000000..ba7946643 --- /dev/null +++ b/src/core/warm-pool/catalog-check.ts @@ -0,0 +1,100 @@ +import type { Clock, Logger } from "../../ports/index.js"; +import type { Platform, VirtualSpec } from "../domain.js"; +import type { DriverCatalog, PlatformCatalog } from "../driver-catalog.js"; +import { stableError } from "../stable-error.js"; +import type { LearnedKind } from "./learned.js"; + +/** why: the longest the pool waits for a catalog read; `avdmanager` has no timeout of its own. */ +const CATALOG_READ_LIMIT_MS = 30_000; + +interface CatalogCheckOptions { + readonly catalog: Pick; + readonly clock: Clock; + readonly hasDriver: (platform: Platform) => boolean; + readonly logger: Logger; + /** why: a read lists a platform that had no answer, so the kinds waiting on it can be planned now, not at the next tick. A failed or timed out read does not call it: its retry would loop. */ + readonly onAnswer: () => void; +} + +/** + * why: reads each platform's catalog beside a pass, never blocking it, and says which learned kinds + * the last answers no longer list. A read that throws or runs past the limit leaves its platform + * with no answer, so none of its kinds is judged on it: they are kept, and planned for nothing + * (`unanswered`) until a read lists the platform, which asks for a pass at once (ADR 0038 §4, §5). + */ +export class CatalogCheck { + readonly #answers = new Map(); + readonly #pending = new Set(); + + constructor(private readonly options: CatalogCheckOptions) {} + + /** why: starts a read for each of `platforms` that has none pending. */ + start(platforms: ReadonlySet): void { + for (const platform of platforms) { + if (this.#pending.has(platform) || !this.options.hasDriver(platform)) continue; + this.#read(platform); + } + } + + /** why: the kinds whose platform has no driver, or that the latest answer for it does not list. */ + gone(kinds: readonly LearnedKind[]): LearnedKind[] { + return kinds.filter((kind) => { + const { platform } = kind.spec; + if (!this.options.hasDriver(platform)) return true; + const answer = this.#answers.get(platform); + return answer !== undefined && !lists(answer, kind.spec); + }); + } + + /** why: the kinds whose platform has a driver and no answer yet: a read pending, failed or timed out. */ + unanswered(kinds: readonly LearnedKind[]): LearnedKind[] { + return kinds.filter( + (kind) => + this.options.hasDriver(kind.spec.platform) && !this.#answers.has(kind.spec.platform), + ); + } + + #read(platform: Platform): void { + const { catalog, clock, logger } = this.options; + this.#pending.add(platform); + let abandoned = false; + const timer = clock.setTimer(CATALOG_READ_LIMIT_MS, () => { + abandoned = true; + this.#pending.delete(platform); + this.#answers.delete(platform); + logger.warn("a warm pool catalog read took too long", { platform }); + }); + const finish = (): boolean => { + if (abandoned) return false; + clock.cancel(timer); + this.#pending.delete(platform); + return true; + }; + catalog.listCatalog(platform).then( + (entries) => { + if (!finish()) return; + const entry = entries.find((candidate) => candidate.platform === platform); + if (entry === undefined) this.#answers.delete(platform); + else { + const first = !this.#answers.has(platform); + this.#answers.set(platform, entry); + if (first) this.options.onAnswer(); + } + }, + (error: unknown) => { + if (!finish()) return; + this.#answers.delete(platform); + logger.warn("a warm pool catalog read failed", { platform, error: stableError(error) }); + }, + ); + } +} + +function lists(catalog: PlatformCatalog, spec: VirtualSpec): boolean { + if (!catalog.models.includes(spec.model)) return false; + if (!(catalog.modelRuntimes[spec.model] ?? []).includes(spec.osVersion)) return false; + if (spec.imageTag === undefined) return true; + return (catalog.images ?? []).some( + (image) => image.runtime === spec.osVersion && image.tag === spec.imageTag, + ); +} diff --git a/src/core/warm-pool/converger.test.ts b/src/core/warm-pool/converger.test.ts index 22075921f..fc576876d 100644 --- a/src/core/warm-pool/converger.test.ts +++ b/src/core/warm-pool/converger.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { EventBus } from "../../bus/index.js"; import { FakeClock, JsonLinesLogger, MemoryLogSink } from "../../ports/index.js"; @@ -9,17 +9,47 @@ import { type VirtualDevice, type VirtualSpec, type LeaseRecord, + type Platform, type TargetResolution, type WaitingDemand, } from "../domain.js"; +import type { PlatformCatalog } from "../driver-catalog.js"; import { BootTimeoutError, type DeviceRequest } from "../driver.js"; import { SerializedDecision } from "../serialized-decision.js"; +import type { StateDatabase } from "../../state/index.js"; +import { openMemoryState } from "../testing.js"; import type { WarmTarget } from "./config.js"; import { WARM_POOL_TICK_MS, WarmPool, type WarmPoolOptions } from "./converger.js"; +import { LearnedKinds, warmPoolOwner } from "./learned.js"; const minute = 60_000; const now = 1_000 * minute; +/** why: a catalog read that lists the iOS models the learned-kind tests lease. */ +const iosListing: PlatformCatalog = { + classDefaults: {}, + defaultRuntime: undefined, + modelAliases: {}, + modelClasses: {}, + modelRuntimes: { "iPad Pro": ["26.0"], "iPhone 15": ["26.0"] }, + models: ["iPad Pro", "iPhone 15"], + platform: "ios", + runtimes: ["26.0"], +}; + +const iphone15: WarmTarget = { + count: 1, + model: "iPhone 15", + osVersion: "26.0", + platform: "ios", +}; + +let learnedState: StateDatabase; + +beforeEach(async () => { + learnedState = await openMemoryState([warmPoolOwner]); +}); + function device( id: string, state: VirtualDevice["state"], @@ -98,6 +128,11 @@ function harness( reserveThrows?: boolean; refusedPlatforms?: readonly ("ios" | "android")[]; provisioning?: Promise; + state?: StateDatabase; + /** why: called with the id of each device the budget is asked to admit a boot of, while a pass proposes. */ + onAdmit?: (deviceId: string) => void; + /** why: what a platform's catalog read answers; by default a catalog that lists nothing. */ + catalog?: (platform?: Platform) => Promise; } = {}, ) { const clock = new FakeClock(now); @@ -180,8 +215,10 @@ function harness( }; return { android: entry, global: entry, ios: entry }; }, - canBoot: () => - options.refuseBoot === true ? { ok: false, reason: "ram-budget" } : { ok: true }, + canBoot: (candidate) => { + if (candidate.id !== undefined) options.onAdmit?.(candidate.id); + return options.refuseBoot === true ? { ok: false, reason: "ram-budget" } : { ok: true }; + }, canProvision: () => options.refuseProvision === true ? { ok: false, reason: "device-limit" } : { ok: true }, tryReserveProvisioning: () => { @@ -214,6 +251,7 @@ function harness( }; }, }, + catalog: { listCatalog: options.catalog ?? (async () => []) }, claims: { claim: (id) => claims.claim(id), isClaimed: (id) => claims.isClaimed(id), @@ -298,6 +336,7 @@ function harness( return { leases: state.leases, virtualDevices: state.devices }; }, }, + state: options.state ?? learnedState, }; const pool = new WarmPool(poolOptions); return { @@ -327,17 +366,20 @@ describe("warm pool converger", () => { boot: async () => { throw new Error("emulator did not come up"); }, + targets: [iphone15], }); await rig.pool.pass(); + await rig.pool.settle(); expect(rig.bootCalls).toEqual(["shut"]); expect(rig.kick).toHaveBeenCalledTimes(1); }); it("kicks acquisition after a boot or a shutdown that succeeds", async () => { - const booted = harness([device("shut", "shutdown", 1_000)]); + const booted = harness([device("shut", "shutdown", 1_000)], { targets: [iphone15] }); await booted.pool.pass(); + await booted.pool.settle(); const shutDown = harness([device("a", "ready", 5_000), device("b", "ready", 1_000)], { limit: 1, }); @@ -371,7 +413,9 @@ describe("warm pool converger", () => { await rig.pool.pass(); expect(rig.shutdownCalls).toEqual(["a"]); - expect(rig.sink.records).toEqual([]); + expect(rig.sink.records.map((record) => record.fields)).toEqual([ + { deviceId: "a", reason: "over-budget" }, + ]); expect(rig.kick).toHaveBeenCalledTimes(1); }); @@ -414,10 +458,14 @@ describe("warm pool converger", () => { limit: 1, shutdown: async () => undefined, }); - const boot = harness([device("shut", "shutdown", 1_000)], { boot: async () => undefined }); + const boot = harness([device("shut", "shutdown", 1_000)], { + boot: async () => undefined, + targets: [iphone15], + }); await shutdown.pool.pass(); await boot.pool.pass(); + await boot.pool.settle(); expect(shutdown.shutdownCalls).toEqual(["a"]); expect(shutdown.kick).not.toHaveBeenCalled(); @@ -458,9 +506,10 @@ describe("warm pool converger", () => { }); it("holds a boot reservation and a boot claim through the boot, and releases the reservation when it commits", async () => { - const rig = harness([device("shut", "shutdown", 1_000)]); + const rig = harness([device("shut", "shutdown", 1_000)], { targets: [iphone15] }); await rig.pool.pass(); + await rig.pool.settle(); expect(rig.reservations).toHaveLength(1); expect(rig.reservations[0]?.claimedAtBoot).toBe(true); @@ -474,14 +523,18 @@ describe("warm pool converger", () => { boot: async () => { throw new Error("boot failed"); }, + targets: [iphone15], }); await rig.pool.pass(); + await rig.pool.settle(); expect(rig.reservations).toHaveLength(1); expect(rig.reservations[0]?.released).toBe(1); expect(rig.claims.isClaimed("shut")).toBe(false); - const lines = rig.sink.records.filter((record) => record.level === "warn"); + const lines = rig.sink.records.filter( + (record) => record.level === "warn" && record.message.startsWith("warm pool boot"), + ); expect(lines).toHaveLength(1); expect(lines[0]).toMatchObject({ fields: { deviceId: "shut", step: "boot" }, @@ -519,106 +572,33 @@ describe("warm pool converger", () => { rig.pool.dispose(); }); - it("does not try a device again within a tick of its boot failing, and does after", async () => { - const rig = harness([device("shut", "shutdown", 1_000)], { - boot: async () => { - throw new Error("boot failed"); - }, - }); - - await rig.pool.pass(); - await rig.pool.pass(); - expect(rig.bootCalls).toEqual(["shut"]); - - rig.clock.advance(WARM_POOL_TICK_MS); - await rig.pool.pass(); - expect(rig.bootCalls).toEqual(["shut", "shut"]); - }); - it("does not boot a device that was claimed between the proposal and the action", async () => { - let claimY: () => void = () => undefined; - const rig = harness([device("x", "shutdown", 1_000), device("y", "shutdown", 2_000)], { - boot: async (target) => { - // The first boot runs outside the decision gate; another operation takes `y` meanwhile. - claimY(); - return { ...target, state: "ready" }; - }, - }); - claimY = () => void rig.claims.tryClaim("y", "eviction"); - - await rig.pool.pass(); - - expect(rig.bootCalls).toEqual(["x"]); - expect(rig.reservations).toHaveLength(1); - }); - - it("boots nothing, takes no claim and does not kick when capacity refuses the reservation", async () => { - const rig = harness([device("shut", "shutdown", 1_000)], { refuseBoot: true }); - - await rig.pool.pass(); - - expect(rig.bootCalls).toEqual([]); - expect(rig.claims.isClaimed("shut")).toBe(false); - expect(rig.kick).not.toHaveBeenCalled(); - expect(rig.sink.records).toEqual([]); - }); - - it("proposes no budget shutdown while a ready device is claimed for a boot on its way to a lease", async () => { - const rig = harness([device("a", "ready", 5_000), device("b", "ready", 1_000)], { limit: 1 }); - const handoff = rig.claims.tryClaim("b", "boot"); - - await rig.pool.pass(); - expect(rig.shutdownCalls).toEqual([]); - - handoff?.release(); - await rig.pool.pass(); - expect(rig.shutdownCalls).toEqual(["a"]); - }); - - it("does nothing while an operator reset holds acquisition closed, and acts again once it is open", async () => { - let closed = true; - const rig = harness( - [device("a", "ready", 5_000), device("b", "ready", 1_000), device("s", "shutdown", 1_000)], - { limit: 1, maintenance: () => closed }, - ); - - await rig.pool.pass(); - expect(rig.shutdownCalls).toEqual([]); - expect(rig.bootCalls).toEqual([]); - expect(rig.waitingDemand).not.toHaveBeenCalled(); - - closed = false; - await rig.pool.pass(); - expect(rig.shutdownCalls).toEqual(["a"]); - }); - - it("stops acting on the rest of a pass when an operator reset begins during it", async () => { - let closed = false; - const rig = harness( - [ - device("a", "ready", 90 * minute), - device("b", "ready", 80 * minute), - device("c", "ready", 70 * minute), - ], + const rig: ReturnType = harness( + [device("x", "shutdown", 1_000), device("y", "shutdown", 2_000)], { - limit: 1, - maintenance: () => closed, - shutdown: async (target) => { - closed = true; - return { ...target, state: "shutdown" }; + maxConcurrentBoots: 2, + onAdmit: (id) => { + if (id === "y") void rig.claims.tryClaim("y", "eviction"); }, + targets: [{ ...iphone15, count: 2 }], }, ); await rig.pool.pass(); + await rig.pool.settle(); - expect(rig.shutdownCalls).toEqual(["a"]); + expect(rig.bootCalls).toEqual(["x"]); + expect(rig.reservations).toHaveLength(1); }); it("releases the reservation and boots nothing when the device claim is refused", async () => { - const rig = harness([device("shut", "shutdown", 1_000)], { refuseClaim: true }); + const rig = harness([device("shut", "shutdown", 1_000)], { + refuseClaim: true, + targets: [iphone15], + }); await rig.pool.pass(); + await rig.pool.settle(); expect(rig.bootCalls).toEqual([]); expect(rig.reservations).toHaveLength(1); @@ -677,24 +657,28 @@ describe("warm pool converger", () => { await rig.pool.pass(); expect(rig.shutdownCalls).toEqual(["a"]); - expect(rig.sink.records).toEqual([]); + expect(rig.sink.records.map((record) => record.fields)).toEqual([ + { deviceId: "a", reason: "over-budget" }, + ]); }); it("leaves a shut-down device alone that is no longer shut down when its boot comes", async () => { - let change: () => void = () => undefined; - const rig = harness([device("x", "shutdown", 1_000), device("y", "shutdown", 2_000)], { - boot: async (target) => { - change(); - return { ...target, state: "ready" }; + const rig: ReturnType = harness( + [device("x", "shutdown", 1_000), device("y", "shutdown", 2_000)], + { + maxConcurrentBoots: 2, + onAdmit: (id) => { + if (id !== "y") return; + rig.state.devices = rig.state.devices.map((item) => + item.id === "y" ? { ...item, state: "ready" } : item, + ); + }, + targets: [{ ...iphone15, count: 2 }], }, - }); - change = () => { - rig.state.devices = rig.state.devices.map((item) => - item.id === "y" ? { ...item, state: "ready" } : item, - ); - }; + ); await rig.pool.pass(); + await rig.pool.settle(); expect(rig.bootCalls).toEqual(["x"]); expect(rig.sink.records).toEqual([]); @@ -704,6 +688,7 @@ describe("warm pool converger", () => { let closed = true; const rig = harness([device("up", "ready", 1_000), device("gone", "shutdown", 2_000)], { maintenance: () => closed, + targets: [iphone15], }); await rig.pool.pass(); closed = false; @@ -713,14 +698,18 @@ describe("warm pool converger", () => { .filter((item) => item.id !== "gone") .map((item) => ({ ...item, state: "shutdown" as const })); await rig.pool.pass(); + await rig.pool.settle(); expect(rig.bootCalls).toEqual(["up"]); expect(rig.sink.records).toEqual([]); }); - it("clears the reset mark once the device has left shutdown, so it is an ordinary recently released device again", async () => { + it("clears the reset mark once the device has left shutdown, so it is an ordinary device again", async () => { let closed = true; - const rig = harness([device("down", "shutdown", 1_000)], { maintenance: () => closed }); + const rig = harness([device("down", "shutdown", 1_000)], { + maintenance: () => closed, + targets: [iphone15], + }); await rig.pool.pass(); closed = false; @@ -728,6 +717,7 @@ describe("warm pool converger", () => { await rig.pool.pass(); rig.state.devices = rig.state.devices.map((item) => ({ ...item, state: "shutdown" })); await rig.pool.pass(); + await rig.pool.settle(); expect(rig.bootCalls).toEqual(["down"]); }); @@ -746,6 +736,46 @@ describe("warm pool converger", () => { expect(rig.bootCalls).toEqual([]); }); + it("does nothing while an operator reset holds acquisition closed, and acts again once it is open", async () => { + let closed = true; + const rig = harness( + [device("a", "ready", 5_000), device("b", "ready", 1_000), device("s", "shutdown", 1_000)], + { limit: 1, maintenance: () => closed }, + ); + + await rig.pool.pass(); + expect(rig.shutdownCalls).toEqual([]); + expect(rig.bootCalls).toEqual([]); + expect(rig.waitingDemand).not.toHaveBeenCalled(); + + closed = false; + await rig.pool.pass(); + expect(rig.shutdownCalls).toEqual(["a"]); + }); + + it("stops acting on the rest of a pass when an operator reset begins during it", async () => { + let closed = false; + const rig = harness( + [ + device("a", "ready", 90 * minute), + device("b", "ready", 80 * minute), + device("c", "ready", 70 * minute), + ], + { + limit: 1, + maintenance: () => closed, + shutdown: async (target) => { + closed = true; + return { ...target, state: "shutdown" }; + }, + }, + ); + + await rig.pool.pass(); + + expect(rig.shutdownCalls).toEqual(["a"]); + }); + it("subscribes once however many times it is started", async () => { const rig = harness([]); rig.pool.start(); @@ -786,6 +816,28 @@ describe("warm pool converger", () => { expect(rig.kick).toHaveBeenCalledTimes(1); }); + it("does not try a failed shutdown of a device again within a tick, and does after", async () => { + const attempts: string[] = []; + const rig = harness([device("a", "ready", 5_000), device("b", "ready", 1_000)], { + limit: 1, + shutdown: async (target) => { + attempts.push(target.id); + throw new Error("simctl shutdown failed"); + }, + }); + + await rig.pool.pass(); + rig.clock.advance(WARM_POOL_TICK_MS - 1); + await rig.pool.pass(); + + expect(attempts).toEqual(["a"]); + + rig.clock.advance(1); + await rig.pool.pass(); + + expect(attempts).toEqual(["a", "a"]); + }); + it("runs a pass on each trigger event and on the tick, and none once disposed", async () => { const triggers = [ ["daemon.started", { configSnapshot: {}, version: "test" }], @@ -1274,6 +1326,7 @@ describe("warm pool targets", () => { expect(rig.pool.targets()).toEqual([ { booting: 0, + configuredCount: 1, count: 1, kind: { mode: "full", @@ -1282,6 +1335,7 @@ describe("warm pool targets", () => { platform: "ios", }, message: "iOS 27.0 is not installed", + origin: "configured", ready: 0, short: "runtime-missing", target: "ios iPhone 17 27.0", @@ -1481,28 +1535,6 @@ describe("warm pool targets", () => { expect(rig.shutdownCalls).toEqual(["a"]); }); - it("does not hold a target back for a keep boot that succeeds or fails, which no target owns", async () => { - const released = device("released", "shutdown", 1_000, "ios"); - const ipad = { ...released, spec: { ...released.spec, model: "iPad Pro" } }; - const failing = harness([ipad, ofKind("ready", "ready")], { - boot: async () => { - throw new Error("simulator did not boot"); - }, - targets: [iphone17], - }); - await failing.pool.pass(); - await failing.pool.settle(); - await failing.pool.pass(); - expect(failing.bootCalls).toEqual(["released"]); - expect(failing.sink.records.filter((record) => record.level === "error")).toEqual([]); - expect(failing.clock.pendingTimerCount).toBe(0); - - const working = harness([ipad, ofKind("ready", "ready")], { targets: [iphone17] }); - await working.pool.pass(); - await working.pool.settle(); - expect(working.sink.records.filter((record) => record.level !== "info")).toEqual([]); - }); - it("resolves no target, reports none and names no device with warmPool disabled", async () => { const rig = harness([ofKind("ready", "ready")], { enabled: false, @@ -1562,33 +1594,6 @@ describe("warm pool targets", () => { expect([...(await rig.pool.targeted())]).toEqual([]); }); - it("lets a target boot a device whose keep boot failed a moment ago, which no target owns", async () => { - const targets: WarmTarget[] = []; - let attempts = 0; - const rig = harness([ofKind("shut", "shutdown")], { - boot: async () => { - attempts += 1; - throw new Error("simulator did not boot"); - }, - targets, - }); - rig.state.devices = rig.state.devices.map((item) => ({ - ...item, - lastLeaseEndedAt: now - 10 * minute + 10_000, - })); - await rig.pool.pass(); - await rig.pool.settle(); - expect(attempts).toBe(1); - - // No longer recently released, so the keep rule leaves it; the 30 s pause has not ended. - rig.clock.advance(15_000); - targets.push(iphone17); - await rig.pool.pass(); - await rig.pool.settle(); - - expect(attempts).toBe(2); - }); - it("starts nothing once closed, before it drains", async () => { const rig = harness([], { targets: [iphone17] }); @@ -1615,34 +1620,6 @@ describe("warm pool targets", () => { ]); }); - it("does not pause a device after a failed target boot, so a keep boot of it a moment later is not dropped", async () => { - const targets: WarmTarget[] = [iphone17]; - let attempts = 0; - const rig = harness([ofKind("shut", "shutdown")], { - boot: async () => { - attempts += 1; - throw new Error("simulator did not boot"); - }, - targets, - }); - await rig.pool.pass(); - await rig.pool.settle(); - expect(attempts).toBe(1); - - // The target is dropped and the device was released a moment ago: the keep rule boots it, - // well inside the 30 s a keep boot's own failure would hold it. - targets.length = 0; - rig.state.devices = rig.state.devices.map((item) => ({ - ...item, - lastLeaseEndedAt: now - 1_000, - })); - rig.clock.advance(1_000); - await rig.pool.pass(); - await rig.pool.settle(); - - expect(attempts).toBe(2); - }); - it("starts nothing new once draining, though a creation that was running ends", async () => { const gate = held(); const rig = harness([], { @@ -2270,6 +2247,21 @@ describe("warm pool targets", () => { expect([...(await rig.pool.targeted())].sort()).toEqual(["older", "oldest"]); }); + it("names a learned kind's ready devices up to its count before the first pass, and again for a pool started over the same record", async () => { + const spec = ofKind("x", "ready").spec; + new LearnedKinds(learnedState).learn(spec, "lease-1", now - minute); + new LearnedKinds(learnedState).learn(spec, "lease-2", now - minute); + const devices = [ofKind("newer", "ready", 20), ofKind("older", "ready", 10)]; + + const before = harness(devices, { limit: 5 }); + const restarted = harness(devices, { limit: 5 }); + const off = harness(devices, { enabled: false, limit: 5 }); + + expect([...(await before.pool.targeted())].sort()).toEqual(["newer", "older"]); + expect([...(await restarted.pool.targeted())].sort()).toEqual(["newer", "older"]); + expect([...(await off.pool.targeted())]).toEqual([]); + }); + it("does not name a device that is leased or claimed", async () => { const rig = harness([ofKind("leased", "ready", 1), ofKind("claimed", "ready", 2)], { limit: 5, @@ -2283,3 +2275,537 @@ describe("warm pool targets", () => { }); }); }); + +describe("warm pool learned kinds", () => { + const kindsOf = (state: StateDatabase, at = now) => new LearnedKinds(state).kinds(at); + const granted = (rig: ReturnType, leaseId: string, deviceId: string): void => + void rig.eventBus.emit( + "lease.granted", + { deviceId, leaseId, platform: "ios", requestId: "req", requester: "a", source: "warm" }, + "test", + ); + + it("learns on lease.granted the leased device's kind, closes it on lease.released and lease.expired, learns nothing for a device the registry does not hold, and nothing with warmPool.enabled false", async () => { + const devices = [device("d1", "leased", 0), device("d2", "leased", 0)]; + const learnedWith = async ( + end: "lease.released" | "lease.expired" | undefined, + options: { enabled?: boolean } = {}, + ) => { + const state = await openMemoryState([warmPoolOwner]); + const rig = harness(devices, { ...options, state }); + rig.pool.start(); + granted(rig, "l1", "d1"); + rig.clock.advance(minute); + if (end === "lease.released") { + rig.eventBus.emit( + end, + { deviceId: "d1", leaseId: "l1", ownerId: "a", reason: "explicit" }, + "test", + ); + } else if (end === "lease.expired") { + rig.eventBus.emit(end, { deviceId: "d1", leaseId: "l1", ownerId: "a" }, "test"); + } + rig.clock.advance(minute); + granted(rig, "l2", "d2"); + const kinds = kindsOf(state, rig.clock.now()); + rig.pool.dispose(); + return kinds; + }; + + const open = await learnedWith(undefined); + expect(open.map((kind) => [kind.spec.model, kind.count])).toEqual([["iPhone 15", 2]]); + const released = await learnedWith("lease.released"); + expect(released.map((kind) => kind.count)).toEqual([1]); + const expired = await learnedWith("lease.expired"); + expect(expired.map((kind) => kind.count)).toEqual([1]); + expect(await learnedWith(undefined, { enabled: false })).toEqual([]); + + const state = await openMemoryState([warmPoolOwner]); + const physical = harness(devices, { state }); + physical.pool.start(); + granted(physical, "l3", "phone-1"); + expect(kindsOf(state)).toEqual([]); + }); + + it("closes at start() the lease rows the registry no longer holds, and the first pass boots the recorded kinds", async () => { + const ipad = { + model: "iPad Pro", + osVersion: "26.0", + physical: false, + platform: "ios", + } as const; + const phone = device("d1", "ready", 0).spec; + const state = await openMemoryState([warmPoolOwner]); + const previous = new LearnedKinds(state); + previous.learn(phone, "orphan", now - 30 * minute); + previous.learn(ipad, "lease-held", now - 10 * minute); + const held = { ...device("held", "leased", 0), spec: ipad }; + const rig = harness([device("d1", "ready", 0), held], { state }); + rig.lease("held"); + + rig.pool.start(); + rig.clock.advance(5 * minute); + granted(rig, "again-phone", "d1"); + granted(rig, "again-ipad", "held"); + + const counts = new LearnedKinds(state) + .kinds(rig.clock.now()) + .map((kind) => [kind.spec.model, kind.count]); + expect(counts).toEqual([ + ["iPad Pro", 2], + ["iPhone 15", 1], + ]); + + const booting = await openMemoryState([warmPoolOwner]); + new LearnedKinds(booting).learn(phone, "past", now - 2 * 60 * minute); + new LearnedKinds(booting).ended("past", now - 60 * minute); + const restarted = harness([device("shut", "shutdown", 60 * minute)], { + catalog: async () => [iosListing], + state: booting, + }); + restarted.pool.start(); + await restarted.pool.pass(); + await restarted.pool.settle(); + expect(restarted.bootCalls).toEqual(["shut"]); + }); + + it("keeps a learned kind and plans nothing for it while its platform's catalog read is pending, failed or timed out, and boots it as soon as a read lists the platform, without waiting for the next tick", async () => { + const phone = device("d1", "ready", 0).spec; + const rigFor = async (catalog: () => Promise) => { + const state = await openMemoryState([warmPoolOwner]); + new LearnedKinds(state).learn(phone, "past", now - 2 * 60 * minute); + new LearnedKinds(state).ended("past", now - 60 * minute); + return { rig: harness([device("shut", "shutdown", 60 * minute)], { catalog, state }), state }; + }; + const later = () => new Promise((resolve) => setImmediate(resolve)); + + let release: (value: readonly PlatformCatalog[]) => void = () => undefined; + const pending = await rigFor( + () => + new Promise((resolve) => { + release = resolve; + }), + ); + await pending.rig.pool.pass(); + await pending.rig.pool.settle(); + expect(pending.rig.bootCalls).toEqual([]); + expect(pending.rig.provisionCalls).toEqual([]); + pending.rig.clock.advance(30_000); + await pending.rig.pool.pass(); + expect(pending.rig.bootCalls).toEqual([]); + expect(new LearnedKinds(pending.state).kinds(pending.rig.clock.now())).toHaveLength(1); + release([iosListing]); + await later(); + await pending.rig.pool.settle(); + expect(pending.rig.bootCalls).toEqual(["shut"]); + + const failed = await rigFor(async () => { + throw new Error("avdmanager failed"); + }); + await failed.rig.pool.pass(); + await later(); + await failed.rig.pool.pass(); + await failed.rig.pool.settle(); + expect(failed.rig.bootCalls).toEqual([]); + expect(failed.rig.provisionCalls).toEqual([]); + expect(new LearnedKinds(failed.state).kinds(failed.rig.clock.now())).toHaveLength(1); + + const answered = await rigFor(async () => [iosListing]); + await answered.rig.pool.pass(); + await later(); + await answered.rig.pool.settle(); + expect(answered.rig.bootCalls).toEqual(["shut"]); + }); + + it("forget() empties the record, and the next lease learns its kind again", async () => { + const phone = device("d1", "ready", 0).spec; + const state = await openMemoryState([warmPoolOwner]); + new LearnedKinds(state).learn(phone, "past", now - 2 * minute); + const rig = harness([device("d1", "leased", 0)], { state }); + rig.pool.start(); + + rig.pool.forget(); + + expect(new LearnedKinds(state).kinds(rig.clock.now())).toEqual([]); + granted(rig, "next", "d1"); + expect(new LearnedKinds(state).kinds(rig.clock.now()).map((kind) => kind.count)).toEqual([1]); + }); + + it("starts one catalog read per platform with a learned kind beside a pass, never two at once, forgets a kind whose model, OS, tag image or driver is gone, and keeps a platform's kinds when its read throws or passes 30 s", async () => { + const phone = device("d1", "ready", 0).spec; + const catalogOf = (entry: Partial): PlatformCatalog => ({ + classDefaults: {}, + defaultRuntime: undefined, + modelAliases: {}, + modelClasses: {}, + modelRuntimes: { "iPhone 15": ["26.0"] }, + models: ["iPhone 15"], + platform: "ios", + runtimes: ["26.0"], + ...entry, + }); + const run = async ( + answer: (() => Promise) | undefined, + options: { spec?: VirtualSpec; refused?: boolean } = {}, + ) => { + const state = await openMemoryState([warmPoolOwner]); + new LearnedKinds(state).learn(options.spec ?? phone, "l1", now - minute); + new LearnedKinds(state).ended("l1", now - 30_000); + const listCatalog = vi.fn(async () => answer?.() ?? []); + const rig = harness([device("d1", "ready", 0)], { + catalog: listCatalog, + state, + ...(options.refused === true ? { refusedPlatforms: ["ios" as const] } : {}), + }); + await rig.pool.pass(); + const startedByFirst = listCatalog.mock.calls.length; + await rig.pool.pass(); + await rig.pool.settle(); + return { + calls: [startedByFirst, listCatalog.mock.calls.length], + kinds: new LearnedKinds(state).kinds(rig.clock.now()).length, + listCatalog, + rig, + }; + }; + + const listed = await run(async () => [ + catalogOf({ modelRuntimes: {}, models: [], platform: "android" }), + catalogOf({}), + ]); + expect(listed.kinds).toBe(1); + expect(listed.calls).toEqual([2, 3]); + listed.rig.clock.advance(30_000); + expect( + listed.rig.sink.records.filter( + (record) => record.message === "a warm pool catalog read took too long", + ), + ).toEqual([]); + + const unlistedModel = await run(async () => [catalogOf({ models: [] })]); + expect(unlistedModel.kinds).toBe(0); + expect( + (await run(async () => [catalogOf({ modelRuntimes: { "iPhone 15": ["18.0"] } })])).kinds, + ).toBe(0); + const tagged = { ...phone, imageTag: "google_apis" }; + const images = (tag: string, runtime = "26.0") => [{ abi: "arm64", runtime, tag }]; + expect( + (await run(async () => [catalogOf({ images: images("default") })], { spec: tagged })).kinds, + ).toBe(0); + expect( + (await run(async () => [catalogOf({ images: images("google_apis") })], { spec: tagged })) + .kinds, + ).toBe(1); + expect( + ( + await run(async () => [catalogOf({ images: images("google_apis", "18.0") })], { + spec: tagged, + }) + ).kinds, + ).toBe(0); + const refused = await run(async () => [catalogOf({})], { refused: true }); + expect(refused.kinds).toBe(0); + expect(refused.listCatalog).not.toHaveBeenCalled(); + + const throwing = await run(async () => { + throw new Error("avdmanager failed"); + }); + expect(throwing.kinds).toBe(1); + + const state = await openMemoryState([warmPoolOwner]); + new LearnedKinds(state).learn(phone, "l1", now - minute); + new LearnedKinds(state).ended("l1", now - 30_000); + const releases: ((value: readonly PlatformCatalog[]) => void)[] = []; + const hanging = vi.fn( + () => + new Promise((resolve) => { + releases.push(resolve); + }), + ); + const rig = harness([device("d1", "ready", 0)], { catalog: hanging, state }); + await rig.pool.pass(); + await rig.pool.pass(); + expect(hanging).toHaveBeenCalledTimes(1); + rig.clock.advance(30_000 - 1); + await rig.pool.pass(); + expect(hanging).toHaveBeenCalledTimes(1); + rig.clock.advance(1); + await rig.pool.pass(); + expect(hanging).toHaveBeenCalledTimes(2); + releases[0]?.([catalogOf({ models: [], modelRuntimes: {} })]); + await rig.pool.pass(); + await rig.pool.settle(); + expect(new LearnedKinds(state).kinds(rig.clock.now())).toHaveLength(1); + releases[1]?.([catalogOf({ models: [], modelRuntimes: {} })]); + await rig.pool.pass(); + await rig.pool.settle(); + expect(new LearnedKinds(state).kinds(rig.clock.now())).toHaveLength(0); + }); + + describe("with a learned kind beside the configured targets", () => { + const phone: WarmTarget = { count: 1, model: "iPhone 15", osVersion: "26.0", platform: "ios" }; + const ipad = { + model: "iPad Pro", + osVersion: "26.0", + physical: false, + platform: "ios", + } as const; + const withLearned = async (counts: number[]) => { + const state = await openMemoryState([warmPoolOwner]); + const learned = new LearnedKinds(state); + learned.learn(ipad, "pad", now - minute); + counts.forEach((_, index) => { + learned.learn(device("d1", "ready", 0).spec, `phone-${index}`, now - 2 * minute); + }); + return state; + }; + + it("shuts down the idle device of an older learned kind for a newer one short for a running slot, and logs the reason displaced", async () => { + const rig = harness([device("d1", "ready", 30 * minute)], { + catalog: async () => [iosListing], + limit: 1, + maxConcurrentBoots: 2, + state: await withLearned([1]), + }); + + await rig.pool.pass(); + await rig.pool.settle(); + + expect(rig.shutdownCalls).toEqual(["d1"]); + expect(rig.shutdownArgs).toEqual([["warm-pool", "cleanup"]]); + expect( + rig.sink.records + .filter((record) => record.message === "a warm pool shut a device down") + .map((record) => record.fields), + ).toEqual([{ deviceId: "d1", reason: "displaced" }]); + }); + + it("lists configured targets only in figures() and the short log, with a learned kind short in the same pass", async () => { + const short = harness([], { limit: 0, state: await withLearned([1]), targets: [phone] }); + await short.pool.pass(); + await short.pool.settle(); + const met = harness([device("d1", "ready", 0)], { + limit: 1, + state: await withLearned([1, 2]), + targets: [phone], + }); + await met.pool.pass(); + await met.pool.settle(); + + expect(short.pool.figures().targets).toEqual([ + { + booting: 0, + count: 1, + mode: "full", + model: "iPhone 15", + osVersion: "26.0", + platform: "ios", + ready: 0, + short: "running-limit", + }, + ]); + const shortLogs = short.sink.records.filter( + (record) => record.message === "a warm pool target is short", + ); + expect(shortLogs.map((record) => record.fields?.target)).toEqual(["ios iPhone 15 26.0"]); + expect( + met.pool.figures().targets.map((target) => [target.model, target.ready, target.short]), + ).toEqual([["iPhone 15", 1, undefined]]); + expect( + met.sink.records.filter((record) => record.message === "a warm pool target is short"), + ).toEqual([]); + }); + + it("emits warm-pool.target-missed for a merged entry by its configured count", async () => { + const payloads = (rig: ReturnType): unknown[] => { + const seen: unknown[] = []; + rig.eventBus.subscribe("warm-pool.target-missed", (envelope) => + seen.push(envelope.payload), + ); + return seen; + }; + const met = harness([device("d1", "ready", 0)], { + limit: 1, + state: await withLearned([1, 2]), + targets: [phone], + }); + const metPayloads = payloads(met); + await met.pool.pass(); + await met.pool.settle(); + const empty = harness([], { limit: 0, state: await withLearned([1, 2]), targets: [phone] }); + const emptyPayloads = payloads(empty); + await empty.pool.pass(); + await empty.pool.settle(); + + expect(metPayloads).toEqual([]); + expect(emptyPayloads).toEqual([ + { + count: 1, + mode: "full", + model: "iPhone 15", + osVersion: "26.0", + platform: "ios", + ready: 0, + reason: "running-limit", + }, + ]); + }); + }); + + describe("when the record fails", () => { + const failing = (real: StateDatabase, broken: { value: boolean }): StateDatabase => ({ + close: () => real.close(), + database: { + close: () => real.database.close(), + exec: (sql) => { + if (broken.value) throw new Error("disk I/O error"); + real.database.exec(sql); + }, + prepare: (sql) => { + if (broken.value) throw new Error("disk I/O error"); + return real.database.prepare(sql); + }, + }, + transaction: (work) => { + if (broken.value) throw new Error("disk I/O error"); + return real.transaction(work); + }, + }); + const phone = device("d1", "ready", 0).spec; + const recordWarnings = (rig: ReturnType, what: string) => + rig.sink.records.filter((record) => record.message === `the warm pool's record ${what}`); + + it("logs a LearnedKinds throw once and runs the pass with no learned kinds", async () => { + const real = await openMemoryState([warmPoolOwner]); + new LearnedKinds(real).learn(phone, "l1", now - minute); + const broken = { value: true }; + const rig = harness([device("shut", "shutdown", 60 * minute)], { + state: failing(real, broken), + targets: [{ count: 1, model: "iPhone 15", osVersion: "26.0", platform: "ios" }], + }); + + await rig.pool.pass(); + await rig.pool.settle(); + + expect(rig.bootCalls).toEqual(["shut"]); + const passes = rig.waitingDemand.mock.calls.length; + expect(passes).toBeGreaterThanOrEqual(1); + expect(recordWarnings(rig, "could not be read")).toHaveLength(passes); + expect(recordWarnings(rig, "could not be read")[0]).toMatchObject({ level: "warn" }); + }); + + it("start() survives a closeOpen throw, and the next pass calls closeOpen again and closes the rows once it succeeds", async () => { + const real = await openMemoryState([warmPoolOwner]); + new LearnedKinds(real).learn(phone, "orphan", now - 30 * minute); + const broken = { value: true }; + const rig = harness([device("d1", "leased", 0)], { state: failing(real, broken) }); + + expect(() => rig.pool.start()).not.toThrow(); + expect(recordWarnings(rig, "could not close its open lease rows")).toHaveLength(1); + broken.value = false; + await rig.pool.pass(); + rig.clock.advance(5 * minute); + granted(rig, "again", "d1"); + + expect(new LearnedKinds(real).kinds(rig.clock.now()).map((kind) => kind.count)).toEqual([1]); + + new LearnedKinds(real).learn(phone, "ghost", rig.clock.now()); + await rig.pool.pass(); + + expect( + real.database.prepare("SELECT lease_id FROM warm_kind_leases WHERE ended_at IS NULL").all(), + ).toEqual([{ lease_id: "again" }, { lease_id: "ghost" }]); + }); + }); + + it("forgets a learned kind on its third failed boot or creation in a row with one warning, and a success in between or a forgetting resets the count, and a configured target's kind is never forgotten", async () => { + const phone = device("d1", "ready", 0).spec; + const configured: WarmTarget = { + count: 1, + model: "iPhone 15", + osVersion: "26.0", + platform: "ios", + }; + const run = async ( + outcomes: readonly ("fail" | "ok")[], + creation: boolean, + options: { relearnAt?: number; targets?: WarmTarget[] } = {}, + ) => { + const state = await openMemoryState([warmPoolOwner]); + new LearnedKinds(state).learn(phone, "l1", now - 2 * minute); + new LearnedKinds(state).ended("l1", now - minute); + let attempt = 0; + const next = (): "fail" | "ok" => outcomes[attempt++] ?? "ok"; + const rig: ReturnType = harness( + creation ? [] : [device("shut", "shutdown", 60 * minute)], + { + boot: async (target) => { + if (next() === "fail") throw new Error("simulator did not boot"); + return { ...target, state: "ready" }; + }, + catalog: async () => [iosListing], + provision: async () => { + if (next() === "fail") throw new Error("creation failed"); + }, + state, + ...(options.targets === undefined ? {} : { targets: options.targets }), + }, + ); + for (let round = 0; round < outcomes.length; round += 1) { + if (round === options.relearnAt) { + new LearnedKinds(state).learn(phone, "l2", rig.clock.now() - 2 * minute); + new LearnedKinds(state).ended("l2", rig.clock.now() - minute); + } + await rig.pool.pass(); + await rig.pool.settle(); + rig.clock.advance(10 * minute); + rig.state.devices = rig.state.devices + .filter((item) => !item.id.startsWith("new-")) + .map((item) => ({ ...item, state: "shutdown" as const })); + } + return { + kinds: new LearnedKinds(state).kinds(rig.clock.now()).length, + warnings: rig.sink.records.filter( + (record) => + record.message === + "a warm pool learned kind failed three times in a row and was forgotten", + ), + }; + }; + + for (const creation of [false, true]) { + const third = await run(["fail", "fail", "fail"], creation); + expect(third.kinds, `creation ${creation}`).toBe(0); + expect(third.warnings).toHaveLength(1); + const reset = await run(["fail", "fail", "ok", "fail", "fail"], creation); + expect(reset.kinds, `creation ${creation}`).toBe(1); + expect(reset.warnings).toEqual([]); + const two = await run(["fail", "fail"], creation); + expect(two.kinds, `creation ${creation}`).toBe(1); + const again = await run(["fail", "fail", "fail", "fail"], creation, { relearnAt: 3 }); + expect(again.kinds, `creation ${creation}`).toBe(1); + const kept = await run(["fail", "fail", "fail"], creation, { targets: [configured] }); + expect(kept.kinds, `creation ${creation}`).toBe(1); + expect(kept.warnings).toEqual([]); + } + + const behind = { ...phone, model: "iPhone 16" }; + const waiters = harness([], { + maxConcurrentBoots: 2, + provision: async () => { + throw new Error("creation failed"); + }, + state: await openMemoryState([warmPoolOwner]), + waiting: () => [waiter({ ...phone, model: "iPhone 15" }, true), waiter(behind)], + }); + for (let round = 0; round < 3; round += 1) { + await waiters.pool.pass(); + await waiters.pool.settle(); + waiters.clock.advance(10 * minute); + } + expect(waiters.provisionCalls).toHaveLength(3); + expect( + waiters.sink.records.filter((record) => record.message.includes("was forgotten")), + ).toEqual([]); + }); +}); diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index f71a6d183..6cc573f47 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -1,4 +1,5 @@ import type { EventBus } from "../../bus/index.js"; +import type { StateDatabase } from "../../state/index.js"; import { type Clock, type Logger, NoopLogger, type TimerHandle } from "../../ports/index.js"; import { capacityDevice, @@ -19,6 +20,7 @@ import { type WaitingDemand, } from "../domain.js"; import type { DeviceRequest } from "../driver.js"; +import type { DriverCatalog } from "../driver-catalog.js"; import type { ManagedDeviceLifecycle } from "../managed-device-lifecycle.js"; import type { SerializedDecision } from "../serialized-decision.js"; import { stableError } from "../stable-error.js"; @@ -34,6 +36,8 @@ import { type WarmProposal, } from "./policy.js"; import type { WarmPoolFigures, WarmTargetFigures } from "./figures.js"; +import { CatalogCheck } from "./catalog-check.js"; +import { type LearnedKind, LearnedKinds } from "./learned.js"; import { RetrySchedule } from "./retry.js"; export interface WarmPoolOptions { @@ -61,9 +65,12 @@ export interface WarmPoolOptions { readonly eventBus: Pick; readonly hasDriver: (platform: Platform) => boolean; readonly idle: { readonly shutdownAfterMs: number }; + /** why: the pool reads the catalog of a platform with a learned kind, to forget a kind whose model or runtime is gone. */ + readonly catalog: Pick; readonly lifecycle: Pick; readonly logger?: Logger; readonly provisioner: Pick; + readonly state: StateDatabase; readonly registry: { readonly snapshot: { readonly virtualDevices: readonly VirtualDevice[]; @@ -72,6 +79,9 @@ export interface WarmPoolOptions { }; } +/** why: how many failed boots or creations in a row make the pool give a learned kind up. */ +const LEARNED_FAILURES_LIMIT = 3; + /** 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; @@ -97,11 +107,17 @@ interface Flight { export class WarmPool { readonly #logger: Logger; readonly #unsubscribe: (() => void)[] = []; - /** When a device whose keep boot or shutdown failed may be tried again, by device id. */ + /** why: when a device whose shutdown failed may be tried again, by device id. */ readonly #retryAfter = new Map(); /** When a target's spec whose boot or creation failed may be tried again. */ readonly #schedule = new RetrySchedule(); readonly #flights = new Set(); + readonly #learned: LearnedKinds; + readonly #catalogCheck: CatalogCheck; + /** why: whether the rows left open by a daemon that stopped have been closed against the registry. */ + #openClosed = false; + /** why: whether this pass has already logged that the record could not be read. */ + #readLogged = false; #again = false; #disposed = false; /** A graceful stop is draining: what is in flight finishes, and nothing new starts. */ @@ -137,6 +153,14 @@ export class WarmPool { constructor(private readonly options: WarmPoolOptions) { this.#logger = options.logger?.child("warm-pool") ?? new NoopLogger(); + this.#learned = new LearnedKinds(options.state); + this.#catalogCheck = new CatalogCheck({ + catalog: options.catalog, + clock: options.clock, + hasDriver: options.hasDriver, + logger: this.#logger, + onAnswer: () => this.#trigger(), + }); } start(): void { @@ -145,9 +169,74 @@ export class WarmPool { for (const event of TRIGGERS) { this.#unsubscribe.push(this.options.eventBus.subscribe(event, () => this.#trigger())); } + this.#subscribeLearning(); + this.#closeOpenRows(); this.#armTick(); } + /** why: forgets every learned kind, as nuke starts the pool over; the next lease learns its kind again. */ + forget(): void { + this.#learned.clear(); + } + + /** why: the pool learns from committed facts on the bus, never from the lease path (ADR 0017 §3). */ + #subscribeLearning(): void { + const { clock, eventBus, registry } = this.options; + this.#unsubscribe.push( + eventBus.subscribe("lease.granted", ({ payload }) => { + if (!this.options.config.enabled) return; + const device = registry.snapshot.virtualDevices.find( + (candidate) => candidate.id === payload.deviceId, + ); + if (device === undefined) return; + this.#recording("learn a lease", () => + this.#learned.learn(device.spec, payload.leaseId, clock.now()), + ); + }), + ); + for (const event of ["lease.released", "lease.expired"] as const) { + this.#unsubscribe.push( + eventBus.subscribe(event, ({ payload }) => + this.#recording("close a lease", () => this.#learned.ended(payload.leaseId, clock.now())), + ), + ); + } + } + + /** why: a failing record costs the pool what it learns, never a lease or a pass: the error is logged and the work goes on. */ + #recording(step: string, work: () => void): void { + try { + work(); + } catch (error: unknown) { + this.#logger.warn(`the warm pool's record could not ${step}`, { error: stableError(error) }); + } + } + + /** why: closes the lease rows no lease holds, once; a failure leaves them for the next pass to try again. */ + #closeOpenRows(): void { + if (this.#openClosed || !this.#started) return; + const held = new Set(this.options.registry.snapshot.leases.map((lease) => lease.id)); + this.#recording("close its open lease rows", () => { + this.#learned.closeOpen(held, this.options.clock.now()); + this.#openClosed = true; + }); + } + + /** why: the learned kinds, or none when the record cannot be read; the failure is logged once per pass. */ + #learnedKinds(): LearnedKind[] { + try { + return this.#learned.kinds(this.options.clock.now()); + } catch (error: unknown) { + if (!this.#readLogged) { + this.#logger.warn("the warm pool's record could not be read", { + error: stableError(error), + }); + } + this.#readLogged = true; + return []; + } + } + dispose(): void { this.#disposed = true; for (const unsubscribe of this.#unsubscribe.splice(0)) unsubscribe(); @@ -210,6 +299,7 @@ export class WarmPool { devices, isClaimed: (deviceId) => this.options.claims.isClaimed(deviceId), leases, + learned: this.#learnedKinds(), targets: [...this.#resolved, ...this.#spared], }); } @@ -233,8 +323,10 @@ export class WarmPool { const kind = this.#kindOfTarget(target); return { booting: 0, + configuredCount: target.count, count: target.count, kind, + origin: "configured", ready: 0, target: describeTarget(target), ...(enabled ? {} : { short: "disabled" as const }), @@ -280,21 +372,33 @@ export class WarmPool { } while (this.#again); } + /** why: whatever is shut down under a reset, an iOS device its forced release left that way included, is meant to stay down. */ + #markReset(): void { + for (const device of this.options.registry.snapshot.virtualDevices) { + if (device.state === "shutdown") this.#reset.add(device.id); + } + } + + /** why: a pool that is off keeps no target: nothing is resolved, reported, checked or spared. */ + async #resolveEnabled(): Promise { + if (!this.options.config.enabled) return []; + const refused = await this.#resolveTargets(); + this.#checkCatalog(); + return refused; + } + async #once(): Promise { if (this.#draining) return; if (this.options.acquisition.maintenanceActive) { - // Whatever is shut down under a reset, an iOS device its forced release left that way - // included, is meant to stay down. - for (const device of this.options.registry.snapshot.virtualDevices) { - if (device.state === "shutdown") this.#reset.add(device.id); - } + this.#markReset(); return; } + this.#readLogged = false; + this.#closeOpenRows(); try { - // A pool that is off keeps no target: nothing is resolved, reported or spared. - const refused = this.options.config.enabled ? await this.#resolveTargets() : []; + const refused = await this.#resolveEnabled(); const plan = await this.options.decisions.run(() => evaluate(this.#view())); - const reports = [...refused, ...plan.targets]; + const reports = configuredOnly([...refused, ...plan.targets]); this.#note(reports); for (const proposal of plan.proposals) { if (this.#draining) break; @@ -307,6 +411,20 @@ export class WarmPool { } } + /** why: forgets the kinds the last catalog answers no longer list, then starts the next reads without waiting for them. */ + #checkCatalog(): void { + const kinds = this.#learnedKinds(); + for (const kind of this.#catalogCheck.gone(kinds)) { + this.#recording("forget a kind", () => this.#learned.forget(kind.spec)); + this.#logger.info("a warm pool learned kind was forgotten: its model or runtime is gone", { + model: kind.spec.model, + osVersion: kind.spec.osVersion, + platform: kind.spec.platform, + }); + } + this.#catalogCheck.start(new Set(kinds.map((kind) => kind.spec.platform))); + } + /** * Resolves every target the way a request is resolved. Per pass, so a runtime installed since * the last one takes effect without a restart. Returns the reports of the targets that were @@ -346,9 +464,11 @@ export class WarmPool { last === undefined ? 0 : [...this.#flights].filter((flight) => sameSpec(flight.spec, last)).length, + configuredCount: target.count, count: target.count, kind: this.#kindOfTarget(target), message: resolution.message, + origin: "configured", ready: last === undefined ? 0 : readyCount(this.#deviceCounts(), last), short: resolution.refusal, target: describeTarget(target), @@ -452,16 +572,20 @@ export class WarmPool { // unfiltered: the device holds its slot, or the pool would see a free one and over-subscribe. const devices = all.filter((device) => this.options.hasDriver(device.spec.platform)); const everyDevice = capacityDevices(all); + const learned = this.#learnedKinds(); return { admit: { - boot: (device) => { - const decision = this.options.capacity.canBoot(capacityDevice(device), everyDevice); + boot: (device, down) => { + const decision = this.options.capacity.canBoot( + capacityDevice(device), + down === undefined ? everyDevice : capacityDevices(shutDownIn(all, down)), + ); return decision.ok ? undefined : decision.reason; }, - create: (spec) => { + create: (spec, down) => { const decision = this.options.capacity.canProvision( plannedCapacityDevice(spec), - everyDevice, + down === undefined ? everyDevice : capacityDevices(shutDownIn(all, down)), ); return decision.ok ? undefined : decision.reason; }, @@ -481,6 +605,7 @@ export class WarmPool { ), inFlight: [...this.#flights].map((flight) => flight.spec), isClaimed: (deviceId) => this.options.claims.isClaimed(deviceId), + learned, leases, now: this.options.clock.now(), onItsWay: this.#onItsWay(devices), @@ -488,6 +613,7 @@ export class WarmPool { retry: this.#schedule, spared: this.#spared, targets: this.#resolved, + unplanned: this.#catalogCheck.unanswered(learned).map((kind) => kind.spec), waiting: this.options.acquisition.waitingDemand(), }; } @@ -527,21 +653,14 @@ export class WarmPool { this.#launch(proposal.target, true, () => this.#provision(proposal.spec, proposal.target)); return; } - // why: a failed keep boot releases its reservation, which changes capacity and so triggers the next - // 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 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 ( - owner === undefined && - (this.#retryAfter.get(proposal.deviceId) ?? 0) > this.options.clock.now() - ) { + if (proposal.action === "shutdown") { + // why: a failed shutdown frees nothing, but any other trigger that comes soon would propose it again, so it is held back for a tick. A boot is held back by the retry schedule, which the policy reads before it proposes one. + if ((this.#retryAfter.get(proposal.deviceId) ?? 0) > this.options.clock.now()) return; + await this.#shutdown(proposal.deviceId, proposal.reason); return; } - if (proposal.action === "shutdown") await this.#shutdown(proposal.deviceId); - else if (owner === undefined) await this.#boot(proposal.deviceId, undefined); - else this.#launch(owner, false, () => this.#boot(proposal.deviceId, owner)); + const owner = this.#ownerOf(proposal); + if (owner !== undefined) 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. */ @@ -582,23 +701,25 @@ export class WarmPool { }); } - async #shutdown(deviceId: string): Promise { + async #shutdown(deviceId: string, reason: string): Promise { const device = await this.options.decisions.run(() => this.#unleased(deviceId, "ready")); if (device === undefined) return; try { const done = await this.options.lifecycle.shutdown(device, "warm-pool", "cleanup"); if (done === undefined) return; + // why: `device.shutdown` carries no reason, so the daemon log is where a shutdown is attributed (safety rule 6). + this.#logger.info("a warm pool shut a device down", { deviceId, reason }); } catch (error: unknown) { - this.#logFailure(device, "shutdown", error, true); + this.#logFailure(device, "shutdown", error); } this.options.acquisition.kick(); } /** - * Boots a shut-down device; for a target, also reports the outcome to the failure schedule. + * why: boots a shut-down device and reports the outcome to the failure schedule of its owner. * Whether a boot was attempted: not when the device is no longer there to boot. */ - async #boot(deviceId: string, target: VirtualSpec | undefined): Promise { + async #boot(deviceId: string, target: VirtualSpec): Promise { const held = await this.options.decisions.run(() => { const device = this.#unleased(deviceId, "shutdown"); if (device === undefined) return undefined; @@ -618,10 +739,10 @@ export class WarmPool { try { const done = await this.options.lifecycle.bootWarm(held.device, held.claim); if (done === undefined) return false; - if (target !== undefined) this.#schedule.succeeded(target); + this.#schedule.succeeded(target); } catch (error: unknown) { - this.#logFailure(held.device, "boot", error, target === undefined); - if (target !== undefined) this.#failed(target); + this.#logFailure(held.device, "boot", error); + this.#failed(target); } finally { await this.options.decisions.run(() => { held.claim.release(); @@ -669,6 +790,16 @@ export class WarmPool { /** Remembers the failure; the pass the ended flight asks for arms the timer for the retry. */ #failed(target: VirtualSpec): void { this.#schedule.failed(target, this.options.clock.now()); + if (this.#schedule.failures(target) < LEARNED_FAILURES_LIMIT) return; + if (this.#resolved.some((configured) => sameSpec(configured.spec, target))) return; + if (!this.#learnedKinds().some((kind) => sameSpec(kind.spec, target))) return; + this.#recording("forget a kind", () => this.#learned.forget(target)); + this.#schedule.succeeded(target); + this.#logger.warn("a warm pool learned kind failed three times in a row and was forgotten", { + model: target.model, + osVersion: target.osVersion, + platform: target.platform, + }); } /** The device, when it is still in `state`, has no lease and no operation claim on it. */ @@ -685,17 +816,10 @@ export class WarmPool { return device; } - /** - * Logs a failed step. Only a keep boot or a shutdown pauses its device: a target's boot is held - * back by the retry schedule alone, so a keep boot of that device is not dropped for it. - */ - #logFailure( - device: VirtualDevice, - step: "shutdown" | "boot", - error: unknown, - pause: boolean, - ): void { - if (pause) this.#retryAfter.set(device.id, this.options.clock.now() + WARM_POOL_TICK_MS); + /** why: only a shutdown pauses its device; a boot is held back by the retry schedule alone. */ + #logFailure(device: VirtualDevice, step: "shutdown" | "boot", error: unknown): void { + if (step === "shutdown") + this.#retryAfter.set(device.id, this.options.clock.now() + WARM_POOL_TICK_MS); this.#logger.warn(`warm pool ${step} of a device failed`, { deviceId: device.id, step, @@ -704,6 +828,29 @@ export class WarmPool { } } +/** why: `devices` with the ones in `down` as they are once shut down, for a capacity question about the plan so far. */ +function shutDownIn(devices: readonly VirtualDevice[], down: ReadonlySet): VirtualDevice[] { + return devices.map((device) => (down.has(device.id) ? { ...device, state: "shutdown" } : device)); +} + +/** + * why: status, the short log and `warm-pool.target-missed` describe the operator's targets only in + * this version, so a learned kind's report is left out and a merged entry is judged by the + * configured count: a configured target that is met is not short however short the learned count is. + */ +function configuredOnly(reports: readonly TargetReport[]): TargetReport[] { + return reports + .filter((report) => report.origin === "configured") + .map((report) => { + if (report.count === report.configuredCount) return report; + const { short: _short, ...rest } = report; + const merged = { ...rest, count: report.configuredCount }; + return report.ready >= report.configuredCount || report.short === undefined + ? merged + : { ...merged, short: report.short }; + }); +} + /** A report as `figures()` lists it: the kind, the numbers and the reason, never the message. */ function figureOf(report: TargetReport): WarmTargetFigures { return { diff --git a/src/core/warm-pool/index.ts b/src/core/warm-pool/index.ts index 1ec2b7c0b..195fff8b0 100644 --- a/src/core/warm-pool/index.ts +++ b/src/core/warm-pool/index.ts @@ -1,4 +1,5 @@ export { WarmPool } from "./converger.js"; +export { warmPoolOwner } from "./learned.js"; export { defaultWarmPoolConfig, warmPoolConfigValidator } from "./config.js"; export type { WarmPoolConfig } from "./config.js"; export type { WarmPoolFigures, WarmTargetFigures } from "./figures.js"; diff --git a/src/core/warm-pool/learned.test.ts b/src/core/warm-pool/learned.test.ts new file mode 100644 index 000000000..5788c0e57 --- /dev/null +++ b/src/core/warm-pool/learned.test.ts @@ -0,0 +1,230 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +import { NodeFilesystem, NodeSqliteOpener, NoopLogger } from "../../ports/index.js"; +import { openStateDatabase } from "../../state/index.js"; +import type { VirtualSpec } from "../domain.js"; +import { openMemoryState } from "../testing.js"; +import { LearnedKinds, warmPoolOwner } from "./learned.js"; + +const HOUR = 3_600_000; +const T0 = 1_000 * HOUR; + +function spec(model: string, extra: Partial = {}): VirtualSpec { + return { model, osVersion: "18.4", physical: false, platform: "ios", ...extra }; +} + +async function open() { + const state = await openMemoryState([warmPoolOwner]); + return { kinds: new LearnedKinds(state), state }; +} + +const directories: string[] = []; + +afterEach(async () => { + await Promise.all( + directories.splice(0).map((path) => rm(path, { force: true, recursive: true })), + ); +}); + +describe("LearnedKinds", () => { + it("counts a kind's peak over the last 24 hours, at least one, lists the newest last lease first, and keeps a full untagged kind leased twice as one row", async () => { + const phone = spec("iPhone 16"); + const cases: readonly { + readonly name: string; + readonly run: (kinds: LearnedKinds) => number; + readonly count: number; + readonly rows?: number; + }[] = [ + { + count: 3, + name: "three overlapping leases", + run: (kinds) => { + kinds.learn(phone, "a", T0); + kinds.learn(phone, "b", T0 + 1); + kinds.learn(phone, "c", T0 + 2); + return T0 + 10; + }, + }, + { + count: 2, + name: "a lease granted at the instant of the read beside a held one", + run: (kinds) => { + kinds.learn(phone, "a", T0); + kinds.learn(phone, "b", T0 + 10); + return T0 + 10; + }, + }, + { + count: 1, + name: "two in sequence", + run: (kinds) => { + kinds.learn(phone, "a", T0); + kinds.ended("a", T0 + 5); + kinds.learn(phone, "b", T0 + 5); + return T0 + 10; + }, + }, + { + count: 1, + name: "one granted 25 hours ago and still held", + run: (kinds) => { + kinds.learn(phone, "a", T0 - 25 * HOUR); + return T0; + }, + }, + { + count: 1, + name: "one ended 24 hours and 1 ms ago beside a held one", + run: (kinds) => { + kinds.learn(phone, "old", T0 - 25 * HOUR); + kinds.learn(phone, "held", T0 - 25 * HOUR + 50); + kinds.ended("old", T0 - 24 * HOUR - 1); + return T0; + }, + }, + { + count: 2, + name: "two overlapping leases, one of them ended inside the window", + run: (kinds) => { + kinds.learn(phone, "old", T0 - 25 * HOUR); + kinds.learn(phone, "held", T0 - 25 * HOUR + 50); + kinds.ended("old", T0 - 24 * HOUR + 1); + return T0 - 24 * HOUR + 1; + }, + }, + { + count: 1, + name: "no lease rows left", + rows: 1, + run: (kinds) => { + kinds.learn(phone, "old", T0 - 30 * HOUR); + kinds.ended("old", T0 - 29 * HOUR); + kinds.learn(spec("iPad Pro"), "other", T0); + return T0; + }, + }, + ]; + + for (const { count, name, rows, run } of cases) { + const { kinds, state } = await open(); + const now = run(kinds); + if (rows !== undefined) { + expect( + state.database.prepare("SELECT COUNT(*) AS n FROM warm_kind_leases").get()?.n, + name, + ).toBe(rows); + } + expect(kinds.kinds(now).find((kind) => kind.spec.model === "iPhone 16")?.count, name).toBe( + count, + ); + } + + const { kinds } = await open(); + kinds.learn(phone, "a", T0); + kinds.learn(spec("iPad Pro"), "b", T0 + 10); + kinds.learn(phone, "c", T0 + 20); + kinds.learn(spec("iPhone 16", { mode: "slim" }), "d", T0 + 5); + expect( + kinds.kinds(T0 + 30).map((kind) => [kind.spec.model, kind.spec.mode, kind.lastLeasedAt]), + ).toEqual([ + ["iPhone 16", undefined, T0 + 20], + ["iPad Pro", undefined, T0 + 10], + ["iPhone 16", "slim", T0 + 5], + ]); + }); + + it("keeps at most 32 kinds per platform, dropping the oldest by last lease with its lease rows, and counts the other platform apart", async () => { + const leaseRows = (state: Awaited>["state"]): number => + Number(state.database.prepare("SELECT COUNT(*) AS n FROM warm_kind_leases").get()?.n); + const { kinds, state } = await open(); + for (let index = 0; index < 32; index += 1) { + kinds.learn(spec(`Phone ${String(index)}`), `lease-${String(index)}`, T0 + index); + } + kinds.learn(spec("Pixel", { platform: "android" }), "lease-pixel", T0 + 40); + + expect(kinds.kinds(T0 + 50)).toHaveLength(33); + expect(leaseRows(state)).toBe(33); + + kinds.learn(spec("Phone 32"), "lease-32", T0 + 41); + + const after = kinds.kinds(T0 + 50); + expect(after).toHaveLength(33); + expect(after.some((kind) => kind.spec.model === "Phone 0")).toBe(false); + expect(after.some((kind) => kind.spec.model === "Phone 1")).toBe(true); + expect(after.some((kind) => kind.spec.platform === "android")).toBe(true); + expect(leaseRows(state)).toBe(33); + }); + + it("survives a reopen of the same file, and forget and clear remove the rows", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-learned-")); + directories.push(directory); + const openFile = () => + openStateDatabase({ + dataDirectory: directory, + filesystem: new NodeFilesystem(), + logger: new NoopLogger(), + oldFiles: [], + owners: [warmPoolOwner], + sqlite: new NodeSqliteOpener(), + upgradeStep: "", + }); + const first = await openFile(); + const written = new LearnedKinds(first); + written.learn(spec("iPhone 16"), "a", T0); + written.learn(spec("iPad Pro"), "b", T0 + 1); + first.close(); + + const second = await openFile(); + const reopened = new LearnedKinds(second); + expect(reopened.kinds(T0 + 5).map((kind) => kind.spec.model)).toEqual([ + "iPad Pro", + "iPhone 16", + ]); + + reopened.forget(spec("iPad Pro")); + expect(reopened.kinds(T0 + 5).map((kind) => kind.spec.model)).toEqual(["iPhone 16"]); + expect( + Number(second.database.prepare("SELECT COUNT(*) AS n FROM warm_kind_leases").get()?.n), + ).toBe(1); + + reopened.clear(); + expect(reopened.kinds(T0 + 5)).toEqual([]); + expect( + Number(second.database.prepare("SELECT COUNT(*) AS n FROM warm_kind_leases").get()?.n), + ).toBe(0); + second.close(); + }); + + it("warmPoolOwner version 1 creates both STRICT tables with their columns", async () => { + const { state } = await open(); + const table = (name: string) => + state.database.prepare("SELECT sql FROM sqlite_master WHERE name = ?").get(name)?.sql; + const columns = (name: string) => + state.database + .prepare(`SELECT name, type, "notnull" AS required FROM pragma_table_info('${name}')`) + .all() + .map((column) => [column.name, column.type, column.required]); + + expect(warmPoolOwner.version).toBe(1); + expect(String(table("warm_kinds"))).toMatch(/STRICT/); + expect(String(table("warm_kind_leases"))).toMatch(/STRICT/); + expect(columns("warm_kinds")).toEqual([ + ["id", "INTEGER", 0], + ["platform", "TEXT", 1], + ["model", "TEXT", 1], + ["os_version", "TEXT", 1], + ["mode", "TEXT", 1], + ["image_tag", "TEXT", 1], + ["last_leased_at", "INTEGER", 1], + ]); + expect(columns("warm_kind_leases")).toEqual([ + ["lease_id", "TEXT", 1], + ["kind_id", "INTEGER", 1], + ["granted_at", "INTEGER", 1], + ["ended_at", "INTEGER", 0], + ]); + }); +}); diff --git a/src/core/warm-pool/learned.ts b/src/core/warm-pool/learned.ts new file mode 100644 index 000000000..682c815a8 --- /dev/null +++ b/src/core/warm-pool/learned.ts @@ -0,0 +1,192 @@ +import type { SqliteDatabase, SqliteSchemaOwner } from "../../ports/index.js"; +import type { StateDatabase } from "../../state/index.js"; +import type { Platform, VirtualSpec } from "../domain.js"; + +const WARM_POOL_V1 = ` +CREATE TABLE warm_kinds ( + id INTEGER PRIMARY KEY, + platform TEXT NOT NULL, + model TEXT NOT NULL, + os_version TEXT NOT NULL, + mode TEXT NOT NULL, + image_tag TEXT NOT NULL, + last_leased_at INTEGER NOT NULL, + UNIQUE (platform, model, os_version, mode, image_tag) +) STRICT; + +CREATE TABLE warm_kind_leases ( + lease_id TEXT PRIMARY KEY, + kind_id INTEGER NOT NULL REFERENCES warm_kinds (id), + granted_at INTEGER NOT NULL, + ended_at INTEGER +) STRICT; +`; + +export const warmPoolOwner: SqliteSchemaOwner = { + migrations: [WARM_POOL_V1], + name: "warm-pool", + version: 1, +}; + +const LEARNED_WINDOW_MS = 24 * 60 * 60 * 1000; + +const LEARNED_KINDS_PER_PLATFORM = 32; + +export interface LearnedKind { + readonly spec: VirtualSpec; + readonly count: number; + readonly lastLeasedAt: number; +} + +/** + * why: the record of the kinds this worker granted a lease of and the leases that make up each + * one's peak. It stores no device id, so the registry and this record never need to agree. Every + * method lets a database error through: the converger decides what a failed read or write costs. + */ +export class LearnedKinds { + readonly #state: StateDatabase; + + constructor(state: StateDatabase) { + this.#state = state; + } + + learn(spec: VirtualSpec, leaseId: string, at: number): void { + this.#state.transaction(() => { + const database = this.#state.database; + const row = database + .prepare( + `INSERT INTO warm_kinds (platform, model, os_version, mode, image_tag, last_leased_at) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (platform, model, os_version, mode, image_tag) + DO UPDATE SET last_leased_at = excluded.last_leased_at + RETURNING id`, + ) + .get( + spec.platform, + spec.model, + spec.osVersion, + spec.mode ?? "full", + spec.imageTag ?? "", + at, + ); + database + .prepare( + "INSERT OR REPLACE INTO warm_kind_leases (lease_id, kind_id, granted_at, ended_at) VALUES (?, ?, ?, NULL)", + ) + .run(leaseId, Number(row?.id), at); + database + .prepare("DELETE FROM warm_kind_leases WHERE ended_at < ?") + .run(at - LEARNED_WINDOW_MS); + const surplus = database + .prepare( + "SELECT id FROM warm_kinds WHERE platform = ? ORDER BY last_leased_at DESC, id DESC LIMIT -1 OFFSET ?", + ) + .all(spec.platform, LEARNED_KINDS_PER_PLATFORM); + for (const { id } of surplus) { + database.prepare("DELETE FROM warm_kind_leases WHERE kind_id = ?").run(Number(id)); + database.prepare("DELETE FROM warm_kinds WHERE id = ?").run(Number(id)); + } + }); + } + + ended(leaseId: string, at: number): void { + this.#state.database + .prepare("UPDATE warm_kind_leases SET ended_at = ? WHERE lease_id = ? AND ended_at IS NULL") + .run(at, leaseId); + } + + /** why: a lease that ended while no daemon ran has no end event, so startup closes the rows the registry no longer holds. */ + closeOpen(heldLeaseIds: ReadonlySet, at: number): void { + this.#state.transaction(() => { + const database = this.#state.database; + for (const { lease_id: leaseId } of database + .prepare("SELECT lease_id FROM warm_kind_leases WHERE ended_at IS NULL") + .all()) { + if (!heldLeaseIds.has(String(leaseId))) this.ended(String(leaseId), at); + } + }); + } + + forget(spec: VirtualSpec): void { + this.#state.transaction(() => { + const database = this.#state.database; + const where = "platform = ? AND model = ? AND os_version = ? AND mode = ? AND image_tag = ?"; + const key = [ + spec.platform, + spec.model, + spec.osVersion, + spec.mode ?? "full", + spec.imageTag ?? "", + ]; + database + .prepare( + `DELETE FROM warm_kind_leases WHERE kind_id IN (SELECT id FROM warm_kinds WHERE ${where})`, + ) + .run(...key); + database.prepare(`DELETE FROM warm_kinds WHERE ${where}`).run(...key); + }); + } + + clear(): void { + this.#state.transaction(() => { + this.#state.database.exec("DELETE FROM warm_kind_leases"); + this.#state.database.exec("DELETE FROM warm_kinds"); + }); + } + + kinds(now: number): LearnedKind[] { + const database: SqliteDatabase = this.#state.database; + const windowStart = now - LEARNED_WINDOW_MS; + return database + .prepare( + "SELECT id, platform, model, os_version, mode, image_tag, last_leased_at FROM warm_kinds ORDER BY last_leased_at DESC, id DESC", + ) + .all() + .map((row) => { + const leases = database + .prepare("SELECT granted_at, ended_at FROM warm_kind_leases WHERE kind_id = ?") + .all(Number(row.id)) + .map((lease) => ({ + end: lease.ended_at === null ? undefined : Number(lease.ended_at), + start: Math.max(Number(lease.granted_at), windowStart), + })); + return { + count: Math.max(1, peakOverlap(leases, windowStart)), + lastLeasedAt: Number(row.last_leased_at), + spec: specOf(row), + }; + }); + } +} + +// why: a lease still held has no end, so one granted this instant counts beside the others instead of closing as it opens. +function peakOverlap( + intervals: readonly { readonly start: number; readonly end: number | undefined }[], + floor: number, +): number { + const edges = intervals + .filter((interval) => interval.end === undefined || interval.end > floor) + .flatMap((interval) => [ + { at: interval.start, delta: 1 }, + ...(interval.end === undefined ? [] : [{ at: interval.end, delta: -1 }]), + ]) + .sort((left, right) => left.at - right.at || left.delta - right.delta); + let open = 0; + let peak = 0; + for (const edge of edges) { + open += edge.delta; + peak = Math.max(peak, open); + } + return peak; +} + +function specOf(row: Record): VirtualSpec { + return { + model: String(row.model), + osVersion: String(row.os_version), + physical: false, + platform: String(row.platform) as Platform, + ...(row.mode === "slim" ? { mode: "slim" as const } : {}), + ...(row.image_tag === "" ? {} : { imageTag: String(row.image_tag) }), + }; +} diff --git a/src/core/warm-pool/policy.test.ts b/src/core/warm-pool/policy.test.ts index af1e63560..017374d69 100644 --- a/src/core/warm-pool/policy.test.ts +++ b/src/core/warm-pool/policy.test.ts @@ -56,6 +56,14 @@ function device( }; } +function learnedOf( + learnedSpec: VirtualSpec, + count = 1, + lastLeasedAt = now, +): WarmPolicyView["learned"][number] { + return { count, lastLeasedAt, spec: learnedSpec }; +} + function leaseOn(target: VirtualDevice): LeaseRecord { return { deviceId: target.id, @@ -147,25 +155,33 @@ function view( reset?: readonly string[]; targets?: readonly ResolvedTarget[]; spared?: readonly ResolvedTarget[]; + learned?: WarmPolicyView["learned"]; inFlight?: readonly VirtualSpec[]; onItsWay?: WarmPolicyView["onItsWay"]; maxConcurrentBoots?: number; blocked?: readonly VirtualSpec[]; refuseProvision?: CapacityRefusalReason; refuseBoot?: CapacityRefusalReason; + /** why: a creation the capacity strategy refuses until the plan has shut a device down. */ + refuseProvisionUntilDown?: CapacityRefusalReason; + unplanned?: readonly VirtualSpec[]; } = {}, ): WarmPolicyView { return { admit: { boot: () => options.refuseBoot, - create: () => options.refuseProvision, + create: (_spec, down) => + options.refuseProvision ?? + ((down?.size ?? 0) === 0 ? options.refuseProvisionUntilDown : undefined), }, + unplanned: options.unplanned ?? [], inFlight: options.inFlight ?? [], onItsWay: options.onItsWay ?? [], retry: { mayAttempt: (target) => !(options.blocked ?? []).some((held) => sameSpec(held, target)), }, spared: options.spared ?? [], + learned: options.learned ?? [], targets: options.targets ?? [], capacity: capacityOf( devices, @@ -348,8 +364,6 @@ describe("warm pool policy", () => { // Full first: a check that refuses only slim-for-full would pick `full` here. const forSlim = evaluate(view([full, slim], { waiting: [classDemand("slim")], limit: 5 })); - // `reason` tells the waiting-request boot from the recently-released one: both devices were - // released a moment ago, so each is booted back either way once a slot is free. expect(forFull.find((item) => item.reason === "waiting-request")).toEqual({ action: "boot", deviceId: "full", @@ -439,24 +453,16 @@ describe("warm pool policy", () => { ]); }); - it("does not boot a shut-down device released longer ago than idle.shutdownAfterMs without a waiting request", () => { - const stale = device("stale", "shutdown", { endedAgo: shutdownAfterMs }); - const fresh = device("fresh", "shutdown", { endedAgo: shutdownAfterMs - 1 }); - const neverLeased = device("never", "shutdown"); - - const proposals = evaluate(view([stale, fresh, neverLeased])); - - expect(proposals).toEqual([{ action: "boot", deviceId: "fresh", reason: "recently-released" }]); - }); - - it("with room for one boot and two recently released shut-down devices, proposes the more recently released one", () => { - const earlier = device("earlier", "shutdown", { endedAgo: 4 * minute }); - const later = device("later", "shutdown", { endedAgo: 1 * minute }); - const busy = device("busy", "leased"); - - const proposals = evaluate(view([earlier, later, busy], { limit: 2 })); + it("proposes no boot back of a shut-down device released a moment ago whose kind is not learned", () => { + const fresh = device("fresh", "shutdown", { endedAgo: 1_000 }); + const later = device("later", "shutdown", { endedAgo: minute }); - expect(proposals).toEqual([{ action: "boot", deviceId: "later", reason: "recently-released" }]); + expect(evaluate(view([fresh, later], { limit: 5 }))).toEqual([]); + expect( + evaluate( + view([fresh, later], { learned: [{ count: 1, lastLeasedAt: now, spec: fresh.spec }] }), + ), + ).toEqual([{ action: "boot", deviceId: "fresh", reason: "target", target: fresh.spec }]); }); it("boots a device for a waiting request before one that was merely released recently", () => { @@ -471,20 +477,20 @@ describe("warm pool policy", () => { expect(proposals).toEqual([{ action: "boot", deviceId: "serving", reason: "waiting-request" }]); }); - it("holds the free slot for a waiting request no idle device serves instead of booting a recently released device into it", () => { + it("holds the free slot for a waiting request no idle device serves instead of booting a learned kind's device into it", () => { const recent = device("recent", "shutdown", { endedAgo: 1_000, spec: spec("iPad Pro") }); const busy = device("busy", "leased"); const unserved = classDemand("full", "android"); const served = device("served", "ready", { endedAgo: 1_000 }); - expect(evaluate(view([recent, busy], { limit: 2, waiting: [unserved] }))).toEqual([]); - expect(evaluate(view([recent, busy], { limit: 2 }))).toEqual([ - { action: "boot", deviceId: "recent", reason: "recently-released" }, - ]); - // A request an idle ready device serves takes no free slot. - expect(evaluate(view([recent, busy, served], { limit: 3, waiting: [classDemand()] }))).toEqual([ - { action: "boot", deviceId: "recent", reason: "recently-released" }, - ]); + const learned = [learnedOf(recent.spec)]; + const boot = { action: "boot", deviceId: "recent", reason: "target", target: recent.spec }; + + expect(evaluate(view([recent, busy], { learned, limit: 2, waiting: [unserved] }))).toEqual([]); + expect(evaluate(view([recent, busy], { learned, limit: 2 }))).toEqual([boot]); + expect( + evaluate(view([recent, busy, served], { learned, limit: 3, waiting: [classDemand()] })), + ).toEqual([boot]); }); 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", () => { @@ -519,7 +525,7 @@ describe("warm pool policy", () => { ).toEqual([boot("phone")]); }); - it("proposes no boot that admit.boot refuses for ram-budget, for a waiter or a recently released device, and holds the waiter's slot", () => { + it("proposes no boot that admit.boot refuses for ram-budget, for a waiter or a learned kind's 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") }); @@ -540,19 +546,20 @@ describe("warm pool policy", () => { { 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" }, + const learned = [learnedOf(recent.spec)]; + expect(evaluate(view([recent], { learned, limit: 3 }))).toEqual([ + { action: "boot", deviceId: "recent", reason: "target", target: recent.spec }, ]); - expect(evaluate(view([recent], { limit: 3, refuseBoot: "ram-budget" }))).toEqual([]); + expect(evaluate(view([recent], { learned, 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", () => { + it("does not boot back a device an operator reset shut down for a learned kind, though it was released a moment ago", () => { const reset = device("reset", "shutdown", { endedAgo: 1_000 }); const other = device("other", "shutdown", { endedAgo: 2_000 }); - expect(evaluate(view([reset, other], { reset: ["reset"] }))).toEqual([ - { action: "boot", deviceId: "other", reason: "recently-released" }, - ]); + expect( + evaluate(view([reset, other], { learned: [learnedOf(reset.spec)], reset: ["reset"] })), + ).toEqual([{ action: "boot", deviceId: "other", reason: "target", target: reset.spec }]); }); it("does not let a request whose device work is in flight shield an idle ready device it serves from an over-budget shutdown", () => { @@ -646,51 +653,58 @@ describe("warm pool policy", () => { const devices = [tablet]; // The request wants a phone, which no device serves, and the only iOS slot is its own. + const learned = [learnedOf(tablet.spec)]; const held = evaluate({ - ...view(devices, { waiting: [classDemand()] }), + ...view(devices, { learned, waiting: [classDemand()] }), capacity: capacityOf(devices, { global: 5, ios: 1 }), }); const free = evaluate({ - ...view(devices), + ...view(devices, { learned }), capacity: capacityOf(devices, { global: 5, ios: 1 }), }); expect(held).toEqual([]); - expect(free).toEqual([{ action: "boot", deviceId: "tablet", reason: "recently-released" }]); + expect(free).toEqual([ + { action: "boot", deviceId: "tablet", reason: "target", target: tablet.spec }, + ]); }); - it("proposes a device that serves a waiting request once, not again as a recently released one", () => { + it("proposes a device that serves a waiting request once, not again for a learned kind", () => { const serving = device("serving", "shutdown", { endedAgo: 1_000 }); const other = device("other", "shutdown", { endedAgo: 2_000, spec: spec("iPad Pro") }); - const proposals = evaluate(view([serving, other], { waiting: [classDemand()] })); + const proposals = evaluate( + view([serving, other], { + learned: [learnedOf(serving.spec), learnedOf(other.spec)], + maxConcurrentBoots: 3, + waiting: [classDemand()], + }), + ); expect(proposals).toEqual([ { action: "boot", deviceId: "serving", reason: "waiting-request" }, - { action: "boot", deviceId: "other", reason: "recently-released" }, + { action: "boot", deviceId: "other", reason: "target", target: other.spec }, ]); }); - it("boots only as many recently released devices as the tighter of the global and the platform room allows", () => { + it("boots only as many of a learned kind's devices as the tighter of the global and the platform room allows", () => { const first = device("first", "shutdown", { endedAgo: 1_000 }); const second = device("second", "shutdown", { endedAgo: 2_000 }); const devices = [first, second]; + const learned = [learnedOf(first.spec, 2)]; const globalTight = evaluate({ - ...view(devices), + ...view(devices, { learned, maxConcurrentBoots: 2 }), capacity: capacityOf(devices, { global: 1, ios: 5 }), }); const platformTight = evaluate({ - ...view(devices), + ...view(devices, { learned, maxConcurrentBoots: 2 }), capacity: capacityOf(devices, { global: 5, ios: 1 }), }); - expect(globalTight).toEqual([ - { action: "boot", deviceId: "first", reason: "recently-released" }, - ]); - expect(platformTight).toEqual([ - { action: "boot", deviceId: "first", reason: "recently-released" }, - ]); + const boot = { action: "boot", deviceId: "first", reason: "target", target: first.spec }; + expect(globalTight).toEqual([boot]); + expect(platformTight).toEqual([boot]); }); it("proposes no shutdown at exactly the budget, globally or on either platform", () => { @@ -722,10 +736,21 @@ describe("warm pool policy", () => { }; const free = device("free", "shutdown", { endedAgo: 2_000 }); - expect(evaluate(view([busy, free], { limit: 1 }))).toEqual([]); + const learned = [learnedOf(free.spec, 4)]; + expect(evaluate(view([busy, free], { learned, limit: 1 }))).toEqual([]); expect( - evaluate(view([busy, claimed, spent, free], { limit: 5, claimed: ["claimed"] })), - ).toEqual([{ action: "boot", deviceId: "free", reason: "recently-released" }]); + evaluate( + view([busy, claimed, spent, free], { + claimed: ["claimed"], + learned, + limit: 5, + maxConcurrentBoots: 2, + }), + ), + ).toEqual([ + { action: "boot", deviceId: "free", reason: "target", target: free.spec }, + { action: "provision", reason: "target", spec: free.spec, target: free.spec }, + ]); }); it("proposes a boot only where its platform has room", () => { @@ -740,12 +765,12 @@ describe("warm pool policy", () => { const devices = [androidBusy, androidShut, iosShut]; const proposals = evaluate({ - ...view(devices), + ...view(devices, { learned: [learnedOf(androidShut.spec, 2), learnedOf(iosShut.spec)] }), capacity: capacityOf(devices, { android: 1, global: 5, ios: 5 }), }); expect(proposals).toEqual([ - { action: "boot", deviceId: "ios-shut", reason: "recently-released" }, + { action: "boot", deviceId: "ios-shut", reason: "target", target: iosShut.spec }, ]); }); @@ -805,28 +830,32 @@ describe("warm pool policy", () => { ).toEqual([]); }); - it("does not boot a recently released device into a global slot the other platform's reserve holds", () => { + it("does not boot a learned kind's device into a global slot the other platform's reserve holds", () => { const androidSpec = spec("Pixel 9", { osVersion: "36", platform: "android" }); const released = device("released", "shutdown", { endedAgo: minute }); const running = device("android-0", "ready", { endedAgo: minute, spec: androidSpec }); const reserve = { android: 1, ios: 1 }; // Global limit 3 with one running leaves two, and the two reserves hold both. - expect(evaluate(view([released, running], { limit: 3, reserve }))).toEqual([]); - expect(evaluate(view([released, running], { limit: 3 }))).toEqual([ - { action: "boot", deviceId: "released", reason: "recently-released" }, + const learned = [learnedOf(released.spec)]; + expect(evaluate(view([released, running], { learned, limit: 3, reserve }))).toEqual([]); + expect(evaluate(view([released, running], { learned, limit: 3 }))).toEqual([ + { action: "boot", deviceId: "released", reason: "target", target: released.spec }, ]); }); - it("does not boot a recently released device into a slot the reserve holds", () => { + it("does not boot a learned kind's device into a slot the reserve holds", () => { const released = device("released", "shutdown", { endedAgo: minute }); const running = idleIos(1); + const learned = [learnedOf(released.spec, 2)]; expect( - evaluate(view([released, ...running], { limits: { ios: 2 }, reserve: { ios: 1 } })), + evaluate( + view([released, ...running], { learned, limits: { ios: 2 }, reserve: { ios: 1 } }), + ), ).toEqual([]); - expect(evaluate(view([released, ...running], { limits: { ios: 2 } }))).toEqual([ - { action: "boot", deviceId: "released", reason: "recently-released" }, + expect(evaluate(view([released, ...running], { learned, limits: { ios: 2 } }))).toEqual([ + { action: "boot", deviceId: "released", reason: "target", target: released.spec }, ]); }); @@ -934,7 +963,7 @@ describe("warm pool policy", () => { expect(evaluate(view([shut], { targets: [target(1)] }))).toHaveLength(1); }); - it("with maxConcurrentBoots 2 proposes two of a target of three and counts a keep boot against the cap", () => { + it("with maxConcurrentBoots 2 proposes two of a target of three and counts a waiter's boot against the cap", () => { const one = ofKind("one", "shutdown"); const two = ofKind("two", "shutdown"); const three = ofKind("three", "shutdown"); @@ -945,17 +974,19 @@ describe("warm pool policy", () => { expect(proposals).toHaveLength(2); expect(proposals.every((proposal) => proposal.reason === "target")).toBe(true); - // A recently released device the keep rule boots is one of the two. - const released = device("released", "shutdown", { endedAgo: minute, spec: spec("iPad Pro") }); - const withKeep = evaluate( - view([released, one, two], { maxConcurrentBoots: 2, targets: [target(2)] }), + const tablet = device("tablet", "shutdown", { endedAgo: minute, spec: spec("iPad Pro") }); + const withWaiter = evaluate( + view([tablet, one, two], { + maxConcurrentBoots: 2, + targets: [target(2)], + waiting: [modelDemand("iPad Pro")], + }), ); - expect(withKeep.map((proposal) => proposal.reason)).toEqual(["recently-released", "target"]); + expect(withWaiter.map((proposal) => proposal.reason)).toEqual(["waiting-request", "target"]); }); it("proposes nothing while a request is queued on its platform, and proposes while that request is already booting its own device", () => { const shut = ofKind("shut", "shutdown"); - // A request for a model the shut-down device does not serve: the keep rule boots nothing. const queued = modelDemand("iPad Pro"); expect(evaluate(view([shut], { targets: [target(1)], waiting: [queued] }))).toEqual([]); @@ -1070,6 +1101,7 @@ describe("warm pool policy", () => { expect(result.targets).toEqual([ { booting: 0, + configuredCount: 1, count: 1, kind: { mode: "full", @@ -1077,6 +1109,7 @@ describe("warm pool policy", () => { osVersion: "26.0", platform: "ios", }, + origin: "configured", ready: 0, short: "running-limit", spec: kind, @@ -1121,6 +1154,7 @@ describe("warm pool policy", () => { expect(result.targets).toStrictEqual([ { booting: 0, + configuredCount: 1, count: 1, kind: { mode: "full", @@ -1128,6 +1162,7 @@ describe("warm pool policy", () => { osVersion: "26.0", platform: "ios", }, + origin: "configured", ready: 1, spec: kind, target: "ios iPhone 17 26.0", @@ -1270,6 +1305,7 @@ describe("warm pool policy", () => { expect(result.targets).toStrictEqual([ { booting: 0, + configuredCount: 1, count: 1, kind: { mode: "full", @@ -1277,6 +1313,7 @@ describe("warm pool policy", () => { osVersion: "26.0", platform: "ios", }, + origin: "configured", ready: 1, spec: kind, target: "ios iPhone 17 26.0", @@ -1305,6 +1342,7 @@ describe("warm pool policy", () => { ]); expect(result.targets[0]).toStrictEqual({ booting: 1, + configuredCount: 2, count: 2, kind: { mode: "full", @@ -1312,6 +1350,7 @@ describe("warm pool policy", () => { osVersion: "26.0", platform: "ios", }, + origin: "configured", ready: 0, spec: kind, target: "ios iPhone 17 26.0", @@ -1372,28 +1411,6 @@ describe("warm pool policy", () => { }, ); - it("counts a recently released device of its kind the keep rule boots as one of the target's, and one of another kind not", () => { - const released = device("released", "shutdown", { endedAgo: minute, spec: kind }); - const other = device("other", "shutdown", { endedAgo: 2 * minute, spec: spec("iPad Pro") }); - const spare = ofKind("spare", "shutdown"); - - expect( - evaluate(view([released, spare], { maxConcurrentBoots: 3, targets: [target(1)] })), - ).toEqual([{ action: "boot", deviceId: "released", reason: "recently-released" }]); - expect( - evaluate(view([released, spare], { maxConcurrentBoots: 3, targets: [target(2)] })), - ).toEqual([ - { action: "boot", deviceId: "released", reason: "recently-released" }, - { action: "boot", deviceId: "spare", reason: "target", target: kind }, - ]); - expect( - evaluate(view([other, spare], { maxConcurrentBoots: 3, targets: [target(1)] })), - ).toEqual([ - { action: "boot", deviceId: "other", reason: "recently-released" }, - { action: "boot", deviceId: "spare", reason: "target", target: kind }, - ]); - }); - it("does not count a boot in flight for another kind toward the target's count", () => { const result = evaluate( view([], { inFlight: [spec("iPad Pro")], maxConcurrentBoots: 2, targets: [target(1)] }), @@ -1486,6 +1503,7 @@ describe("warm pool policy", () => { devices: [leasedReady], isClaimed: () => false, leases: [leaseOn(leasedReady)], + learned: [], targets: [target(1)], }); @@ -1497,6 +1515,7 @@ describe("warm pool policy", () => { devices, isClaimed: (id: string) => id === "claimed", leases: devices.filter((item) => item.state === "leased").map(leaseOn), + learned: [] as WarmPolicyView["learned"], targets, }); @@ -1511,6 +1530,27 @@ describe("warm pool policy", () => { ).toEqual(["older", "oldest"]); }); + it("names a learned kind's ready unleased devices up to its count, oldest first, and the larger of a configured and a learned count", () => { + const devices = [ + ofKind("newer", "ready", { createdAt: 20 }), + ofKind("older", "ready", { createdAt: 10 }), + ofKind("oldest", "ready", { createdAt: 5 }), + device("ipad", "ready", { spec: spec("iPad Pro") }), + ]; + const named = (learnedCount: number, targets: readonly ResolvedTarget[] = []) => + [ + ...targetedDevices({ + ...input(devices, targets), + learned: [learnedOf(kind, learnedCount)], + }), + ].sort(); + + expect(named(2)).toEqual(["older", "oldest"]); + expect(named(1)).toEqual(["oldest"]); + expect(named(1, [target(2)])).toEqual(["older", "oldest"]); + expect(named(3, [target(2)])).toEqual(["newer", "older", "oldest"]); + }); + it("leaves out a leased, claimed, shut-down or spent device and one of another mode", () => { const devices = [ ofKind("leased", "leased"), @@ -1541,5 +1581,179 @@ describe("warm pool policy", () => { ).toEqual(["a", "b", "c", "ipad"]); }); }); + + describe("learned kinds", () => { + const older = spec("iPad Pro"); + const provision = (wanted: VirtualSpec) => ({ + action: "provision", + reason: "target", + spec: wanted, + target: wanted, + }); + + it("fills configured targets in config order, then learned kinds newest first, booting a shut-down device of the kind before creating, and counts a learned kind's leased, reclaiming and claimed devices as had", () => { + const learned = [learnedOf(kind, 1, now - minute), learnedOf(older, 1, now - 2 * minute)]; + + const first = plan(view([], { learned, limit: 1, maxConcurrentBoots: 2 })); + expect(first.proposals).toEqual([provision(kind)]); + expect(first.targets.map((report) => [report.target, report.origin, report.short])).toEqual( + [ + ["ios iPhone 17 26.0", "learned", undefined], + ["ios iPad Pro 26.0", "learned", "running-limit"], + ], + ); + + const configured = spec("iPhone 15"); + expect( + evaluate(view([], { learned, limit: 1, targets: [{ count: 1, spec: configured }] })), + ).toEqual([provision(configured)]); + + const shut = ofKind("shut", "shutdown"); + expect(evaluate(view([shut], { learned: [learnedOf(kind, 1, now)] }))).toEqual([ + { action: "boot", deviceId: "shut", reason: "target", target: kind }, + ]); + + const held = [ofKind("a", "leased"), ofKind("b", "leased"), ofKind("c", "leased")]; + expect(evaluate(view(held, { learned: [learnedOf(kind, 3, now)] }))).toEqual([]); + const claimed = ofKind("claimed", "ready"); + expect( + evaluate(view([claimed], { claimed: ["claimed"], learned: [learnedOf(kind, 1, now)] })), + ).toEqual([]); + const reclaiming = [ + ofKind("a", "leased"), + ofKind("b", "leased"), + ofKind("c", "reclaiming"), + ]; + expect(evaluate(view(reclaiming, { learned: [learnedOf(kind, 3, now)] }))).toEqual([]); + + const mixed = [ofKind("a", "leased"), ofKind("b", "ready")]; + expect( + evaluate(view(mixed, { learned: [learnedOf(kind, 3, now)], maxConcurrentBoots: 3 })), + ).toEqual([provision(kind)]); + + const merged = plan( + view([ofKind("a", "leased")], { + learned: [learnedOf(kind, 2, now), learnedOf(older, 1, now - minute)], + limit: 2, + targets: [{ count: 1, spec: kind }], + }), + ); + expect(merged.proposals).toEqual([provision(kind)]); + expect( + merged.targets.map((report) => [report.origin, report.count, report.configuredCount]), + ).toEqual([ + ["configured", 2, 1], + ["learned", 1, 0], + ]); + }); + + it("keeps a learned kind's never-leased device out of never-leased-idle while the kind wants it, and proposes one beyond its count after idle.shutdownAfterMs", () => { + const old = now - shutdownAfterMs - 1; + const wanted = ofKind("wanted", "ready", { createdAt: 1, readyAt: old }); + const extra = ofKind("extra", "ready", { createdAt: 2, readyAt: old }); + const young = ofKind("young", "ready", { createdAt: 3, readyAt: now - 1_000 }); + const learned = [learnedOf(kind, 1, now)]; + + expect(evaluate(view([wanted], { learned }))).toEqual([]); + expect(evaluate(view([wanted, extra], { learned }))).toEqual([ + { action: "shutdown", deviceId: "extra", reason: "never-leased-idle" }, + ]); + expect(evaluate(view([wanted, young], { learned }))).toEqual([]); + expect(evaluate(view([wanted, extra], { learned: [learnedOf(kind, 2, now)] }))).toEqual([]); + }); + + it("keeps a learned kind and its devices but plans nothing for it while it is unplanned, and still plans a configured target of its spec", () => { + const learned = [learnedOf(kind, 1, now)]; + const old = now - shutdownAfterMs - 1; + const spare = ofKind("spare", "ready", { createdAt: 1, readyAt: old }); + + expect(evaluate(view([], { learned, unplanned: [kind] }))).toEqual([]); + expect(evaluate(view([spare], { learned, unplanned: [kind] }))).toEqual([]); + expect(evaluate(view([], { learned }))).toEqual([provision(kind)]); + expect( + evaluate(view([], { learned, targets: [{ count: 1, spec: kind }], unplanned: [kind] })), + ).toEqual([provision(kind)]); + }); + + it("displaces the least recently used idle ready device of an older learned kind for a newer one short for a running slot, and never a configured target's device, one that serves a waiting request or is already shut down for the budget, for a kind short for ram-budget, device-limit or reserve, or for a configured target", () => { + const learned = [learnedOf(kind, 1, now - minute), learnedOf(older, 2, now - 2 * minute)]; + const recent = device("recent", "ready", { endedAgo: 5 * minute, spec: older }); + const stale = device("stale", "ready", { endedAgo: 30 * minute, spec: older }); + const displace = { action: "shutdown", deviceId: "stale", reason: "displaced" }; + + const base = plan(view([recent, stale], { learned, limit: 2, maxConcurrentBoots: 2 })); + expect(base.proposals).toEqual([displace, provision(kind)]); + expect(base.targets.map((report) => [report.target, report.ready, report.short])).toEqual([ + ["ios iPhone 17 26.0", 0, undefined], + ["ios iPad Pro 26.0", 1, "running-limit"], + ]); + + const refused = (options: Parameters[1]) => + evaluate(view([recent, stale], { learned, maxConcurrentBoots: 2, ...options })); + expect(refused({ limit: 2 })).toEqual([displace, provision(kind)]); + expect(refused({ limit: 2, targets: [{ count: 1, spec: older }] })).toEqual([]); + expect(refused({ limit: 2, waiting: [modelDemand("iPad Pro")] })).toEqual([]); + expect(evaluate(view([recent], { learned, limit: 1, maxConcurrentBoots: 2 }))).toEqual([ + { ...displace, deviceId: "recent" }, + provision(kind), + ]); + expect(refused({ handoffInFlight: true, limit: 2 })).toEqual([]); + const holder = device("holder", "leased", { spec: spec("iPad Air") }); + expect( + evaluate( + view([holder, stale], { + learned: [learnedOf(kind, 2, now - minute), learnedOf(older, 1, now - 2 * minute)], + limit: 1, + maxConcurrentBoots: 2, + }), + ), + ).toEqual([{ action: "shutdown", deviceId: "stale", reason: "over-budget" }]); + const droid = device("droid", "ready", { + endedAgo: 40 * minute, + spec: spec("Pixel 8", { platform: "android" }), + }); + expect( + evaluate( + view([droid], { + learned: [learnedOf(kind, 1, now), learnedOf(droid.spec, 1, now - minute)], + limit: 2, + limits: { ios: 0 }, + maxConcurrentBoots: 2, + }), + ), + ).toEqual([]); + expect(refused({ limit: 3, refuseProvision: "ram-budget" })).toEqual([]); + // why: short for a slot and for RAM the shutdown would not free: no shutdown, or the pool would reboot the victim every pass. + expect(refused({ limit: 2, refuseProvision: "ram-budget" })).toEqual([]); + expect(refused({ limit: 2, refuseProvisionUntilDown: "ram-budget" })).toEqual([ + displace, + provision(kind), + ]); + expect(refused({ limit: 2, spared: [{ count: 2, spec: older }] })).toEqual([]); + expect(refused({ limit: 3, refuseProvision: "device-limit" })).toEqual([]); + expect(refused({ limit: 3, reserve: { ios: 1 } })).toEqual([]); + + const newer = device("newer", "ready", { endedAgo: 30 * minute, spec: kind }); + expect( + evaluate( + view([newer], { + learned, + limit: 1, + maxConcurrentBoots: 2, + }), + ), + ).toEqual([]); + expect( + evaluate( + view([recent], { + learned: [learnedOf(older, 1, now)], + limit: 1, + maxConcurrentBoots: 2, + targets: [{ count: 1, spec: spec("iPhone 15") }], + }), + ), + ).toEqual([]); + }); + }); }); }); diff --git a/src/core/warm-pool/policy.ts b/src/core/warm-pool/policy.ts index 644d235c4..29395cf0a 100644 --- a/src/core/warm-pool/policy.ts +++ b/src/core/warm-pool/policy.ts @@ -13,6 +13,7 @@ import { type WaitingDemand, } from "../domain.js"; import { compareLeastRecentlyUsed } from "../idle-order.js"; +import type { LearnedKind } from "./learned.js"; /** * What one pass acts on: shut a running device down, boot a shut-down one back, or create a new @@ -27,7 +28,7 @@ export type WarmProposal = | "over-budget" | "disabled" | "waiting-request" - | "recently-released" + | "displaced" | "target" | "never-leased-idle"; readonly target?: VirtualSpec; @@ -72,7 +73,9 @@ export interface TargetReport { /** The kind as resolved, or as configured for a target that did not resolve. */ readonly kind: TargetKind; readonly spec?: VirtualSpec; + readonly origin: "configured" | "learned"; readonly count: number; + readonly configuredCount: number; readonly ready: number; /** Boots and creations of the kind running or proposed in the pass. */ readonly booting: number; @@ -104,6 +107,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[]; + readonly learned: readonly LearnedKind[]; + /** why: learned kinds kept but planned for nothing this pass, as no catalog read has listed their platform yet (ADR 0038 §4). */ + readonly unplanned: readonly VirtualSpec[]; /** 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 }[]; @@ -111,8 +117,9 @@ export interface WarmPolicyView { readonly retry: { mayAttempt(spec: VirtualSpec, now: number): boolean }; /** What the capacity strategy refuses besides the running slots `capacity` already totals. */ readonly admit: { - create(spec: VirtualSpec): CapacityRefusalReason | undefined; - boot(device: VirtualDevice): CapacityRefusalReason | undefined; + /** why: `down` names devices the plan has already shut down, which no longer hold their RAM. */ + create(spec: VirtualSpec, down?: ReadonlySet): CapacityRefusalReason | undefined; + boot(device: VirtualDevice, down?: ReadonlySet): CapacityRefusalReason | undefined; }; /** * A device is on its way to a lease: booted, `ready` and claimed, still counted as running @@ -130,7 +137,7 @@ export interface WarmPolicyView { type Slots = { global: number; ios: number; android: number }; /** - * The one place the pool decides what to shut down, what to boot back and what to create for a + * why: the one place the pool decides what to shut down, what to boot back and what to create for a * target. Pure: reads the view, returns proposals in the order they are to run and the state of * every target; the converger revalidates each proposal before it acts. * @@ -139,7 +146,7 @@ type Slots = { global: number; ios: number; android: number }; * that is shut down to bring it back under, and only an idle `shutdown` device is booted into a * slot that is free. The operator's `reserveRunning` takes slots off that budget for idle devices * only (see `reservedOf`). Apart from the budget, an idle device that never served a lease and that - * no target keeps is shut down once it has been ready past `idle.shutdownAfterMs` + * no target or learned kind keeps is shut down once it has been ready past `idle.shutdownAfterMs` * (`neverLeasedIdle`). */ export function evaluate(view: WarmPolicyView): WarmPlan { @@ -166,11 +173,32 @@ export function evaluate(view: WarmPolicyView): WarmPlan { const bootable = view.devices.filter( (device) => device.state === "shutdown" && mayBeGranted(device) && idle(device), ); - const queued = boots(view, running, bootable, room, held); + const queued = boots(view, running, bootable, room); const keeps = queued.proposals; const targets = mergeTargets(view.targets); const unneeded = neverLeasedIdle(view, running, shutdowns, room); - const wanted = planTargets(view, targets, bootable, queued, room, held, idle); + const proposed = new Set([...shutdowns, ...unneeded].map((proposal) => proposal.deviceId)); + const sparedDevices = targetedDevices({ ...view, learned: [], targets: view.spared }); + const wanted = planTargets( + view, + plannedKinds( + targets, + view.learned.filter((kind) => !view.unplanned.some((spec) => sameSpec(spec, kind.spec))), + ), + bootable, + queued, + room, + held, + idle, + view.handoffInFlight + ? [] + : running.filter( + (device) => + !proposed.has(device.id) && + !sparedDevices.has(device.id) && + !view.waiting.some((demand) => !demand.inFlight && serves(device, demand)), + ), + ); return { proposals: [...shutdowns, ...keeps, ...unneeded, ...wanted.proposals], targets: wanted.reports, @@ -226,12 +254,6 @@ function hasRoom(room: Slots, device: VirtualDevice): boolean { return room.global >= 1 && room[device.spec.platform] >= 1; } -/** Whether an idle warm device may take a slot: one beyond what the reserve holds back. */ -function hasWarmRoom(room: Slots, held: Slots, device: VirtualDevice): boolean { - const platform = device.spec.platform; - return room.global - held.global >= 1 && room[platform] - held[platform] >= 1; -} - /** 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) && servesSpec(device.spec, demand); @@ -289,16 +311,13 @@ interface QueueState { * 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. + * Slots a waiting request no idle device serves is about to take are held back from the targets. */ function boots( view: WarmPolicyView, running: readonly VirtualDevice[], bootable: readonly VirtualDevice[], room: Slots, - held: Slots, ): QueuePass { const state: QueueState = { bootable, @@ -328,7 +347,6 @@ function boots( holdSlot(room, demand.platform); } } - bootRecentlyReleased(state, held); return { proposals: state.proposals, started: state.started, stuck: state.stuck }; } @@ -340,26 +358,6 @@ function onItsWayFor( return view.onItsWay.find((entry) => !matched.has(entry) && servesSpec(entry.spec, demand)); } -function bootRecentlyReleased(state: QueueState, held: Slots): void { - const { room, view } = state; - const recent = state.bootable - .filter( - (device) => - !state.taken.has(device.id) && - !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) && view.admit.boot(device) === undefined) { - claim(room, device); - state.started += 1; - state.proposals.push({ action: "boot", deviceId: device.id, reason: "recently-released" }); - } - } -} - function holdSlot(room: Slots, platform: Platform): void { room.global -= 1; room[platform] -= 1; @@ -412,6 +410,61 @@ function createForWaiter(state: QueueState, demand: WaitingDemand, head: boolean } else state.stuck.add(demand.platform); } +interface PlannedKind { + readonly spec: VirtualSpec; + readonly configuredCount: number; + readonly learnedCount: number; + readonly origin: "configured" | "learned"; +} + +// why: configured targets fill in config order, then learned kinds newest first; a learned kind of a configured target's spec is that entry, not a second one. +function plannedKinds( + targets: readonly ResolvedTarget[], + learned: readonly LearnedKind[], +): PlannedKind[] { + const kinds: PlannedKind[] = targets.map((target) => ({ + configuredCount: target.count, + learnedCount: 0, + origin: "configured", + spec: target.spec, + })); + for (const kind of learned) { + const index = kinds.findIndex((entry) => sameSpec(entry.spec, kind.spec)); + const existing = kinds[index]; + if (existing === undefined) { + kinds.push({ + configuredCount: 0, + learnedCount: kind.count, + origin: "learned", + spec: kind.spec, + }); + } else kinds[index] = { ...existing, learnedCount: kind.count }; + } + return kinds; +} + +/** + * why: what a learned kind has: its ready idle devices, and the ones leased, reclaiming or under + * an operation claim (a reclaim that has not yet given its claim up), which come back on their own. + * A burst held at its peak so makes nothing more. + */ +function haveOfKind( + view: WarmPolicyView, + isIdle: (device: VirtualDevice) => boolean, + spec: VirtualSpec, +): number { + const leased = new Set(view.leases.map((lease) => lease.deviceId)); + const ready = new Set(readyOfKind(view.devices, isIdle, spec).map((device) => device.id)); + return view.devices.filter( + (device) => + sameSpec(device.spec, spec) && + (ready.has(device.id) || + leased.has(device.id) || + device.state === "reclaiming" || + (device.state !== "provisioning" && view.isClaimed(device.id))), + ).length; +} + /** The targets with those that resolved to one spec merged into one, counts summed. */ function mergeTargets(targets: readonly ResolvedTarget[]): ResolvedTarget[] { const merged: ResolvedTarget[] = []; @@ -471,20 +524,23 @@ export function readyCount(input: DeviceCounts, spec: VirtualSpec): number { * devices a target counts. */ export function targetedDevices( - input: DeviceCounts & { readonly targets: readonly ResolvedTarget[] }, + input: DeviceCounts & { + readonly targets: readonly ResolvedTarget[]; + readonly learned: readonly LearnedKind[]; + }, ): ReadonlySet { const isIdle = idlePredicate(input.leases, input.isClaimed); return new Set( - mergeTargets(input.targets).flatMap((target) => - readyOfKind(input.devices, isIdle, target.spec) - .slice(0, target.count) + 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), ), ); } /** - * Shutdowns for the ready, unleased devices that never served a lease and that no target keeps, + * why: shutdowns for the ready, unleased devices that never served a lease and that no target or learned kind keeps, * once they have been ready longer than `idle.shutdownAfterMs`. The cleanup reaper times an idle * device from the end of its last lease, so it never sees one of these; this is the one rule that * does. A device a waiting request is about to be granted is spared, as in the budget's choice. @@ -495,7 +551,10 @@ function neverLeasedIdle( proposed: readonly DeviceProposal[], room: Slots, ): DeviceProposal[] { - const kept = targetedDevices({ ...view, targets: [...view.targets, ...view.spared] }); + const kept = targetedDevices({ + ...view, + targets: [...view.targets, ...view.spared], + }); const already = new Set(proposed.map((proposal) => proposal.deviceId)); const proposals: DeviceProposal[] = []; for (const device of running) { @@ -540,6 +599,10 @@ interface TargetPlan { readonly taken: Set; readonly stuck: ReadonlySet; readonly proposals: WarmProposal[]; + readonly kinds: readonly PlannedKind[]; + /** why: the idle ready devices a newer learned kind may shut down for a slot, least recently used first. */ + readonly victims: VirtualDevice[]; + readonly displaced: Set; /** Pool boots and creations running or proposed, which `maxConcurrentBoots` bounds. */ started: number; } @@ -553,24 +616,31 @@ interface TargetPlan { */ function planTargets( view: WarmPolicyView, - targets: readonly ResolvedTarget[], + targets: readonly PlannedKind[], bootable: readonly VirtualDevice[], queued: QueuePass, room: Slots, held: Slots, - isIdle: (device: VirtualDevice) => boolean, + isIdleDevice: (device: VirtualDevice) => boolean, + victims: readonly VirtualDevice[], ): { proposals: WarmProposal[]; reports: TargetReport[] } { const keepBoots = queued.proposals.flatMap((proposal) => proposal.action === "boot" ? [proposal.deviceId] : [], ); + const displaced = new Set(); + const isIdle = (device: VirtualDevice): boolean => + isIdleDevice(device) && !displaced.has(device.id); const plan: TargetPlan = { bootable, + displaced, held, + kinds: targets, proposals: [], room, started: queued.started, stuck: queued.stuck, taken: new Set(keepBoots), + victims: [...victims], view, }; const pending = (spec: VirtualSpec): number => @@ -583,16 +653,19 @@ function planTargets( (device) => device.id === proposal.deviceId && sameSpec(device.spec, spec), ), ).length; - const reports = targets.map(({ count, spec }): TargetReport => { + const reports = targets.map(({ configuredCount, learnedCount, origin, spec }): TargetReport => { const ready = readyOfKind(view.devices, isIdle, spec).length; const filling = pending(spec); - const missing = count - ready - filling; + const missing = + Math.max(configuredCount - ready, learnedCount - haveOfKind(view, isIdle, spec)) - filling; const before = plan.proposals.length; const short = missing > 0 ? fillTarget(plan, spec, missing, filling > 0) : undefined; const report = { booting: filling + plan.proposals.length - before, - count, + configuredCount, + count: Math.max(configuredCount, learnedCount), kind: kindOf(spec), + origin, ready, spec, target: describeTarget(spec), @@ -617,25 +690,72 @@ function fillTarget( 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--) { - const refused = addOne(plan, spec); + const refused = addDisplacing(plan, spec); if (refused !== undefined) return added > 0 || filling ? undefined : refused; added += 1; } return undefined; } -/** Proposes one boot of a shut-down device of the kind, else one creation; or why it cannot. */ -function addOne(plan: TargetPlan, spec: VirtualSpec): TargetShort | undefined { - const shutDown = plan.bootable.find( +/** + * why: a learned kind short for a running slot takes the least recently used idle ready device of + * an older learned kind: the newest kinds are the ones asked for most lately. A configured target + * and a kind short for anything but the slot never displace; configured targets come first in + * `kinds`, so none is older than a learned kind and none is displaced. + */ +function displaceFor(plan: TargetPlan, spec: VirtualSpec): boolean { + const index = plan.kinds.findIndex((entry) => sameSpec(entry.spec, spec)); + if (plan.kinds[index]?.origin !== "learned") return false; + const victim = plan.victims.find((device) => { + const entry = plan.kinds.findIndex((candidate) => sameSpec(candidate.spec, device.spec)); + return entry > index && device.spec.platform === spec.platform; + }); + if (victim === undefined) return false; + // why: a slot is not all the kind lacks; when the capacity strategy still refuses it with the victim down, the shutdown would free nothing the kind can use and the victim would boot back next pass. + if (admitted(plan, spec, new Set([...plan.displaced, victim.id])) !== undefined) return false; + plan.victims.splice(plan.victims.indexOf(victim), 1); + plan.displaced.add(victim.id); + release(plan.room, victim); + plan.proposals.push({ action: "shutdown", deviceId: victim.id, reason: "displaced" }); + return true; +} + +/** why: a learned kind refused for a running slot tries again after each displacement it can make. */ +function addDisplacing(plan: TargetPlan, spec: VirtualSpec): TargetShort | undefined { + let refused = addOne(plan, spec); + while (refused === "running-limit" && displaceFor(plan, spec)) refused = addOne(plan, spec); + return refused; +} + +/** why: the shut-down device a boot of `spec` would use, which decides whether the capacity strategy is asked about a boot or a creation. */ +function bootCandidate(plan: TargetPlan, spec: VirtualSpec): VirtualDevice | undefined { + return plan.bootable.find( (device) => !plan.taken.has(device.id) && !plan.view.resetDevices.has(device.id) && sameSpec(device.spec, spec), ); - // The order a user reads: device limit, running limit, reserve, then RAM budget. - const capacity = shortOf( - shutDown === undefined ? plan.view.admit.create(spec) : plan.view.admit.boot(shutDown), +} + +/** why: what the capacity strategy refuses for a boot or creation of `spec` once the `down` devices are shut down. */ +function admitted( + plan: TargetPlan, + spec: VirtualSpec, + down: ReadonlySet, +): TargetShort | undefined { + const shutDown = bootCandidate(plan, spec); + return shortOf( + shutDown === undefined + ? plan.view.admit.create(spec, down) + : plan.view.admit.boot(shutDown, down), ); +} + +/** why: proposes one boot of a shut-down device of the kind, else one creation, or says why it cannot. */ +function addOne(plan: TargetPlan, spec: VirtualSpec): TargetShort | undefined { + const shutDown = bootCandidate(plan, spec); + // why: the order a user reads: device limit, running limit, reserve, then RAM budget. + const capacity = admitted(plan, spec, plan.displaced); const refused = capacity === "device-limit" ? capacity diff --git a/src/core/warm-pool/retry.test.ts b/src/core/warm-pool/retry.test.ts index 2165a5147..10fca5f73 100644 --- a/src/core/warm-pool/retry.test.ts +++ b/src/core/warm-pool/retry.test.ts @@ -32,6 +32,22 @@ describe("retry schedule", () => { expect(new RetrySchedule().mayAttempt(spec, 0)).toBe(true); }); + it("answers the failures in a row of a spec, and 0 after a success", () => { + const schedule = new RetrySchedule(); + expect(schedule.failures(spec)).toBe(0); + + failTimes(schedule, spec, 2); + schedule.failed(other, 0); + + expect(schedule.failures(spec)).toBe(2); + expect(schedule.failures(other)).toBe(1); + + schedule.succeeded(spec); + + expect(schedule.failures(spec)).toBe(0); + expect(schedule.failures(other)).toBe(1); + }); + it("after one failure allows a try one minute later and not a moment before", () => { const schedule = new RetrySchedule(); diff --git a/src/core/warm-pool/retry.ts b/src/core/warm-pool/retry.ts index 6d132edf7..af2044592 100644 --- a/src/core/warm-pool/retry.ts +++ b/src/core/warm-pool/retry.ts @@ -14,13 +14,13 @@ interface Failure { } /** - * Where a target's failed boot or creation is remembered, keyed by the resolved spec (`sameSpec` + * why: where a target's failed boot or creation is remembered, keyed by the resolved spec (`sameSpec` * says which specs are one): a failure records the attempt and when the next try is allowed (one * minute after the first, doubling per failure in a row, never more than ten minutes), and a * success forgets it. The policy asks one question (`mayAttempt`), the converger reports two facts * (`failed`, `succeeded`) and asks when to look again (`nextAttemptAt`); nothing else knows how a * target is held back, so a later schedule (an attempt limit, a delay per reason) replaces this - * file. A device's own short pause after a failed keep boot or shutdown is the converger's; a target's + * file. A device's own short pause after a failed shutdown is the converger's; a target's * boot is held back here and nowhere else. */ export class RetrySchedule { @@ -38,6 +38,10 @@ export class RetrySchedule { this.#failures.push({ count, retryAt: now + delay, spec }); } + failures(spec: VirtualSpec): number { + return this.#failureOf(spec)?.count ?? 0; + } + succeeded(spec: VirtualSpec): void { this.#failures = this.#failures.filter((failure) => !sameSpec(failure.spec, spec)); } diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 801cf6b30..f716fae6e 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -6,6 +6,7 @@ import { openTestState, testComponentWiring, type FakeDriverOptions, + testStateOf, } from "../core/testing.js"; import type { StateDatabase } from "../state/index.js"; @@ -351,6 +352,7 @@ async function buildDispatcher( eventBus, idGenerator: sequence(), registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte, diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 3bf62f20d..3f50c0462 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -1144,7 +1144,11 @@ describe("startDaemon wires core and leasing together", () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); driver.failOn("reclaim", 1, new DriverCrashError("purge exploded")); - const { daemon } = await start({ clock, drivers: [driver] }); + const { daemon } = await start({ + clock, + configOverrides: { warmPool: { enabled: false } }, + drivers: [driver], + }); const grant = (await daemon.dispatch("lease.request", ios, agent)) as Grant; await daemon.dispatch("lease.release", { leaseId: grant.lease.id }, agent); await settleRealTime(); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index eb402860d..81b86508d 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -37,6 +37,7 @@ import { OwnedRootError, Registry, registryOwner, + warmPoolOwner, Nuke, SerializedDecision, sweepWriteLeftovers, @@ -251,7 +252,7 @@ async function composeDaemon( owners: role === "gateway" ? [tokensOwner, drainedWorkersOwner] - : [registryOwner, tokensOwner, ...new Set(deviceDataTables.values())], + : [registryOwner, warmPoolOwner, tokensOwner, ...new Set(deviceDataTables.values())], sqlite: new NodeSqliteOpener(), upgradeStep: role === "gateway" ? GATEWAY_UPGRADE_STEP : WORKER_UPGRADE_STEP, }); @@ -386,6 +387,7 @@ async function composeDaemon( optionalModules: () => moduleHost.findings(), prerequisiteChecks, registry, + state, systemStats, }); const leaseEnvironment: Record = Object.assign( diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 17807cc57..9eee108bd 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -8,6 +8,7 @@ import { loadTestRegistry, openTestState, testComponentWiring, + testStateOf, } from "../core/testing.js"; import type { StateDatabase } from "../state/index.js"; @@ -3358,6 +3359,7 @@ async function createHarness( eventBus, idGenerator: sequence(), registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte, diff --git a/src/leasing/create-leasing.test.ts b/src/leasing/create-leasing.test.ts index 90f195eb9..26639c96c 100644 --- a/src/leasing/create-leasing.test.ts +++ b/src/leasing/create-leasing.test.ts @@ -11,7 +11,7 @@ import { type Registry, UnknownLeaseError, } from "../core/index.js"; -import { type CapacityLimits, type ResourceStrategyOptions } from "../core/testing.js"; +import { type CapacityLimits, type ResourceStrategyOptions, testStateOf } from "../core/testing.js"; import { capacityChangedPayload, FakeDriver, @@ -173,8 +173,10 @@ async function createHarness( readonly warmPoolEnabled?: boolean; /** Replaces keys of the `warmPool` block, `targets` and `maxConcurrentBoots` among them. */ readonly warmPool?: Partial; - /** `0` leaves no device recently released, so the pool boots none back unasked. */ + /** why: how long a ready device may idle before the pool shuts it down. */ readonly idleShutdownAfterMs?: number; + /** why: starts the warm pool as the daemon's startup does, so it learns from the leases and reacts to events. */ + readonly startPool?: boolean; } = {}, ) { const clock = new FakeClock(1_000); @@ -225,9 +227,11 @@ async function createHarness( ? {} : { modelPreferences: options.modelPreferences }), registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes }), }); + if (options.startPool === true) await engine.convergeRunningCapacity(); return { bus, clock, decisions: wiring.decisions, driver, engine, registry, state }; } @@ -1499,6 +1503,7 @@ describe("createLeasing RAM budget by mode", () => { it("over its limit after a restart with larger sizes, creates no device in either mode and boots no shut-down slim device, but grants an idle one; a delete brings it back under", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ + knownModels: ["iPhone 16", "iPhone 16 Pro"], availableOsVersions: ["26.4", "26.5"], clock, platform: "ios", @@ -1581,13 +1586,14 @@ describe("createLeasing RAM budget by mode", () => { ] as const) { await after.engine.cleanup.execute({ action, reason: "test", rule: "test", target }); } + await after.engine.settle(); + // why: the pool keeps the kind the reused lease taught it: the one slim device it made takes the 2 GiB the deletes freed. + expect(operations(driver, "makeReady")).toBe(boots + 1); expect(after.engine.ramBudget).toEqual({ limitBytes: 5 * gibibyte, overLimit: false, - usedBytes: 2 * gibibyte, + usedBytes: 4 * gibibyte, }); - await after.engine.request(request, { noWait: true, ownerId: "new", requesterId: "new" }); - expect(operations(driver, "provision")).toBe(provisions + 1); }); }); @@ -1734,6 +1740,7 @@ describe("createLeasing startup reclaim backgrounding (#43)", () => { eventBus: bus1, idGenerator, registry: registry1, + state: testStateOf(registry1), systemStats: systemStats(), }); const granted = await engine1.request(request, { @@ -1776,6 +1783,7 @@ describe("createLeasing startup reclaim backgrounding (#43)", () => { eventBus: bus2, idGenerator, registry: registry2, + state: testStateOf(registry2), systemStats: systemStats(), }); @@ -1998,6 +2006,7 @@ describe("createLeasing fresh lease identity (#75)", () => { eventBus: bus, idGenerator, registry: beforeRegistry, + state: testStateOf(beforeRegistry), systemStats, }); const granted = await before.request(request, { ownerId: "a", requesterId: "a" }); @@ -2025,6 +2034,7 @@ describe("createLeasing fresh lease identity (#75)", () => { eventBus: bus, idGenerator, registry, + state: testStateOf(registry), systemStats, }); await after.convergeRunningCapacity(); @@ -2123,6 +2133,7 @@ describe("createLeasing fresh lease identity (#75)", () => { eventBus: bus, idGenerator, registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte, @@ -3043,13 +3054,14 @@ describe("createLeasing warm pool", () => { it("a nuke waits for a warm pool boot already in flight, then deletes the device", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ + knownModels: ["iPhone 16"], availableOsVersions: ["26.5"], clock, latencyMs: { makeReady: 50 }, platform: "ios", reclaimResult: "shutdown", }); - const harness = await createHarness({ driver }); + const harness = await createHarness({ driver, startPool: true }); const granting = harness.engine.request(request, { ownerId: "a", requesterId: "a" }); await flush(); clock.advance(50); @@ -3075,6 +3087,7 @@ describe("createLeasing warm pool", () => { async function releasedDeviceBooting(failBoot = false) { const clock = new FakeClock(1_000); const driver = new FakeDriver({ + knownModels: ["iPhone 16"], availableOsVersions: ["26.5"], clock, latencyMs: { makeReady: 50 }, @@ -3082,6 +3095,7 @@ describe("createLeasing warm pool", () => { reclaimResult: "shutdown", }); const harness = await createHarness({ + startPool: true, driver, limits: { android: { maxDevices: 1, maxRunning: 1 }, @@ -3284,12 +3298,13 @@ describe("createLeasing warm pool", () => { it("boots a released iOS device back to ready when the running limit has room", async () => { const driver = new FakeDriver({ + knownModels: ["iPhone 16"], availableOsVersions: ["26.5"], clock: new FakeClock(1_000), platform: "ios", reclaimResult: "shutdown", }); - const harness = await createHarness({ driver }); + const harness = await createHarness({ driver, startPool: true }); const first = await harness.engine.request(request, { ownerId: "a", requesterId: "a" }); await harness.engine.release(first.lease.id, "explicit"); @@ -4510,6 +4525,7 @@ describe("createLeasing: a waiting request says why it is not placed (#636)", () it("lists a request that waits for a device the warm pool is booting as waiting-for-device", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ + knownModels: ["iPhone 16"], availableOsVersions: ["26.5"], clock, latencyMs: { makeReady: 50 }, @@ -4517,6 +4533,7 @@ describe("createLeasing: a waiting request says why it is not placed (#636)", () reclaimResult: "shutdown", }); const harness = await createHarness({ + startPool: true, driver, limits: { android: { maxDevices: 1, maxRunning: 1 }, diff --git a/src/leasing/lease-end-participants.test.ts b/src/leasing/lease-end-participants.test.ts index cda8cc95a..497de4b7c 100644 --- a/src/leasing/lease-end-participants.test.ts +++ b/src/leasing/lease-end-participants.test.ts @@ -14,6 +14,7 @@ import { loadTestRegistry, openTestState, testComponentWiring, + testStateOf, } from "../core/testing.js"; import type { StateDatabase } from "../state/index.js"; import { FakeClock, FakeSystemStats, JsonLinesLogger, MemoryLogSink } from "../ports/index.js"; @@ -214,6 +215,7 @@ async function startEngine(options: EngineOptions = {}): Promise { ...(options.participants === undefined ? {} : { leaseEndParticipants: options.participants }), logger: new JsonLinesLogger({ clock, level: "debug", sink }), registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), }); started.push(engine); diff --git a/src/leasing/physical-device-watcher.test.ts b/src/leasing/physical-device-watcher.test.ts index 7f2785e7b..914afcdea 100644 --- a/src/leasing/physical-device-watcher.test.ts +++ b/src/leasing/physical-device-watcher.test.ts @@ -12,6 +12,7 @@ import { loadTestRegistry, openTestState, testComponentWiring, + testStateOf, } from "../core/testing.js"; import type { StateDatabase } from "../state/index.js"; import { EventBus } from "../bus/index.js"; @@ -165,6 +166,7 @@ async function createHarness( idGenerator: { generate: () => `request-${nextId++}` }, ...(options.logger === undefined ? {} : { logger: options.logger }), registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), }); const harness = { diff --git a/src/leasing/physical-leasing.test.ts b/src/leasing/physical-leasing.test.ts index 1faba99d5..0120dda5d 100644 --- a/src/leasing/physical-leasing.test.ts +++ b/src/leasing/physical-leasing.test.ts @@ -8,7 +8,7 @@ import { type PhysicalDevice, UnknownModelError, } from "../core/index.js"; -import { FakeDriver, loadTestRegistry, testComponentWiring } from "../core/testing.js"; +import { FakeDriver, loadTestRegistry, testComponentWiring, testStateOf } from "../core/testing.js"; import { EventBus, type EventMap } from "../bus/index.js"; import { FakeClock, FakeSystemStats } from "../ports/index.js"; import { NoCapacityError } from "./lease-acquisition-coordinator.js"; @@ -134,6 +134,7 @@ async function createHarness( eventBus: bus, idGenerator: { generate: () => `request-${nextId++}` }, registry, + state: testStateOf(registry), systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), }); return { bus, clock, decisions: wiring.decisions, driver, engine, registry }; diff --git a/src/leasing/testing.ts b/src/leasing/testing.ts index 83ac84434..7e6c13deb 100644 --- a/src/leasing/testing.ts +++ b/src/leasing/testing.ts @@ -1,5 +1,6 @@ import type { EventBus } from "../bus/index.js"; import type { Clock, IdGenerator, Logger, SystemStats } from "../ports/index.js"; +import type { StateDatabase } from "../state/index.js"; import { type CapacityReader, type WarmPoolReader, @@ -45,6 +46,7 @@ export interface TestEngineOptions { readonly idGenerator: IdGenerator; readonly logger?: Logger | undefined; readonly registry: Registry; + readonly state: StateDatabase; readonly systemStats: SystemStats; readonly describeFailure?: ((error: unknown) => LeaseRequestFailure) | undefined; readonly defaultModes?: Readonly>> | undefined; @@ -92,6 +94,7 @@ export function createTestEngine(options: TestEngineOptions): TestEngine { logger: options.logger, modelPreferences: options.modelPreferences, registry: options.registry, + state: options.state, systemStats: options.systemStats, }); const leasing = createLeasing({