diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 4d121b978..608f92ffa 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -46,9 +46,9 @@ in short: `subject.past-tense-fact`, emitted post-commit, facts not commands. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `lease.requested` | request id, request spec (platform, `model` only when the request named one, `class` when it named one -- a request naming neither carries neither, ADR 0015 §9, os version -- an exact version or an OS range as typed, ADR 0015 §2, device `mode` as the request named it -- absent when it named none, since the worker's default is applied after this event, ADR 0007 §2; `imageTag` when the request named one, #214, additive; `physical: true` when the request asked for an enrolled physical device, ADR 0022, additive; `baseline`, the name, when the request named one, #1207, additive), requester, wait policy, `fleetRequestId` on a worker's event for a gateway's dispatch (a probe; ADR 0021 §3, additive, events rule 6) | a lease request is accepted by the daemon and stored; the request id is the stored request's, so an observer can match this event to it (#72 added the id; additive, events rule 6) | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway, ADR 0005 §11 — its own fleet queue's admission, before any worker is chosen) | implemented | +| `lease.requested` | request id, request spec (platform, `model` only when the request named one, `class` when it named one -- a request naming neither carries neither, ADR 0015 §9, os version -- an exact version or an OS range as typed, ADR 0015 §2, device `mode` as the request named it -- absent when it named none, since the worker's default is applied after this event, ADR 0007 §2; `imageTag` when the request named one, #214, additive; `physical: true` when the request asked for an enrolled physical device, ADR 0022, additive; `baseline`, the name, when the request named one, #1207, additive; `except`, the list as the request named it, when it named one, ADR 0066 §1, additive), requester, wait policy, `fleetRequestId` on a worker's event for a gateway's dispatch (a probe; ADR 0021 §3, additive, events rule 6) | a lease request is accepted by the daemon and stored; the request id is the stored request's, so an observer can match this event to it (#72 added the id; additive, events rule 6) | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway, ADR 0005 §11 — its own fleet queue's admission, before any worker is chosen) | implemented | | `lease.queued` | request id, queue position (counted in the request's own line, ADR 0022 §3: a physical request waits apart from simulator and emulator requests) | no capacity; request entered the wait queue | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway) | implemented | -| `lease.granted` | lease id, device id, requester, request id, source (`warm`/`booted`/`provisioned`, ADR 0016 §2: the kind of the plan that granted it -- an eviction never grants by itself, so the plan made after it decides; a physical grant is `warm`, ADR 0022 §3), `fleetRequestId` when the grant served a probe (ADR 0021 §3, additive), the device's `platform` (`ios` or `android`), `baseline: { name, version }` when the device is a copy of a baseline (#1207, additive) | a device was assigned and handed out | LeaseLifecycle | implemented (payload per ADR 0004 pending) | +| `lease.granted` | lease id, device id, requester, request id, source (`warm`/`booted`/`provisioned`, ADR 0016 §2: the kind of the plan that granted it -- an eviction never grants by itself, so the plan made after it decides; a physical grant is `warm`, ADR 0022 §3; a ready warm device shut down and booted again for a request with `except` is `booted`, because the requester waited for a boot, ADR 0066 §2), `fleetRequestId` when the grant served a probe (ADR 0021 §3, additive), the device's `platform` (`ios` or `android`), `baseline: { name, version }` when the device is a copy of a baseline (#1207, additive) | a device was assigned and handed out | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock, or a daemon start found its device not running, or (device-lost, ADR 0022 §7) a physical device was not present for the grace period (`health.stableObservations` reads in a row, `health.probeIntervalMs` apart; emitted by the `PhysicalDeviceWatcher` through `LeaseReleaseCoordinator.endForAbsentDevice`; the device becomes `absent` in the same write and nothing is wiped), and the device of that lease was wiped and returned to the pool, left waiting in `reclaiming` on a platform the daemon could not list, or marked missing. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented (payload per ADR 0004 pending) | @@ -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` (`lease-engine` for a device that never served a lease) | 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; `daemon-stop` when a stopping daemon shut down an idle device, #1056; `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 idle device shut down so a newer learned kind, or a configured target, can boot into its slot) | device stopped, still on disk | Registry; ReclaimCoordinator for interrupted reclaim recovery | implemented | +| `device.shutdown` | device id, initiator (rule/command; `daemon-stop` when a stopping daemon shut down an idle device, #1056; `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 idle device shut down so a newer learned kind, or a configured target, can boot into its slot; `lease-engine` when a ready warm device failed the reboot a lease with `except` asked of it, ADR 0066 §2) | 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, or when quarantine's delete retry removed a device that never served a lease; `cleanup-reaper` when the cleanup reaper destroyed a device; `nuke` when `nuke` destroyed it; `baseline-save` when `baseline save` kept a copy of the device and deleted it; `baseline-remove` when `baseline remove` deleted an idle device made from the baseline; `baseline-replaced` when a newer baseline version replaced the one an idle device was made from and the device was deleted), 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/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index 1882a99bf..e43717e21 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -17,6 +17,8 @@ interface LeaseGrant { readonly lease: string; readonly udid: string; readonly mode: "slim" | "full"; + /** why: the categories the grant says the lease kept running; absent for a lease with no `--except`. */ + readonly except?: readonly string[]; /** The device set the grant says the device lives in; no simctl call reaches it without. */ readonly deviceSet: string; } @@ -103,6 +105,23 @@ async function catalogModelAndOs(env: TestEnv): Promise<{ model: string; os: str return { model: model as string, os: os as string }; } +/** why: a runtime is picked by version, not by being the newest installed (ADR 0066): the first model the catalog pairs with a runtime `pick` accepts. */ +async function catalogModelWithOs( + env: TestEnv, + pick: (versions: readonly string[]) => string | undefined, +): Promise<{ model: string; os: string }> { + const catalog = await env.cli(["catalog", "--json", "--platform", "ios"]); + expect(catalog.code, `catalog failed: ${catalog.stderr}`).toBe(0); + const iosCatalog = (catalog.json as { platforms: CatalogPlatform[] }).platforms.find( + (platform) => platform.platform === "ios", + ); + for (const model of iosCatalog?.models ?? []) { + const os = pick([...(iosCatalog?.modelRuntimes[model] ?? [])].sort(compareVersionsDescending)); + if (os !== undefined) return { model, os }; + } + throw new Error("simlock catalog pairs no iOS model with the runtime this case needs"); +} + async function leaseDetached( env: TestEnv, model: string, @@ -128,7 +147,7 @@ async function leaseDetached( ); expect(lease.code, `lease failed: ${lease.stderr}`).toBe(0); const grant = lease.json as { - device: { driverDeviceId: string; mode: "slim" | "full" }; + device: { driverDeviceId: string; except?: readonly string[]; mode: "slim" | "full" }; environment: Record; lease: { id: string }; }; @@ -136,6 +155,7 @@ async function leaseDetached( expect(deviceSet, "an iOS grant must name the device set its device lives in").toBeDefined(); return { deviceSet: deviceSet as string, + ...(grant.device.except === undefined ? {} : { except: grant.device.except }), lease: grant.lease.id, mode: grant.device.mode, udid: grant.device.driverDeviceId, @@ -311,6 +331,117 @@ describe.skipIf(process.platform !== "darwin")( }, ); + it.each([ + ["iOS 18.5", (versions: readonly string[]) => versions.find((v) => v === "18.5")], + [ + "the newest iOS 26.x", + (versions: readonly string[]) => versions.find((v) => v.startsWith("26.")), + ], + ])( + "a lease of --mode slim --except store,other on %s finds every store and other label enabled", + { timeout: 900_000 }, + async (_label, pick) => { + const env = await withRealDaemon(); + const { model, os } = await catalogModelWithOs(env, pick); + const except = ["store", "other"]; + + const grant = await leaseDetached(env, model, os, "slim-except", [ + "--mode", + "slim", + "--except", + except.join(","), + ]); + + await expectSlim(env, grant.mode, "a --mode slim lease with --except must be slim"); + expect(grant.except).toEqual(except); + const disabled = await printDisabled(grant); + const kept = labelsFor( + SLIM_CATEGORIES.filter((category) => except.includes(category.name)), + ); + expect( + kept.filter((label) => disabled.has(label)), + "a label of an excepted category is still disabled", + ).toEqual([]); + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + }, + ); + + it( + "on the newest iOS 26.x, excepting each category in turn finds its labels enabled", + { timeout: 7_200_000 }, + async () => { + const env = await withRealDaemon(); + const { model, os } = await catalogModelWithOs(env, (versions) => + versions.find((version) => version.startsWith("26.")), + ); + for (const category of SLIM_CATEGORIES) { + const grant = await leaseDetached(env, model, os, `slim-except-${category.name}`, [ + "--mode", + "slim", + "--except", + category.name, + ]); + await expectSlim( + env, + grant.mode, + `a --mode slim lease excepting ${category.name} must be slim`, + ); + expect(grant.except).toEqual([category.name]); + const disabled = await printDisabled(grant); + expect( + labelsFor([category]).filter((label) => disabled.has(label)), + `a label of the excepted category ${category.name} is still disabled`, + ).toEqual([]); + await env.cli(["release", grant.lease]); + } + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + }, + ); + + it( + "a warm slim device is rebooted with the smaller list and granted", + { timeout: 1_200_000 }, + async () => { + const env = await withRealDaemon({ ios: { defaultMode: "slim" } }); + const { model, os } = await catalogModelWithOs(env, (versions) => + versions.find((version) => version.startsWith("26.")), + ); + // why: the pool learns the kind of a lease and boots a warm replacement once it is released. + const taught = await leaseDetached(env, model, os, "slim-teach"); + await env.cli(["release", taught.lease]); + let warmUdid: string | undefined; + await waitFor( + async () => { + const rows = (await env.cli(["list", "--devices"])).json as { + driverDeviceId: string; + mode: string; + state: string; + }[]; + warmUdid = rows.find( + (row) => row.state === "ready" && row.mode === "slim", + )?.driverDeviceId; + return warmUdid !== undefined; + }, + { timeout: 600_000, label: "a warm slim device is ready" }, + ); + + const grant = await leaseDetached(env, model, os, "slim-warm-except", [ + "--except", + "store", + ]); + + expect(grant.udid, "the warm device is the one granted").toBe(warmUdid); + expect(grant.except).toEqual(["store"]); + const disabled = await printDisabled(grant); + expect( + labelsFor(SLIM_CATEGORIES.filter((category) => category.name === "store")).filter( + (label) => disabled.has(label), + ), + ).toEqual([]); + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + }, + ); + it( "no simulator from this file's device sets is still running after its flows", { timeout: 60_000 }, diff --git a/src/cli/commands/lease.ts b/src/cli/commands/lease.ts index 3bf7040f6..e0026477e 100644 --- a/src/cli/commands/lease.ts +++ b/src/cli/commands/lease.ts @@ -49,6 +49,7 @@ async function runLease( detach: { type: "boolean" }, device: { type: "string" }, "export-env": { type: "boolean" }, + except: { type: "string" }, help: { type: "boolean", short: "h" }, "image-tag": { type: "string" }, "lease-id": { type: "string" }, @@ -64,7 +65,7 @@ async function runLease( environment.stdout.write( "Usage: simlock lease --platform [--device | --class ]\n" + " [--os ] [--mode ] [--image-tag ] [--agent-id ]\n" + - " [--baseline ]\n" + + " [--except ] [--baseline ]\n" + " [--timeout ] [--lease-id ] [--physical]\n" + " [--no-wait] [--detach] [--ttl ] [--allow-download]\n" + " [--export-env] [--bind-pid ]\n", @@ -202,6 +203,7 @@ async function runLease( ...(values.physical === true ? { physical: true } : {}), platform, ...(typeof values.mode === "string" ? { mode: values.mode as "slim" | "full" } : {}), + ...(typeof values.except === "string" ? { except: values.except.split(",") } : {}), ...(typeof values["image-tag"] === "string" ? { imageTag: values["image-tag"] } : {}), ...(baseline === undefined ? {} : { baseline }), ...(typeof values["lease-id"] === "string" ? { leaseId: values["lease-id"] } : {}), diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index ca991a17a..629dd450e 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6761,6 +6761,14 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( flagArgs: ["--image-tag", "google_apis_playstore"], envOverride: () => ({}), }, + { + flag: "--except", + field: "except", + value: ["store", "other"], + lease: ["lease", "--platform", "ios", "--mode", "slim", "--detach"], + flagArgs: ["--except", "store,other"], + envOverride: () => ({}), + }, { flag: "--baseline", field: "baseline", @@ -6850,7 +6858,7 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( ); await runCli(lease, outputCapture().environmentWith({ connectAdmin: async () => client })); - expect(inputs[0]?.[field]).toBe(value); + expect(inputs[0]?.[field]).toEqual(value); expect(inputs[1]).not.toHaveProperty(field); }, ); @@ -9809,7 +9817,7 @@ describe("simlock lease: a request names a model, a class, or nothing", () => { expect(output.stdout).toBe( "Usage: simlock lease --platform [--device | --class ]\n" + " [--os ] [--mode ] [--image-tag ] [--agent-id ]\n" + - " [--baseline ]\n" + + " [--except ] [--baseline ]\n" + " [--timeout ] [--lease-id ] [--physical]\n" + " [--no-wait] [--detach] [--ttl ] [--allow-download]\n" + " [--export-env] [--bind-pid ]\n", diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 625035a46..7ccc9d3f6 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -9,6 +9,7 @@ Shapes: - Public types are `z.infer`red from these schemas, never written a second time. - The daemon parses every handler result through the output schema; a core field the schema does not declare is stripped, never sent. - `config.get` carries a driver's own keys under `ios` and `android`, and a module's under `capabilities`, as sent: a new one is no shape change. +- `lease.request` holds `except` (a slim iOS simulator lease keeping slim categories running, ADR 0066) to one object-level refinement with no path (`exceptRefusal`, `operations.ts`), so every transport answers `BAD_REQUEST` with the message as written: 1 to 16 names matching `EXCEPT_NAME_PATTERN`, none twice, never with `physical`, a platform but iOS or `mode: full`. The worker's default mode and a baseline's mode are checked in leasing. - Wire input is a claim: every field a gateway parses from a worker is bounded here (`fit*`, `CONSOLE_URL_MAX_LENGTH`, `relay.ts`). - One OS grammar (`os-range.ts`), one duration parser (`duration.ts`), one usage window (`usageWindow`, `usage-window.ts`), one events page query (`eventsPageQuery`, `events-page.ts`). Nobody else parses. - `inbox.ts` and `version-order.ts` import nothing at run time: the console imports each by its own path, not the index (the index carries zod). diff --git a/src/contract/device-schemas.ts b/src/contract/device-schemas.ts index 7085495f4..88b6b8bb9 100644 --- a/src/contract/device-schemas.ts +++ b/src/contract/device-schemas.ts @@ -34,6 +34,14 @@ const devicePresenceSchema = z.discriminatedUnion("present", [ z.object({ present: z.literal(false), reason: absentReasonSchema }), ]); +/** why: the category names a slim lease kept running (ADR 0066 §1); the same bounds as the request's `except`. */ +export const EXCEPT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,31}$/; +export const EXCEPT_MAX_NAMES = 16; +export const exceptCategoriesSchema = z + .array(z.string().regex(EXCEPT_NAME_PATTERN)) + .min(1) + .max(EXCEPT_MAX_NAMES); + export const physicalClassSchema = z.enum(["phone", "tablet"]); function checkDeviceType( @@ -225,6 +233,7 @@ export const deviceRecordSchema = z absentReason: absentReasonSchema.optional(), physical: z.boolean(), mode: deviceModeSchema.optional(), + except: exceptCategoriesSchema.optional(), class: physicalClassSchema.optional(), leaseIdentity: leaseIdentitySchema.optional(), transitionAgeMs: z.number().optional(), @@ -246,6 +255,7 @@ export const statusDeviceSchema = z state: deviceStateSchema, physical: z.boolean(), mode: deviceModeSchema.optional(), + except: exceptCategoriesSchema.optional(), class: physicalClassSchema.optional(), driverDeviceId: z.string().optional(), servesDefaultMode: z.boolean(), @@ -284,6 +294,7 @@ export const grantedDeviceSchema = z address: z.string().optional(), physical: z.boolean(), mode: deviceModeSchema.optional(), + except: exceptCategoriesSchema.optional(), class: physicalClassSchema.optional(), }) .superRefine((device, context) => checkDeviceType(device, context, false)); diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 1fbeb1f66..4dbbeecce 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -25,6 +25,8 @@ import { doctorReportSchema, eventEnvelopeSchema, EVENT_ID_PATTERN, + EXCEPT_MAX_NAMES, + EXCEPT_NAME_PATTERN, hostFactsSchema, requesterIdSchema, historyStatusSchema, @@ -158,6 +160,8 @@ const leaseRequestBaseSchema = z // before the handler, and its error would stand in for `BAD_REQUEST`. osVersion: z.string().optional(), mode: z.enum(["slim", "full"]).optional(), + // why: A plain array of plain strings, bounded by `refuseBadExcept` as the one object-level check, like `osVersion`: a bound on the field itself would be checked by the MCP SDK before the handler. + except: z.array(z.string()).optional(), imageTag: imageTagSchema.optional(), baseline: baselineNameSchema.optional(), physical: z.boolean().optional(), @@ -263,6 +267,46 @@ function refuseRequiresWithIdempotencyKey(): < }; } +/** why: one object-level check with no path (like `osVersion`), so every transport, MCP included, answers `BAD_REQUEST` with the message as written. */ +function refuseBadExcept(): < + T extends { + readonly except?: readonly string[] | undefined; + readonly mode?: unknown; + readonly physical?: boolean | undefined; + readonly platform: string; + }, +>( + input: T, + context: z.RefinementCtx, +) => void { + return (input, context) => { + const { except } = input; + if (except === undefined) return; + const message = exceptRefusal(input, except); + if (message !== undefined) context.addIssue({ code: "custom", message }); + }; +} + +function exceptRefusal( + input: { + readonly mode?: unknown; + readonly physical?: boolean | undefined; + readonly platform: string; + }, + except: readonly string[], +): string | undefined { + if (except.length < 1 || except.length > EXCEPT_MAX_NAMES) { + return `except names 1 to ${EXCEPT_MAX_NAMES} categories`; + } + const bad = except.find((name) => !EXCEPT_NAME_PATTERN.test(name)); + if (bad !== undefined) return `except: "${bad}" is not a category name`; + const twice = except.find((name, index) => except.indexOf(name) !== index); + if (twice !== undefined) return `except names "${twice}" twice`; + if (input.physical === true || input.platform !== "ios") return "except is for iOS simulators"; + if (input.mode === "full") return "except needs a slim lease (mode is full)"; + return undefined; +} + function refuseBadOsVersion(): ( input: T, context: z.RefinementCtx, @@ -297,6 +341,7 @@ const leaseRequestInputSchema = leaseRequestBaseSchema .superRefine(refuseModelWithClass()) .superRefine(refuseBaselineWithClass()) .superRefine(refuseBadOsVersion()) + .superRefine(refuseBadExcept()) .superRefine(refusePhysicalWithImageFields()) .superRefine(refuseRequiresWithIdempotencyKey()); @@ -311,13 +356,18 @@ export const leaseRequest = defineOperation({ // `requesterId` (printable, at most 256 characters), and `owner` is gated by role in the handler (the resource does not exist yet). }); -export function requestedDevice(input: z.infer) { +export function requestedDevice( + input: Omit, "except"> & { + readonly except?: readonly string[] | undefined; + }, +) { return { ...(input.model === undefined ? {} : { model: input.model }), ...(input.class === undefined ? {} : { class: input.class }), platform: input.platform, ...(input.osVersion === undefined ? {} : { osVersion: input.osVersion }), ...(input.mode === undefined ? {} : { mode: input.mode }), + ...(input.except === undefined ? {} : { except: [...input.except] }), ...(input.imageTag === undefined ? {} : { imageTag: input.imageTag }), ...(input.baseline === undefined ? {} : { baseline: input.baseline }), ...(input.physical === true ? { physical: true as const } : {}), diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index bb24a0aa4..89a573197 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 78, max: 78 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 79, max: 79 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index 780d2b3ef..50ab4d0a1 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -31,6 +31,8 @@ Devices: - Grant paths select by exact state. `mayBeGranted` refuses every virtual device that has ended a lease, whatever its `leaseIdentity` (ADR 0061 §2). - A physical device is never destroyed and never counted against capacity. - `bootForLease` and `readyProvisionedForLease` keep the `boot` claim for the grant; `bootWarm` drops it at `ready`. +- `rebootForLease` shuts a `ready` device down and prepares it again with a lease's `except` list under that claim. The record stays `ready` (one `recordRebootedDevice` write, no event); on a failure it commits `ready → shutdown` first. +- `devices.except_categories` holds the list a lease kept running, written in the grant commit (`createLease`). - `shutdown`, `destroy` and `dispose` answer `undefined` for a leased, gone or moved device. That is not an error. - Unreadable is not gone: startup skips a platform it could not list; doctor reports no drift there. - Warm pool and startup never install. Instance id is never regenerated. diff --git a/src/core/device-provisioner.ts b/src/core/device-provisioner.ts index dd85a6c5b..b79b153e3 100644 --- a/src/core/device-provisioner.ts +++ b/src/core/device-provisioner.ts @@ -49,6 +49,8 @@ export interface ProvisionDeviceOptions { * handoff, so a request planning in between sees a device that is on its way, and whose. */ readonly claim?: { readonly kind: "boot"; readonly owner?: string }; + /** why: the categories a slim lease keeps running, handed to the driver at the boot before the grant (ADR 0066 §2). */ + readonly except?: readonly string[]; readonly onProgress?: (progress: ProvisionProgress) => void; readonly reservation: CapacityReservation; } @@ -168,7 +170,11 @@ export class DeviceProvisioner { ): Promise { try { options.onProgress?.({ stage: "booting", etaMs: bootEstimate() }); - const ready = await this.options.lifecycle.readyProvisionedForLease(device, bootClaim); + const ready = await this.options.lifecycle.readyProvisionedForLease( + device, + bootClaim, + options.except, + ); if (ready === undefined) throw new Error(`Registered device could not be made ready: ${device.id}`); return ready; diff --git a/src/core/domain.ts b/src/core/domain.ts index fb8ab9065..8f88cd511 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -351,6 +351,8 @@ export interface VirtualDevice extends DeviceRecordFields { readonly spec: VirtualSpec; readonly state: VirtualState; readonly mode: DeviceMode; + /** why: the categories the lease this device serves kept running (ADR 0066 §4); written in the grant commit and never cleared, since a virtual device serves one lease. */ + readonly except?: readonly string[]; /** why: a record written before this field existed loads as `reusable`. */ readonly leaseIdentity?: LeaseIdentity; } @@ -364,6 +366,7 @@ export interface PhysicalDevice extends DeviceRecordFields { readonly reclaimingSince?: number; readonly absentReason?: AbsentReason; readonly mode?: undefined; + readonly except?: undefined; readonly leaseIdentity?: undefined; } diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index 1f5aa3a4a..9e47daeb9 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -37,6 +37,7 @@ import { type PresentPhysical, type ReclaimResult, removeListedComponent, + BadDeviceRequestError, RuntimeMissingError, UnknownModelError, uninstallPlan, @@ -98,6 +99,8 @@ export interface FakeDriverOptions { readonly fullCleanReclaimEstimateMs?: number; readonly mode?: DeviceMode | undefined; readonly slimmableOsVersions?: readonly string[]; + /** why: the categories this worker slims; a request's `except` naming another is refused at resolve, as the iOS driver does. Absent: every name is accepted. */ + readonly slimCategories?: readonly string[]; readonly knownModels?: readonly string[]; readonly modelRuntimes?: Readonly>; readonly modelAliases?: Readonly>; @@ -160,6 +163,7 @@ export class FakeDriver implements Driver { readonly #estimateMs: FakeDriverOptions["estimateMs"]; readonly #mode: DeviceMode | undefined; readonly #slimmableOsVersions: ReadonlySet; + readonly #slimCategories: ReadonlySet | undefined; readonly #fullCleanReclaimEstimateMs: number | undefined; readonly #failures = new Map(); #hangMakeReady = false; @@ -204,6 +208,8 @@ export class FakeDriver implements Driver { this.#estimateMs = options.estimateMs; this.#mode = options.mode; this.#slimmableOsVersions = new Set(options.slimmableOsVersions ?? []); + this.#slimCategories = + options.slimCategories === undefined ? undefined : new Set(options.slimCategories); this.#fullCleanReclaimEstimateMs = options.fullCleanReclaimEstimateMs; this.#knownModels = options.knownModels === undefined ? undefined : new Set(options.knownModels); @@ -262,6 +268,10 @@ export class FakeDriver implements Driver { if (this.#knownModels !== undefined && !this.#knownModels.has(request.model)) { throw new UnknownModelError(this.platform, request.model); } + const unknownCategory = request.except?.find((name) => !this.#slimCategories?.has(name)); + if (this.#slimCategories !== undefined && unknownCategory !== undefined) { + throw new BadDeviceRequestError(`unknown slim category "${unknownCategory}"`); + } const osVersion = request.imageTag === undefined @@ -492,7 +502,11 @@ export class FakeDriver implements Driver { async makeReady( device: DriverDevice, - options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode }, + options: { + readonly purpose: "prepare" | "recover"; + readonly mode: DeviceMode; + readonly except?: readonly string[]; + }, ): Promise { await this.#beforeCall("makeReady", device, options); this.#requireDevice(device); diff --git a/src/core/managed-device-lifecycle.test.ts b/src/core/managed-device-lifecycle.test.ts index ef671aaaf..7974e4cab 100644 --- a/src/core/managed-device-lifecycle.test.ts +++ b/src/core/managed-device-lifecycle.test.ts @@ -315,6 +315,23 @@ describe("ManagedDeviceLifecycle", () => { ).resolves.toMatchObject({ state: "shutdown" }); }); + it("rebootForLease ends its boot claim when recording the rebooted device throws", async () => { + const harness = await createHarness(); + const ready = await readyDevice(harness); + vi.spyOn(harness.registry, "recordRebootedDevice").mockRejectedValueOnce( + new Error("state.db is read-only"), + ); + + const claim = harness.claims.tryClaim(ready.id, "boot"); + if (claim === undefined) throw new Error("the device was already claimed"); + + await expect(harness.lifecycle.rebootForLease(ready, claim, ["store"])).rejects.toThrow( + "state.db is read-only", + ); + + expect(harness.claims.isClaimed(ready.id)).toBe(false); + }); + describe("recoverLeased", () => { it("reboots a leased device under its own lease id without a registry transition", async () => { const harness = await createHarness(); diff --git a/src/core/managed-device-lifecycle.ts b/src/core/managed-device-lifecycle.ts index a6e8460b8..9477a0363 100644 --- a/src/core/managed-device-lifecycle.ts +++ b/src/core/managed-device-lifecycle.ts @@ -40,6 +40,10 @@ export interface ManagedDeviceRegistry { }, update?: DeviceTransitionUpdate, ): Promise; + recordRebootedDevice( + deviceId: string, + update: Required>, + ): Promise; } interface ClaimedDevice { @@ -71,8 +75,9 @@ export class ManagedDeviceLifecycle { async bootForLease( target: VirtualDevice, claim: DeviceOperationClaim, + except?: readonly string[], ): Promise { - return this.#makeReadyForLease(target, "shutdown", claim); + return this.#makeReadyForLease(target, "shutdown", claim, except); } /** @@ -91,12 +96,73 @@ export class ManagedDeviceLifecycle { return handoff.device; } + /** + * why: Shuts a ready device down and prepares it again with a lease's except list under the `boot` + * claim the caller took, and keeps the claim for the handoff. The record stays `ready` + * throughout, so capacity and the warm pool see no change; the new boot is recorded in one + * write with no transition and no event. `undefined` when the device is no longer a ready, + * unleased one. + */ + async rebootForLease( + target: VirtualDevice, + claim: DeviceOperationClaim, + except: readonly string[], + ): Promise { + const claimed = await this.#claim(target, ["ready"], "boot", claim); + if (claimed === undefined) return undefined; + const driver = this.catalog.get(claimed.device.spec.platform); + let ready: DriverDevice; + try { + await driver.shutdown(toDriverDevice(claimed.device)); + ready = await driver.makeReady(toDriverDevice(claimed.device), { + except, + mode: specMode(claimed.device.spec), + purpose: "prepare", + }); + } catch (error: unknown) { + // why: the device is half way between two boots, so it is recorded as shut down for the caller to destroy; the claim ends either way. + try { + await this.#commitWithoutRelease(claimed, ["ready"], "shutdown", { + event: "device.shutdown", + payload: { deviceId: claimed.device.id, initiator: "lease-engine" }, + }); + } finally { + await this.#release(claimed); + } + throw error; + } + let device: VirtualDevice | undefined; + try { + device = await this.decisions.run(async () => { + const current = this.#registeredTarget(claimed.device, ["ready"]); + if (current === undefined) return undefined; + // why: `mode` defaults to full here as `readyTransitionUpdate` does, so a reboot granted full records full. + return assertVirtual( + await this.registry.recordRebootedDevice(current.id, { + address: ready.address, + driverData: ready.driverData, + mode: ready.mode ?? "full", + }), + ); + }); + } catch (error: unknown) { + await this.#release(claimed); + throw error; + } + if (device === undefined) { + await this.#release(claimed); + return undefined; + } + return { claim: claimed.claim, device }; + } + /** Makes a provisioned device ready while retaining its claim for lease handoff. */ async readyProvisionedForLease( target: VirtualDevice, claim?: DeviceOperationClaim, + except?: readonly string[], ): Promise { - return this.#makeReadyForLease(target, "provisioning", claim); + return this.#makeReadyForLease(target, "provisioning", claim, except); } async shutdown( @@ -231,6 +297,7 @@ export class ManagedDeviceLifecycle { target: VirtualDevice, expectedState: "provisioning" | "shutdown", existingClaim?: DeviceOperationClaim, + except?: readonly string[], ): Promise { const claimed = await this.#claim(target, [expectedState], "boot", existingClaim); if (claimed === undefined) return undefined; @@ -242,6 +309,7 @@ export class ManagedDeviceLifecycle { .makeReady(toDriverDevice(claimed.device), { mode: specMode(claimed.device.spec), purpose: "prepare", + ...(except === undefined ? {} : { except }), }); } catch (error: unknown) { await this.#release(claimed); diff --git a/src/core/registry-except.test.ts b/src/core/registry-except.test.ts new file mode 100644 index 000000000..6c0567c9d --- /dev/null +++ b/src/core/registry-except.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; + +import { EventBus } from "../bus/index.js"; +import { FakeClock } from "../ports/index.js"; +import { loadTestRegistry, openTestState } from "./testing.js"; +import type { VirtualSpec } from "./index.js"; + +const spec: VirtualSpec = { + mode: "slim", + model: "iPhone 16", + osVersion: "26.5", + physical: false, + platform: "ios", +}; + +describe("Registry: an except list", () => { + it("keeps the list a lease kept running on its device and on its stored request across a reload, and none where none was named", async () => { + const clock = new FakeClock(1_000); + const state = await openTestState(); + let next = 0; + const load = () => + loadTestRegistry({ + clock, + eventBus: new EventBus(clock), + idGenerator: { generate: () => String((next += 1)) }, + state, + }); + const registry = await load(); + const except = ["store", "other"]; + const lease = async (name: string, withExcept: boolean) => { + const device = await registry.registerDevice({ + driverData: { fakeDeviceId: name }, + driverDeviceId: name, + provisionDuration: 0, + spec, + }); + await registry.transitionDevice(device.id, "ready", { + event: "device.ready", + payload: { bootDuration: 0, deviceId: device.id }, + }); + await registry.createLeaseRequest({ + id: `req_${name}`, + ownerId: "agent", + request: { platform: "ios", ...(withExcept ? { except } : {}) }, + requesterId: name, + }); + await registry.createLease({ + deviceId: device.id, + ...(withExcept ? { except } : {}), + ownerId: "agent", + requesterId: name, + ttlDeadline: 5_000, + ttlMs: 4_000, + }); + return device.id; + }; + const kept = await lease("with", true); + const plain = await lease("without", false); + + const reloaded = await load(); + + const deviceOf = (id: string) => reloaded.snapshot.devices.find((d) => d.id === id); + expect(deviceOf(kept)).toMatchObject({ except }); + expect(deviceOf(plain)).not.toHaveProperty("except"); + const requestOf = (name: string) => + reloaded.leaseRequests().find((record) => record.id === `req_${name}`)?.request; + expect(requestOf("with")).toEqual({ except, platform: "ios" }); + expect(requestOf("without")).toEqual({ platform: "ios" }); + }); +}); diff --git a/src/core/registry-rows.ts b/src/core/registry-rows.ts index 604a32788..1a66c3f4c 100644 --- a/src/core/registry-rows.ts +++ b/src/core/registry-rows.ts @@ -170,6 +170,7 @@ const DEVICE_COLUMNS = [ "absent_reason", "baseline_name", "baseline_version", + "except_categories", ] as const; const LEASE_COLUMNS = [ @@ -197,6 +198,7 @@ const REQUEST_COLUMNS = [ "mode", "image_tag", "baseline", + "except_categories", "class", "physical", "created_at", @@ -274,6 +276,7 @@ function deviceValues(device: DeviceRecord): SqliteValue[] { device.address ?? null, ...physicalColumns(device), ...baselineColumns(device), + device.except === undefined ? null : device.except.join(","), ]; } @@ -343,6 +346,7 @@ export function writeLeaseRequest(database: SqliteDatabase, record: LeaseRequest request.mode ?? null, request.imageTag ?? null, request.baseline ?? null, + request.except === undefined ? null : request.except.join(","), request.class ?? null, flagValue(request.physical), record.createdAt, @@ -496,6 +500,7 @@ function deviceFromRow( ...shared, driverData: readDeviceData(database, deviceData, platform, id), ...present("leaseIdentity", reader.optOneOf("lease_identity", LEASE_IDENTITIES)), + ...present("except", exceptOf(reader)), mode: reader.oneOf("mode", DEVICE_MODES), physical: false, spec: { @@ -512,6 +517,10 @@ function deviceFromRow( return virtual; } +function exceptOf(reader: RowReader): readonly string[] | undefined { + return reader.optText("except_categories")?.split(","); +} + function baselineOf(reader: RowReader): { baseline?: { name: string; version: number } } { const name = reader.optText("baseline_name"); const version = reader.optInt("baseline_version"); @@ -620,6 +629,7 @@ function requestFromRow(reader: RowReader): DeviceRequest { ...present("mode", reader.optOneOf("mode", DEVICE_MODES)), ...present("imageTag", reader.optText("image_tag")), ...present("baseline", reader.optText("baseline")), + ...present("except", exceptOf(reader)), ...present("class", reader.optOneOf("class", DEVICE_CLASSES)), ...present("physical", reader.optFlag("physical")), }; diff --git a/src/core/registry-schema.ts b/src/core/registry-schema.ts index d3a6b15d4..794f2c1a9 100644 --- a/src/core/registry-schema.ts +++ b/src/core/registry-schema.ts @@ -124,8 +124,13 @@ const REGISTRY_V3 = ` ALTER TABLE lease_requests ADD COLUMN baseline TEXT; `; +const REGISTRY_V4 = ` +ALTER TABLE devices ADD COLUMN except_categories TEXT; +ALTER TABLE lease_requests ADD COLUMN except_categories TEXT; +`; + export const registryOwner: SqliteSchemaOwner = { - migrations: [REGISTRY_V1, REGISTRY_V2, REGISTRY_V3], + migrations: [REGISTRY_V1, REGISTRY_V2, REGISTRY_V3, REGISTRY_V4], name: "registry", - version: 3, + version: 4, }; diff --git a/src/core/registry.ts b/src/core/registry.ts index db2ea06cd..002be9828 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -114,6 +114,8 @@ export interface CreateLeaseInput { readonly ttlDeadline: number; /** why: the caller has already refused an ID that is in use: one place enforces that rule. */ readonly leaseId?: string; + /** why: the categories the lease keeps running, written to the device in the commit that leases it (ADR 0066 §4). */ + readonly except?: readonly string[]; /** * why: when given, the commit that adds the lease also marks the request `granted`, so no crash can * fall between the two. @@ -294,6 +296,25 @@ export class Registry implements LeaseRequestStore { return this.#committed(deviceId); } + /** + * why: a ready device shut down and prepared again for a lease (ADR 0066 §2) keeps its state, so this is no transition and emits no event (`ready → ready` is no edge); it records only what the new boot produced. + */ + // fallow-ignore-next-line unused-class-member -- called through `ManagedDeviceRegistry`, which `Registry` implements. + async recordRebootedDevice( + deviceId: string, + update: Required>, + ): Promise { + const { device, index } = this.#requireDeviceRecord(deviceId); + if (device.physical || device.state !== "ready") { + throw new RegistryEventError(`Only a ready virtual device can be rebooted: ${deviceId}`); + } + const updated = { ...device, ...update }; + const devices = [...this.#devices]; + devices[index] = updated; + this.#commit(devices, this.#leases); + return this.#committed(deviceId); + } + async completeReclaimWithoutPurge(deviceId: string): Promise { const { device, index } = this.#requireDeviceRecord(deviceId); if (device.state !== "reclaiming") { @@ -745,6 +766,7 @@ export class Registry implements LeaseRequestStore { ttlMs, ttlDeadline, leaseId, + except, request, }: CreateLeaseInput): Promise { const index = this.#devices.findIndex((device) => device.id === deviceId); @@ -760,7 +782,8 @@ export class Registry implements LeaseRequestStore { throw new RegistryEventError(`Device already has an active lease: ${deviceId}`); } - const leasedDevice = this.#transitioned(device, "leased"); + const leased = this.#transitioned(device, "leased"); + const leasedDevice = except === undefined || leased.physical ? leased : { ...leased, except }; const grantedAt = this.options.clock.now(); const lease: LeaseRecord = { deviceId, diff --git a/src/daemon/dispatcher-except.test.ts b/src/daemon/dispatcher-except.test.ts new file mode 100644 index 000000000..287eb6748 --- /dev/null +++ b/src/daemon/dispatcher-except.test.ts @@ -0,0 +1,388 @@ +import { describe, expect, it, vi } from "vitest"; + +import { readyTransitionUpdate } from "../core/testing.js"; +import { DriverCrashError } from "../core/index.js"; +import { classifyError } from "./error-code.js"; +import { buildDispatcher, session } from "./test-dispatcher.js"; + +/** why: the answer of a request that must settle by itself once the event loop has run to rest; a hang fails here, on a named assertion, rather than by the test's timeout. */ +async function grantedOnceSettled(request: Promise): Promise { + const rest = (async () => { + for (let turn = 0; turn < 50; turn += 1) await new Promise((resolve) => setImmediate(resolve)); + return undefined; + })(); + const answer = await Promise.race([request, rest]); + expect(answer, "the request settled").toBeDefined(); + return answer as T; +} + +/** why: a slim device a worker already holds, ready or shut down, as the warm pool or an earlier lease leaves one. */ +async function seedSlimDevice( + built: Awaited>, + state: "ready" | "shutdown", +) { + const spec = { + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + physical: false, + platform: "ios", + } as const; + const driverDevice = await built.driver.provision(spec); + const driven = await built.driver.makeReady(driverDevice, { mode: "slim", purpose: "prepare" }); + // why: the seed is a slim device whatever the fake reports on its boot, so a test whose driver answers `full` still starts from slim. + const ready = { ...driven, mode: "slim" as const }; + const registered = await built.registry.registerDevice({ + driverData: driverDevice.driverData, + driverDeviceId: driverDevice.deviceId, + provisionDuration: 0, + spec, + }); + await built.registry.transitionDevice( + registered.id, + "ready", + { event: "device.ready", payload: { bootDuration: 0, deviceId: registered.id } }, + readyTransitionUpdate(ready), + ); + if (state === "ready") return registered; + await built.driver.shutdown(driverDevice); + await built.registry.transitionDevice(registered.id, "shutdown", { + event: "device.shutdown", + payload: { deviceId: registered.id, initiator: "test" }, + }); + return registered; +} + +describe("Dispatcher: lease.request with an except list", () => { + it("a client leases slim with except and is granted a device reporting it", async () => { + const except = ["store", "other"]; + const ask = { model: "iPhone 17 Pro", platform: "ios", mode: "slim", except } as const; + + const slimmed = await buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); + const granted = await slimmed.dispatcher.dispatch( + "lease.request", + { ...ask, osVersion: "26.5" }, + session(), + ); + const listed = await slimmed.dispatcher.dispatch( + "list.get", + { kind: "devices" }, + session({ role: "admin" }), + ); + const status = await slimmed.dispatcher.dispatch("status.get", {}, session()); + expect(granted.device).toMatchObject({ except, mode: "slim" }); + expect( + slimmed.driver.calls.find((call) => call.operation === "makeReady")?.arguments[1], + ).toMatchObject({ except, mode: "slim", purpose: "prepare" }); + expect( + (listed as { id: string; except?: string[] }[]).find((d) => d.id === granted.device.id), + ).toMatchObject({ except }); + expect(status.devices?.find((d) => d.id === granted.device.id)).toMatchObject({ except }); + expect( + slimmed.eventBus.replay().find((event) => event.event === "lease.requested")?.payload, + ).toMatchObject({ requestSpec: { except } }); + + const warm = await buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); + const registered = await seedSlimDevice(warm, "ready"); + const seededCalls = warm.driver.calls.length; + const grantedWarm = await warm.dispatcher.dispatch( + "lease.request", + { ...ask, osVersion: "26.5" }, + session(), + ); + expect(grantedWarm.device).toMatchObject({ except, id: registered.id, mode: "slim" }); + // why: the seed's boot was the device's first, so the reboot's address is the second boot's. + expect(grantedWarm.device.address).toBe(`${registered.driverDeviceId}-addr-2`); + expect( + warm.driver.calls + .slice(seededCalls) + .filter((call) => call.operation === "shutdown" || call.operation === "makeReady") + .map((call) => call.operation), + ).toEqual(["shutdown", "makeReady"]); + expect( + warm.driver.calls.slice(seededCalls).find((call) => call.operation === "makeReady") + ?.arguments[1], + ).toMatchObject({ except, mode: "slim", purpose: "prepare" }); + expect( + warm.eventBus.replay().find((event) => event.event === "lease.granted")?.payload, + ).toMatchObject({ source: "booted" }); + + const full = await buildDispatcher({ + driverOptions: { availableOsVersions: ["18.4", "26.5"], slimmableOsVersions: ["26.5"] }, + }); + const grantedFull = await full.dispatcher.dispatch( + "lease.request", + { ...ask, osVersion: "18.4" }, + session(), + ); + expect(grantedFull.device.mode).toBe("full"); + expect(grantedFull.device).not.toHaveProperty("except"); + expect( + full.driver.calls.find((call) => call.operation === "makeReady")?.arguments[1], + ).not.toHaveProperty("except"); + }); + + it("a client's except request is refused with BAD_REQUEST and the reason, and a slim baseline on a full-default worker is granted", async () => { + const ask = { + except: ["store"], + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + } as const; + const { mode: _mode, ...noMode } = ask; + const driverOptions = { slimCategories: ["store", "other"], slimmableOsVersions: ["26.5"] }; + const attempt = async (input: unknown, defaultMode: "slim" | "full" = "slim") => { + const built = await buildDispatcher({ + driverOptions, + engine: { defaultModes: { ios: defaultMode } }, + }); + return built.dispatcher.dispatch("lease.request", input as never, session()).then( + () => undefined, + (error: unknown) => error, + ); + }; + + expect(await attempt(ask)).toBeUndefined(); + const refusals: readonly [string, unknown, string, ("slim" | "full")?][] = [ + ["duplicate", { ...ask, except: ["store", "store"] }, 'except names "store" twice'], + ["bad characters", { ...ask, except: ["Store"] }, 'except: "Store" is not a category name'], + ["none named", { ...ask, except: [] }, "except names 1 to 16 categories"], + [ + "too many", + { ...ask, except: Array.from({ length: 17 }, (_, index) => `c${index}`) }, + "except names 1 to 16 categories", + ], + ["mode full", { ...ask, mode: "full" }, "except needs a slim lease (mode is full)"], + [ + "default full", + noMode, + "except needs a slim lease (this worker's default mode is full)", + "full", + ], + ["physical", { ...ask, physical: true }, "except is for iOS simulators"], + ["android", { ...ask, platform: "android" }, "except is for iOS simulators"], + [ + "a name the driver refuses", + { ...ask, except: ["wallet"] }, + 'unknown slim category "wallet"', + ], + ]; + for (const [label, input, message, defaultMode] of refusals) { + const error = await attempt(input, defaultMode); + expect(classifyError(error), label).toBe("BAD_REQUEST"); + expect((error as Error).message, label).toContain(message); + } + + const { dispatcher } = await buildDispatcher({ + driverOptions, + engine: { defaultModes: { ios: "full" } }, + }); + const save = async (name: string, mode: "slim" | "full", principal: string) => { + const lease = await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", mode, osVersion: "26.5", platform: "ios" }, + session({ principal }), + ); + await dispatcher.dispatch( + "baseline.save", + { leaseId: lease.lease.id, name }, + session({ principal, role: "admin" }), + ); + }; + await save("slim-base", "slim", "tok_a"); + await save("full-base", "full", "tok_b"); + const fromFull = await dispatcher + .dispatch( + "lease.request", + { baseline: "full-base", except: ["store"], platform: "ios" }, + session({ principal: "tok_c" }), + ) + .catch((error: unknown) => error); + expect(classifyError(fromFull)).toBe("BAD_REQUEST"); + expect((fromFull as Error).message).toContain( + 'except needs a slim lease (baseline "full-base" is full)', + ); + const fromSlim = await dispatcher.dispatch( + "lease.request", + { baseline: "slim-base", except: ["store"], platform: "ios" }, + session({ principal: "tok_d" }), + ); + expect(fromSlim.device).toMatchObject({ except: ["store"], mode: "slim" }); + const unknownFromSlim = await dispatcher + .dispatch( + "lease.request", + { baseline: "slim-base", except: ["wallet"], platform: "ios" }, + session({ principal: "tok_e" }), + ) + .catch((error: unknown) => error); + expect(classifyError(unknownFromSlim)).toBe("BAD_REQUEST"); + expect((unknownFromSlim as Error).message).toContain('unknown slim category "wallet"'); + }); + + it("a slim except boot the driver grants full leaves the device full with no except, on a reboot and on a boot", async () => { + const ask = { + except: ["store"], + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + } as const; + const build = () => + buildDispatcher({ driverOptions: { mode: "full", slimmableOsVersions: ["26.5"] } }); + + for (const state of ["ready", "shutdown"] as const) { + const built = await build(); + const seeded = await seedSlimDevice(built, state); + const granted = await built.dispatcher.dispatch("lease.request", ask, session()); + + expect(granted.device.id, state).toBe(seeded.id); + expect(granted.device, state).not.toHaveProperty("except"); + const record = built.registry.snapshot.devices.find((d) => d.id === seeded.id); + expect(record, state).toMatchObject({ mode: "full", state: "leased" }); + expect(record, state).not.toHaveProperty("except"); + } + }); + + it("a failed except boot is never granted", async () => { + const ask = { + except: ["store"], + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + } as const; + const crash = new DriverCrashError("simulator never booted"); + const build = () => buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); + + const prepareFails = await build(); + const seededPrepare = await seedSlimDevice(prepareFails, "ready"); + // why: call 1 of makeReady is the seed's own boot; the reboot is call 2. + prepareFails.driver.failOn("makeReady", 2, crash); + const afterPrepare = await grantedOnceSettled( + prepareFails.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterPrepare.device.id).not.toBe(seededPrepare.id); + expect(afterPrepare.device).toMatchObject({ except: ask.except, mode: "slim" }); + expect( + prepareFails.registry.snapshot.devices.find((d) => d.id === seededPrepare.id)?.state, + ).toBe("deleted"); + expect( + prepareFails.eventBus + .replay() + .filter((event) => event.event === "lease.granted") + .map((event) => (event.payload as { deviceId: string }).deviceId), + ).toEqual([afterPrepare.device.id]); + + const shutdownFails = await build(); + const seededShutdown = await seedSlimDevice(shutdownFails, "ready"); + shutdownFails.driver.failOn("shutdown", 1, crash); + const afterShutdown = await grantedOnceSettled( + shutdownFails.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterShutdown.device.id).not.toBe(seededShutdown.id); + expect( + shutdownFails.registry.snapshot.devices.find((d) => d.id === seededShutdown.id)?.state, + ).toBe("deleted"); + expect( + shutdownFails.eventBus + .replay() + .filter((event) => event.event === "device.shutdown") + .map((event) => event.payload), + ).toContainEqual({ deviceId: seededShutdown.id, initiator: "lease-engine" }); + + const booting = await build(); + const seededShut = await seedSlimDevice(booting, "shutdown"); + const bootedShut = await booting.dispatcher.dispatch("lease.request", ask, session()); + expect(bootedShut.device).toMatchObject({ except: ask.except, id: seededShut.id }); + expect( + booting.driver.calls.filter((call) => call.operation === "makeReady").at(-1)?.arguments[1], + ).toMatchObject({ except: ask.except, purpose: "prepare" }); + expect( + booting.eventBus.replay().find((event) => event.event === "lease.granted")?.payload, + ).toMatchObject({ source: "booted" }); + + const bootFails = await build(); + const seededBootFails = await seedSlimDevice(bootFails, "shutdown"); + bootFails.driver.failOn("makeReady", 2, crash); + const afterBoot = await grantedOnceSettled( + bootFails.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterBoot.device.id).not.toBe(seededBootFails.id); + expect( + bootFails.registry.snapshot.devices.find((d) => d.id === seededBootFails.id)?.state, + ).toBe("deleted"); + + const twice = await build(); + twice.driver.failOn("provision", 1, crash); + twice.driver.failOn("makeReady", 1, crash); + const refusal = await twice.dispatcher + .dispatch("lease.request", ask, session()) + .catch((error: unknown) => error); + expect(classifyError(refusal)).toBe("PROVISION_FAILED"); + + const replay = await build(); + const keyed = { ...ask, idempotencyKey: "key-1" }; + const first = await replay.dispatcher.dispatch("lease.request", keyed, session()); + const same = await replay.dispatcher.dispatch("lease.request", keyed, session()); + expect(same.lease.id).toBe(first.lease.id); + const conflict = await replay.dispatcher + .dispatch("lease.request", { ...keyed, except: ["other"] }, session()) + .catch((error: unknown) => error); + expect(classifyError(conflict)).toBe("IDEMPOTENCY_CONFLICT"); + + // why: each failed boot or reboot counts toward the one retry, so a provision failure after it is the second. + for (const state of ["ready", "shutdown"] as const) { + const counted = await build(); + await seedSlimDevice(counted, state); + // why: call 1 of makeReady and of provision is the seed's own; call 2 of each is the waiter's. + counted.driver.failOn("makeReady", 2, crash); + counted.driver.failOn("provision", 2, crash); + const countedRefusal = await grantedOnceSettled( + counted.dispatcher.dispatch("lease.request", ask, session()).then( + () => undefined, + (error: unknown) => error ?? "granted", + ), + ); + expect(classifyError(countedRefusal), state).toBe("PROVISION_FAILED"); + } + + // why: a worker with one running slot is granted after a failed boot only when that boot released the slot it reserved. + const oneSlot = await buildDispatcher({ + capacity: { + config: { + limits: { + android: { maxDevices: 1, maxRunning: 1 }, + ios: { maxDevices: 1, maxRunning: 1 }, + maxRunning: 1, + }, + ramBudget: { androidBytesPerDevice: 4 * 1024 ** 3, iosBytesPerDevice: 1024 ** 3 }, + }, + strategy: "resource", + }, + driverOptions: { slimmableOsVersions: ["26.5"] }, + }); + await seedSlimDevice(oneSlot, "shutdown"); + oneSlot.driver.failOn("makeReady", 2, crash); + const afterOneSlot = await grantedOnceSettled( + oneSlot.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterOneSlot.device).toMatchObject({ except: ask.except, mode: "slim" }); + + const rebooting = await build(); + const seededWarm = await seedSlimDevice(rebooting, "ready"); + const before = (await rebooting.dispatcher.dispatch("status.get", {}, session())).capacity; + rebooting.driver.hangMakeReady(); + const pending = rebooting.dispatcher.dispatch("lease.request", ask, session()); + await vi.waitFor(() => { + expect(rebooting.driver.calls.filter((call) => call.operation === "makeReady")).toHaveLength( + 2, + ); + }); + const during = await rebooting.dispatcher.dispatch("status.get", {}, session()); + expect(during.devices?.find((d) => d.id === seededWarm.id)?.state).toBe("ready"); + expect(during.capacity).toEqual(before); + rebooting.driver.releaseMakeReady(); + expect((await pending).device.id).toBe(seededWarm.id); + }); +}); diff --git a/src/http/app-leases.test.ts b/src/http/app-leases.test.ts index c08c345f3..d4c7d46ae 100644 --- a/src/http/app-leases.test.ts +++ b/src/http/app-leases.test.ts @@ -128,6 +128,7 @@ describe("POST /v1/lease-requests", () => { it.each<[string, Record, Record?]>([ ["imageTag", { imageTag: "google_apis_playstore" }], ["mode", { mode: "slim" }], + ["except", { except: ["store", "other"] }], ["baseline", { baseline: "checkout" }], ["owner field rather than silently dropping it (ADR §27a, H7)", { owner: "someone-else" }], ["physical true", { physical: true }], diff --git a/src/http/app.ts b/src/http/app.ts index 9053693cf..a05843bc9 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -188,6 +188,7 @@ function leaseRequestOptionFields(body: z.infer) ...(body.noWait === undefined ? {} : { noWait: body.noWait }), ...(body.allowDownload === undefined ? {} : { allowDownload: body.allowDownload }), ...(body.mode === undefined ? {} : { mode: body.mode }), + ...(body.except === undefined ? {} : { except: body.except }), ...(body.physical === undefined ? {} : { physical: body.physical }), ...leaseRequestImageFields(body), }; diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index 4f0fcfaa6..19014dab2 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -5,6 +5,7 @@ import { deviceRecordSchema, baselineNameSchema, imageTagSchema, + exceptCategoriesSchema, EXEC_STDIN_MAX_LENGTH, INPUT_ORIENTATIONS, leaseIdSchema, @@ -29,6 +30,7 @@ const leasePayloadSchema = z.object({ baseline: z.object({ name: z.string(), version: z.number().int() }).optional(), imageTag: z.string().optional(), mode: z.enum(["slim", "full"]).optional(), + except: exceptCategoriesSchema.optional(), os: z.string(), platform: z.string(), requestId: z.string().optional(), @@ -205,6 +207,8 @@ export const leaseRequestBodySchema = z imageTag: imageTagSchema.optional(), leaseId: leaseIdSchema.optional(), mode: z.enum(["slim", "full"]).optional(), + // why: a coarse bound only; `lease.request`'s own check words the refusal (count, characters, repeats), as for the CLI and MCP. + except: z.array(z.string().max(64)).max(64).optional(), noWait: z.boolean().optional(), // why: forwarded, not dropped: the dispatcher's `lease.request` handler alone decides whether this token may set it. owner: z.string().min(1).optional(), diff --git a/src/http/tracker.test.ts b/src/http/tracker.test.ts index f21ed9d2a..b4a7cf11e 100644 --- a/src/http/tracker.test.ts +++ b/src/http/tracker.test.ts @@ -33,6 +33,7 @@ async function createTracked( readonly platform: "ios" | "android"; readonly ttlMs?: number; readonly mode?: "slim" | "full"; + readonly except?: readonly string[]; readonly imageTag?: string; readonly baseline?: string; readonly physical?: boolean; @@ -319,6 +320,7 @@ describe("LeaseRequestTracker.submit with allowDownload on a gateway", () => { describe("LeaseRequestTracker.submit with an optional request field", () => { it.each([ ["mode", { mode: "slim" }], + ["except", { except: ["store", "other"] }], ["imageTag", { imageTag: "google_apis_playstore" }], ["baseline", { baseline: "checkout" }], ["physical", { physical: true }], @@ -348,11 +350,25 @@ describe("LeaseRequestTracker granted lease payload", () => { const state = tracker.get(view.id)?.state; if (state?.stage !== "granted") throw new Error("expected granted"); expect(state.lease.mode).toBe(mode); + expect(state.lease).not.toHaveProperty("except"); expect(state.lease).not.toHaveProperty("slim"); expect(state.lease).not.toHaveProperty("featureProfile"); }, ); + it("reports the granted device's except list beside its mode", async () => { + const { dispatcher, tracker } = buildTracker(); + const { view, callIndex } = await createTracked(tracker, dispatcher); + dispatcher.calls[callIndex]?.resolve( + makeGrant({ device: { except: ["store", "other"], mode: "slim" } }), + ); + await Promise.resolve(); + await Promise.resolve(); + const state = tracker.get(view.id)?.state; + if (state?.stage !== "granted") throw new Error("expected granted"); + expect(state.lease).toMatchObject({ except: ["store", "other"], mode: "slim" }); + }); + it("leaves mode off the lease for a granted physical device, which has none", async () => { const { dispatcher, tracker } = buildTracker(); const { view, callIndex } = await createTracked(tracker, dispatcher); diff --git a/src/http/tracker.ts b/src/http/tracker.ts index f4ba09280..2117fbdbe 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -16,6 +16,7 @@ export interface LeaseRequestInput { readonly noWait?: boolean; readonly allowDownload?: boolean; readonly mode?: "slim" | "full"; + readonly except?: readonly string[]; readonly imageTag?: string; readonly baseline?: string; readonly physical?: boolean; @@ -80,6 +81,7 @@ export function buildLeasePayload( ttlMs: lease.ttlMs, dataPlane: null, ...(device.mode === undefined ? {} : { mode: device.mode }), + ...(device.except === undefined ? {} : { except: device.except }), ...(device.spec.imageTag === undefined ? {} : { imageTag: device.spec.imageTag }), ...(device.spec.baseline === undefined ? {} : { baseline: device.spec.baseline }), // `workerId` derives from `worker` so the two never disagree. @@ -94,11 +96,18 @@ function leaseRequestDispatchInput(body: LeaseRequestInput, idempotencyKey: stri platform: body.platform, ...(body.os === undefined ? {} : { osVersion: body.os }), ...(body.mode === undefined ? {} : { mode: body.mode }), + ...(body.except === undefined ? {} : { except: body.except }), + ...requestImageFields(body), + ...requestOptions(body), + ...(idempotencyKey === undefined ? {} : { idempotencyKey }), + }; +} + +function requestImageFields(body: LeaseRequestInput) { + return { ...(body.imageTag === undefined ? {} : { imageTag: body.imageTag }), ...(body.baseline === undefined ? {} : { baseline: body.baseline }), ...(body.physical === undefined ? {} : { physical: body.physical }), - ...requestOptions(body), - ...(idempotencyKey === undefined ? {} : { idempotencyKey }), }; } @@ -395,6 +404,8 @@ export interface HttpLeaseDevice { }; /** Absent only for a physical device, which has no mode. */ readonly mode?: "slim" | "full" | undefined; + /** why: absent when the lease keeps no category running. */ + readonly except?: readonly string[] | undefined; } interface HttpLeaseRecord { diff --git a/src/leasing/AGENTS.md b/src/leasing/AGENTS.md index 69363f4b3..a579d7fb0 100644 --- a/src/leasing/AGENTS.md +++ b/src/leasing/AGENTS.md @@ -27,6 +27,8 @@ The queue: - A grant of a ready device wakes the queue, so the next waiter plans without another event. - A device made from an older baseline version is never granted: a copy that finishes after a save is deleted at the grant check, and its waiter plans again. - A request naming a baseline attempts no download. +- A request with `except` (ADR 0066) boots with the list. A ready warm device is shut down and prepared again under its `boot` claim, with no capacity reservation (plan `reboot-ready`, `ManagedDeviceLifecycle.rebootForLease`); the grant is `booted`. Any failure of that reboot or of a boot destroys the device and counts one failure with a failed provision. A request without `except` that fails to boot rejects `boot-timeout`. +- A slim baseline's `except` names go to `driver.resolveSpec` too, so an unknown name is `BAD_REQUEST`; a full baseline refuses `except`. Ending a lease: @@ -52,6 +54,7 @@ Boundaries: ## Known gaps +- **A crash mid-reboot of a warm device for an `except` lease** leaves the request failed at startup (`daemon-restarted`) and a `ready` record whose simulator may be shut down; startup's reconcile only reports that drift. A later grant of it is caught by the health monitor, which reboots it under the lease. - **A SIGKILLed holder keeps its device until the TTL.** It runs no release. Bound it with `lease.defaultTtlMs` or `--ttl`; `simlock release ` ends it now. - **Recovery restores the disk, not the session.** Apps, log streams and diff --git a/src/leasing/acquisition-planner.ts b/src/leasing/acquisition-planner.ts index bb93e2b69..c879de234 100644 --- a/src/leasing/acquisition-planner.ts +++ b/src/leasing/acquisition-planner.ts @@ -38,6 +38,8 @@ export interface AcquisitionPlannerInput { readonly snapshot: AcquisitionPlannerSnapshot; readonly spec: VirtualSpec; readonly requirement?: DeviceRequirement | undefined; + /** why: a slim request with an except list never takes a ready warm device as it is: the device is rebooted with the list first (ADR 0066 §2). */ + readonly rebootReady?: boolean | undefined; readonly classOf?: ((model: string) => DeviceClass | undefined) | undefined; } @@ -74,6 +76,11 @@ export function capacityReasonOf( export type AcquisitionPlan = | { readonly kind: "grant-ready"; readonly device: DeviceRecord } + | { + readonly kind: "reboot-ready"; + readonly claim: DeviceOperationClaim; + readonly device: VirtualDevice; + } | { readonly kind: "grant-physical"; readonly claim: DeviceOperationClaim; @@ -126,7 +133,7 @@ export class AcquisitionPlanner { const ready = snapshot.devices.find( (device) => device.state === "ready" && servesRequest(device), ); - if (ready !== undefined) return { device: ready, kind: "grant-ready" }; + if (ready !== undefined) return this.#planReady(input, ready); // A device the warm pool is booting for nobody in particular will serve this // request when it is ready: waiting for it costs less than starting a second. A device @@ -164,6 +171,14 @@ export class AcquisitionPlanner { return blocked(input.noWait, heldForOlder ? "behind-earlier-request" : "no-free-physical"); } + // why: no capacity reservation: the device keeps its running slot and RAM, because its record stays `ready` through the reboot. + #planReady(input: AcquisitionPlannerInput, ready: DeviceRecord): AcquisitionPlan { + if (input.rebootReady !== true || ready.physical) return { device: ready, kind: "grant-ready" }; + const claim = this.claims.tryClaim(ready.id, "boot", input.owner); + if (claim === undefined) return blocked(input.noWait, "waiting-for-device"); + return { claim, device: ready, kind: "reboot-ready" }; + } + #isOnItsWay(device: VirtualDevice, serves: (device: DeviceRecord) => boolean): boolean { if (device.state !== "provisioning" && device.state !== "shutdown") return false; const claim = this.claims.claim(device.id); diff --git a/src/leasing/acquisition-requests.ts b/src/leasing/acquisition-requests.ts new file mode 100644 index 000000000..4fe60797c --- /dev/null +++ b/src/leasing/acquisition-requests.ts @@ -0,0 +1,95 @@ +import { compareVersions, type OsRange, parseOsConstraint, satisfies } from "../contract/index.js"; +import { + type ComponentInstallerProgress, + type LeaseProgress, + type DeviceRequest, + type DeviceRequirement, + type DriverCatalogEntry, + pairedRuntimes, + type PhysicalRequest, + RuntimeMissingError, + type VirtualSpec, +} from "../core/index.js"; + +export function physicalRequestOf(request: DeviceRequest): PhysicalRequest { + return { + platform: request.platform, + ...(request.model === undefined ? {} : { model: request.model }), + ...(request.class === undefined ? {} : { class: request.class }), + ...(request.osVersion === undefined ? {} : { osVersion: request.osVersion }), + }; +} + +export function fullSpec(spec: VirtualSpec): VirtualSpec { + if (spec.mode === undefined) return spec; + const { mode: _mode, ...full } = spec; + return full; +} + +export type DownloadingProgress = Extract; + +export function downloadingProgress( + component: string, + progress: ComponentInstallerProgress, +): DownloadingProgress { + if (progress.stage === "waiting") return { component, stage: "downloading", waiting: true }; + const { percent } = progress; + return percent === undefined + ? { component, stage: "downloading", waiting: false } + : { component, percent: Math.floor(percent), stage: "downloading", waiting: false }; +} + +/** why: both reports are for the one component a `#resolveOrInstall` call downloads. */ +export function sameDownloadingProgress( + left: DownloadingProgress, + right: DownloadingProgress, +): boolean { + return left.waiting === right.waiting && left.percent === right.percent; +} + +export function matchingRuntimes( + entry: DriverCatalogEntry, + model: string, + { imageTag, osVersion }: Pick, + range: OsRange | undefined, +): string[] { + return pairedRuntimes(entry, model).filter( + (runtime) => + (range === undefined + ? osVersion === undefined || runtime === osVersion + : satisfies(runtime, range)) && + (imageTag === undefined || + (entry.images ?? []).some((image) => image.runtime === runtime && image.tag === imageTag)), + ); +} + +/** why: the newest runtime `model` pairs with that the request's range accepts, or none installed. */ +export function newestRuntime( + entry: DriverCatalogEntry, + model: string, + request: DeviceRequest, + range: OsRange, +): string { + const newest = matchingRuntimes(entry, model, request, range).sort(compareVersions).at(-1); + if (newest === undefined) throw new RuntimeMissingError(request.platform, range.text); + return newest; +} + +/** why: what a device's OS must satisfy: the range, the exact version named, or any installed runtime. */ +export function requiredOs( + entry: DriverCatalogEntry, + { osVersion }: DeviceRequest, + range: OsRange | undefined, +): DeviceRequirement["osVersion"] { + if (range !== undefined) return range; + return osVersion === undefined + ? { kind: "installed", versions: entry.runtimes } + : { kind: "exact", version: osVersion }; +} + +/** why: the request's OS range, when its `osVersion` is one rather than an exact version. */ +export function requestedRange(request: DeviceRequest): OsRange | undefined { + if (request.osVersion === undefined) return undefined; + const parsed = parseOsConstraint(request.osVersion); + return parsed.ok && parsed.constraint.kind === "range" ? parsed.constraint : undefined; +} diff --git a/src/leasing/acquisition-timing.ts b/src/leasing/acquisition-timing.ts new file mode 100644 index 000000000..4953f72bd --- /dev/null +++ b/src/leasing/acquisition-timing.ts @@ -0,0 +1,55 @@ +import { + type DeviceRecord, + type DeviceSpec, + type Driver, + type LeaseTiming, + toDriverDevice, +} from "../core/index.js"; + +export function estimatedTiming(driver: Driver, spec: DeviceSpec): LeaseTiming { + const estimatedProvisionMs = driver.estimate({ operation: "provision" }, spec); + const estimatedBootMs = driver.estimate({ operation: "boot" }, spec); + return { + estimatedBootMs, + estimatedProvisionMs, + estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), + estimatedReadyMs: estimatedProvisionMs + estimatedBootMs, + }; +} + +export async function estimatedBootTiming( + driver: Driver, + device: DeviceRecord, +): Promise { + const spec = device.spec; + // why: The quote is advisory. A driver that cannot read the device's own boot path (a failed + // `emulator -version`, say) must not strand the claim and capacity reservation that the boot + // below releases, so the device-less figure stands in. + const estimatedBootMs = await Promise.resolve( + driver.estimate( + { device: toDriverDevice(device), operation: "boot", purpose: "prepare" }, + spec, + ), + ).catch(() => driver.estimate({ operation: "boot" }, spec)); + return { + estimatedBootMs, + estimatedProvisionMs: 0, + estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), + estimatedReadyMs: estimatedBootMs, + }; +} + +/** why: a device that is already ready costs nothing to hand over; only its reclaim lies ahead. */ +export function grantReadyTiming(driver: Driver, spec: DeviceSpec): LeaseTiming { + return { + estimatedBootMs: 0, + estimatedProvisionMs: 0, + estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), + estimatedReadyMs: 0, + }; +} + +/** why: `standard`: every release path asks for it; a holder cannot request another clean level. */ +export function releaseReclaimEstimateMs(driver: Driver, spec: DeviceSpec): number { + return driver.estimate({ clean: "standard", operation: "reclaim" }, spec); +} diff --git a/src/leasing/lease-acquisition-coordinator.test.ts b/src/leasing/lease-acquisition-coordinator.test.ts index 8166b997c..f8034e203 100644 --- a/src/leasing/lease-acquisition-coordinator.test.ts +++ b/src/leasing/lease-acquisition-coordinator.test.ts @@ -677,6 +677,7 @@ describe("LeaseAcquisitionCoordinator", () => { // why: Fallow does not follow the type through the imported harness, and reports dispose unused. lifecycle: (lifecycle: ManagedDeviceLifecycle) => ({ bootForLease: (...args) => lifecycle.bootForLease(...args), + rebootForLease: (...args) => lifecycle.rebootForLease(...args), dispose: (...args) => { // why: an eviction is the waiter's own device work, so this is where a real one spends // the seconds its `timeoutMs` covers. The clock moves here to land the armed deadline @@ -1259,6 +1260,7 @@ describe("LeaseAcquisitionCoordinator", () => { const harness = await createHarness({ lifecycle: (lifecycle) => ({ bootForLease: (device, claim) => lifecycle.bootForLease(device, claim), + rebootForLease: (...args) => lifecycle.rebootForLease(...args), dispose: (...args) => lifecycle.dispose(...args), shutdown: (...args) => lifecycle.shutdown(...args), destroy: () => Promise.reject(new DriverCrashError("simulator would not delete")), @@ -1289,6 +1291,7 @@ describe("LeaseAcquisitionCoordinator", () => { maxRunning: 2, lifecycle: (lifecycle, { capacity, claims, registry }) => ({ bootForLease: (device, claim) => lifecycle.bootForLease(device, claim), + rebootForLease: (...args) => lifecycle.rebootForLease(...args), dispose: (...args) => lifecycle.dispose(...args), shutdown: (...args) => lifecycle.shutdown(...args), destroy: (device, initiator, operation, claim) => { diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index b1a53ee29..6b83c7cfd 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -1,12 +1,23 @@ import type { EventBus, EventMap } from "../bus/index.js"; -import { - compareVersions, - type OsRange, - parseOsConstraint, - requestedClass, - satisfies, -} from "../contract/index.js"; +import { type OsRange, requestedClass } from "../contract/index.js"; import { type IdGenerator, type Logger, NoopLogger } from "../ports/index.js"; +import { + downloadingProgress, + type DownloadingProgress, + fullSpec, + matchingRuntimes, + newestRuntime, + physicalRequestOf, + requestedRange, + requiredOs, + sameDownloadingProgress, +} from "./acquisition-requests.js"; +import { + estimatedBootTiming, + estimatedTiming, + grantReadyTiming, + releaseReclaimEstimateMs, +} from "./acquisition-timing.js"; import { type CapacityReservation, type DeviceOperationClaim, @@ -15,7 +26,6 @@ import { classCandidates, findCatalogModel, modelClass, - pairedRuntimes, type DeviceClass, type DeviceMode, type DeviceRecord, @@ -30,7 +40,6 @@ import { type VirtualSpec, exactRequirement, type LeaseGrant, - type LeaseProgress, type LeaseRecord, type MaxPerRequester, type LeaseTiming, @@ -40,7 +49,6 @@ import { specMode, ComponentBeingRemovedError, type ComponentInstaller, - type ComponentInstallerProgress, BootTimeoutError, type DeviceRequest, type Driver, @@ -55,6 +63,7 @@ import { type CurrentBaseline, UnknownBaselineError, BaselineMismatchError, + BadDeviceRequestError, BaselineStaleError, baselineMismatch, type AcquisitionMaintenance, @@ -176,7 +185,7 @@ export interface LeaseAcquisitionCoordinatorOptions { readonly leases: Pick; readonly lifecycle: Pick< ManagedDeviceLifecycle, - "bootForLease" | "destroy" | "dispose" | "shutdown" + "bootForLease" | "destroy" | "dispose" | "rebootForLease" | "shutdown" >; /** * The model names to try for each class, per platform, operator's list first (ADR 0015 §4), @@ -201,13 +210,19 @@ interface AcquisitionWaiter extends Waiter { timing: LeaseTiming; } -type GrantingPlanKind = "grant-ready" | "grant-physical" | "boot-shutdown" | "provision"; +type GrantingPlanKind = + | "grant-ready" + | "grant-physical" + | "boot-shutdown" + | "reboot-ready" + | "provision"; const GRANT_SOURCE: Readonly> = { "boot-shutdown": "booted", "grant-physical": "warm", "grant-ready": "warm", provision: "provisioned", + "reboot-ready": "booted", }; type OperationPlan = Exclude< @@ -543,9 +558,16 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { readonly requirement: DeviceRequirement; readonly classOf: ((model: string) => DeviceClass | undefined) | undefined; }> { - if (request.baseline !== undefined) return this.#resolveBaseline(request.baseline, request); + if (request.baseline !== undefined) { + return this.#resolveBaseline(driver, request.baseline, request); + } // The one place a request with no mode gets the worker's default (ADR 0007 §2). const mode = request.mode ?? this.defaultMode(request.platform); + if (request.except !== undefined && mode !== "slim") { + throw new BadDeviceRequestError( + "except needs a slim lease (this worker's default mode is full)", + ); + } const range = requestedRange(request); const target = range === undefined @@ -566,6 +588,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { /** why: a request naming a baseline takes the baseline's own platform, model, OS, mode and image tag; no download is ever attempted. */ async #resolveBaseline( + driver: Driver, name: string, request: DeviceRequest, ): Promise<{ @@ -582,6 +605,20 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { } if (current.staleReason !== undefined) throw new BaselineStaleError(name, current.staleReason); const spec = baselineSpec(current); + if (request.except !== undefined && spec.mode !== "slim") { + throw new BadDeviceRequestError(`except needs a slim lease (baseline "${name}" is full)`); + } + if (request.except !== undefined) { + // why: the driver judges the names (ADR 0066 §2); its answer is dropped, the baseline's spec stands. + await driver.resolveSpec({ + except: request.except, + mode: "slim", + model: spec.model, + osVersion: spec.osVersion, + platform: spec.platform, + ...(spec.imageTag === undefined ? {} : { imageTag: spec.imageTag }), + }); + } return { classOf: undefined, requirement: exactRequirement(spec), spec }; } @@ -950,6 +987,14 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { await this.#bootShutdown(waiter, action.device, action.capacityReservation, action.claim); return; } + if (action.kind === "reboot-ready") { + waiter.timing = await estimatedBootTiming( + this.options.drivers.get(action.device.spec.platform), + action.device, + ); + await this.#rebootReady(waiter, action.device, action.claim); + return; + } if (action.kind === "evict-running") { await this.#evictRunning(waiter, action.device, action.claim, action.reason); return; @@ -967,11 +1012,12 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { try { handoff = await this.options.provisioner.provision(spec, { claim: { kind: "boot", owner: waiter.id }, + ...exceptOption(waiter), onProgress: (progress) => this.options.queue.notifyProgress(waiter, progress), reservation, }); } catch (error: unknown) { - if (error instanceof BootTimeoutError) { + if (error instanceof BootTimeoutError && exceptOption(waiter).except === undefined) { await this.options.decisions.run(async () => { if (waiter.state !== "rejected") this.#reject(waiter, error, "boot-timeout"); }); @@ -986,27 +1032,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { this.#wakeQueue(); return; } - const retry = await this.options.decisions.run(async () => { - if (waiter.state === "rejected") return false; - waiter.failures += 1; - if (waiter.failures === 1) { - this.options.queue.markNew(waiter); - return true; - } - // why: ADR 0021 §1 declines a probe instead of rejecting it, and its caller (the gateway) reads the code. - this.#reject( - waiter, - new ProvisionFailedError(error), - waiter.options.fleetRequestId === undefined ? "unresolvable-spec" : "no-wait", - ); - return false; - }); - if (retry) { - this.#driving.delete(waiter); - await this.#drive(waiter); - } else { - this.#wakeQueue(); - } + await this.#countFailure(waiter, error); return; } await this.#grantHandoff(waiter, handoff, "provision"); @@ -1081,6 +1107,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { spec: waiter.spec, requirement: waiter.requirement, classOf: waiter.classOf, + rebootReady: exceptOption(waiter).except !== undefined, }); } @@ -1110,6 +1137,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { requesterId: waiter.options.requesterId, source: GRANT_SOURCE[kind], timing: waiter.timing, + ...(device.mode === "slim" ? exceptOption(waiter) : {}), ...(waiter.options.ttlMs === undefined ? {} : { ttlMs: waiter.options.ttlMs }), ...(waiter.options.leaseId === undefined ? {} : { leaseId: waiter.options.leaseId }), ...(waiter.options.fleetRequestId === undefined @@ -1205,10 +1233,9 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { }); } - async #bootShutdown( + async #rebootReady( waiter: AcquisitionWaiter, device: VirtualDevice, - capacityReservation: CapacityReservation, claim: DeviceOperationClaim, ): Promise { let handoff: ReadyDeviceHandoff; @@ -1217,55 +1244,132 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { stage: "booting", etaMs: waiter.timing.estimatedBootMs, }); - const ready = await this.options.lifecycle.bootForLease(device, claim); - if (ready === undefined) throw new Error(`Boot target is no longer safe: ${device.id}`); + const except = exceptOption(waiter).except ?? []; + const ready = await this.options.lifecycle.rebootForLease(device, claim, except); + if (ready === undefined) throw new Error(`Reboot target is no longer safe: ${device.id}`); handoff = ready; } catch (error: unknown) { this.#logFailure( - "booting a shut-down device for a waiter failed", + "rebooting a warm device for a waiter failed", waiter, device, - "boot", + "reboot", error, ); - let destroyed = true; + await this.#destroyFailedBoot(waiter, device, "shutdown"); + await this.#countFailure(waiter, error); + return; + } + await this.#grantHandoff(waiter, handoff, "reboot-ready"); + } + + /** why: a device that failed to boot is destroyed, or quarantined when the destroy fails too, before the waiter's slot is freed (see below). */ + async #destroyFailedBoot( + waiter: AcquisitionWaiter, + device: VirtualDevice, + state: VirtualDevice["state"], + ): Promise { + let destroyed = true; + try { + await this.options.lifecycle.destroy(device, "lease-engine", "cleanup"); + } catch (destroyError: unknown) { + this.#logFailure( + "destroying a device that failed to boot failed", + waiter, + device, + "destroy", + destroyError, + ); + destroyed = false; + } + // why: a device the destroy could not retire may still be running, so it is handed to + // quarantine before the waiter's reservation is freed: `quarantined` is the one state that + // retries it, keeps it out of every plan and still counts it as running. Freeing the slot + // first would leave a window where the next planner boots a device that may be running. + if (!destroyed) { try { - await this.options.lifecycle.destroy(device, "lease-engine", "cleanup"); - } catch (destroyError: unknown) { + const quarantined = await this.options.quarantine.enterFromStalledTransition( + device.id, + state, + ); + if (!quarantined) { + this.#logger.warn( + "a device that failed to be destroyed was not quarantined: something else owns it now", + { deviceId: device.id, requesterId: waiter.options.requesterId, step: "quarantine" }, + ); + } + } catch (quarantineError: unknown) { this.#logFailure( - "destroying a device that failed to boot failed", + "quarantining a device that failed to boot and to be destroyed failed", waiter, device, - "destroy", - destroyError, + "quarantine", + quarantineError, ); - destroyed = false; } - // why: a device the destroy could not retire may still be running, so it is handed to - // quarantine before the waiter's reservation is freed: `quarantined` is the one state that - // retries it, keeps it out of every plan and still counts it as running. Freeing the slot - // first would leave a window where the next planner boots a device that may be running. - if (!destroyed) { - try { - const quarantined = await this.options.quarantine.enterFromStalledTransition( - device.id, - device.state, - ); - if (!quarantined) { - this.#logger.warn( - "a device that failed to be destroyed was not quarantined: something else owns it now", - { deviceId: device.id, requesterId: waiter.options.requesterId, step: "quarantine" }, - ); - } - } catch (quarantineError: unknown) { - this.#logFailure( - "quarantining a device that failed to boot and to be destroyed failed", - waiter, - device, - "quarantine", - quarantineError, - ); - } + } + } + + /** + * why: a failed boot of an except lease counts like a failed provision (ADR 0066 §3): the first + * plans again, the second rejects `PROVISION_FAILED`, one count for provision, boot and reboot. + */ + async #countFailure(waiter: AcquisitionWaiter, error: unknown): Promise { + const retry = await this.options.decisions.run(async () => { + if (waiter.state === "rejected") return false; + waiter.failures += 1; + if (waiter.failures === 1) { + this.options.queue.markNew(waiter); + return true; + } + // why: ADR 0021 §1 declines a probe instead of rejecting it, and its caller (the gateway) reads the code. + this.#reject( + waiter, + new ProvisionFailedError(error), + waiter.options.fleetRequestId === undefined ? "unresolvable-spec" : "no-wait", + ); + return false; + }); + if (retry) { + this.#driving.delete(waiter); + await this.#drive(waiter); + } else { + this.#wakeQueue(); + } + } + + async #bootShutdown( + waiter: AcquisitionWaiter, + device: VirtualDevice, + capacityReservation: CapacityReservation, + claim: DeviceOperationClaim, + ): Promise { + let handoff: ReadyDeviceHandoff; + try { + this.options.queue.notifyProgress(waiter, { + stage: "booting", + etaMs: waiter.timing.estimatedBootMs, + }); + const ready = await this.options.lifecycle.bootForLease( + device, + claim, + exceptOption(waiter).except, + ); + if (ready === undefined) throw new Error(`Boot target is no longer safe: ${device.id}`); + handoff = ready; + } catch (error: unknown) { + this.#logFailure( + "booting a shut-down device for a waiter failed", + waiter, + device, + "boot", + error, + ); + await this.#destroyFailedBoot(waiter, device, device.state); + if (exceptOption(waiter).except !== undefined) { + await this.options.decisions.run(() => capacityReservation.release()); + await this.#countFailure(waiter, error); + return; } await this.options.decisions.run(async () => { capacityReservation.release(); @@ -1452,53 +1556,14 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { } } -function asError(error: unknown): Error { - return error instanceof Error ? error : new Error(String(error)); +/** why: a request's `except` reaches the driver and the device only when the resolved spec is slim; on a runtime that cannot be slimmed the lease is granted full with no `except` (ADR 0066 §1). */ +function exceptOption(waiter: AcquisitionWaiter): { readonly except?: readonly string[] } { + const except = waiter.request.except; + return except === undefined || waiter.spec?.mode !== "slim" ? {} : { except }; } -function estimatedTiming(driver: Driver, spec: DeviceSpec): LeaseTiming { - const estimatedProvisionMs = driver.estimate({ operation: "provision" }, spec); - const estimatedBootMs = driver.estimate({ operation: "boot" }, spec); - return { - estimatedBootMs, - estimatedProvisionMs, - estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), - estimatedReadyMs: estimatedProvisionMs + estimatedBootMs, - }; -} - -async function estimatedBootTiming(driver: Driver, device: DeviceRecord): Promise { - const spec = device.spec; - // why: The quote is advisory. A driver that cannot read the device's own boot path (a failed - // `emulator -version`, say) must not strand the claim and capacity reservation that the boot - // below releases, so the device-less figure stands in. - const estimatedBootMs = await Promise.resolve( - driver.estimate( - { device: toDriverDevice(device), operation: "boot", purpose: "prepare" }, - spec, - ), - ).catch(() => driver.estimate({ operation: "boot" }, spec)); - return { - estimatedBootMs, - estimatedProvisionMs: 0, - estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), - estimatedReadyMs: estimatedBootMs, - }; -} - -/** A device that is already ready costs nothing to hand over; only its reclaim lies ahead. */ -function grantReadyTiming(driver: Driver, spec: DeviceSpec): LeaseTiming { - return { - estimatedBootMs: 0, - estimatedProvisionMs: 0, - estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), - estimatedReadyMs: 0, - }; -} - -/** `standard`: every release path asks for it; a holder cannot request another clean level. */ -function releaseReclaimEstimateMs(driver: Driver, spec: DeviceSpec): number { - return driver.estimate({ clean: "standard", operation: "reclaim" }, spec); +function asError(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)); } /** @@ -1526,39 +1591,6 @@ function operationPlan(plan: AcquisitionPlan): OperationPlan | undefined { : plan; } -function physicalRequestOf(request: DeviceRequest): PhysicalRequest { - return { - platform: request.platform, - ...(request.model === undefined ? {} : { model: request.model }), - ...(request.class === undefined ? {} : { class: request.class }), - ...(request.osVersion === undefined ? {} : { osVersion: request.osVersion }), - }; -} - -function fullSpec(spec: VirtualSpec): VirtualSpec { - if (spec.mode === undefined) return spec; - const { mode: _mode, ...full } = spec; - return full; -} - -type DownloadingProgress = Extract; - -function downloadingProgress( - component: string, - progress: ComponentInstallerProgress, -): DownloadingProgress { - if (progress.stage === "waiting") return { component, stage: "downloading", waiting: true }; - const { percent } = progress; - return percent === undefined - ? { component, stage: "downloading", waiting: false } - : { component, percent: Math.floor(percent), stage: "downloading", waiting: false }; -} - -/** Both reports are for the one component a `#resolveOrInstall` call downloads. */ -function sameDownloadingProgress(left: DownloadingProgress, right: DownloadingProgress): boolean { - return left.waiting === right.waiting && left.percent === right.percent; -} - /** * The spec a driver resolved, held to what the request asked. The image tag is the request's, or * none: a driver that returns another, or one the request did not name, would plan the device @@ -1595,49 +1627,3 @@ interface ResolvedTarget { * in its range, or any when it names none; and only runtimes that have an image of the requested * tag when it names one (the rule the gateway's `matchRequest` applies). */ -function matchingRuntimes( - entry: DriverCatalogEntry, - model: string, - { imageTag, osVersion }: Pick, - range: OsRange | undefined, -): string[] { - return pairedRuntimes(entry, model).filter( - (runtime) => - (range === undefined - ? osVersion === undefined || runtime === osVersion - : satisfies(runtime, range)) && - (imageTag === undefined || - (entry.images ?? []).some((image) => image.runtime === runtime && image.tag === imageTag)), - ); -} - -/** The newest runtime `model` pairs with that the request's range accepts, or none installed. */ -function newestRuntime( - entry: DriverCatalogEntry, - model: string, - request: DeviceRequest, - range: OsRange, -): string { - const newest = matchingRuntimes(entry, model, request, range).sort(compareVersions).at(-1); - if (newest === undefined) throw new RuntimeMissingError(request.platform, range.text); - return newest; -} - -/** What a device's OS must satisfy: the range, the exact version named, or any installed runtime. */ -function requiredOs( - entry: DriverCatalogEntry, - { osVersion }: DeviceRequest, - range: OsRange | undefined, -): DeviceRequirement["osVersion"] { - if (range !== undefined) return range; - return osVersion === undefined - ? { kind: "installed", versions: entry.runtimes } - : { kind: "exact", version: osVersion }; -} - -/** The request's OS range, when its `osVersion` is one rather than an exact version. */ -function requestedRange(request: DeviceRequest): OsRange | undefined { - if (request.osVersion === undefined) return undefined; - const parsed = parseOsConstraint(request.osVersion); - return parsed.ok && parsed.constraint.kind === "range" ? parsed.constraint : undefined; -} diff --git a/src/leasing/lease-lifecycle.ts b/src/leasing/lease-lifecycle.ts index 42ad36301..33efca807 100644 --- a/src/leasing/lease-lifecycle.ts +++ b/src/leasing/lease-lifecycle.ts @@ -21,6 +21,7 @@ export interface LeaseLifecycleRegistry { readonly ttlMs: number; readonly ttlDeadline: number; readonly leaseId?: string; + readonly except?: readonly string[]; readonly request?: { readonly id: string; readonly environment: LeaseGrant["environment"]; @@ -78,6 +79,8 @@ export class LeaseLifecycle { /** ADR 0020: the lease ID the requester chose, when it did. The caller has already refused one * that is in use. */ readonly leaseId?: string; + /** why: the categories a slim lease keeps running, written to the device in the grant commit (ADR 0066 §4). */ + readonly except?: readonly string[]; /** ADR 0021: the gateway's request id, when the request is a gateway dispatch, carried on * `lease.granted`. */ readonly fleetRequestId?: string; diff --git a/src/leasing/lease-request-book.ts b/src/leasing/lease-request-book.ts index 461bbefdc..2daef5786 100644 --- a/src/leasing/lease-request-book.ts +++ b/src/leasing/lease-request-book.ts @@ -411,13 +411,18 @@ function storedResult(record: LeaseRequestRecord): Promise /** An omitted field equals only an omitted one: a request naming no mode is not one naming the worker's default. */ function sameDeviceRequest(left: DeviceRequest, right: DeviceRequest): boolean { return ( - left.platform === right.platform && - left.model === right.model && - left.class === right.class && - left.osVersion === right.osVersion && - left.mode === right.mode && - left.imageTag === right.imageTag && - left.baseline === right.baseline && + SAME_DEVICE_FIELDS.every((field) => left[field] === right[field]) && + (left.except ?? []).join(",") === (right.except ?? []).join(",") && (left.physical === true) === (right.physical === true) ); } + +const SAME_DEVICE_FIELDS = [ + "platform", + "model", + "class", + "osVersion", + "mode", + "imageTag", + "baseline", +] as const; diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 81162d492..85937c786 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -206,7 +206,7 @@ export function createMcpServer( { title: "Lease simulator", description: - "Lease one simulator or emulator for this MCP session. Name an exact model (`model`), or a device class (`class`: phone, tablet, watch, tv, vision, auto or desktop), or name neither to get a phone; naming both is an error. A class or no-model request is served by a fitting idle device before a new one is created. The lease is held until released or this MCP connection closes; provisioning can block unless noWait is true. `osVersion` is an exact version (`18.4`) or a range: `>=`, `>`, `<=` or `<` followed by a version, joined by single spaces (`>=18 <26`), or a hyphen range (`18 - 26`); a range is served by a fitting device or the newest installed runtime in it, and never downloads. Downloads are disabled by default and require allowDownload: true. On Android, imageTag picks the system image type (a tag from list_devices' images, such as google_apis_playstore); a request with imageTag uses only an installed image and never downloads. Pass `baseline` (a name the operator saved) to get a new copy of that baseline, with the operator's apps, files and settings; it must match any `model`, `osVersion`, `mode` or `imageTag` you also pass (BASELINE_MISMATCH otherwise), cannot be combined with `class`, and fails at once as UNKNOWN_BASELINE or BASELINE_STALE when the baseline is missing or unusable. Pass `leaseId` to choose the lease's ID instead of getting one generated: 1 to 64 ASCII letters, digits, `-` or `_`, starting with a letter or digit; you keep it unique for all time, and an ID that an active lease or a waiting request already holds is refused with LEASE_ID_TAKEN.", + "Lease one simulator or emulator for this MCP session. Name an exact model (`model`), or a device class (`class`: phone, tablet, watch, tv, vision, auto or desktop), or name neither to get a phone; naming both is an error. A class or no-model request is served by a fitting idle device before a new one is created. The lease is held until released or this MCP connection closes; provisioning can block unless noWait is true. `osVersion` is an exact version (`18.4`) or a range: `>=`, `>`, `<=` or `<` followed by a version, joined by single spaces (`>=18 <26`), or a hyphen range (`18 - 26`); a range is served by a fitting device or the newest installed runtime in it, and never downloads. Downloads are disabled by default and require allowDownload: true. On Android, imageTag picks the system image type (a tag from list_devices' images, such as google_apis_playstore); a request with imageTag uses only an installed image and never downloads. Pass `baseline` (a name the operator saved) to get a new copy of that baseline, with the operator's apps, files and settings; it must match any `model`, `osVersion`, `mode` or `imageTag` you also pass (BASELINE_MISMATCH otherwise), cannot be combined with `class`, and fails at once as UNKNOWN_BASELINE or BASELINE_STALE when the baseline is missing or unusable. On iOS, `except` (1 to 16 category names, such as `store`) with `mode` slim keeps those categories running on the slim simulator; it needs a slim lease (BAD_REQUEST on `mode` full, a full default or a full baseline, and for a physical or Android request), and the leased device reports it as `except`. Pass `leaseId` to choose the lease's ID instead of getting one generated: 1 to 64 ASCII letters, digits, `-` or `_`, starting with a letter or digit; you keep it unique for all time, and an ID that an active lease or a waiting request already holds is refused with LEASE_ID_TAKEN.", inputSchema: leaseSimulatorInputSchema, outputSchema: leaseSimulatorOutputSchema, }, diff --git a/website/src/content/docs/docs/getting-started/connect-your-agent.mdx b/website/src/content/docs/docs/getting-started/connect-your-agent.mdx index f1da9a78b..b93baf018 100644 --- a/website/src/content/docs/docs/getting-started/connect-your-agent.mdx +++ b/website/src/content/docs/docs/getting-started/connect-your-agent.mdx @@ -123,7 +123,7 @@ The server starts the daemon if it is not running. It renews the agent's lease w | Tool | What it does | | --- | --- | | `list_devices` | Lists the models, OS versions and Android system images you can lease here, and, as `physicalDevices`, the enrolled phones and tablets with their state (`ready`, `leased`, `absent`), why an absent one is absent, and, through a gateway, which worker holds it. It never downloads anything, never says who holds a phone, and `physicalDevices` is empty while the daemon is still starting. | -| `lease_simulator` | Leases one simulator or emulator for this session. Takes `platform` and, optionally, `model` or `class`, `osVersion`, `ttlMs`, `noWait`, `timeoutMs` and `allowDownload`, the same options as `simlock lease`. Returns the same lease the CLI prints. | +| `lease_simulator` | Leases one simulator or emulator for this session. Takes `platform` and, optionally, `model` or `class`, `osVersion`, `mode`, `except`, `ttlMs`, `noWait`, `timeoutMs` and `allowDownload`, the same options as `simlock lease`. Returns the same lease the CLI prints. | | `release_simulator` | Releases this session's lease. | | `lease_status` | Reports this session's lease, or `held: false` when it has none. Safe to call any time, for example after the agent's context was compacted. | | `run_on_device` | Runs one `simctl`, `adb` or `devicectl` command on this session's device. Takes `tool`, `args` and, optionally, `stdin` (at most 8,388,608 characters; a longer one fails the tool's input validation, before Simlock sees it). | diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index 39b1670ec..5275fdecc 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -96,7 +96,7 @@ Lease a device. The command waits for a device, prints the grant, then stays run ```text simlock lease --platform [--device | --class ] [--os ] [--mode ] [--image-tag ] [--agent-id ] - [--baseline ] + [--except ] [--baseline ] [--timeout ] [--lease-id ] [--physical] [--no-wait] [--detach] [--ttl ] [--allow-download] [--export-env] [--bind-pid ] @@ -109,6 +109,7 @@ simlock lease --platform [--device | --class ] | `--class ` | Any model of this class: `phone`, `tablet`, `watch`, `tv`, `vision`, `auto` or `desktop`. | `phone` when `--device` is not given | | `--os ` | An exact OS version (`18.4`, `35`), or a range such as `>=18 <26` or `18 - 26`. A range never downloads. | The newest runtime installed for the platform | | `--mode ` | The device mode. `full` is guaranteed; `slim` is best effort and falls back to `full`. | The serving worker's default mode (`full` unless configured) | +| `--except ` | iOS only: keep these slim categories running on a slim simulator, such as `store,other`. One to 16 names, each lowercase letters, digits and `-`, starting with a letter, none twice. Needs a slim lease: a `--mode full`, a worker whose default mode is `full` with no `--mode`, a full `--baseline`, `--physical` and `--platform android` are each a `BAD_REQUEST`. The grant's `device.except` lists them; on a runtime older than iOS 18.5 you get a `full` device with no `except`. See [Keep a category running](/simlock/docs/using-devices/choosing-a-device#keep-a-category-running). | None: the worker's whole slim set is turned off | | `--image-tag ` | Android only: the system image type, such as `google_apis_playstore`. Never downloads. | Simlock picks an installed image | | `--baseline ` | Start from a saved baseline: the device is a new copy of it, with the operator's apps, files and settings. The `SIMLOCK_BASELINE` environment variable sets it when the flag is absent; an empty value sends nothing. Cannot be combined with `--class` or `--physical`. See [Start from a baseline](/simlock/docs/using-devices/choosing-a-device#start-from-a-baseline). | None: a plain device | | `--agent-id ` | The requester identity for this lease. Must not be empty, hold no control characters, and be at most 256 characters. | See [Requester identity](#requester-identity) | diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 8964a33f4..36bf326fe 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -42,14 +42,14 @@ In a script, check `code`, not the message: the wording of a message can change, | `QUEUE_TIMEOUT` | 10 | 500 | The request waited in the queue for its whole `--timeout` and got no device. | Raise `--timeout`, or check `simlock list --requests` for why requests wait. | | `REQUESTER_ALREADY_LEASED` | 13 | 409 | Your requester identity already holds or waits for its limit of leases (`lease.maxPerRequester`, 1 by default, counted per platform when the operator sets a limit for each), or, with a limit per platform, has a request waiting on that platform. The message names your lease. | Release that lease first, or give each agent session its own identity. | | `LEASE_ID_TAKEN` | 13 | 409 | `--lease-id` names an ID that an active lease or a waiting request already holds. | Use a new ID. Never reuse a lease ID. | -| `IDEMPOTENCY_CONFLICT` | 2 | 409 | A lease request reused an idempotency key its requester already sent for a different device or lease ID. | Send a new key for a new request. | -| `PROVISION_FAILED` | 1 | 500 | Creating or booting a device for the request failed twice. The message carries the platform tool's error. | Read the message and `simlock daemon logs`, then run `simlock doctor`. | +| `IDEMPOTENCY_CONFLICT` | 2 | 409 | A lease request reused an idempotency key its requester already sent for a different device, `except` list or lease ID. | Send a new key for a new request. | +| `PROVISION_FAILED` | 1 | 500 | Creating or booting a device for the request failed twice. A request with `--except` counts a failed boot of a device it was given, warm or new, the same way. The message carries the platform tool's error. | Read the message and `simlock daemon logs`, then run `simlock doctor`. | | `UNKNOWN_MODEL` | 12 | 422 | The model is not one this platform offers here, or no model of the requested class exists. | Run `simlock catalog` for the models and their exact names. | | `RUNTIME_MISSING` | 12 | 422 | The OS version, or an image of the `--image-tag`, is not installed. A range or an image tag never downloads. | Add `--allow-download`, install it with `simlock component install`, or pick an installed version from `simlock catalog`. | | `NO_DRIVER` | 12 | 422 | This machine cannot run the platform: iOS on Linux, or a platform whose tools are missing. | Run `simlock doctor` to see what is missing, install it, then restart the daemon. | | `CAPABILITY_MISSING` | 12 | 422 | No worker that could serve the request has every optional module it asks for, such as screen streaming. Only the programmatic client asks for modules. | Ask for fewer, or turn the module on for a worker under `capabilities` in its configuration. | | `UNKNOWN_LEASE` | 1 | 404 | No active lease has this ID: it was released, it expired, or it never existed. | Take a new lease. | -| `BAD_REQUEST` | 2 | 400 | The request has an invalid value: an unknown class or mode, both `--device` and `--class`, a TTL over `lease.maxTtlMs`, `--image-tag` on iOS, `--physical` with `--mode`, and so on. The message names the field. | Fix the value the message names. | +| `BAD_REQUEST` | 2 | 400 | The request has an invalid value: an unknown class or mode, both `--device` and `--class`, a TTL over `lease.maxTtlMs`, `--image-tag` on iOS, `--physical` with `--mode`, `--except` on a lease that is not a slim iOS simulator or naming a category twice, one the worker does not slim or a bad name, and so on. The message names the field. | Fix the value the message names. | | `CANCELLED` | 1 | 499 | The programmatic client gave up a lease request it was waiting on. Never sent by the daemon. | Nothing, unless you did not mean to cancel. | ## Runtimes, images and downloads diff --git a/website/src/content/docs/docs/reference/events.mdx b/website/src/content/docs/docs/reference/events.mdx index 98aa6e99c..484268b0c 100644 --- a/website/src/content/docs/docs/reference/events.mdx +++ b/website/src/content/docs/docs/reference/events.mdx @@ -104,9 +104,9 @@ The **Gateway** column below says what a gateway shows for each event: | Event | When it fires | Payload | Gateway | | --- | --- | --- | --- | -| `lease.requested` | A lease request was accepted and stored. | `requestId`, `requestSpec` (the request as sent, with `baseline` when it named one), `requester`, `waitPolicy` (`wait` or `no-wait`), `fleetRequestId` on a worker when the request came from a gateway | Own and relayed | +| `lease.requested` | A lease request was accepted and stored. | `requestId`, `requestSpec` (the request as sent, with `baseline` and `except` when it named them), `requester`, `waitPolicy` (`wait` or `no-wait`), `fleetRequestId` on a worker when the request came from a gateway | Own and relayed | | `lease.queued` | No device was free, so the request started waiting. | `requestId`, `queuePosition` (counted among requests of the same kind: physical requests wait in a line of their own) | Own and relayed | -| `lease.granted` | A device was handed to a request. | `leaseId`, `deviceId`, `requester`, `requestId`, `source` (`warm`: ready device; `booted`: shut-down device booted; `provisioned`: device created), `platform`, `baseline` (`{ name, version }`) when the device is a copy of a baseline, `fleetRequestId` when it served a gateway | Relayed | +| `lease.granted` | A device was handed to a request. | `leaseId`, `deviceId`, `requester`, `requestId`, `source` (`warm`: ready device; `booted`: shut-down device booted, or a ready device booted again for a request with `except`; `provisioned`: device created), `platform`, `baseline` (`{ name, version }`) when the device is a copy of a baseline, `fleetRequestId` when it served a gateway | Relayed | | `lease.renewed` | A lease was renewed. | `leaseId`, `newDeadline` | Relayed | | `lease.released` | A lease ended because someone or something ended it. | `leaseId`, `deviceId`, `reason` (`explicit`: released; `killed`: `release --all` or `nuke`; `device-lost`: the device crashed and could not be brought back, or a physical device went away), `ownerId` | Relayed | | `lease.expired` | A lease reached its deadline without a renew. | `leaseId`, `deviceId`, `ownerId` | Relayed | diff --git a/website/src/content/docs/docs/using-devices/choosing-a-device.mdx b/website/src/content/docs/docs/using-devices/choosing-a-device.mdx index f5ede8b46..dc500ba52 100644 --- a/website/src/content/docs/docs/using-devices/choosing-a-device.mdx +++ b/website/src/content/docs/docs/using-devices/choosing-a-device.mdx @@ -120,6 +120,27 @@ What to expect: If a test fails because a push notification, a Spotlight result, an App Store sheet or a system picker never appears, check `device.mode`. Ask for `--mode full` when your app needs those features. +### Keep a category running + +When a test needs one part of what slim turns off, name its category with `--except` instead of giving up the whole saving: + +```sh +simlock lease --platform ios --mode slim --except store,other +``` + +The simulator boots with those categories running and the rest of the slim set off, and the grant reports `device.except` beside `device.mode`: + +```json +{ "device": { "mode": "slim", "except": ["store", "other"] } } +``` + +- `--except` needs a slim lease. With `--mode full`, a worker whose default is `full` and no `--mode`, or a full `--baseline`, it is refused with `BAD_REQUEST`. A slim baseline on a worker whose default is `full` is granted. +- A name the worker does not slim is refused with `BAD_REQUEST`, as is a name given twice, a name that is not lowercase letters, digits and `-`, and more than 16 names. +- It is for iOS simulators: `--platform android` and `--physical` are refused. +- On a runtime older than iOS 18.5 you get a `full` device with no `except`. +- A device the worker holds warm is shut down and booted again with your list before you get it, so the lease can take a little longer than one without `--except`. If that boot fails, the device is deleted and Simlock tries once more with another; a second failure is `PROVISION_FAILED`. +- Over HTTP the body takes `except` as a list, and over MCP `lease_simulator` takes the same `except`. + ## Choose the system image (Android) `--image-tag` picks the kind of Android system image, such as `google_apis_playstore` for Google Play or `default` for plain Android. You can use the tags that `simlock catalog --platform android` lists under images. diff --git a/website/src/content/docs/docs/using-devices/remote-agents.mdx b/website/src/content/docs/docs/using-devices/remote-agents.mdx index 70939a557..5b3662827 100644 --- a/website/src/content/docs/docs/using-devices/remote-agents.mdx +++ b/website/src/content/docs/docs/using-devices/remote-agents.mdx @@ -51,7 +51,7 @@ export SIMLOCK_TOKEN=slk_d2FybS1wb29sLWFnZW50LXRva2VuLWV4YW1wbGUtMDM -1. **Ask for a device.** The body takes the same choices as `simlock lease`: `platform` (required), `device` or `class`, `os`, `mode`, `imageTag`, `physical`, `ttlMs`, `timeoutMs`, `noWait` and `allowDownload`. See [Choosing a device](/simlock/docs/using-devices/choosing-a-device). +1. **Ask for a device.** The body takes the same choices as `simlock lease`: `platform` (required), `device` or `class`, `os`, `mode`, `except`, `imageTag`, `physical`, `ttlMs`, `timeoutMs`, `noWait` and `allowDownload`. See [Choosing a device](/simlock/docs/using-devices/choosing-a-device). ```sh curl -sS -X POST "$SIMLOCK_URL/v1/lease-requests" \