diff --git a/docs/CLI.md b/docs/CLI.md index 85c567112..5a9af769b 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -175,7 +175,7 @@ a timer and releasing it when it exits. ``` simlock lease --platform [--device | --class ] - [--os ] [--mode ] [--image-tag ] [--agent-id ] + [--os ] [--mode ] [--image-tag ] [--agent-id ] [--timeout ] [--no-wait] [--detach] [--ttl ] [--allow-download] [--export-env] [--bind-pid ] @@ -191,6 +191,18 @@ granted. or `desktop`); with neither, the lease asks for a `phone`. Naming both is a `BAD_REQUEST` (exit 2). `--os` defaults to the newest runtime already installed for that platform. See [What a lease asks for](#what-a-lease-asks-for). +- `--os ` — an exact version (`18.4`), or a range: one or more + of `>=`, `>`, `<=`, `<` followed by a version, joined by single spaces + (`>=18 <26`), or a hyphen range (`18 - 26`). A short version covers + everything under it: `>=18` is 18.0 and newer, `<=26` includes every 26.x, + `>26` excludes them, `18 - 26` is `>=18 <=26`. Anything written like + a range but outside these forms (`^18`, `~18`, `18.x`, `*`, `||`) is + `BAD_REQUEST` (exit 2) and the message names these forms; any other string, + such as the Android runtimes `Baklava` or `34-ext12`, is an exact version. + A range is served by a fitting idle device first, or else by a new device + on the newest installed runtime in the range; when no installed runtime is + in the range the lease fails at once with `RUNTIME_MISSING` (exit 12), with + or without `--allow-download`, because a range never downloads. - `--class ` — the kind of device to lease, in place of a model. See [What a lease asks for](#what-a-lease-asks-for). - `--agent-id` — this invocation's requester identity; see @@ -445,7 +457,8 @@ A class lease is served by the first of these that applies: an idle device that is already running and fits, then an idle device that is shut down and fits (it is booted), then a new device. A device fits when its platform, class, OS, mode and image tag all satisfy the request: with no `--os` a class -lease fits a device on any installed runtime, `--mode full` and `--image-tag` +lease fits a device on any installed runtime, with `--os` a device whose OS +satisfies it, `--mode full` and `--image-tag` are never relaxed, and a lease that names no mode fits only the worker's default mode. When several devices fit, which one is granted is not promised. diff --git a/docs/CLIENT.md b/docs/CLIENT.md index e47807107..722a93cdc 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -72,7 +72,16 @@ type to create the device from, such as `"google_apis_playstore"`, as `getCatalog()` lists it under each image's `tag`. Without it Simlock picks the image itself (`google_apis` for the host's ABI when installed). With it the device comes from an installed image of that tag, and without `osVersion` from -the newest API level that has one. A request with `imageTag` never downloads: +the newest API level that has one. + +`osVersion` is an exact version (`"18.4"`) or a range: one or more of `>=`, +`>`, `<=`, `<` followed by a version, joined by single spaces (`">=18 <26"`), +or a hyphen range (`"18 - 26"`). A short version covers everything under it, so +`">=18"` is 18.0 and newer. Anything written like a range but outside those forms (`^18`, `~18`, `18.x`, `*`, `||`) is `BAD_REQUEST`; any other string, such as `Baklava` or `34-ext12`, is an exact version. A range is served +by an idle device whose OS satisfies it or by a new device on the newest +installed runtime in it, and when none is installed it fails at once with +`RUNTIME_MISSING`, whatever `allowDownload` says. Through a gateway a range is +`BAD_REQUEST` for now. A request with `imageTag` never downloads: when no image of that tag is installed for the API level it fails with `RUNTIME_MISSING`, whatever `allowDownload` says. On iOS it is a `BAD_REQUEST`, and so is a tag that is not 1 to 64 letters, digits, `_`, `.` diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 7a0c9f1dd..4c3e81a5c 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -9,13 +9,13 @@ through `simlock events` and `simlock events --follow`. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `lease.requested` | request id, request spec (platform, model when the request named one, device class when the request named one, os version, device mode when the request named one, image tag when the request named one), requester, wait policy | 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 | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway — its own fleet queue's admission, before any worker is chosen) | implemented | +| `lease.requested` | request id, request spec (platform, model when the request named one, device class when the request named one, os version, as an exact version or a range as typed, device mode when the request named one, image tag when the request named one), requester, wait policy | 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 | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway — its own fleet queue's admission, before any worker is chosen) | implemented | | `lease.queued` | request id, queue position | no capacity; request entered the wait queue | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway) | implemented | | `lease.granted` | lease id, device id, requester, request id (the `lease.requested` it answers), source (`warm`: a ready device handed over; `booted`: a shut-down device booted for it; `provisioned`: a device created for it) | a device was assigned and handed out | LeaseLifecycle | implemented | | `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 | | `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. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented | | `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 | -| `lease.rejected` | request id, requester, request spec (as on `lease.requested`: a request that named a class or nothing has no model), reason (timeout/no-wait/unresolvable-spec/no-worker/already-leased/boot-timeout/killed/cancelled/daemon-restarted) | a request ended without a grant. A request refused before it was stored (`killed`, `already-leased`) emits no `lease.requested`, and its `lease.rejected` carries the id it would have been stored under; on a gateway, `no-worker` is a request no worker that takes requests can serve, `NO_CAPACITY` at once, and `unresolvable-spec` is one no known worker has the platform, model, or runtime for, and such a request emits no `lease.queued`. A request a worker refused as unable to serve (`RUNTIME_MISSING`, `UNKNOWN_MODEL`, `NO_DRIVER`) while another worker was busy waits in the gateway queue, unless it is a `noWait` request, which is rejected at once with reason `no-wait` and emits no `lease.queued`; a request that did queue and then finds no worker left emits `unresolvable-spec` after its `lease.queued`, and one that never queued gets only the refusing worker's own `lease.rejected`; `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again. The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter — one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue / StartupConverger (worker) / FleetLeaseCoordinator (gateway) | implemented | +| `lease.rejected` | request id, requester, request spec (as on `lease.requested`: a request that named a class or nothing has no model, and one that named an OS range carries it as typed), reason (timeout/no-wait/unresolvable-spec/no-worker/already-leased/boot-timeout/killed/cancelled/daemon-restarted) | a request ended without a grant. A request refused before it was stored (`killed`, `already-leased`) emits no `lease.requested`, and its `lease.rejected` carries the id it would have been stored under; on a gateway, `no-worker` is a request no worker that takes requests can serve, `NO_CAPACITY` at once, and `unresolvable-spec` is one no known worker has the platform, model, or runtime for, and such a request emits no `lease.queued`. A request a worker refused as unable to serve (`RUNTIME_MISSING`, `UNKNOWN_MODEL`, `NO_DRIVER`) while another worker was busy waits in the gateway queue, unless it is a `noWait` request, which is rejected at once with reason `no-wait` and emits no `lease.queued`; a request that did queue and then finds no worker left emits `unresolvable-spec` after its `lease.queued`, and one that never queued gets only the refusing worker's own `lease.rejected`; `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again. The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter — one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue / StartupConverger (worker) / FleetLeaseCoordinator (gateway) | implemented | On a **gateway**, the first three of these are its own fleet queue's facts, emitted by `FleetLeaseCoordinator` and never by the worker whose device is diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 876fbeccd..9f8b3195b 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -357,8 +357,16 @@ class's preference list that the machine lists (see with no listed model fails with `422 UNKNOWN_MODEL`, naming the config key, and one whose listed models pair with no installed runtime fails with `RUNTIME_MISSING`. The granted lease's `device`, `os`, `mode` and `imageTag` always name the device -you got. Through a gateway a request that names no `device` is `400 BAD_REQUEST` -for now. `os` defaults to the newest installed runtime; `ttlMs` defaults to `lease.defaultTtlMs` and is `400 BAD_REQUEST` +you got. Through a gateway a request that names no `device`, or whose `os` is a +range, is `400 BAD_REQUEST` for now. `os` is an exact version (`"18.4"`) or a +range: one or more of `>=`, `>`, `<=`, `<` followed by a version, joined by single +spaces (`">=18 <26"`), or a hyphen range (`"18 - 26"`); a short version covers +everything under it, so `">=18"` is 18.0 and newer and `"<=26"` includes every +26.x. Anything written like a range but outside those forms (`^18`, `~18`, `18.x`, `*`, `||`) is `400 BAD_REQUEST`, and the message names these forms; any other string, such as `Baklava` or `34-ext12`, is an exact version. A +range is granted an idle device whose OS satisfies it, or else a new device on the +newest installed runtime in it; one no installed runtime satisfies fails at once +with `422 RUNTIME_MISSING`, `downloadable: false` and the range as `osVersion`, +whatever `allowDownload` says. `os` defaults to the newest installed runtime; `ttlMs` defaults to `lease.defaultTtlMs` and is `400 BAD_REQUEST` above `lease.maxTtlMs`; `timeoutMs` (optional) is enforced daemon-side so a vanished client can't hold a queue slot forever. `mode` (optional, `"slim"` or `"full"`) is the device mode the request asks for; without it the request diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 9c0f8a2a8..6c04fffdf 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -1937,6 +1937,18 @@ still names pool identity for the warm pool, reclaim and the idempotency check. A class is read from the catalog entry (`modelClasses`) at the moment a fit is decided; a device record stores none. +`osVersion` is an exact version or an OS range (ADR 0015 §2). The one grammar +is `src/contract/os-range.ts`: the contract schema refines `osVersion` +through its parser (a refinement over the request object, so the MCP SDK's own +field validation never answers first), so a malformed range is `BAD_REQUEST` on +every transport; a string that is not range-like is a bare version and stays +exact, as `Baklava` or `34-ext12` on Android, +and the core and the gateway import `satisfies` and `compareVersions` from it. +For a range the coordinator picks the newest `modelRuntimes` entry in range +(of the requested image tag) for the exact model, or for the first class +candidate that has one, and hands the driver that exact version; none is +`RUNTIME_MISSING` with `downloadable: false`, and a range never installs. + For an exact model: **platform + device model + OS version**. OS defaults to the newest runtime already installed on the machine that can actually run the requested model — for iOS specifically, the newest diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index f1cdbd92e..def9c76c9 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -38,13 +38,13 @@ 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, 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), requester, wait policy | 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), requester, wait policy | 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 | 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 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. 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) | -| `lease.rejected` | request id, requester (both required on every reason, additive, ADR 0016 §2), request spec (as on `lease.requested`; `full` replaced by `mode`, ADR 0007 §13; `model` optional and `class` added, ADR 0015 §9), reason (timeout/no-wait/unresolvable-spec/no-worker/already-leased/boot-timeout/killed/cancelled/daemon-restarted) | a request ended without a grant. A request refused at admission (`killed`, `already-leased`) was never stored and has no `lease.requested`; it carries the id minted for it before the check, the one the stored request would have had; on a gateway (ADR 0009 §4, §8) `no-worker` is rows 1 and 5 of the fast-fail table (`NO_CAPACITY`: no worker takes requests, or none that does can serve it) and `unresolvable-spec` rows 2 to 4 (`NO_DRIVER`, `UNKNOWN_MODEL`, `RUNTIME_MISSING`), emitted in the dispatch walk before the request is queued, so a request rejected on arrival emits no `lease.queued`, and a waiting one is rejected when the views change (additive, events rule 6). A request a worker refused with one of those codes (ADR 0009 §5) and the table later ends with that stored refusal gets a gateway `unresolvable-spec` only if it had entered the gateway queue (its `lease.queued` needs a terminal fact); otherwise the worker's own `lease.rejected` is the terminal fact and the gateway emits none; `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again (#72; widens a published vocabulary, which events rule 6 allows as additive). The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (`LeaseEngine#cancelPending`, backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter -- one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue / StartupConverger (worker) / FleetLeaseCoordinator (gateway) | implemented | +| `lease.rejected` | request id, requester (both required on every reason, additive, ADR 0016 §2), request spec (as on `lease.requested`; `full` replaced by `mode`, ADR 0007 §13; `model` optional and `class` added, ADR 0015 §9; `osVersion` may be a range as typed, ADR 0015 §2), reason (timeout/no-wait/unresolvable-spec/no-worker/already-leased/boot-timeout/killed/cancelled/daemon-restarted) | a request ended without a grant. A request refused at admission (`killed`, `already-leased`) was never stored and has no `lease.requested`; it carries the id minted for it before the check, the one the stored request would have had; on a gateway (ADR 0009 §4, §8) `no-worker` is rows 1 and 5 of the fast-fail table (`NO_CAPACITY`: no worker takes requests, or none that does can serve it) and `unresolvable-spec` rows 2 to 4 (`NO_DRIVER`, `UNKNOWN_MODEL`, `RUNTIME_MISSING`), emitted in the dispatch walk before the request is queued, so a request rejected on arrival emits no `lease.queued`, and a waiting one is rejected when the views change (additive, events rule 6). A request a worker refused with one of those codes (ADR 0009 §5) and the table later ends with that stored refusal gets a gateway `unresolvable-spec` only if it had entered the gateway queue (its `lease.queued` needs a terminal fact); otherwise the worker's own `lease.rejected` is the terminal fact and the gateway emits none; `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again (#72; widens a published vocabulary, which events rule 6 allows as additive). The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (`LeaseEngine#cancelPending`, backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter -- one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue / StartupConverger (worker) / FleetLeaseCoordinator (gateway) | implemented | On a **gateway**, these three are its own fleet queue's facts (ADR 0005 §11/§14), emitted by `FleetLeaseCoordinator` and never by the worker whose device is diff --git a/e2e/http-api.test.ts b/e2e/http-api.test.ts index e96ca97fa..64402925f 100644 --- a/e2e/http-api.test.ts +++ b/e2e/http-api.test.ts @@ -309,6 +309,39 @@ describe("HTTP API", () => { await env.cli(["release", lease?.id ?? ""]); }); + it("POST /v1/lease-requests refuses a malformed os range as BAD_REQUEST naming the accepted forms", async () => { + const port = await reservePort(); + const env = await withDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, + driverScript: { ios: { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] } }, + }); + const baseUrl = `http://127.0.0.1:${port}`; + const { secret } = (await env.cli(["token", "create", "--role", "agent"])).json as { + secret: string; + }; + await waitFor( + async () => { + try { + return (await fetch(`${baseUrl}/v1/healthz`)).ok; + } catch { + return false; + } + }, + { label: "HTTP gateway accepting connections" }, + ); + + const response = await fetch(`${baseUrl}/v1/lease-requests`, { + body: JSON.stringify({ device: "iPhone 16", os: "^18", platform: "ios" }), + headers: { authorization: `Bearer ${secret}`, "content-type": "application/json" }, + method: "POST", + }); + + expect(response.status).toBe(400); + const { error } = (await response.json()) as { error: { code: string; message: string } }; + expect(error.code).toBe("BAD_REQUEST"); + expect(error.message).toContain("18 - 26"); + }); + it("POST /v1/lease-requests takes a class, or only a platform, and refuses a device beside a class", async () => { const port = await reservePort(); const env = await withDaemon({ diff --git a/e2e/lease-lifecycle.test.ts b/e2e/lease-lifecycle.test.ts index 587bb3b0c..6ff8b83ad 100644 --- a/e2e/lease-lifecycle.test.ts +++ b/e2e/lease-lifecycle.test.ts @@ -286,6 +286,30 @@ describe("lease lifecycle across both frontends", () => { expect(result.stderr).toContain("BAD_REQUEST"); }); + it("grants --os '>=18' a device on 18.0 or newer, fails --os '<=17' at once with RUNTIME_MISSING with and without --allow-download, and refuses --os '^18' with BAD_REQUEST naming the accepted forms", async () => { + const env = await withDaemon({ driverScript: { ios: iosScript } }); + + const inRange = await lease(env, "in-range", ["--os", ">=18"]); + expect(inRange.code, inRange.stderr).toBe(0); + expect(Number.parseFloat(granted(inRange).device.spec.osVersion)).toBeGreaterThanOrEqual(18); + await env.cli(["release", granted(inRange).lease.id]); + + await env.driverLog.clear(); + for (const extra of [[], ["--allow-download"]]) { + const missing = await lease(env, "missing", ["--os", "<=17", ...extra]); + expect(missing.code).toBe(12); + expect(missing.stderr).toContain("RUNTIME_MISSING"); + } + expect( + (await env.driverLog.calls()).filter((call) => call.operation === "installComponent"), + ).toEqual([]); + + const malformed = await lease(env, "malformed", ["--os", "^18"]); + expect(malformed.code).not.toBe(0); + expect(malformed.stderr).toContain("BAD_REQUEST"); + expect(malformed.stderr).toContain("18 - 26"); + }); + it.each([ [undefined, "iPhone 17"], ["iPhone 15", "iPhone 15"], diff --git a/e2e/mcp-session.test.ts b/e2e/mcp-session.test.ts index 6646ccc1c..ffebbab57 100644 --- a/e2e/mcp-session.test.ts +++ b/e2e/mcp-session.test.ts @@ -202,6 +202,29 @@ describe("MCP session semantics", () => { } }); + it("lease_simulator refuses a malformed osVersion range as BAD_REQUEST naming the accepted forms", async () => { + const env = await withDaemon({ + driverScript: { ios: { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] } }, + }); + const mcp = await env.mcpClient({ env: { SIMLOCK_AGENT_ID: "range-agent" } }); + + try { + const result = await mcp.client.callTool({ + name: "lease_simulator", + arguments: { model: "iPhone 16", osVersion: "^18", platform: "ios" }, + }); + + expect(result.isError).toBe(true); + const payload = JSON.parse( + (result.content as { text: string }[])[0]?.text ?? "{}", + ) as McpErrorPayload; + expect(payload.code).toBe("BAD_REQUEST"); + expect(payload.message).toContain("18 - 26"); + } finally { + await mcp.close(); + } + }); + it("lease_simulator accepts a class or only a platform and grants a device naming its model, and refuses a class beside a model", async () => { const env = await withDaemon({ driverScript: { diff --git a/e2e/slow-ios-os-range.test.ts b/e2e/slow-ios-os-range.test.ts new file mode 100644 index 000000000..f674ce859 --- /dev/null +++ b/e2e/slow-ios-os-range.test.ts @@ -0,0 +1,86 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { describe, expect, it } from "vitest"; + +import { withDaemon } from "./helpers/index.js"; +import { sweepStaleDeviceSets } from "./helpers/ios-device-set.js"; + +const execFileAsync = promisify(execFile); + +/** The installed, available iOS runtimes' versions, as real simctl reports them. */ +async function installedRuntimes(): Promise { + const { stdout } = await execFileAsync("xcrun", ["simctl", "list", "runtimes", "-j"]); + const parsed = JSON.parse(stdout) as { + runtimes: { version: string; isAvailable: boolean; platform?: string }[]; + }; + return parsed.runtimes + .filter((runtime) => runtime.isAvailable && (runtime.platform ?? "iOS") === "iOS") + .map((runtime) => runtime.version); +} + +/** The major number of a dotted version. */ +function major(version: string): number { + return Number.parseInt(version, 10); +} + +// This lane needs the real simctl toolchain, hence darwin-only. It never installs a runtime: +// the RUNTIME_MISSING lines below run with --allow-download and must still not download. +describe.skipIf(process.platform !== "darwin")( + "iOS --os ranges (real simctl)", + { tags: ["slow", "ios"] }, + () => { + it( + "fails --os '<=17' at once with RUNTIME_MISSING with and without --allow-download when nothing older than 18 is installed, grants --os '>=18' a device on 18.0 or newer, and refuses --os '^18' with BAD_REQUEST", + { timeout: 600_000 }, + async () => { + await sweepStaleDeviceSets(); + const runtimes = await installedRuntimes(); + expect( + runtimes.filter((version) => major(version) < 18), + "this lane needs a host with nothing older than iOS 18 installed", + ).toEqual([]); + expect( + runtimes.filter((version) => major(version) >= 18).length, + "this lane needs at least one installed iOS runtime of 18 or newer", + ).toBeGreaterThan(0); + + const env = await withDaemon({ driver: "real" }); + + for (const extra of [[], ["--allow-download"]]) { + const missing = await env.cli( + ["lease", "--platform", "ios", "--os", "<=17", "--agent-id", "os-range", ...extra], + { timeout: 60_000 }, + ); + expect(missing.code, `expected RUNTIME_MISSING (exit 12): ${missing.stderr}`).toBe(12); + expect(missing.error?.code).toBe("RUNTIME_MISSING"); + } + + const malformed = await env.cli([ + "lease", + "--platform", + "ios", + "--os", + "^18", + "--agent-id", + "os-range", + ]); + expect(malformed.code, malformed.stderr).not.toBe(0); + expect(malformed.error?.code).toBe("BAD_REQUEST"); + + const granted = await env.cli( + ["lease", "--platform", "ios", "--os", ">=18", "--agent-id", "os-range", "--detach"], + { timeout: 300_000 }, + ); + expect(granted.code, `lease failed: ${granted.stderr}`).toBe(0); + const grant = granted.json as { + device: { spec: { osVersion: string } }; + lease: { id: string }; + }; + expect(major(grant.device.spec.osVersion)).toBeGreaterThanOrEqual(18); + + await env.cli(["release", grant.lease.id]); + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + }, + ); + }, +); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index c8f2be66b..ec0ec7f79 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -5275,7 +5275,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" + + " [--os ] [--mode ] [--image-tag ] [--agent-id ]\n" + " [--timeout ]\n" + " [--no-wait] [--detach] [--ttl ] [--allow-download]\n" + " [--export-env] [--bind-pid ]\n", @@ -5337,4 +5337,29 @@ describe("simlock lease: a request names a model, a class, or nothing", () => { "Request req_2: b, android class phone, queued at 2, waiting 0s\n", ); }); + + it("prints a waiting request's OS range as typed", async () => { + const output = outputCapture(); + const client = fakeClient({ + list: async () => [ + { + createdAt: 0, + id: "req_1", + queuePosition: 1, + requesterId: "a", + spec: { osVersion: ">=18 <26", platform: "ios" }, + stage: "queued", + }, + ], + }); + + await runCli( + ["list", "--requests"], + output.environmentWith({ connectAdmin: async () => client }), + ); + + expect(output.stdout).toBe( + "Request req_1: a, ios class phone >=18 <26, queued at 1, waiting 0s\n", + ); + }); }); diff --git a/src/cli/index.ts b/src/cli/index.ts index 6ffbf5168..1f843c2d2 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -953,7 +953,7 @@ async function runLease( if (values.help) { environment.stdout.write( "Usage: simlock lease --platform [--device | --class ]\n" + - " [--os ] [--mode ] [--image-tag ] [--agent-id ]\n" + + " [--os ] [--mode ] [--image-tag ] [--agent-id ]\n" + " [--timeout ]\n" + " [--no-wait] [--detach] [--ttl ] [--allow-download]\n" + " [--export-env] [--bind-pid ]\n", diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 1c520b62e..77f67fe08 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -209,6 +209,30 @@ describe("component.install input", () => { }); }); +describe("lease.request osVersion", () => { + const parse = (osVersion: string) => + OPERATIONS["lease.request"].input.safeParse({ model: "iPhone 17", osVersion, platform: "ios" }); + + it.each([["18.4"], ["Baklava"], ["34-ext12"], [">=18"], [">=18 <26"], ["18 - 26"]])( + "accepts %s", + (osVersion) => { + expect(parse(osVersion).success).toBe(true); + }, + ); + + it.each([["^18"], ["~18"], ["18.x"], ["18.X"], ["*"], [">=18 || <17"], [""]])( + "refuses %j with a message naming the accepted forms", + (osVersion) => { + const result = parse(osVersion); + expect(result.success).toBe(false); + if (!result.success) { + expect(result.error.issues[0]?.message).toContain("18 - 26"); + expect(result.error.issues[0]?.path).toEqual(["osVersion"]); + } + }, + ); +}); + describe("operation input/output round trips", () => { it("lease.request: round-trips a representative request and rejects legacy aliases", () => { const input = OPERATIONS["lease.request"].input.parse({ diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 93be1f8c5..2a9ad0522 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -10,6 +10,7 @@ import { z } from "zod"; import { CONSOLE_URL_MAX_LENGTH } from "./console-url.js"; +import { parseOsConstraint } from "./os-range.js"; import { ownsLease, type AuthorizeContext, type Role } from "./roles.js"; import { cleanupRuleSummarySchema, @@ -165,6 +166,11 @@ const leaseRequestBaseSchema = z model: z.string().min(1).optional(), class: deviceClassSchema.optional(), platform: platformSchema, + /** + * ADR 0015 §2: an exact version or a range. A plain string here, checked by + * `refuseBadOsVersion` beside it: a refined field would be checked by the MCP SDK before the + * handler, and its own error would stand in for `BAD_REQUEST`. + */ osVersion: z.string().optional(), mode: z.enum(["slim", "full"]).optional(), imageTag: imageTagSchema.optional(), @@ -226,10 +232,30 @@ export function refuseModelWithClass( }; } +/** Refuses an `osVersion` that is neither an exact version nor a range (ADR 0015 §2); one place, one check. */ +export function refuseBadOsVersion(): ( + input: T, + context: z.RefinementCtx, +) => void { + return (input, context) => { + if (input.osVersion === undefined) return; + const parsed = parseOsConstraint(input.osVersion); + if (!parsed.ok) { + context.addIssue({ + code: z.ZodIssueCode.custom, + message: parsed.message, + path: ["osVersion"], + }); + } + }; +} + /** The fields of `lease.request` without the model-or-class refinement, for schemas derived from it. */ export const leaseRequestFields = leaseRequestBaseSchema; -const leaseRequestInputSchema = leaseRequestBaseSchema.superRefine(refuseModelWithClass()); +const leaseRequestInputSchema = leaseRequestBaseSchema + .superRefine(refuseModelWithClass()) + .superRefine(refuseBadOsVersion()); // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. export const leaseRequest = defineOperation({ diff --git a/src/contract/os-range.test.ts b/src/contract/os-range.test.ts new file mode 100644 index 000000000..a4cd32910 --- /dev/null +++ b/src/contract/os-range.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from "vitest"; + +import { compareVersions, parseOsConstraint, satisfies } from "./os-range.js"; + +function parsed(text: string) { + const result = parseOsConstraint(text); + if (!result.ok) throw new Error(`expected ${text} to parse: ${result.message}`); + return result.constraint; +} + +describe("parseOsConstraint", () => { + it.each([ + ["18.40"], + [">=18.4.2 <19.10"], + ["18.4 - 26.10.1"], + ["18.4"], + [">=18"], + [">18"], + ["<=26"], + ["<26"], + [">=18 <26"], + ["18 - 26"], + ])("accepts %s", (text) => { + expect(parseOsConstraint(text).ok).toBe(true); + }); + + it.each([ + ["^18"], + ["~18"], + ["18.x"], + ["*"], + [">=18 || <17"], + [">=18 <26"], + [""], + [">=x18"], + [">=18x"], + [">= 18"], + ["x18 - 26"], + ["18x - 26"], + ["18 - x26"], + ["18 - 26x"], + ["18 - 26 - 30"], + ["18 - 26"], + [">=18 - 26"], + ])("refuses %j with a message naming the accepted forms", (text) => { + const result = parseOsConstraint(text); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.message).toContain(">="); + expect(result.message).toContain("18 - 26"); + expect(result.message).toContain("exact version"); + } + }); +}); + +describe("a string that is not range-like", () => { + it.each([ + ["Baklava"], + ["34-ext12"], + ["26.5-beta"], + ["x18"], + ["18x"], + [" 18"], + ["18 "], + ["ext>1"], + ["a=b"], + ])("is a bare version and stays exact: %j", (text) => { + expect(parsed(text)).toEqual({ kind: "exact", version: text }); + }); + + it("satisfies no range when the version is not dotted integers", () => { + expect(satisfies("Baklava", parsed(">=18"))).toBe(false); + expect(satisfies("34-ext12", parsed("<=40"))).toBe(false); + expect(satisfies("Baklava", parsed("Baklava"))).toBe(true); + }); +}); + +describe("parseOsConstraint structure", () => { + it("keeps the text as typed and one bound per comparator", () => { + expect(parsed(">=18 <26")).toEqual({ + bounds: [{ from: [18] }, { before: [26] }], + kind: "range", + text: ">=18 <26", + }); + expect(parsed("18 - 26")).toEqual({ + bounds: [{ from: [18] }, { before: [27] }], + kind: "range", + text: "18 - 26", + }); + }); +}); + +describe("satisfies", () => { + it.each([ + [">=18", "18.0", true], + [">=18", "18.4", true], + [">=18", "17.5", false], + ["<=26", "26.5", true], + ["<=26", "27.0", false], + [">26", "26.5", false], + [">26", "27.0", true], + ["<18", "18.0", false], + ["<18", "17.9", true], + ["18 - 26", "18.0", true], + ["18 - 26", "26.5", true], + ["18 - 26", "27.0", false], + [">=18 <26", "26.0", false], + [">=18 <26", "25.9", true], + [">18.4", "18.4", false], + [">18.4", "18.5", true], + ])("reads %s against %s as %s, as node-semver does", (text, version, expected) => { + expect(satisfies(version, parsed(text))).toBe(expected); + }); + + it("reads a bare version as exact: 18 does not satisfy a device on 18.4", () => { + expect(satisfies("18.4", parsed("18"))).toBe(false); + expect(satisfies("18", parsed("18"))).toBe(true); + expect(satisfies("18.4", parsed("18.4"))).toBe(true); + }); +}); + +describe("compareVersions", () => { + it("orders 9.3 before 18.4 before 26.5, and 34 before 35", () => { + expect(compareVersions("9.3", "18.4")).toBeLessThan(0); + expect(compareVersions("18.4", "26.5")).toBeLessThan(0); + expect(compareVersions("34", "35")).toBeLessThan(0); + expect(compareVersions("35", "34")).toBeGreaterThan(0); + expect(compareVersions("26.5", "26.5")).toBe(0); + }); + + it("reads a missing segment as 0 and compares segments as numbers", () => { + expect(compareVersions("26", "26.1")).toBeLessThan(0); + expect(compareVersions("26.0.1", "26")).toBeGreaterThan(0); + expect(compareVersions("26", "26.0")).toBe(0); + expect(compareVersions("1.10", "1.9")).toBeGreaterThan(0); + }); +}); diff --git a/src/contract/os-range.ts b/src/contract/os-range.ts new file mode 100644 index 000000000..d05ba18c0 --- /dev/null +++ b/src/contract/os-range.ts @@ -0,0 +1,135 @@ +/** + * The one grammar for an OS constraint (ADR 0015 §2; architecture rule 10): a bare version, which + * is exact, or a range in a node-semver subset. Parses a string, tests a version against the + * result, and orders versions. It lives in the contract so the `osVersion` schema can refine + * through it and the core and the gateway can import it; no dependency is added. + * + * A partial version covers its prefix as node-semver reads it: `>=18` is 18.0 onward, `<=26` + * includes every 26.x, `>26` excludes every 26.x, `<18` excludes every 18.x, and `18 - 26` is + * `>=18 <=26`. + */ + +/** A version at or above `from`, and below `before` when it has one. */ +interface Bound { + readonly from?: readonly number[]; + readonly before?: readonly number[]; +} + +export interface OsRange { + readonly kind: "range"; + /** The text as typed, so an event or an error can show it back. */ + readonly text: string; + readonly bounds: readonly Bound[]; +} + +export type OsConstraint = { readonly kind: "exact"; readonly version: string } | OsRange; + +export type ParsedOsConstraint = + | { readonly ok: true; readonly constraint: OsConstraint } + | { readonly ok: false; readonly message: string }; + +/** The message a refused constraint carries, naming every accepted form. */ +const ACCEPTED_FORMS = + "an OS constraint is an exact version (`18.4`), or a range: one or more of `>=`, `>`, `<=`, `<` " + + "followed by a version, joined by single spaces (`>=18 <26`), or a hyphen range (`18 - 26`)"; + +const VERSION = /^\d+(?:\.\d+)*$/; +const OPERATORS = [">=", ">", "<=", "<"] as const; + +/** + * Whether a string is written as a range rather than a version: it starts with a comparator, or + * has a hyphen range, a caret, a tilde, a star, `||`, or an `x` segment. Anything else is a bare + * version, which stays exact as on `main`, so a runtime a driver lists as `Baklava` or `34-ext12` + * still names itself. + */ +function looksLikeRange(text: string): boolean { + return ( + /^[<>=]/.test(text) || + / - |\^|~|\*|\|\|/.test(text) || + text.split(".").some((segment) => segment === "x" || segment === "X") + ); +} + +export function parseOsConstraint(text: string): ParsedOsConstraint { + if (text === "") return refused(text); + if (!looksLikeRange(text)) return { constraint: { kind: "exact", version: text }, ok: true }; + const bounds = hyphenBounds(text) ?? comparatorBounds(text); + return bounds === undefined + ? refused(text) + : { constraint: { bounds, kind: "range", text }, ok: true }; +} + +/** `A - B` is `>=A <=B`. */ +function hyphenBounds(text: string): readonly Bound[] | undefined { + const parts = text.split(" - "); + if (parts.length !== 2 || !parts.every((part) => VERSION.test(part))) return undefined; + const [from, to] = parts.map(segments) as [readonly number[], readonly number[]]; + return [comparatorBound(">=", from), comparatorBound("<=", to)]; +} + +/** One or more comparators joined by single spaces. */ +function comparatorBounds(text: string): readonly Bound[] | undefined { + const bounds: Bound[] = []; + for (const token of text.split(" ")) { + const operator = OPERATORS.find((candidate) => token.startsWith(candidate)); + if (operator === undefined) return undefined; + const version = token.slice(operator.length); + if (!VERSION.test(version)) return undefined; + bounds.push(comparatorBound(operator, segments(version))); + } + return bounds; +} + +function refused(text: string): ParsedOsConstraint { + return { message: `Invalid OS constraint ${JSON.stringify(text)}: ${ACCEPTED_FORMS}`, ok: false }; +} + +function comparatorBound(operator: (typeof OPERATORS)[number], version: readonly number[]): Bound { + switch (operator) { + case ">=": + return { from: version }; + case ">": + return { from: bump(version) }; + case "<=": + return { before: bump(version) }; + default: + return { before: version }; + } +} + +/** The next version of the same precision: 18 -> 19, 18.4 -> 18.5. */ +function bump(version: readonly number[]): readonly number[] { + return version.map((part, index) => (index === version.length - 1 ? part + 1 : part)); +} + +function segments(version: string): readonly number[] { + return version.split(".").map(Number); +} + +/** + * Whether a device OS satisfies a constraint; a bare version is string equality. A version that is + * not dotted integers (`Baklava`) reads as NaN, which every bound refuses, so it satisfies no range. + */ +export function satisfies(version: string, constraint: OsConstraint): boolean { + if (constraint.kind === "exact") return constraint.version === version; + const parts = segments(version); + return constraint.bounds.every( + (bound) => + (bound.from === undefined || compareSegments(parts, bound.from) >= 0) && + (bound.before === undefined || compareSegments(parts, bound.before) < 0), + ); +} + +/** Orders dotted integers, a missing segment reading as 0: negative when `left` is older. */ +export function compareVersions(left: string, right: string): number { + return compareSegments(segments(left), segments(right)); +} + +function compareSegments(left: readonly number[], right: readonly number[]): number { + const length = Math.max(left.length, right.length); + const differences = Array.from( + { length }, + (_, index) => (left[index] ?? 0) - (right[index] ?? 0), + ); + return differences.find((difference) => difference !== 0) ?? 0; +} diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 905aa3fab..49c6217d9 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -42,9 +42,9 @@ const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().in * The consequence ADR 0005 §31 names: a pre-0005 worker's uplink negotiates nothing, so its * gateway marks it `incompatible` -- with both ranges on the view -- and never dispatches to it. * A worker on 5 is marked `incompatible` the same way (ADR 0008 §10), and so is one on 7 - * (ADR 0007 §12), and so is one on 8 (ADR 0010 §9), one on 10 (ADR 0009 §7), one on 11 (ADR 0015 §3), one on 12 (ADR 0015 §4), and one on 13 (ADR 0015 §1). + * (ADR 0007 §12), and so is one on 8 (ADR 0010 §9), one on 10 (ADR 0009 §7), one on 11 (ADR 0015 §3), one on 12 (ADR 0015 §4), one on 13 (ADR 0015 §1), and one on 14 (ADR 0015 §2). */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 14, max: 14 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 15, max: 15 }; /** * The one protocol version that ever existed before ranges did. Used only to build the diff --git a/src/core/domain.ts b/src/core/domain.ts index 999704a96..1b4a33714 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -1,3 +1,4 @@ +import { type OsConstraint as RequestedOs, satisfies } from "../contract/os-range.js"; import type { DeviceRequest } from "./driver.js"; export type Platform = "ios" | "android"; @@ -63,10 +64,11 @@ export function sameSpec(left: DeviceSpec, right: DeviceSpec): boolean { /** * The OS a requirement accepts (ADR 0015 §5). `exact` is one version, the one an exact request * resolves to or one the request named; `installed` is any runtime the catalog lists as installed, - * which is what a class request with no OS accepts. + * which is what a class request with no OS accepts. A `range` is the request's own range, parsed + * by the contract's `os-range`, the one grammar. */ -export type OsConstraint = - | { readonly kind: "exact"; readonly version: string } +export type OsRequirement = + | RequestedOs | { readonly kind: "installed"; readonly versions: readonly string[] }; /** @@ -79,7 +81,7 @@ export interface DeviceRequirement { readonly target: | { readonly kind: "model"; readonly model: string } | { readonly kind: "class"; readonly class: DeviceClass }; - readonly osVersion: OsConstraint; + readonly osVersion: OsRequirement; readonly imageTag: string | undefined; } @@ -126,13 +128,10 @@ function fitsTarget( } } -function satisfiesOs(constraint: OsConstraint, osVersion: string): boolean { - switch (constraint.kind) { - case "exact": - return constraint.version === osVersion; - case "installed": - return constraint.versions.includes(osVersion); - } +function satisfiesOs(constraint: OsRequirement, osVersion: string): boolean { + return constraint.kind === "installed" + ? constraint.versions.includes(osVersion) + : satisfies(osVersion, constraint); } /** diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 93ec2cace..404654caf 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -22,6 +22,7 @@ import { type Driver, DriverCrashError, readyTransitionUpdate, + RuntimeMissingError, UnsupportedRequestOptionError, } from "./driver.js"; import { type DeviceMode, type DeviceSpec, type Platform, specMode } from "./domain.js"; @@ -2010,6 +2011,262 @@ describe("LeaseAcquisitionCoordinator: class requests", () => { }); }); + describe("OS ranges", () => { + const rangeDriver = (options: Partial[0]> = {}) => + iosDriver({ + availableOsVersions: ["18.0", "18.4", "26.5"], + modelRuntimes: { + "iPhone 15": ["18.0", "18.4", "26.5"], + "iPhone 16": ["18.0", "18.4", "26.5"], + "iPhone 17": ["26.5"], + }, + ...options, + }); + + it("sends a class request with no osVersion to the driver without pinning a runtime", async () => { + const driver = rangeDriver(); + const harness = await classHarness(driver); + + await harness.coordinator.request({ platform: "ios" }, owner("agent")); + + const resolve = driver.calls.find((call) => call.operation === "resolveSpec"); + expect(resolve?.arguments[0]).toEqual({ mode: "full", model: "iPhone 17", platform: "ios" }); + }); + + it("grants a ready idle device whose OS satisfies the range, and not one outside it", async () => { + const inside = await classHarness(rangeDriver()); + const warm = await seedReady(inside, { ...iphone15, osVersion: "18.0" }); + const grantedInside = await inside.coordinator.request( + { ...phone, osVersion: ">=18 <26" }, + owner("agent"), + ); + expect(grantedInside.device.id).toBe(warm.id); + + const outside = await classHarness(rangeDriver()); + const stale = await seedReady(outside, { ...iphone15, osVersion: "26.5" }); + const grantedOutside = await outside.coordinator.request( + { ...phone, osVersion: ">=18 <26" }, + owner("agent"), + ); + expect(grantedOutside.device.id).not.toBe(stale.id); + expect(grantedOutside.device.spec.osVersion).toBe("18.4"); + }); + + it("fails an exact model the catalog does not list, sent with a range, at once with UnknownModelError", async () => { + const driver = rangeDriver(); + const harness = await classHarness(driver); + + await expect( + harness.coordinator.request( + { model: "iPhone 99", osVersion: ">=18", platform: "ios" }, + owner("agent"), + ), + ).rejects.toMatchObject({ model: "iPhone 99", name: "UnknownModelError" }); + expect(deviceWork(driver)).toBe(0); + }); + + it("grants an exact model with a range a ready idle device of that model in range, and not one of another model", async () => { + const harness = await classHarness(rangeDriver()); + const other = await seedReady(harness, { ...iphone15, osVersion: "18.0" }); + const same = await seedReady(harness, { + model: "iPhone 16", + osVersion: "18.0", + platform: "ios", + }); + const before = deviceWork(harness.driver); + + const granted = await harness.coordinator.request( + { model: "iPhone 16", osVersion: ">=18 <26", platform: "ios" }, + owner("agent"), + ); + + expect(granted.device.id).toBe(same.id); + expect(granted.device.id).not.toBe(other.id); + expect(deviceWork(harness.driver)).toBe(before); + }); + + it("fails an exact model with a range at once with UnknownModelError when the platform lists no catalog", async () => { + const harness = await createHarness({ + catalogReader: { listCatalog: async () => [] }, + drivers: [rangeDriver()], + }); + + await expect( + harness.coordinator.request( + { model: "iPhone 16", osVersion: ">=18", platform: "ios" }, + owner("agent"), + ), + ).rejects.toMatchObject({ model: "iPhone 16", name: "UnknownModelError" }); + }); + + it("never installs for a range even when the driver then reports a downloadable runtime missing", async () => { + class Racing extends FakeDriver { + override async resolveSpec(): Promise { + throw new RuntimeMissingError("ios", "18.4", { component: "18.4" }); + } + } + const asked: unknown[] = []; + const harness = await createHarness({ + components: { + install: async (call) => { + asked.push(call); + return { outcome: "installed", version: "18.4" }; + }, + }, + drivers: [ + new Racing({ + availableOsVersions: ["18.4"], + clock: new FakeClock(1_000), + knownModels: ["iPhone 16"], + modelClasses: { "iPhone 16": "phone" }, + platform: "ios", + }), + ], + }); + + await expect( + harness.coordinator.request( + { model: "iPhone 16", osVersion: ">=18", platform: "ios" }, + { ...owner("agent"), allowDownload: true }, + ), + ).rejects.toMatchObject({ name: "RuntimeMissingError" }); + expect(asked).toEqual([]); + }); + + it("creates an exact model with a range on the newest listed pairing in range", async () => { + const harness = await classHarness(rangeDriver()); + + const granted = await harness.coordinator.request( + { model: "iPhone 16", osVersion: "<26", platform: "ios" }, + owner("agent"), + ); + + expect(granted.device.spec).toMatchObject({ model: "iPhone 16", osVersion: "18.4" }); + expect(provisioned(harness).map((spec) => spec.osVersion)).toEqual(["18.4"]); + }); + + it.each([ + ["without allowDownload", false], + ["with allowDownload", true], + ])( + "fails an exact model with a range nothing installed satisfies at once with RuntimeMissingError, not downloadable, naming the range, and never installs, %s", + async (_label, allowDownload) => { + const driver = rangeDriver(); + const harness = await classHarness(driver); + + await expect( + harness.coordinator.request( + { model: "iPhone 16", osVersion: "<=17", platform: "ios" }, + { ...owner("agent"), allowDownload }, + ), + ).rejects.toMatchObject({ + downloadable: false, + name: "RuntimeMissingError", + osVersion: "<=17", + }); + expect(installs(driver)).toEqual([]); + expect(deviceWork(driver)).toBe(0); + }, + ); + + it.each([["Baklava"], ["34-ext12"]])( + "reaches resolveSpec with the bare version %s exact, as without ranges, and a range never picks it", + async (name) => { + const driver = rangeDriver({ + availableOsVersions: ["18.4", name], + modelRuntimes: { "iPhone 16": ["18.4", name] }, + }); + const harness = await classHarness(driver); + + await harness.coordinator.request( + { model: "iPhone 16", osVersion: name, platform: "ios" }, + owner("agent"), + ); + const resolved = driver.calls.find((call) => call.operation === "resolveSpec"); + expect(resolved?.arguments[0]).toMatchObject({ osVersion: name }); + + const ranged = await classHarness(driver); + const granted = await ranged.coordinator.request( + { model: "iPhone 16", osVersion: ">=18", platform: "ios" }, + owner("agent"), + ); + expect(granted.device.spec.osVersion).toBe("18.4"); + }, + ); + + it("picks the newest in-range runtime whatever order the catalog lists them in", async () => { + const harness = await classHarness( + rangeDriver({ + availableOsVersions: ["18.4", "26.5", "9.3", "18.0"], + modelRuntimes: { "iPhone 16": ["18.4", "26.5", "9.3", "18.0"] }, + }), + ); + + const granted = await harness.coordinator.request( + { model: "iPhone 16", osVersion: "<26", platform: "ios" }, + owner("agent"), + ); + + expect(granted.device.spec.osVersion).toBe("18.4"); + }); + + it("takes the first class candidate that has an in-range pairing and its newest such runtime: <=18 creates an iPhone 16 on the newest 18.x", async () => { + const harness = await classHarness(rangeDriver()); + + const granted = await harness.coordinator.request( + { ...phone, osVersion: "<=18" }, + owner("agent"), + ); + + expect(granted.device.spec).toMatchObject({ model: "iPhone 16", osVersion: "18.4" }); + }); + + it.each([ + ["without allowDownload", false], + ["with allowDownload", true], + ])( + "fails a class with a range no candidate pairs with at once with RuntimeMissingError and never installs, %s", + async (_label, allowDownload) => { + const driver = rangeDriver(); + const harness = await classHarness(driver); + + await expect( + harness.coordinator.request( + { ...phone, osVersion: "<=17" }, + { ...owner("agent"), allowDownload }, + ), + ).rejects.toMatchObject({ + downloadable: false, + name: "RuntimeMissingError", + osVersion: "<=17", + }); + expect(installs(driver)).toEqual([]); + }, + ); + + it("does not pick a runtime in range whose only images carry another tag: API 35 default only and API 34 google_apis, >=33 with tag google_apis creates on 34", async () => { + const driver = new FakeDriver({ + availableOsVersions: ["34", "35"], + clock: new FakeClock(1_000), + images: [ + { abi: "arm64-v8a", runtime: "34", tag: "google_apis" }, + { abi: "arm64-v8a", runtime: "35", tag: "default" }, + ], + knownModels: ["Pixel 8"], + modelClasses: { "Pixel 8": "phone" }, + modelRuntimes: { "Pixel 8": ["34", "35"] }, + platform: "android", + }); + const harness = await classHarness(driver, { android: { phone: ["Pixel 8"] } }); + + const byModel = await harness.coordinator.request( + { imageTag: "google_apis", model: "Pixel 8", osVersion: ">=33", platform: "android" }, + owner("agent"), + ); + expect(byModel.device.spec).toMatchObject({ imageTag: "google_apis", osVersion: "34" }); + }); + }); + describe("creating a device for a class", () => { it("creates the first name on the class's list the catalog lists, and device.provisioned carries that model", async () => { const harness = await classHarness(); diff --git a/src/core/lease-acquisition-coordinator.ts b/src/core/lease-acquisition-coordinator.ts index db8c354bb..9a725628d 100644 --- a/src/core/lease-acquisition-coordinator.ts +++ b/src/core/lease-acquisition-coordinator.ts @@ -1,5 +1,11 @@ import type { EventBus, EventMap } from "../bus/index.js"; import { requestedClass } from "../contract/index.js"; +import { + compareVersions, + type OsRange, + parseOsConstraint, + satisfies, +} from "../contract/os-range.js"; import { type IdGenerator, type Logger, NoopLogger } from "../ports/index.js"; import type { CapacityReservation } from "./capacity/index.js"; import { type AcquisitionPlan, type AcquisitionPlanner } from "./acquisition-planner.js"; @@ -9,7 +15,7 @@ import { } from "./device-operation-claims.js"; import { type DeviceProvisioner } from "./device-provisioner.js"; import { type LeaseRequestBook, newLeaseRequestId } from "./lease-request-book.js"; -import { classCandidates, modelClass, pairedRuntimes } from "./catalog-match.js"; +import { classCandidates, findCatalogModel, modelClass, pairedRuntimes } from "./catalog-match.js"; import { type DeviceClass, type DeviceMode, @@ -331,8 +337,16 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { try { // The one place a request with no mode gets the worker's default (ADR 0007 §2). const mode = request.mode ?? this.options.defaultModes[request.platform] ?? "full"; - const target = this.#exactTarget(request, mode) ?? (await this.#resolveClass(request, mode)); - const resolved = await this.#resolveOrInstall(waiter, driver, target.exact, options); + const range = requestedRange(request); + const target = + range === undefined + ? (this.#exactTarget(request, mode) ?? (await this.#resolveClass(request, mode))) + : await this.#resolveRanged(request, mode, range); + // A range was settled against the catalog above, so it never installs (ADR 0015 §5). + const resolved = await this.#resolveOrInstall(waiter, driver, target.exact, { + ...options, + allowDownload: options.allowDownload === true && range === undefined, + }); waiter.spec = checkedSpec(resolved, request, mode); waiter.requirement = target.requirement ?? exactRequirement(waiter.spec); waiter.classOf = target.classOf; @@ -356,14 +370,21 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { } /** - * Turns a request that names no model into the exact one a driver resolves (ADR 0015 §5). A class, named or meant by naming nothing, becomes the first model on its preference - * list that this host's catalog lists, classes as that class, and pairs with an installed - * runtime (of the requested image tag, when it names one); the catalog is read, and nothing is - * downloaded. A class with no listed model fails as `UnknownModelError`, and one whose listed - * models pair with no runtime as a `RuntimeMissingError` no download can fix. + * Turns a request that names no model, or names an OS range, into the exact one a driver + * resolves (ADR 0015 §5). A class, named or meant by naming nothing, becomes the first model + * on its preference list that this host's catalog lists, classes as that class, and pairs with + * an installed runtime (of the requested image tag, and in the requested range, when it names + * them); an exact model with a range must be listed, or the request fails as + * `UnknownModelError`. With a range the runtime is the newest paired one in it, passed on as an + * exact version. The catalog is read, and nothing is downloaded. A class with no listed model + * fails as `UnknownModelError`, and a model or class with no pairing as a `RuntimeMissingError` + * no download can fix. */ - async #resolveClass(request: DeviceRequest, mode: DeviceMode): Promise { - const { class: _class, model: _model, ...rest } = request; + async #resolveClass( + request: DeviceRequest, + mode: DeviceMode, + range?: OsRange, + ): Promise { const deviceClass = requestedClass({ class: request.class }); const entry = (await this.options.catalog.listCatalog(request.platform))[0]; if (entry === undefined) throw new UnknownModelError(request.platform, undefined, deviceClass); @@ -375,21 +396,68 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { if (candidates.length === 0) { throw new UnknownModelError(request.platform, undefined, deviceClass); } - const chosen = candidates.find((candidate) => pairs(entry, candidate, request)); + const chosen = candidates.find( + (candidate) => matchingRuntimes(entry, candidate, request, range).length > 0, + ); if (chosen === undefined) { throw new RuntimeMissingError(request.platform, request.osVersion ?? "default"); } return { + ...this.#rangedTarget( + entry, + chosen, + { class: deviceClass, kind: "class" }, + request, + mode, + range, + ), classOf: (candidate) => modelClass(entry, candidate), - exact: { ...rest, mode, model: chosen }, + }; + } + + /** A request that names a model and an OS range: the model must be listed (ADR 0015 §5). */ + async #resolveRanged( + request: DeviceRequest, + mode: DeviceMode, + range: OsRange, + ): Promise { + if (request.model === undefined) return this.#resolveClass(request, mode, range); + const entry = (await this.options.catalog.listCatalog(request.platform))[0]; + if (entry === undefined) throw new UnknownModelError(request.platform, request.model); + const listed = findCatalogModel(entry, request.model); + if (listed === undefined) throw new UnknownModelError(request.platform, request.model); + return this.#rangedTarget( + entry, + listed, + { kind: "model", model: listed }, + request, + mode, + range, + ); + } + + /** The target for `model` once the request's runtime constraints are settled against `entry`. */ + #rangedTarget( + entry: DriverCatalogEntry, + model: string, + target: DeviceRequirement["target"], + request: DeviceRequest, + mode: DeviceMode, + range: OsRange | undefined, + ): ResolvedTarget { + const { class: _class, model: _model, ...rest } = request; + return { + exact: { + ...rest, + mode, + model, + ...(range === undefined ? {} : { osVersion: newestRuntime(entry, model, request, range) }), + }, requirement: { imageTag: request.imageTag, - osVersion: - request.osVersion === undefined - ? { kind: "installed", versions: entry.runtimes } - : { kind: "exact", version: request.osVersion }, + osVersion: requiredOs(entry, request, range), platform: request.platform, - target: { class: deviceClass, kind: "class" }, + target, }, }; } @@ -978,18 +1046,53 @@ interface ResolvedTarget { } /** - * Whether a model pairs with an installed runtime, counting only the requested OS version when the - * request names one, and only runtimes that have an image of the requested tag when it names one (the rule the gateway's `matchRequest` applies). + * The installed runtimes a model pairs with that the request accepts: the one it names, or those + * 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 pairs( +function matchingRuntimes( entry: DriverCatalogEntry, model: string, { imageTag, osVersion }: Pick, -): boolean { - return pairedRuntimes(entry, model).some( + range: OsRange | undefined, +): string[] { + return pairedRuntimes(entry, model).filter( (runtime) => - (osVersion === undefined || runtime === osVersion) && + (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/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 09c947577..cea46d221 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -18,8 +18,8 @@ describe("daemon protocol", () => { // lets a lease request choose it, taking it to 8, each the same way. ADR 0010 adds // `component.install` and its `component-progress` push, which a gateway relays to its // workers, taking it to 9. ADR 0014 gives every event envelope an `id`, taking it to 10. ADR 0009 §7 makes `atRamBudget` a - // required field of each platform's `status.get` capacity, taking it to 11, then ADR 0015 §3 made `modelClasses` a required field of each platform catalog, taking it to 12, then ADR 0015 §4 made `classDefaults` a required field of each platform catalog too, taking it to 13, then ADR 0015 §1 made a lease request's `model` optional beside a new `class`, taking it to 14. - expect(DAEMON_PROTOCOL_VERSION).toBe(14); + // required field of each platform's `status.get` capacity, taking it to 11, then ADR 0015 §3 made `modelClasses` a required field of each platform catalog, taking it to 12, then ADR 0015 §4 made `classDefaults` a required field of each platform catalog too, taking it to 13, then ADR 0015 §1 made a lease request's `model` optional beside a new `class`, taking it to 14, then ADR 0015 §2 let `osVersion` be a range, taking it to 15. + expect(DAEMON_PROTOCOL_VERSION).toBe(15); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index bfc04aafd..4486fd54e 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -2146,7 +2146,7 @@ describe("DaemonServer download policy", () => { const client = await createClient(harness.socketPath); await hello(client); // The fake names the requested version as the component: 65 characters, one past the bound. - const osVersion = "x".repeat(65); + const osVersion = "9".repeat(65); const grant = await client.request("lease.request", { allowDownload: true, diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index e52ba6c6f..4a17b7983 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -857,6 +857,48 @@ describe("GatewayDispatcher", () => { }, ); + it("answers a lease.request whose osVersion is a range BAD_REQUEST, as a gateway does not route OS ranges yet", async () => { + const { directory, dispatcher } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_1", client); + + await expect( + dispatcher.dispatch( + "lease.request", + { model: "iPhone 17", osVersion: ">=18", platform: "ios" }, + session({ role: "agent" }), + ), + ).rejects.toMatchObject({ + code: "BAD_REQUEST", + message: expect.stringContaining("does not route OS ranges yet"), + }); + expect(client.lastRequestLeaseInput).toBeUndefined(); + }); + + it("forwards a lease.request's exact osVersion to the worker unchanged", async () => { + const { directory, dispatcher, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_1", client); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { + capacity: statusFixture().capacity, + health: "running", + queueDepth: 0, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "on-request" }, + }); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17", noWait: true, osVersion: "26.0", platform: "ios" }, + session({ role: "agent" }), + ); + + expect(client.lastRequestLeaseInput).toMatchObject({ osVersion: "26.0" }); + }); + it("forwards a lease.request's image tag to the worker unchanged", async () => { const { directory, dispatcher, workers } = harness(); const client = new ScriptedWorkerClient(); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index b5e8de317..93fb4909f 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -41,6 +41,7 @@ import { type OperationName, type tokenRecordSchema, } from "../contract/index.js"; +import { parseOsConstraint } from "../contract/os-range.js"; import { DispatchError, runDispatch, @@ -437,6 +438,10 @@ export class GatewayDispatcher { if (input.model === undefined) { throw new DispatchError("BAD_REQUEST", "a gateway does not route class requests yet"); } + // The same stub for an OS range: matching one against workers is the next task. + if (input.osVersion !== undefined && isRange(input.osVersion)) { + throw new DispatchError("BAD_REQUEST", "a gateway does not route OS ranges yet"); + } const { model } = input; return this.options.coordinator.request( // Forwarded as it arrived (ADR 0007 §2): the gateway has no default mode of its own, and @@ -532,3 +537,9 @@ function unsupportedByDesign( throw new DispatchError("UNSUPPORTED_IN_GATEWAY_MODE", message, { operation }); }; } + +/** Whether an `osVersion` is a range rather than an exact version. */ +function isRange(osVersion: string): boolean { + const parsed = parseOsConstraint(osVersion); + return parsed.ok && parsed.constraint.kind === "range"; +} diff --git a/src/mcp/contracts.ts b/src/mcp/contracts.ts index aebe268e5..cc57d827f 100644 --- a/src/mcp/contracts.ts +++ b/src/mcp/contracts.ts @@ -33,7 +33,8 @@ import { * `imageTag` is inherited too, bounded by the contract. `model` and `class` are both optional and * refused together (ADR 0015 §1) by the contract's own refinement when the request reaches * `lease.request`, not here: a refined schema has no `.shape`, so the SDK would list the tool with - * no fields at all. + * no fields at all. A malformed `osVersion` is refused the same way, by the contract's own check + * when the request reaches `lease.request`: the MCP side adds no second check. */ export const leaseSimulatorInputSchema = leaseRequestFields.omit({ requesterId: true }); diff --git a/src/mcp/server.ts b/src/mcp/server.ts index cee7309eb..e15d044af 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -123,7 +123,7 @@ export function createMcpServer(session: McpSession): McpServer { { 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. 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.", + "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.", inputSchema: leaseSimulatorInputSchema, outputSchema: leaseSimulatorOutputSchema, },