diff --git a/AGENTS.md b/AGENTS.md index 4818ff4fb..38a39c433 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,13 +10,17 @@ changes in this repo: - [architecture.md](docs/agent-rules/architecture.md) — loosely coupled modules; platform-agnostic core; iOS and Android encapsulated in their own - driver modules; event bus for observers only. + driver modules; event bus for observers only; one place enforces a rule; + bounded cross-process waits; every exit leaves one named state. - [events.md](docs/agent-rules/events.md) — event naming (`subject.past-tense-fact`), post-commit emission, payload contracts, keeping EVENTS.md in sync. - [safety.md](docs/agent-rules/safety.md) — registry-only destruction, never touch leased devices, no implicit downloads, ownership proven not inferred, - root validation fails closed. + root validation fails closed, wire input is a claim not a fact. +- [testing.md](docs/agent-rules/testing.md) — a test's title is a claim its + body must prove; every test must be able to fail for the right reason; + untested code is code you can delete with a green suite. So are the accepted records in [docs/adr/](docs/adr/). An ADR marked _Accepted — not yet implemented_ means the documentation already describes the diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 248e76f4d..dcfb72fd9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -177,10 +177,10 @@ agent / console ──token auth──> │ HTTP frontend + unix socket `driver.passthrough` answer `UNSUPPORTED_IN_GATEWAY_MODE` permanently: they act on one machine's devices, and stay per-worker. The lease lifecycle (`lease.request`/`renew`/`release`/`cancel`/`release-all`) and `device.exec` - answer the same code until the fleet queue and routing land; reads — - `lease.list`, - `list.get`, `status.get`, `catalog.get`, `events.*` — already answer for the - whole fleet. + are forwarded through the fleet's own queue and routing policy (§10-§19, + `FleetLeaseCoordinator`) rather than answering `UNSUPPORTED_IN_GATEWAY_MODE`; + reads — `lease.list`, `list.get`, `status.get`, `catalog.get`, `events.*` — + answer for the whole fleet the same way. - **The one piece of persisted gateway state** is the drained set (`workers.json`, owner-only): drain is an operator's decision about a machine, not a fact the machine reports, so it must survive both the diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index f3c47dc4a..340f3fe82 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -24,6 +24,7 @@ a warning. Inspect the effective, merged configuration at any time with | `gateway.routing` | **Gateway side.** Which routing policy places a queued request on a worker. `warm-then-free` is the only policy in v1: warm hit first, then the most free running capacity for the platform. See [Routing](ARCHITECTURE.md#routing). | `warm-then-free` | | `gateway.disconnectedRetentionMs` | **Gateway side.** How long a disconnected worker is kept (greyed, never dispatched to) before the gateway forgets it. The clock is held while the gateway still knows of gateway-issued leases on that worker, and that hold ends when the last of those leases passes its deadline. | `24 hours` | | `gateway.execTimeoutMs` | **Gateway side.** How long the gateway waits on a proxied `device.exec` before giving up. A backstop for a worker that never answers at all — deliberately longer than the worker's own `exec.timeoutMs`, which is authoritative because that side owns the process and can kill it, so an ordinary timeout surfaces as the worker's `EXEC_TIMEOUT` rather than racing this one. See [ADR 0005](adr/0005-gateway-and-worker-modes.md) §19e. | `11 minutes` | +| `gateway.leaseRequestTimeoutMs` | **Gateway side.** How long the gateway waits on a forwarded `lease.request` before giving up on that worker for this request, answering `WORKER_UNREACHABLE`. Bounds the one uplink call that otherwise had no timeout of its own, so a wedged worker cannot park a request where neither a deadline nor `lease.cancel` could ever reach it again. Generous against a cold device provision-plus-boot; well below `gateway.execTimeoutMs`, since granting a lease should never take as long as a command run against the device afterward. | `5 minutes` | | `http.enabled` | Master switch for the network-facing HTTP API (see [HTTP-API.md](HTTP-API.md)). Off by default; the daemon binds nothing until this is `true`. A gateway is the fleet's contact point, so it must be `true` there — see [Modes](#modes-gateway-and-worker). | `false` | | `http.host` | Address the HTTP listener binds. `127.0.0.1` keeps it loopback-only; reaching it remotely is the operator's own tunnel (Tailscale, cloudflared, reverse proxy) — Simlock does no TLS termination in v1. | `127.0.0.1` | | `http.port` | Port the HTTP listener binds. Must be an integer `1`-`65535`. | `4700` | @@ -33,6 +34,7 @@ a warning. Inspect the effective, merged configuration at any time with | `gateway.label` | **Worker side.** Display name for this worker in the gateway's views. Need not be unique, and is never used to route. | unset (views show the worker's id) | | `gateway.disconnectedRetentionMs` | **Gateway side.** How long a disconnected worker's view is kept before the gateway forgets it. The clock only applies once every lease on that view has passed its deadline. | `24 hours` | | `gateway.execTimeoutMs` | **Gateway side.** Backstop on a proxied `device.exec`, deliberately longer than the worker's own `exec.timeoutMs`, which is the authoritative one. | `11 minutes` | +| `gateway.leaseRequestTimeoutMs` | **Gateway side.** Backstop on a forwarded `lease.request` -- expiry answers `WORKER_UNREACHABLE`, freeing the request for the queue's own deadline/cancel handling again. | `5 minutes` | | `diskPressure.freeBytesThreshold` | Free disk space below which Simlock treats the machine as under disk pressure. | `10 GiB` | | `eventBuffer.capacity` | Number of business events kept in the in-memory ring buffer (see `simlock events`). | `1000` | | `health.enabled` | Master switch for leased-device crash detection and recovery. | `true` | @@ -61,8 +63,9 @@ must be non-negative numbers (milliseconds and bytes, respectively). `http.enabled` is a boolean, `http.host` a string, and `http.port` an integer in `1`-`65535`. `mode` is `worker` or `gateway`; `gateway.url`, `gateway.token` and -`gateway.label` are strings, and `gateway.disconnectedRetentionMs` and -`gateway.execTimeoutMs` positive numbers. +`gateway.label` are strings, and `gateway.disconnectedRetentionMs`, +`gateway.execTimeoutMs`, and `gateway.leaseRequestTimeoutMs` positive +numbers. `ios.slim.enabled` is a boolean, `ios.slim.categories` an array of non-empty strings, and `ios.slim.bootTimeoutMs` a positive number. `mode` must be exactly `"worker"` or `"gateway"`. `gateway.url` must be an @@ -75,7 +78,8 @@ warned about and ignored like every other worker key — a gateway is not misconfigured by leftovers from the config it was flipped out of. `gateway.label` is a non-empty string, `gateway.routing` one of the registered routing policies, and `exec.timeoutMs`, `gateway.execTimeoutMs`, -and `gateway.disconnectedRetentionMs` positive numbers. +`gateway.leaseRequestTimeoutMs`, and `gateway.disconnectedRetentionMs` +positive numbers. **`mode: "gateway"` with `http.enabled: false` is rejected at load** (ADR 0005 §2), naming the key: a gateway is the fleet's contact point over HTTP, so one nothing can reach has no safe reading. @@ -180,7 +184,7 @@ does not apply to it. It reads: | Key group | Why | |---|---| | `mode` | to be a gateway at all | -| `gateway.routing`, `gateway.disconnectedRetentionMs`, `gateway.execTimeoutMs` | how to run the fleet | +| `gateway.routing`, `gateway.disconnectedRetentionMs`, `gateway.execTimeoutMs`, `gateway.leaseRequestTimeoutMs` | how to run the fleet | | `http.*` | it is the fleet's contact point | | `lease.*` | `defaultTtlMs`/`maxTtlMs` bound what its own clients may ask for, before a request is dispatched — see below | | `log.*`, `eventBuffer.*` | logging and the event ring buffer, as anywhere | diff --git a/docs/EVENTS.md b/docs/EVENTS.md index c2725e7a5..e32fa76a7 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -21,13 +21,22 @@ in short: `subject.past-tense-fact`, emitted post-commit, facts not commands. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `lease.requested` | request spec, requester, wait policy | a lease request is accepted by the daemon | LeaseAcquisitionCoordinator | implemented | -| `lease.queued` | request id, queue position | no capacity; request entered the wait queue | LeaseAcquisitionCoordinator | implemented | +| `lease.requested` | request spec, requester, wait policy | a lease request is accepted by the daemon | 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 | 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 spec, reason (timeout/no-wait/unresolvable-spec/already-leased/boot-timeout/killed/cancelled) | a request ended without a grant; `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 | implemented | +| `lease.rejected` | request spec, reason (timeout/no-wait/unresolvable-spec/already-leased/boot-timeout/killed/cancelled) | a request ended without a grant; `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 (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 +eventually granted — `lease.granted`/`renewed`/`released`/`expired` for a fleet +lease arrive already relayed from the owning worker (see "Fleet (gateway +mode)" below), so a gateway never emits those four itself. `already-leased` +on a gateway is the fleet-wide one-lease-per-requester check (§14, keyed on +`requesterId`), answered from the gateway's own lease index before any +worker is ever contacted. ## Device lifecycle @@ -95,29 +104,32 @@ progress gap this leaves. ## Fleet (gateway mode) -These are the facts a daemon running as a **gateway** emits about the workers +These are the facts a daemon running as a **gateway** emits about the fleet connected to it ([ADR 0005](adr/0005-gateway-and-worker-modes.md)). A worker -never emits them — it has no workers of its own — and a gateway emits none of -the device- or lease-lifecycle facts above on its own behalf, because it owns -no devices. All are **planned (ADR 0005)**. +never emits them — it has no workers or fleet queue of its own — and a +gateway emits none of the device-lifecycle facts above on its own behalf, +because it owns no devices. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `worker.connected` | worker id, label, daemon version, negotiated protocol range, platforms, capacity per platform, download policy | a worker's uplink completed its `hello` and the gateway committed the resulting worker view — including a reconnect, which is a new connection and so a new fact | WorkerRegistry | planned (ADR 0005) | -| `worker.rejected` | `{ reason, workerId?, label?, protocol? }` — reason is `unauthenticated` (the join token was missing or unrecognized, `401`) or `forbidden` (a valid token of the wrong role, `403`) | an uplink was refused at the door, before it could become a worker at all. Every field but `reason` is optional, because a dial that fails authentication proves no identity: there may be no worker id or label to report, and `protocol` is present only when the dial advertised a range before it was refused. Nothing enters the registry either way. A **version mismatch is not a rejection** — that uplink authenticated, so its worker enters the registry as `incompatible` (see the note under this table) | WorkerRegistry | planned (ADR 0005) | -| `worker.disconnected` | worker id, label, reason (closed/token-revoked), connected duration, leases still held on it | the uplink closed and the view was marked `disconnected`. The worker's leases are *not* ended by this: the gateway never guesses a lease is gone before the worker says so | WorkerRegistry | planned (ADR 0005) | -| `worker.removed` | worker id, label, initiator (operator/retention), time since disconnect | a disconnected worker's view was forgotten — by `worker.remove`, or because `gateway.disconnectedRetentionMs` elapsed. Never emitted for a connected worker (`WORKER_CONNECTED` refuses that), nor while gateway-issued leases on it are still known | WorkerRegistry | planned (ADR 0005) | -| `worker.drain-started` | worker id, label, leases held at that moment | `worker.drain` committed: the worker takes no new dispatches and keeps the leases it has | WorkerRegistry | planned (ADR 0005) | -| `worker.drain-ended` | worker id, label | `worker.undrain` committed and the worker became dispatchable again. Nothing else ends a drain: the flag lives in the gateway's persisted worker registry, so it survives both a worker reconnect and a gateway restart, and this fact only ever follows an explicit undrain | WorkerRegistry | planned (ADR 0005) | -| `request.dispatched` | request id, worker id, requester id, platform, model, selection reason (warm-hit/free-capacity), time spent queued | the gateway's dispatch sent a queued request to a worker and the worker took it (a grant, or device work already under way). A `NO_CAPACITY` refusal is a stale view, not a dispatch, and emits nothing — the request stays queued | FleetDispatcher | planned (ADR 0005) | +| `worker.connected` | worker id, label, worker's daemon version | a worker's uplink opened and its `hello` completed, so the gateway can drive it. A worker whose `hello` found no overlapping protocol range emits nothing: it is in the registry as `incompatible`, which is where an operator finds it | WorkerRegistry | implemented | +| `worker.rejected` | `{ reason, workerId?, label?, protocol? }` — reason is `unauthenticated` (the join token was missing or unrecognized, `401`) or `forbidden` (a valid token of the wrong role, `403`) | an uplink was turned away at the door, before any session existed. Every field but `reason` is optional, because a dial that fails authentication proves no identity. Version skew is deliberately not one of these: that uplink authenticated, so the worker enters the registry as `incompatible` and emits nothing (see the note below the table) | WorkerRegistry | implemented | +| `worker.disconnected` | worker id, label, lease count | a worker's uplink closed. `leaseCount` is what its view still shows it holding — how much is stranded, and why the view is kept rather than dropped, not ended: the gateway never guesses a lease is gone before the worker says so | WorkerRegistry | implemented | +| `worker.removed` | worker id, label, reason (operator/retention) | a disconnected worker's view was forgotten: by `simlock worker remove`, or because every gateway-issued lease on it had expired and `gateway.disconnectedRetentionMs` elapsed. Never emitted for a connected worker (`WORKER_CONNECTED` refuses that) | WorkerRegistry | implemented | +| `worker.drain-started` | worker id, label | `simlock worker drain` flagged a worker: it keeps its leases and receives no new dispatches | WorkerRegistry | implemented | +| `worker.drain-ended` | worker id, label | `simlock worker undrain` cleared that flag. Nothing else ends a drain: the flag lives in the gateway's persisted worker registry, so it survives both a worker reconnect and a gateway restart | WorkerRegistry | implemented | +| `request.dispatched` | `{ requestId, workerId, requesterId, platform, model, reason, queuedMs }` — `reason` is the routing policy's own `warm-hit`/`free-capacity` distinction (ADR 0005 §13), `queuedMs` how long the request sat queued before this dispatch | the gateway's fleet queue sent a queued request to a worker with `noWait: true`, and the worker took it — the grant itself, or its first `progress` push, whichever arrives first (ADR 0005 §11: device work having started means the request is that worker's now). An immediate `NO_CAPACITY` is a stale view, not a dispatch, and emits nothing — the request stays queued and is retried on the next pass | FleetLeaseCoordinator | implemented | + +Drain and undrain are idempotent, and an event is a fact about a *change*: +draining an already-drained worker succeeds and emits nothing. `worker.rejected` exists because the alternative is silence (ADR 0005 §22): a worker whose credential is refused produces no `worker.connected`, and without this fact an operator staring at `simlock worker list` sees a machine -that simply never appears, with nothing anywhere to say why. It is deliberately *not* a -`worker.disconnected` with another reason — nothing connected, so nothing -disconnected, and a fact whose subject never existed should not borrow the -vocabulary of one that did. +that simply never appears, with nothing anywhere to say why. It is +deliberately *not* a `worker.disconnected` with another reason — nothing +connected, so nothing disconnected, and a fact whose subject never existed +should not borrow the vocabulary of one that did. **A protocol mismatch is neither of those.** That uplink presented a valid join token and authenticated; what failed was `hello`'s range negotiation. So @@ -129,7 +141,7 @@ nothing usable connected. That is also why `incompatible` is not one of `worker.disconnected`'s reasons: an incompatible worker was never a connected worker to lose. -**`device.exec` emits no event, and that is deliberate.** It is the one new +**`device.exec` emits no event, and that is deliberate.** It is the one operation here with no fact of its own. Running a command against a device is not a state change simlock owns — the lease that authorizes it already emitted `lease.granted`, the device's own state is untouched, and a fleet @@ -139,14 +151,16 @@ agents ran on their devices is a different feature with different retention needs, not a line in this catalogue. **Every worker's own business events are republished on the gateway's bus** -with `workerId` added to their payload, and land in the gateway's ring -buffer, so `simlock events --follow` against a gateway shows the fleet -(`lease.granted`, `device.ready`, `cleanup.executed`, and the rest, each -naming the machine it happened on). That addition is additive per events rule -6, and it is the only change: payloads are otherwise relayed as the worker -emitted them, with the worker's own emitting module intact — the gateway -observed the fact, it did not commit it, so re-attributing it would be a -lie. +with `workerId` added to the payload, under their original names and with +their original emitting module — the fact happened in that worker's lease +engine or reaper, and rewriting either would make the audit trail lie about +where. That is what makes `simlock events` and `simlock events --follow` +against a gateway a fleet-wide view (`lease.granted`, `device.ready`, +`cleanup.executed`, and the rest, each naming the machine it happened on), +and it is the one place a payload documented above arrives with an extra +field: additive, and only ever on a gateway. The seven events in this +section's own table are the gateway's own, and carry no `workerId` beyond +the worker they are about. Two consequences of relaying rather than owning: the gateway's ring buffer only holds what arrived while its uplinks were up (a worker's events from @@ -181,6 +195,19 @@ fleet-wide view, and it is the one place a payload documented above arrives with an extra field: additive, and only ever on a gateway. The six events in this section are the gateway's own, and carry no `workerId` beyond the worker they are about. +A relayed `lease.expired`/`lease.released`/`device.crash-detected`/ +`device.recovered` names the *worker's own* lease id in its payload, not the +gateway's — `GatewayOwnerRoutedFacts` (the gateway's `OwnerRoutedFacts`) is +what resolves the gateway's own lease id, and the `ownerId` to route the +corresponding `lease-lost`/`device-unhealthy`/`device-recovered` push by, +from the fleet lease index rather than the relayed payload directly. The +payload's own `ownerId` is correct for a worker's own local lease (the +worker never had a reason to touch it), but for a gateway-issued one it is +whatever that worker echoed back of what the gateway forwarded when it +granted the lease (ADR §27a) — round-tripped through a machine this gateway +does not control, not a value it minted itself, so it is resolved from the +index (which recorded the real answer at grant time) rather than trusted +verbatim off the wire. ## Conventions recap diff --git a/docs/adr/0005-gateway-and-worker-modes.md b/docs/adr/0005-gateway-and-worker-modes.md index 5bd082aec..d6da05618 100644 --- a/docs/adr/0005-gateway-and-worker-modes.md +++ b/docs/adr/0005-gateway-and-worker-modes.md @@ -336,10 +336,20 @@ drive the device it leased. and the local passthrough does not: **a bare `adb shell` with no command is refused** ("needs a terminal"), because there is no pseudo-terminal to attach it to and accepting it would only stall until - the timeout. Output streams back as request-scoped pushes (`output`, - carrying `stream: "stdout" | "stderr"` and a chunk, keyed by the frame - id like `progress`); chunks are UTF-8 text, so a command whose output - is binary should write a file on the worker instead. The operation + the timeout. Two request-scoped pushes carry the command, both keyed by + the frame id like `progress`. **`started`** (payload: the frame id + alone) says the process now exists — sent once, after every failure + that can happen before one does (a refused verb, an unknown tool, an + unowned lease, a daemon still starting) and before any output. It is + the fact a transport chooses its response shape on, which is why it is + on the wire rather than inferred: a gateway proxying the command holds + no driver refusal list and cannot repeat the worker's ownership check, + so it relays this instead of guessing, and a pre-process refusal keeps + its own status code (§19a′'s `FORBIDDEN`, `PASSTHROUGH_REFUSED`) + instead of arriving inside an already-committed stream. **`output`** + carries `stream: "stdout" | "stderr"` and a chunk; chunks are UTF-8 + text, so a command whose output is binary should write a file on the + worker instead. The operation resolves with `{ exitCode }` — the tool's own, so a non-zero one is the command's answer and not an API failure. `stdin` is a **single string sent with the request** and written to the process, which is then @@ -606,7 +616,8 @@ drive the device it leased. - The contract gains: `mode` in `status.get`'s daemon block, `workerId` on devices and leases, `worker` on the lease object, `workers` on status, - `worker.*` operations, `device.exec` with its `output` push family, the + `worker.*` operations, `device.exec` with its `started`/`output` push + family, the `worker` token role, and five error codes. All additive. - **The five new error codes, with the columns the contract's table already has for every other code** (`kind`, `cliExitCode`, `httpStatus`): @@ -619,7 +630,8 @@ drive the device it leased. all: they reuse `PASSTHROUGH_REFUSED` and `UNKNOWN_PASSTHROUGH_TOOL` (requirement 19a), which already carry exit 2 and `422`. - **The socket wire moves to protocol 5 with no compatibility shim**, so - both sides advertise `{min: 5, max: 5}`: `device.exec` and its `output` + both sides advertise `{min: 5, max: 5}`: `device.exec` and its + `started`/`output` push family are new frames and no compatibility path is kept for them, and under ADR 0003 §6's honesty rule a range widens only where one is. This is the same wire ADR 0004 took to 4, so what ships carries both moves at diff --git a/docs/agent-rules/architecture.md b/docs/agent-rules/architecture.md index d762b3104..18a4baaec 100644 --- a/docs/agent-rules/architecture.md +++ b/docs/agent-rules/architecture.md @@ -43,3 +43,52 @@ grounds for rejecting a change even if it works. application code. Tests use the in-memory/fake implementations; if a new external dependency appears, define its port first. See "External APIs behind interfaces" in [../ARCHITECTURE.md](../ARCHITECTURE.md). +10. **A rule is enforced in exactly one place.** Never implement the same + decision twice — not in two modules, not on two code paths through one + module, not "once for the fast path and once for the general path". If + two call sites both have to answer the same question, one of them calls + the other or they both call a third; whichever shape you pick, deleting + the duplicate must be part of the change, not a follow-up. + + This is not a style preference. Duplicated enforcement does not stay + duplicated — it *diverges*, and it diverges silently, because each copy + keeps passing its own tests. The two copies then answer differently + depending on which path a caller happened to take, which reads to + everyone downstream as non-determinism rather than as a bug with an + address. + + Worked example, from this repo: the gateway's `noWait` rejection was + enforced both in `FleetLeaseCoordinator#admit`'s direct look and in + `#dispatch`'s ordered walk. Four consecutive review rounds each found a + real defect in that loop, and each fix to one path opened a gap in the + other — a request that answered `NO_CAPACITY` immediately or waited in + the queue depending on whether *unrelated* requests happened to be + queued at the time. No single patch closed it; the duplication was the + defect, and it was only fixed by making one path call the other. + + So when a review finding says "and the same check in the other path + needs updating too", treat that sentence as the finding. Fix the + duplication, not the symptom. +11. **Every wait that crosses a process boundary is bounded, and the budget + does not reset.** An RPC to a worker, a handshake, a subscription, a + forwarded command: each needs an explicit deadline, and a caller that + times out must leave the far side no worse off. A budget that restarts + on an internal state change (a waiter cycling `processing` -> `queued`, + a link reconnecting) is not a bound at all — the caller can wait forever + while every individual wait looks bounded. Say what the budget is + measured from, and make it monotonic from there. +12. **Every exit from a method leaves its subject in exactly one named + state.** A waiter, lease, timer, subscription or callback is, at every + return and every throw, either terminal or in a state something else is + driving — never both, never neither, and never live after the thing it + belongs to has settled. Two pieces of bookkeeping that must agree about + one subject will eventually disagree; keep the state in one place and + let the other read it. The tell is a resource that "usually" gets + cleaned up on the happy path: enumerate the exits instead, including + the ones that throw. +13. **A claim in a comment or doc is part of the change.** If your change + makes a nearby comment, doc paragraph or test name false, fix it or + delete it in the same commit — a stale claim is worse than no claim, + because it is trusted. Do not trust the comments you are reading either: + verify a strong claim about an invariant against the code before relying + on it, and treat one that is no longer true as a defect you found. diff --git a/docs/agent-rules/safety.md b/docs/agent-rules/safety.md index 3464a4d27..86db152db 100644 --- a/docs/agent-rules/safety.md +++ b/docs/agent-rules/safety.md @@ -71,3 +71,14 @@ never enforce them only inside an individual rule or driver. root Simlock did not create empty itself. The same applies to Simlock's adb server port: if it is occupied, the Android driver fails rather than attaching to whatever server is already listening there. +10. **Anything that arrives over the wire is a claim, not a fact.** A peer's + stated identity, an echoed owner, a lease id, a tool name, a command's + arguments: validate shape and bounds *before* authenticating on them, + and never store one unbounded or unsanitized. Match structured input by + structure — parse it, compare by position or field — never by substring + or prefix, which accepts everything the author forgot to think of. + Input that does not match something known is refused, not passed + through: unknown fails closed. This is rule 8 ("ownership is proven, + never inferred") applied to the network rather than to devices, and it + binds a gateway relaying a worker's answer exactly as much as it binds a + daemon reading a client's request. diff --git a/docs/agent-rules/testing.md b/docs/agent-rules/testing.md new file mode 100644 index 000000000..71085cfea --- /dev/null +++ b/docs/agent-rules/testing.md @@ -0,0 +1,43 @@ +# Agent rules: testing + +Rules for writing tests in this repo. A test is a claim about behaviour that +outlives the person who wrote it, so these are binding in the same way the +other files here are: a change whose tests violate them is rejected even +though the suite is green — being green is exactly the failure mode. + +1. **A test's title is a claim, and the body must prove that claim.** A title + that promises more than the body asserts is a defect, not a wording + problem: it tells every later reader the case is covered when it is not, + and that reader stops looking. If the body cannot prove the title, narrow + the title to what it does prove. The same goes for a comment above a test + explaining what it guards. + +2. **Every test must be able to fail, for the right reason.** Before you + trust a test, break the code it covers, run it, and watch it fail on a + *named assertion* — then restore the code. A test that still passes is not + a test; it is a green light wired to nothing. A test that fails only by + timing out pins the schedule rather than the behaviour, and will keep + passing when the behaviour is wrong but fast. This is the single most + repeated defect in this repo's review history: assertions that hold + equally against the correct and the broken implementation. + +3. **Production code that can be deleted with a green suite is untested.** + For a new code path, try deleting it and run the suite. If nothing goes + red, whatever you believed covered it stops short of the part that + matters — usually because the test exercises an internal callback rather + than the observable output the path exists to produce. Write the test that + goes red, then restore the code. + +4. **A test that enforces a rule must see everything the rule covers.** A + boundary or invariant test enforces its rule only where it happens to + look. One that scans a single directory, follows only static imports, or + checks only the first element of a collection leaves the rest + unguarded — and reads, to everyone after you, as though the whole rule + were covered. + +5. **A flake is not diagnosed until it reproduces on a commit that predates + the change.** "Probably unrelated" and "it passed when I re-ran it" are + guesses. Check out the base commit, run the same test, and let the result + decide; a failure that reproduces there is not yours to fix in this + change, and one that does not reproduce is yours. Never skip, disable, or + quarantine a test to get to green. diff --git a/docs/known-pitfalls.md b/docs/known-pitfalls.md index 919cf5985..c38717e75 100644 --- a/docs/known-pitfalls.md +++ b/docs/known-pitfalls.md @@ -890,3 +890,39 @@ in the job that does not mean to pipe anything (`simlock adb shell getprop void`, not +`=> void | Promise` — so even though the *worker's* own process runner +still awaits its local write exactly as it does today, nothing on the +gateway's side of the uplink ever waits for the far end (the actual fleet +client behind the gateway) to keep up before telling the worker's driver +"go ahead, write the next chunk." A slow fleet client behind a gateway gets +its data queued in the gateway's own process instead of the backpressure +§19e promises — the worker's device keeps writing at full speed regardless. + +**Why it is not fixed here:** it predates the round 3 hardening batch this +file's other new entries describe, and closing it means widening a wire +contract (`simlock-client`'s `onOutput` return type, and the uplink's own +`output` push acknowledgement) that reaches every uplink implementation, not +a self-contained fix inside one class the way the round's other findings +were. It is `#119`-or-later-shaped work (ADR §28/§29's own uplink-recovery +scope), not something to bolt onto this round in passing. + +**Status:** accepted for now, and worth closing before a fleet's own worked +examples lean on `device.exec` for anything genuinely large or slow to +consume. Docs and code comments should describe §19e's backpressure +guarantee as holding for a worker reached directly, not (yet) end to end +through a gateway — this entry is that correction; nothing in +`src/gateway/` should claim otherwise. diff --git a/docs/loop.md b/docs/loop.md index 682646094..569fef0fb 100644 --- a/docs/loop.md +++ b/docs/loop.md @@ -44,8 +44,9 @@ specifications have been removed from `docs/stages/`. - every rule in `docs/agent-rules/architecture.md`, `events.md`, `safety.md` against the new code; - the stage's "Watch out" list; - - test quality: would each test fail if the behavior regressed? Delete - tests that can't fail. + - test quality, against `docs/agent-rules/testing.md` — which is the + binding statement of it; this file is historical and does not restate + it. 11. Fix every issue found, then re-run `pnpm check`. Repeat until a review pass finds nothing. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 56101d99e..5288aea7b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,3 +1,202 @@ +--- +lockfileVersion: '9.0' + +importers: + + .: + configDependencies: {} + packageManagerDependencies: + '@pnpm/exe': + specifier: 11.22.0 + version: 11.22.0 + pnpm: + specifier: 11.22.0 + version: 11.22.0 + +packages: + + '@pnpm/exe@11.22.0': + resolution: {integrity: sha512-B1SGeKm+v9pX9YkzMmrnO2FbgBd8TDwzZ3jSj6J6ThxdyGvI4TsOfMeHARW4Wb25visPpmMDfIXrU76EZdJM4g==} + hasBin: true + + '@pnpm/linux-arm64@11.22.0': + resolution: {integrity: sha512-xzzn3jYG9QaiFZPaHcWM3yX4Fm9UGz5E42mzpbvUEvXYf5O9fwNolenOhGLpRl2qS5u35fjZSvDZbWlOwHMcug==} + cpu: [arm64] + os: [linux] + + '@pnpm/linux-x64@11.22.0': + resolution: {integrity: sha512-isvaPctGinbsM2hsTtRsMarN8Sr5QhXDTNmn8Xv9Lp1PjincCvH2RBbhpo+xYIOxzgls1dtQSdgoORUbfRVALQ==} + cpu: [x64] + os: [linux] + + '@pnpm/linuxstatic-arm64@11.22.0': + resolution: {integrity: sha512-i4J+AQWW0T3JBdXaLsvxu8ZmMG1HLS6JZQESdOR9uBv8Zumb4yg8GYT83eWRLacr6ngVdhEBiC3W4eOG64MFbA==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@pnpm/linuxstatic-x64@11.22.0': + resolution: {integrity: sha512-QYzk8jhSuSbVthW/OxEOhU3f3zhjpw4HqgedrlwbVNb7btCWn5del2Hb5PsYYka2PbmKq5EtF5IzYN8Yp1CfxQ==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@pnpm/macos-arm64@11.22.0': + resolution: {integrity: sha512-Io8Axk5kutPgMuAfOg1QGj3J0/KpLvH5iiPcmp7up8D4q7BNWT02ndQo3RyGWqrlkf5nwspM41GFpWTShrZ4Aw==} + cpu: [arm64] + os: [darwin] + + '@pnpm/win-arm64@11.22.0': + resolution: {integrity: sha512-QgaRuKGQKov7xW2utPCgDT83fn/PU5cD6HFgib48oTslz7wv26E89d4jMCxL4GRmEL2YCfkYuj5ITj1oVWg5WQ==} + cpu: [arm64] + os: [win32] + + '@pnpm/win-x64@11.22.0': + resolution: {integrity: sha512-iWYsiSwpgxqur+TwsnSoPdOQaEfd4ygB84mb5tJUOgim6PHr1xhKJBndaQzH+At/WkLxLdYN+K8dYc4M7naezg==} + cpu: [x64] + os: [win32] + + '@reflink/reflink-darwin-arm64@0.1.19': + resolution: {integrity: sha512-ruy44Lpepdk1FqDz38vExBY/PVUsjxZA+chd9wozjUH9JjuDT/HEaQYA6wYN9mf041l0yLVar6BCZuWABJvHSA==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [darwin] + + '@reflink/reflink-darwin-x64@0.1.19': + resolution: {integrity: sha512-By85MSWrMZa+c26TcnAy8SDk0sTUkYlNnwknSchkhHpGXOtjNDUOxJE9oByBnGbeuIE1PiQsxDG3Ud+IVV9yuA==} + engines: {node: '>= 10'} + cpu: [x64] + os: [darwin] + + '@reflink/reflink-linux-arm64-gnu@0.1.19': + resolution: {integrity: sha512-7P+er8+rP9iNeN+bfmccM4hTAaLP6PQJPKWSA4iSk2bNvo6KU6RyPgYeHxXmzNKzPVRcypZQTpFgstHam6maVg==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@reflink/reflink-linux-arm64-musl@0.1.19': + resolution: {integrity: sha512-37iO/Dp6m5DDaC2sf3zPtx/hl9FV3Xze4xoYidrxxS9bgP3S8ALroxRK6xBG/1TtfXKTvolvp+IjrUU6ujIGmA==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@reflink/reflink-linux-x64-gnu@0.1.19': + resolution: {integrity: sha512-jbI8jvuYCaA3MVUdu8vLoLAFqC+iNMpiSuLbxlAgg7x3K5bsS8nOpTRnkLF7vISJ+rVR8W+7ThXlXlUQ93ulkw==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@reflink/reflink-linux-x64-musl@0.1.19': + resolution: {integrity: sha512-e9FBWDe+lv7QKAwtKOt6A2W/fyy/aEEfr0g6j/hWzvQcrzHCsz07BNQYlNOjTfeytrtLU7k449H1PI95jA4OjQ==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@reflink/reflink-win32-arm64-msvc@0.1.19': + resolution: {integrity: sha512-09PxnVIQcd+UOn4WAW73WU6PXL7DwGS6wPlkMhMg2zlHHG65F3vHepOw06HFCq+N42qkaNAc8AKIabWvtk6cIQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [win32] + + '@reflink/reflink-win32-x64-msvc@0.1.19': + resolution: {integrity: sha512-E//yT4ni2SyhwP8JRjVGWr3cbnhWDiPLgnQ66qqaanjjnMiu3O/2tjCPQXlcGc/DEYofpDc9fvhv6tALQsMV9w==} + engines: {node: '>= 10'} + cpu: [x64] + os: [win32] + + '@reflink/reflink@0.1.19': + resolution: {integrity: sha512-DmCG8GzysnCZ15bres3N5AHCmwBwYgp0As6xjhQ47rAUTUXxJiK+lLUxaGsX3hd/30qUpVElh05PbGuxRPgJwA==} + engines: {node: '>= 10'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + pnpm@11.22.0: + resolution: {integrity: sha512-H/hwxMYTPf2I+yr8Rt0T1H8JyXlLQ4xv20fKmMrzvBY4HuC+k6CRuOOCTPAfiJ9G19niCRD7C+GrD7W6qA3WIQ==} + engines: {node: '>=22.13'} + hasBin: true + +snapshots: + + '@pnpm/exe@11.22.0': + dependencies: + '@reflink/reflink': 0.1.19 + detect-libc: 2.1.2 + optionalDependencies: + '@pnpm/linux-arm64': 11.22.0 + '@pnpm/linux-x64': 11.22.0 + '@pnpm/linuxstatic-arm64': 11.22.0 + '@pnpm/linuxstatic-x64': 11.22.0 + '@pnpm/macos-arm64': 11.22.0 + '@pnpm/win-arm64': 11.22.0 + '@pnpm/win-x64': 11.22.0 + + '@pnpm/linux-arm64@11.22.0': + optional: true + + '@pnpm/linux-x64@11.22.0': + optional: true + + '@pnpm/linuxstatic-arm64@11.22.0': + optional: true + + '@pnpm/linuxstatic-x64@11.22.0': + optional: true + + '@pnpm/macos-arm64@11.22.0': + optional: true + + '@pnpm/win-arm64@11.22.0': + optional: true + + '@pnpm/win-x64@11.22.0': + optional: true + + '@reflink/reflink-darwin-arm64@0.1.19': + optional: true + + '@reflink/reflink-darwin-x64@0.1.19': + optional: true + + '@reflink/reflink-linux-arm64-gnu@0.1.19': + optional: true + + '@reflink/reflink-linux-arm64-musl@0.1.19': + optional: true + + '@reflink/reflink-linux-x64-gnu@0.1.19': + optional: true + + '@reflink/reflink-linux-x64-musl@0.1.19': + optional: true + + '@reflink/reflink-win32-arm64-msvc@0.1.19': + optional: true + + '@reflink/reflink-win32-x64-msvc@0.1.19': + optional: true + + '@reflink/reflink@0.1.19': + optionalDependencies: + '@reflink/reflink-darwin-arm64': 0.1.19 + '@reflink/reflink-darwin-x64': 0.1.19 + '@reflink/reflink-linux-arm64-gnu': 0.1.19 + '@reflink/reflink-linux-arm64-musl': 0.1.19 + '@reflink/reflink-linux-x64-gnu': 0.1.19 + '@reflink/reflink-linux-x64-musl': 0.1.19 + '@reflink/reflink-win32-arm64-msvc': 0.1.19 + '@reflink/reflink-win32-x64-msvc': 0.1.19 + + detect-libc@2.1.2: {} + + pnpm@11.22.0: {} + +--- lockfileVersion: '9.0' settings: diff --git a/src/bus/index.test.ts b/src/bus/index.test.ts index e23adf5e1..59924d889 100644 --- a/src/bus/index.test.ts +++ b/src/bus/index.test.ts @@ -158,6 +158,7 @@ describe("EventBus", () => { | "worker.removed" | "worker.drain-started" | "worker.drain-ended" + | "request.dispatched" >(); expectTypeOf().toMatchTypeOf>(); }); diff --git a/src/bus/index.ts b/src/bus/index.ts index 4211f146c..d44d58284 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -232,6 +232,31 @@ export interface EventMap { /** ADR 0005 §9: the worker keeps its leases and receives no new dispatches from here on. */ "worker.drain-started": { readonly workerId: string; readonly label?: string }; "worker.drain-ended": { readonly workerId: string; readonly label?: string }; + /** + * ADR 0005 §11/§22 (#118): the gateway's own dispatch sent a queued request to a worker and + * the worker took it (a grant, or the first `progress` push, whichever came first -- device + * work having started means the request is that worker's now). A `NO_CAPACITY` refusal is a + * stale view, not a dispatch, and emits nothing -- the request stays queued. + * + * C2 (round 2 review): widened back to what `docs/EVENTS.md` always specified for this row -- + * `requesterId`/`platform`/`model` so the fact is self-contained (events rule 6) rather than + * naming only the gateway-internal `requestId`, `reason` (the routing policy's own warm-hit / + * free-capacity distinction, already computed by `RoutingPolicy#select` and previously + * discarded rather than plumbed through), and `queuedMs` (time spent queued before this + * dispatch). `reason` is spelled out as a literal union here rather than importing + * `RoutingReason` from `src/gateway/routing.ts`: this module stays platform- and + * gateway-agnostic (`architecture.md`), so a payload shape is duplicated rather than an import + * reaching up into a module layered above it. + */ + "request.dispatched": { + readonly requestId: string; + readonly workerId: string; + readonly requesterId: string; + readonly platform: string; + readonly model: string; + readonly reason: "warm-hit" | "free-capacity"; + readonly queuedMs: number; + }; /** Payloads owned by the driver module that refused the root; see `DriverRejection`. */ "driver.root-rejected": { readonly platform: string; diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index dd963042b..63ae0557c 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -3306,7 +3306,12 @@ function testConfig(): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, eventBuffer: { capacity: 100 }, health: { diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 314ba02da..9b6f78a4c 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -377,7 +377,12 @@ describe("operation input/output round trips", () => { it("config.get: round-trips a representative config", () => { const config = { mode: "worker", - gateway: { disconnectedRetentionMs: 86_400_000, execTimeoutMs: 660_000 }, + gateway: { + disconnectedRetentionMs: 86_400_000, + execTimeoutMs: 660_000, + leaseRequestTimeoutMs: 300_000, + routing: "warm-then-free", + }, capacity: { strategy: "fixed", config: { maxRunning: 4 } }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_000 }, idle: { shutdownAfterMs: 1, deleteAfterMs: 2 }, diff --git a/src/contract/operations.ts b/src/contract/operations.ts index bc2ade499..28109e0f9 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -130,6 +130,18 @@ const leaseRequestInputSchema = z * through to `LeaseRequestOptions.ttlMs` (src/core/wait-queue.ts) by that same handler. */ ttlMs: z.number().finite().positive().optional(), + /** + * ADR 0005 §27a: the gateway's own forward of the lease's *owner* -- the principal it + * authorized the request against on its own side -- so the worker stores that verbatim as + * `ownerId` instead of deriving one from the connection that reached it (which, over the + * uplink, is always the gateway's own admin session, never the fleet client). Read **only + * on an admin session**; the dispatcher's `#leaseRequest` rejects the request outright if + * any other role's session sends it (see that handler's own comment) rather than silently + * ignoring it, because silently ignoring it is exactly the "guess or fail open" the ADR + * calls out as the alternative to rejecting. Omitting it keeps today's behaviour -- the + * owner is the calling connection -- so this is additive and no existing caller changes. + */ + owner: z.string().optional(), }) .strict(); @@ -143,10 +155,14 @@ export const leaseRequest = defineOperation({ * §4 is explicit that any agent session may request a lease under an arbitrary * `requesterId` -- that is the whole mechanism behind "one connection (the host, acting as * a proxy for many agents) holds many leases by passing one requester id per session". The - * lease's actual `ownerId` is never client-supplied (always `session.principal`, see the - * dispatcher's `#leaseRequest`), so this does not let one session take over another's - * lease -- only choose the attribution label on a lease it will itself own. `lease.cancel` - * used to look inconsistent next to this (forbidding a `requesterId` that did not equal the + * lease's actual `ownerId` is never client-supplied by an ordinary agent session (always + * `session.principal`, see the dispatcher's `#leaseRequest`) -- only an admin session's + * explicit `owner` above overrides that, and that gate is a role check on one field, not an + * ownership question about an existing resource, so it lives in the handler rather than as an + * `authorize` hook here (which runs against a resource this request has not created yet). + * Neither lets one session take over another's lease -- only choose the attribution label, or + * (admin only) the owner, on a lease it will itself cause to be granted. `lease.cancel` used + * to look inconsistent next to this (forbidding a `requesterId` that did not equal the * principal, on an operation that has none of `lease.request`'s ownership protection to * begin with) -- fixed by gating `lease.cancel` on the pending request's recorded owner * (`pendingRequestOwner`, see its own `authorize` hook below) instead, which is consistent diff --git a/src/contract/pushes.ts b/src/contract/pushes.ts index b80648273..7c904c92d 100644 --- a/src/contract/pushes.ts +++ b/src/contract/pushes.ts @@ -2,7 +2,8 @@ * Server pushes (ADR 0003 §8). Three families, each with its correlation key required by * schema: * - * - Request-scoped (`progress`, `output`): carries the originating request's frame id. + * - Request-scoped (`progress`, `started`, `output`): carries the originating request's + * frame id. * - Lease-scoped (`lease-lost`, `device-unhealthy`, `device-recovered`): carries the lease id, * and goes to every live connection whose principal owns that lease (ADR 0004 §5 keeps * these; they are facts about the device, not a liveness channel). @@ -48,6 +49,28 @@ const outputPushSchema = z.object({ chunk: z.string(), }); +/** + * ADR 0005 §19a: a forwarded `device.exec`'s process now exists on the worker, keyed by the + * originating request's frame id exactly as `output` is. + * + * This is the fact a transport needs to choose its response shape on, and it is the one fact a + * gateway cannot infer. The worker already knows the moment -- its dispatcher spawns the child + * and then calls `DispatchSession.onStarted`, after every failure that can happen before a + * process exists (a refused verb, an unknown tool, an unowned lease, a daemon still starting) + * and before any output. Directly against a worker that signal reaches the transport; across an + * uplink it used to stop at the worker's edge, so the gateway guessed with a timer -- and a + * refusal that arrived after the timer got a `200` with the error buried in the stream, where + * §19a requires a `422`. Sending the fact removes the guess. + * + * Part of protocol 5, not an addition on top of it: 5 has never shipped, so nothing will ever + * advertise 5 without this frame, and a peer older than 5 is `incompatible` by range (ADR 0005 + * §31) rather than a peer that merely stays quiet. There is no "never sends it" case to keep a + * fallback for, which is why the gateway has exactly one path to this signal. + */ +const startedPushSchema = z.object({ + requestId: requestIdSchema, +}); + const leaseLostPushSchema = z.object({ leaseId: z.string(), deviceId: z.string(), @@ -74,6 +97,7 @@ const eventPushSchema = z.object({ export const PUSH_SCHEMAS = { progress: progressPushSchema, output: outputPushSchema, + started: startedPushSchema, "lease-lost": leaseLostPushSchema, "device-unhealthy": deviceUnhealthyPushSchema, "device-recovered": deviceRecoveredPushSchema, diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 27249dbad..bf2296376 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -178,6 +178,16 @@ export const leaseRecordSchema = z.object({ ttlMs: z.number(), ttlDeadline: z.number(), lastRenewedAt: z.number(), + /** + * ADR 0005 §18: "the lease object gains `worker: { id, label }` (additive) so a client and + * the console can tell where the device lives. A worker's network address is never exposed." + * Additive and gateway-only -- a worker granting its own local lease has no second machine to + * name and never sets this; a gateway stamps it on every lease it forwards a grant/renew for, + * using the same worker id `id` already encodes (§16: a gateway lease id is + * `.`) plus the worker's display `label`, when it has one, for a + * console to render without a second lookup. + */ + worker: z.object({ id: z.string(), label: z.string().optional() }).optional(), }); const leaseTimingSchema = z.object({ @@ -460,6 +470,21 @@ export const configSchema = z.object({ label: z.string().optional(), disconnectedRetentionMs: z.number(), execTimeoutMs: z.number(), + /** ADR 0005 §29/P2: the forwarded `lease.request`'s own bound. Round 6 review: this was + * declared on `Config`, validated by `loadConfig`, and documented in CONFIGURATION.md, but + * missing here -- and since this schema is `config.get`'s declared output, zod stripped it, + * so an operator inspecting the effective config saw every other gateway key and concluded + * this one did not exist. `config.test.ts` now parses a loaded config through this schema + * and compares key sets, so the next such omission fails rather than disappears. */ + leaseRequestTimeoutMs: z.number(), + /** ADR 0005 §13/Decision 7: which routing policy dispatch uses. Gateway-side, read once at + * construction like `capacity.strategy` -- never a per-request choice. The set of names is + * re-declared here rather than imported from `src/gateway/routing.ts`'s own registry, the + * same way `capacityConfigSchema` above re-declares "fixed"/"resource" instead of importing + * `src/core/capacity`'s: this module describes wire shapes and imports no engine (its own + * header comment), gateway or worker alike. `"warm-then-free"` is the only policy in v1; + * adding a second means adding it to both registries, exactly as a capacity strategy does. */ + routing: z.enum(["warm-then-free"]), }), stalledTransition: z.object({ thresholdMultiplier: z.number(), diff --git a/src/core/acquisition-planner.test.ts b/src/core/acquisition-planner.test.ts index 72e4e7d35..83b0868c3 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -13,7 +13,12 @@ const config: Config = { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, eventBuffer: { capacity: 100 }, health: { diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index ca6b97b06..c77423574 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -9,7 +9,12 @@ const config: Config = { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 0 }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, eventBuffer: { capacity: 1 }, health: { diff --git a/src/core/cleanup/idle-shutdown.test.ts b/src/core/cleanup/idle-shutdown.test.ts index ed332ab1c..d7832b13e 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -7,7 +7,12 @@ const config: Config = { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 0 }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, eventBuffer: { capacity: 1 }, health: { diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 215e5cfc6..a049dc4c8 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import { MemoryFilesystem, FakeSystemStats } from "../ports/index.js"; import type { ResourceStrategyOptions } from "./capacity/index.js"; +import { configSchema } from "../contract/schemas.js"; import { type Config, effectiveAllowDownload, loadConfig } from "./index.js"; /** Narrows the capacity block for assertions on resource-strategy configs. */ @@ -23,6 +24,20 @@ function dottedValue(config: Config, key: string): unknown { return current; } +/** + * Every leaf of a config object as a dotted key. Recursive on purpose: a first version of this + * walked only one level and so would have missed a key dropped from a *nested* block such as + * `capacity.config` or `warmPool.quarantine`. + */ +function dottedLeafKeys(value: unknown, prefix = ""): string[] { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return prefix === "" ? [] : [prefix]; + } + return Object.entries(value as Record).flatMap(([key, child]) => + dottedLeafKeys(child, prefix === "" ? key : `${prefix}.${key}`), + ); +} + const configPath = "/home/agent/.simlock/config.json"; const gibibyte = 1024 ** 3; @@ -1011,6 +1026,8 @@ describe("loadConfig modes (ADR 0005)", () => { expect(config.gateway).toEqual({ disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free", }); }); @@ -1137,6 +1154,20 @@ describe("loadConfig modes (ADR 0005)", () => { expect(config.gateway.execTimeoutMs).toBe(11 * 60_000); }); + it("rejects a non-positive lease-request timeout", async () => { + // P2 (round 2 review): bounds the one forwarded uplink call that used to have none of its + // own -- see FleetLeaseCoordinator#withLeaseRequestTimeout. + await expect(load({ gateway: { leaseRequestTimeoutMs: 0 } })).rejects.toThrow( + "gateway.leaseRequestTimeoutMs", + ); + }); + + it("defaults the gateway lease-request timeout to five minutes, well under the exec backstop", async () => { + const config = await load({ mode: "gateway" }); + expect(config.gateway.leaseRequestTimeoutMs).toBe(5 * 60_000); + expect(config.gateway.leaseRequestTimeoutMs).toBeLessThan(config.gateway.execTimeoutMs); + }); + it("lets an override name the mode, like every other key", async () => { const config = await load({}, { overrides: { mode: "gateway" } }); @@ -1161,3 +1192,55 @@ describe("effectiveAllowDownload", () => { expect(effectiveAllowDownload("on-request", true)).toBe(true); }); }); + +describe("configSchema agrees with the config the daemon actually loads", () => { + /** + * `config.get` declares `configSchema` as its output (`contract/operations.ts`), and zod's + * object mode strips unknown keys -- so a key this schema does not list is not a type error + * anywhere, it simply vanishes on the way to the caller. + * + * Round 6 review found `gateway.leaseRequestTimeoutMs` doing exactly that: declared on + * `Config`, validated by `loadConfig`, documented in CONFIGURATION.md as inspectable via + * `simlock config get`, and silently dropped. Nothing referenced `configSchema` from any test, + * so the drift was invisible in both directions. + * + * This compares key sets per block rather than asserting one key, so the next block that gains + * a field fails here instead of shipping a `config get` that quietly omits it (testing rule 4: + * a test that enforces a rule has to see everything the rule covers). + */ + it("strips no key from any block of a freshly loaded config", async () => { + const config = await loadConfig({ + configPath, + filesystem: new MemoryFilesystem(), + systemStats: createStats(), + }); + + const parsed = configSchema.parse(config); + // `drivers` is deliberately off the wire: an open-ended + // `Record>` whose contents are each driver's own business + // (architecture rule 2), so the contract cannot declare its shape. Excluded by name and + // asserted separately below rather than skipped silently -- it defaults to `{}`, so a + // key-walk would otherwise "cover" it by finding nothing to lose and keep passing if it + // ever gained something. + const declared = dottedLeafKeys(config).filter((key) => !key.startsWith("drivers")); + const onTheWire = new Set(dottedLeafKeys(parsed)); + + expect(declared.filter((key) => !onTheWire.has(key))).toEqual([]); + // The one intentional omission, stated as an assertion so it is a decision and not an + // accident: if `drivers` is ever added to the wire, this fails and the filter is revisited. + expect(Object.keys(parsed)).not.toContain("drivers"); + }); + + it("carries gateway.leaseRequestTimeoutMs through to what config get answers", async () => { + const config = await loadConfig({ + configPath, + filesystem: new MemoryFilesystem(), + systemStats: createStats(), + }); + + const parsed = configSchema.parse(config) as unknown as Config; + expect(dottedValue(parsed, "gateway.leaseRequestTimeoutMs")).toBe( + config.gateway.leaseRequestTimeoutMs, + ); + }); +}); diff --git a/src/core/config.ts b/src/core/config.ts index 834588f78..125766d25 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -49,6 +49,30 @@ const DEFAULT_DISCONNECTED_RETENTION_MS = 24 * 60 * 60_000; * worker's authoritative ten, so the worker's timeout is the one that fires. */ const DEFAULT_GATEWAY_EXEC_TIMEOUT_MS = 11 * 60_000; +/** `gateway.leaseRequestTimeoutMs`'s default (P2, round 2 review): five minutes -- generous + * against a cold device provision-plus-boot, and well short of `execTimeoutMs`, since granting a + * lease should never take as long as a command a caller runs against the device afterward. */ +const DEFAULT_LEASE_REQUEST_TIMEOUT_MS = 5 * 60_000; + +/** + * `gateway.routing`'s valid names (ADR 0005 §13/Decision 7) and its default. Declared here + * rather than imported from `src/gateway/routing.ts`'s own registry: `core` stays + * platform-agnostic and gateway-unaware (`AGENTS.md`/`architecture.md`), so this list is + * re-declared the same way `src/contract/schemas.ts` re-declares it independently rather than + * importing across its own boundary -- three places name `"warm-then-free"`, the same + * redundancy `capacity.strategy`'s "fixed"/"resource" already carries between `core` and the + * contract. Adding a second policy means adding it here, in the gateway's own registry, and in + * the contract schema -- one line each, never a shared import. + */ +const ROUTING_POLICIES = ["warm-then-free"] as const; +const DEFAULT_ROUTING_POLICY = "warm-then-free"; + +/** The literal union `ROUTING_POLICIES` names -- `Config["gateway"]["routing"]`'s type, so it + * agrees with the contract's own `z.enum(["warm-then-free"])` (also re-declared, never + * imported) instead of widening to a bare `string` the boundary between the two would otherwise + * force. */ +type RoutingPolicyName = (typeof ROUTING_POLICIES)[number]; + /** * `exec.timeoutMs`'s default (ADR 0005 §19e): how long a single `device.exec` command may run * on this worker before it is killed and the operation fails with `EXEC_TIMEOUT`. Ten minutes, @@ -192,6 +216,25 @@ export interface Config { * which is what proxies `device.exec`; declared now so the key does not appear mid-series. */ readonly execTimeoutMs: number; + /** + * P2 (round 2 review): bounds a forwarded `lease.request` -- the one uplink call that used + * to have no timeout of its own, parking a waiter `processing` where neither `timeoutMs`'s + * deadline check nor `lease.cancel` could reach it (`WaitQueue#armTimeout` declines to + * reject a `processing` waiter, and `cancelPending` answers `not-cancellable`) if the + * worker's own `lease.request` handler ever wedged. Generous relative to how long granting a + * lease can plausibly take -- provisioning plus a cold device boot -- and bounded well below + * `execTimeoutMs`, since granting a lease should never take as long as an arbitrary command + * a caller runs afterward might. Expiry maps to `WORKER_UNREACHABLE`, returning the waiter + * to a state `enqueue`'s deadline check and `cancelPending` can both act on again. + */ + readonly leaseRequestTimeoutMs: number; + /** + * ADR 0005 §13/Decision 7: which routing policy dispatch uses. Gateway-side, read once at + * daemon start -- routing is "a pure function over worker views, a module with one entry + * point selected by `gateway.routing`, the same shape as `CapacityStrategy`", never a + * per-request choice. `"warm-then-free"` is the only value in v1 (`ROUTING_POLICIES` above). + */ + readonly routing: RoutingPolicyName; }; readonly stalledTransition: { /** @@ -319,7 +362,8 @@ const GATEWAY_CONFIG_KEYS: readonly string[] = [ ]; /** The `gateway.*` sub-keys a *worker* reads. A gateway ignores these three (it dials nobody); - * `disconnectedRetentionMs` and `execTimeoutMs` are the ones the gateway itself reads. */ + * `disconnectedRetentionMs`, `execTimeoutMs`, and `leaseRequestTimeoutMs` are the ones the + * gateway itself reads. */ const WORKER_ONLY_GATEWAY_KEYS: readonly string[] = ["url", "token", "label"]; /** @@ -549,6 +593,8 @@ function defaultConfig( gateway: { disconnectedRetentionMs: DEFAULT_DISCONNECTED_RETENTION_MS, execTimeoutMs: DEFAULT_GATEWAY_EXEC_TIMEOUT_MS, + leaseRequestTimeoutMs: DEFAULT_LEASE_REQUEST_TIMEOUT_MS, + routing: DEFAULT_ROUTING_POLICY, }, stalledTransition: { thresholdMultiplier: 3, @@ -614,6 +660,8 @@ function configValidators(strategy: CapacityStrategyName): Record mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 1 }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, eventBuffer: { capacity: 10 }, health: { diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index b681a4fd4..6ba021134 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -28,7 +28,12 @@ function config(maxDevices = 1): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, eventBuffer: { capacity: 100 }, diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 0b4297090..b4c527c5f 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -25,7 +25,12 @@ function config(overrides: Partial = {}): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, eventBuffer: { capacity: 100 }, diff --git a/src/core/lease-health-monitor.test.ts b/src/core/lease-health-monitor.test.ts index be19002c0..f42194844 100644 --- a/src/core/lease-health-monitor.test.ts +++ b/src/core/lease-health-monitor.test.ts @@ -20,7 +20,12 @@ function config(overrides: Partial = {}): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, eventBuffer: { capacity: 100 }, warmPool: { diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index 703abfcc5..e326ce19a 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -148,7 +148,12 @@ function config(): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 1 }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, eventBuffer: { capacity: 10 }, health: { diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index a8df99721..77f306c9a 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -47,7 +47,12 @@ function config(): Config { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, eventBuffer: { capacity: 100 }, health: { diff --git a/src/core/wait-queue.test.ts b/src/core/wait-queue.test.ts index 4ba4c52eb..3aae5e859 100644 --- a/src/core/wait-queue.test.ts +++ b/src/core/wait-queue.test.ts @@ -122,6 +122,109 @@ describe("WaitQueue", () => { expect(timedOut).toHaveBeenCalledWith(queued); }); + // Pre-existing gap, now routinely triggered by the gateway's own stale-view re-queue (round 2 + // review): a waiter cycling queued -> processing -> queued used to have `timeoutMs` re-armed + // from zero on every return to `queued`, so the total wait before `QUEUE_TIMEOUT` could exceed + // the caller's own budget by a multiple. These two tests pin the fixed behaviour: the budget is + // one fixed deadline from the *first* enqueue, survives any number of cycles, and a re-enqueue + // past that deadline settles immediately rather than granting another full window. + it("rejects immediately on a re-enqueue past the original deadline, instead of granting a fresh timeoutMs window", async () => { + const timedOut = vi.fn(); + const { clock, queue } = createQueue(timedOut); + const waiter = createWaiter(queue, "agent", { timeoutMs: 100 }); + + queue.enqueue(waiter); + clock.advance(60); // still well inside the original 100ms budget + queue.markProcessing(waiter); + // The original timer (armed for the full 100ms at t=0) fires during this advance, at + // t=100 -- but the waiter is `processing`, not `queued`, so `#armTimeout`'s own timer + // callback does nothing here. Total elapsed is now 120ms, past the original deadline. + clock.advance(60); + expect(waiter.state).toBe("processing"); + + // A stale-view (or worker retry) re-queue lands after the deadline already passed. + expect(queue.enqueue(waiter)).toBe(false); + + await expect(waiter.promise).rejects.toEqual(expect.any(QueueTimeoutError)); + expect(waiter.state).toBe("rejected"); + expect(queue.depth).toBe(0); + expect(timedOut).toHaveBeenCalledWith(waiter); + }); + + // H5 (round 3 review): this test used to claim it proved a re-enqueue "re-arms only the time + // actually remaining" -- but every assertion in it (the waiter's `state` at various clock + // ticks, and when its promise finally rejects) would come out identical whether `#armTimeout` + // actually cancelled the original timer and started a fresh one for the recomputed remainder, + // or simply left that still-live timer alone. Both mechanisms hit the same fixed `deadlineAt`. + // The `setTimer` spy below is what tells them apart: it asserts directly on the *mechanism* -- + // exactly one timer is ever armed across the whole `queued -> processing -> queued` cycle, not + // two -- which is what `#armTimeout`'s own doc comment now documents as the only thing that + // can happen (its `waiter.timer !== undefined` guard makes a genuine recompute-and-re-arm + // unreachable through this class's public API). The externally observed timing this test also + // pins is real and worth keeping; it just is not, on its own, evidence of which mechanism + // produced it. + it("leaves a still-live timer alone across a queued -> processing -> queued cycle, rather than cancelling and re-arming it, so the total wait never exceeds the original timeoutMs (H5, round 3 review)", async () => { + const { clock, queue } = createQueue(); + const waiter = createWaiter(queue, "agent", { timeoutMs: 100 }); + const setTimerSpy = vi.spyOn(clock, "setTimer"); + const cancelSpy = vi.spyOn(clock, "cancel"); + + queue.enqueue(waiter); + expect(setTimerSpy).toHaveBeenCalledTimes(1); // the first (and, this test proves, only) arm + clock.advance(30); + queue.markProcessing(waiter); + clock.advance(20); // t=50: still well before the t=100 deadline + expect(queue.enqueue(waiter)).toBe(true); // re-queued, e.g. a stale-view NO_CAPACITY + expect(waiter.state).toBe("queued"); + + // The proof this test exists for: re-enqueuing well before the deadline armed nothing new + // and cancelled nothing -- `#armTimeout`'s guard found the original timer still live and + // returned immediately. A recompute-and-re-arm implementation would have cancelled that + // timer and called `setTimer` a second time here, for the ~50ms actually remaining. + expect(setTimerSpy).toHaveBeenCalledTimes(1); + expect(cancelSpy).not.toHaveBeenCalled(); + + // If this cycle had re-armed a fresh 100ms window, the waiter would still be pending here + // (t=50 + 49ms = 99ms of its own window, or 149ms of total elapsed time either way). It + // does not: the original deadline was t=100, and only 50ms of elapsed time remain from it. + clock.advance(49); + expect(waiter.state).toBe("queued"); + clock.advance(1); // t=100: the original deadline, reached exactly once, not once per cycle + await expect(waiter.promise).rejects.toEqual(expect.any(QueueTimeoutError)); + expect(queue.depth).toBe(0); + // Still just the one timer, start to finish -- the fixed deadline was honoured by leaving it + // running, not by any second arm. + expect(setTimerSpy).toHaveBeenCalledTimes(1); + }); + + it("never delivers a progress push to a waiter that already settled, even the very same tick (P3, round 2 review)", async () => { + // `enqueue` can reject synchronously once a waiter's deadline has already passed (the + // re-arm-only-remaining-time fix above); a caller that unconditionally pushes progress right + // after its own `enqueue` call (`LeaseAcquisitionCoordinator#defer` always does, for its + // reclaim-wait notice) must not be able to deliver that push to a waiter `enqueue` just + // rejected out from under it. + const received: LeaseProgress[] = []; + const { clock, queue } = createQueue(); + const waiter = queue.create(request satisfies DeviceRequest, { + onProgress: (progress) => received.push(progress), + ownerId: "agent", + requesterId: "agent", + timeoutMs: 100, + }); + queue.enqueue(waiter); + queue.markProcessing(waiter); + clock.advance(150); // past the 100ms deadline while `processing`, same as the test above + + expect(queue.enqueue(waiter)).toBe(false); // rejects synchronously with QueueTimeoutError + expect(waiter.state).toBe("rejected"); + received.length = 0; // only care about anything delivered *after* settlement + + queue.notifyProgress(waiter, { etaMs: 5_000, stage: "reclaiming" }); + + await expect(waiter.promise).rejects.toEqual(expect.any(QueueTimeoutError)); + expect(received).toEqual([]); + }); + it("attaches and detaches queued progress without changing the request outcome", () => { const received: LeaseProgress[] = []; const reattached: LeaseProgress[] = []; diff --git a/src/core/wait-queue.ts b/src/core/wait-queue.ts index 19c8e783e..19dfea97b 100644 --- a/src/core/wait-queue.ts +++ b/src/core/wait-queue.ts @@ -98,6 +98,12 @@ interface MutableWaiter extends Waiter { resolvePromise: (grant: LeaseGrant) => void; state: WaiterState; timer: TimerHandle | undefined; + /** + * The absolute clock reading `options.timeoutMs` counts down to, fixed the *first* time this + * waiter is ever armed and never moved afterward -- see `#armTimeout`'s own doc comment for why + * (pre-existing, now routinely triggered: round 2 review of ADR 0005's fleet queue). + */ + deadlineAt: number | undefined; } export interface WaitQueueOptions { @@ -130,6 +136,18 @@ export class WaitQueue { return this.#waiters[0]; } + /** + * Every waiter currently holding a queue slot (`queued` or `processing`), oldest first. The + * single-lease acquisition path never needs this -- it only ever advances `head` -- but a + * caller that places requests across more than one resource (the gateway's fleet queue, + * ADR 0005 §11: "for each queued request, oldest first, the routing policy picks an eligible + * worker ... a request no worker can serve right now is passed over") has to walk the whole + * FIFO in order rather than block on its front. Returns a snapshot copy, not a live view. + */ + list(): readonly Waiter[] { + return [...this.#waiters]; + } + hasPendingRequester(requesterId: string): boolean { return this.#pendingRequesters.has(requesterId); } @@ -159,6 +177,7 @@ export class WaitQueue { rejectPromise = reject; }); const waiter: MutableWaiter = { + deadlineAt: undefined, id: `req_${this.options.idGenerator.generate()}`, onProgress: requestOptions.onProgress, options: requestOptions, @@ -175,10 +194,30 @@ export class WaitQueue { return waiter; } + /** + * Pre-existing gap, now routinely triggered (round 2 review): a waiter that cycles + * `queued` -> `processing` -> `queued` again (a worker's own retry, or the gateway's stale-view + * re-queue) used to have its whole `timeoutMs` budget re-armed from zero on every return to + * `queued`, because `#armTimeout` only ever knew "start a fresh timer for the full duration." + * `deadlineAt` (fixed once, on the very first arm) is what makes the budget survive the cycle: + * a re-enqueue past that deadline is rejected on the spot instead of getting another full + * `timeoutMs`, and one still short of it gets only the time actually left. + */ enqueue(waiter: Waiter): boolean { const mutable = this.#mutable(waiter); if (isTerminal(mutable.state)) return false; + if (mutable.deadlineAt !== undefined && this.options.clock.now() >= mutable.deadlineAt) { + if (this.reject(mutable, new QueueTimeoutError(mutable.id))) { + try { + this.options.onTimeout?.(mutable); + } catch { + // Queue wake-up is an observer of this committed timeout fact. + } + } + return false; + } + if (!this.#waiters.includes(mutable)) { this.#waiters.push(mutable); this.notifyProgress(mutable, { queuePosition: this.#waiters.length, stage: "queued" }); @@ -220,8 +259,17 @@ export class WaitQueue { return true; } + /** + * P3 (round 2 review): a terminal waiter never gets a push. Before this guard, `enqueue` + * rejecting synchronously (the deadline-check branch above) left a caller free to keep calling + * `notifyProgress` on the same waiter regardless -- `LeaseAcquisitionCoordinator#defer` + * unconditionally pushes a `reclaiming` progress right after its own `#enqueue` call, so a + * request that had just settled `QUEUE_TIMEOUT` could still receive a push after its error, + * with nothing here or at that call site distinguishing "still waiting" from "already told". + */ notifyProgress(waiter: Waiter, progress: LeaseProgress): void { const mutable = this.#mutable(waiter); + if (isTerminal(mutable.state)) return; try { mutable.onProgress?.(progress); } catch { @@ -258,9 +306,51 @@ export class WaitQueue { return cancelled; } + /** + * Arms (or re-arms, after a cycle back through `queued`) this waiter's timeout. `deadlineAt` is + * computed once, the first time a waiter with a `timeoutMs` is ever armed, and never moved + * afterward -- every later call here (a re-enqueue `enqueue` already let through because the + * deadline had not yet passed) times the remaining budget against that same fixed deadline + * instead of starting a fresh `timeoutMs` window, which is what let the total wait exceed + * `timeoutMs` by a multiple across repeated `processing` <-> `queued` cycles before this fix. + * + * If the timer fires while `waiter.state !== "queued"` (mid-attempt), it does *not* reject -- + * the request is actively being handled, and this class does not know whether that attempt is + * about to succeed. `enqueue`'s own deadline check is what catches this case at the next + * re-queue, since `waiter.timer` is already cleared by the time this branch returns. + * + * H5 (round 3 review): the `waiter.timer !== undefined` guard above means `remainingMs` is + * only ever actually computed with a genuinely partial value in theory, essentially never in + * practice under a real `Clock` -- every real call into this method lands in one of exactly two + * cases. A fresh arm (`waiter.timer` was never set) always computes the *full* `timeoutMs`, + * since `deadlineAt` is being fixed in the same line. Every later call finds one of two things: + * the original timer is still counting down (`waiter.timer !== undefined`), so the guard above + * returns immediately and the still-live timer -- already targeting the correct fixed + * `deadlineAt` -- is left untouched, no second `setTimer` call, no recompute, no re-arm; or that + * timer already fired at (or acceptably near) `deadlineAt` (clearing itself, above), in which + * case `enqueue`'s own upfront `clock.now() >= deadlineAt` check rejects the waiter before this + * method is even called again. That "acceptably near" is not exact under a real `Clock`: Node's + * own timers can fire a little early (sub-millisecond to a few ms, platform- and load- + * dependent), so a re-`enqueue` landing in that narrow window between the timer's early fire and + * the deadline it was targeting can reach here with `waiter.timer === undefined`, `deadlineAt` + * already set, and `clock.now()` still (fractionally) short of it -- the one shape this + * arithmetic then computes a genuinely partial `remainingMs` for, rather than the full budget or + * an already-expired one. Harmless (the re-armed timer still targets the same fixed + * `deadlineAt`, just via a few-millisecond-shorter final `setTimer` call instead of one that + * would have fired at the identical moment anyway), but real, not merely theoretical -- + * `FakeClock` (every test here) never fires early, so no test under it can ever land in this + * window, which is why the difference is a doc claim to get right rather than a behavior to + * cover with one. Separately: `markNew` (below) is a public path back to `queued` that arms no + * timer at all -- a waiter it returns to `queued` sits with no deadline until some *other* + * `enqueue` call re-arms it, which is a real gap in `timeoutMs` enforcement for whichever + * caller uses that path (`LeaseAcquisitionCoordinator`'s own eviction and provision-retry + * callers, not this module's problem to close on its own). + */ #armTimeout(waiter: MutableWaiter): void { if (waiter.timer !== undefined || waiter.options.timeoutMs === undefined) return; - waiter.timer = this.options.clock.setTimer(waiter.options.timeoutMs, () => { + waiter.deadlineAt ??= this.options.clock.now() + waiter.options.timeoutMs; + const remainingMs = Math.max(0, waiter.deadlineAt - this.options.clock.now()); + waiter.timer = this.options.clock.setTimer(remainingMs, () => { waiter.timer = undefined; if (waiter.state !== "queued") return; if (this.reject(waiter, new QueueTimeoutError(waiter.id))) { diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index 7a6f34cc1..c5f34f26a 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -18,7 +18,12 @@ const config: Config = { mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, eventBuffer: { capacity: 100 }, health: { diff --git a/src/daemon/dispatch.ts b/src/daemon/dispatch.ts index 5f8aee952..906d06e19 100644 --- a/src/daemon/dispatch.ts +++ b/src/daemon/dispatch.ts @@ -50,6 +50,24 @@ export type DispatchProgress = z.infer; export interface DispatchSession { readonly principal: string; readonly role: Role; + /** + * ADR 0005 §27a (narrowed, round 3 review, H3): true only for the one session `owner` was + * ever meant for -- a worker's own connection to *its own configured gateway*, accepted + * through `DaemonServer#acceptUplink` and forced to `admin` there regardless of any + * credential, because that connection's existence already proves the trust chain (this + * worker dialled `gateway.url`, presenting `gateway.token`, before the connection existed -- + * see `acceptUplink`'s own comment). `role === "admin"` alone used to gate `owner`, but HTTP's + * `operator` token maps onto that same role (`dispatcher-session.ts`), so any operator bearer + * credential -- on a plain worker with no gateway anywhere -- passed the same check a real + * uplink was supposed to require. This field is that narrower, harder-to-forge signal: it + * reflects how the *connection* was accepted, never anything a `hello` payload can claim, and + * is left `undefined`/`false` by every other session-building path (HTTP's + * `buildHttpSession`, an ordinary socket connection's `#session`, and every session a + * `GatewayDispatcher` itself is ever handed -- nothing forwards *into* a gateway's own front + * door the way a gateway forwards into a worker, so `owner` is unconditionally refused there + * now, admin included). + */ + readonly isGatewayUplink?: boolean; /** Called for each progress update while this specific `lease.request` call is in flight. * Ignored by every other operation. */ readonly onProgress?: (progress: DispatchProgress) => void; diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 800612c6d..05b24406f 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -367,6 +367,64 @@ describe("Dispatcher: ownership", () => { return (grant as { lease: { id: string } }).lease.id; } + it("lease.request: rejects a non-admin session naming owner with FORBIDDEN, never silently ignoring it (ADR §27a, H7)", async () => { + const { dispatcher } = await buildDispatcher(); + + await expect( + dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", osVersion: "26.5", owner: "someone-else", platform: "ios" }, + session({ principal: "tok_agent", role: "agent" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); + + // H3 (round 3 review): §27a's gate used to be `role !== "admin"`, which an HTTP `operator` + // bearer token satisfies just as well as the gateway's own uplink -- on a plain worker with no + // gateway anywhere, any operator token could name someone else as owner. `isGatewayUplink` is + // the narrower signal `DaemonServer#session` stamps only for a connection accepted through + // `acceptUplink` (this worker dialled its own configured `gateway.url`); a session merely + // carrying `role: "admin"` from anywhere else -- an operator token's HTTP session included -- + // no longer suffices. + it("lease.request: rejects a plain admin session (not the gateway's uplink) naming owner with FORBIDDEN (ADR §27a, H3)", async () => { + const { dispatcher } = await buildDispatcher(); + + await expect( + dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", osVersion: "26.5", owner: "someone-else", platform: "ios" }, + session({ principal: "tok_operator", role: "admin" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); + + it("lease.request: the gateway's own uplink session may set owner, and the granted lease ends up owned by that, not the uplink's own principal (ADR §27a, H3)", async () => { + const { dispatcher } = await buildDispatcher(); + + const grant = await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", osVersion: "26.5", owner: "agent-7", platform: "ios" }, + session({ isGatewayUplink: true, principal: "tok_gateway", role: "admin" }), + ); + + expect((grant as { lease: { ownerId: string } }).lease.ownerId).toBe("agent-7"); + // The lease is now gated on the named owner, not the uplink session that requested it. + await expect( + dispatcher.dispatch( + "lease.renew", + { leaseId: (grant as { lease: { id: string } }).lease.id }, + session({ principal: "tok_gateway", role: "agent" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + await expect( + dispatcher.dispatch( + "lease.renew", + { leaseId: (grant as { lease: { id: string } }).lease.id }, + session({ principal: "agent-7", role: "agent" }), + ), + ).resolves.toMatchObject({ id: (grant as { lease: { id: string } }).lease.id }); + }); + it("lease.renew: rejects a non-owner with FORBIDDEN, admits the owner, admin bypasses", async () => { const { dispatcher } = await buildDispatcher(); const leaseId = await grantLease(dispatcher); @@ -1253,7 +1311,12 @@ function testConfig( ): Config { return { mode: "worker", - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, exec: { timeoutMs: 600_000, ...execOverrides }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index c83d9a480..4c9067644 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -286,13 +286,30 @@ export class Dispatcher { const requesterId = input.requesterId ?? session.principal; const requestedAllowDownload = input.allowDownload ?? false; const downloadsPolicy = this.options.config.downloads.policy; + // ADR 0005 §27a (narrowed, round 3 review, H3): `owner` is read only from the gateway's own + // uplink session -- forwarding the principal it authorized the request against on its own + // side -- never merely from `role === "admin"`. HTTP's `operator` token maps onto that same + // role (`dispatcher-session.ts`), so gating on role alone let *any* operator bearer + // credential set someone else's owner on a plain worker with no gateway anywhere; the field + // exists for one caller (the gateway's uplink, forced to `admin` by `acceptUplink` + // regardless of credential -- see `session.isGatewayUplink`'s own doc), not for every + // session that happens to carry that role. Any session that is not the uplink naming one is + // rejected outright rather than silently ignored: a caller free to name someone else as + // owner would be naming its way into their lease, and "ignore the field" would hide that a + // non-uplink caller tried. Omitting it keeps today's behaviour -- the owner is always the + // calling connection. + if (input.owner !== undefined && session.isGatewayUplink !== true) { + throw new DispatchError( + "FORBIDDEN", + "Only the gateway's own uplink session may set lease.request's `owner` field", + ); + } + const ownerId = input.owner ?? session.principal; try { return await this.options.leases.request(request, { allowDownload: effectiveAllowDownload(downloadsPolicy, requestedAllowDownload), noWait: input.noWait ?? false, - // ADR §4: the lease's owner is always the session principal -- never client-supplied, - // unlike `requesterId`. - ownerId: session.principal, + ownerId, requesterId, ...(session.onProgress === undefined ? {} : { onProgress: session.onProgress }), ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }), diff --git a/src/daemon/error-code.ts b/src/daemon/error-code.ts index c2593f83f..b4da0ccd8 100644 --- a/src/daemon/error-code.ts +++ b/src/daemon/error-code.ts @@ -75,6 +75,12 @@ export function classifyError(error: unknown): SimlockErrorCode | undefined { if (error instanceof AdminAuthenticationFailedError) { return "ADMIN_AUTHENTICATION_FAILED"; } + // The gateway's own admission refusal (`FleetLeaseCoordinator#admit`) is a plain + // `DispatchError("NO_CAPACITY", ...)`, not a distinct class -- caught by the `DispatchError` + // branch above (H9, round 2 review). Before this it was its own class in + // `src/gateway/fleet-coordinator.ts`, imported here so `src/daemon` -- every worker-mode + // daemon, not just gateway mode -- pulled the whole gateway module graph into ordinary + // startup just to recognize it. if (error instanceof NoCapacityError) { return "NO_CAPACITY"; } diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts new file mode 100644 index 000000000..fc820adae --- /dev/null +++ b/src/daemon/gateway-fleet.e2e.test.ts @@ -0,0 +1,186 @@ +/** + * ADR 0005 §35's one e2e test: "two fake-driver workers and a gateway in one process tree and + * leases through the gateway". A real gateway daemon and two real worker daemons (each with a + * `FakeDriver` instead of real simulator tooling), joined over a real WebSocket uplink on + * loopback -- not the in-memory uplink port `service.test.ts`/`worker-link.test.ts` script, + * because the point of *this* test is that the whole stack (uplink listener, worker's own + * `GatewayUplink`, the fleet queue, routing, and `device.exec` forwarding) works together, not + * any one piece of it in isolation. + * + * Two workers, not one, and with disjoint catalogs (`knownModels`): the smoke test this is meant + * to catch is "the gateway leased a device on the *wrong* machine", which one worker cannot + * exercise (see `fleet-coordinator.test.ts`'s own two-worker tests for the pass-over and + * dispatch-race cases this file does not re-prove). + * + * A fixed port, matching `main.test.ts`'s own real-HTTP tests (`describe("startDaemon HTTP + * gateway bind failure")`) rather than a dynamically-chosen one: the worker's `gateway.url` has + * to be known before that worker's daemon is constructed, and this codebase's other real-socket + * tests already accept a fixed port's small collision risk over that chicken-and-egg problem. + * + * Traps doc: this suite starts real child processes (`device.exec`'s target) and real sockets, + * so it can flake under CPU contention alongside an unrelated file's own suite -- re-run this + * file alone before treating a failure here as a real regression. + */ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { FakeDriver } from "../core/index.js"; +import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; +import type { DispatchSession } from "./dispatch.js"; +import { startDaemon } from "./main.js"; +import type { DaemonServer } from "./server.js"; + +const GATEWAY_PORT = 48173; +const GATEWAY_URL = `ws://127.0.0.1:${GATEWAY_PORT}`; + +function adminSession(): DispatchSession { + return { manageEventSubscription: () => undefined, principal: "test-operator", role: "admin" }; +} + +function agentSession(overrides: Partial = {}): DispatchSession { + return { + manageEventSubscription: () => undefined, + principal: "fleet-agent-1", + role: "agent", + ...overrides, + }; +} + +describe("gateway fleet smoke (ADR 0005 §35)", () => { + const daemons: DaemonServer[] = []; + const directories: string[] = []; + + afterEach(async () => { + await Promise.all(daemons.splice(0).map((daemon) => daemon.stop("test"))); + await Promise.all( + directories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })), + ); + }); + + async function startGateway(): Promise { + const directory = await mkdtemp(join(tmpdir(), "simlock-e2e-gateway-")); + directories.push(directory); + const daemon = await startDaemon({ + configOverrides: { + mode: "gateway", + http: { enabled: true, host: "127.0.0.1", port: GATEWAY_PORT }, + }, + dataDirectory: directory, + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + statePath: join(directory, "state.json"), + version: "1.0.0-e2e", + }); + daemons.push(daemon); + return daemon; + } + + async function startWorker(options: { + readonly label: string; + readonly model: string; + readonly token: string; + readonly stdout: string; + }): Promise { + const directory = await mkdtemp(join(tmpdir(), `simlock-e2e-${options.label}-`)); + directories.push(directory); + const daemon = await startDaemon({ + configOverrides: { + gateway: { url: GATEWAY_URL, token: options.token, label: options.label }, + }, + dataDirectory: directory, + drivers: [ + new FakeDriver({ + availableOsVersions: ["18.0"], + // A real command, so `device.exec` proves a real child process actually ran on + // *this* worker: it prints which worker answered and exits with a distinguishing + // code, both asserted below. + passthrough: () => ({ + args: [ + "-e", + `process.stdout.write(${JSON.stringify(options.stdout)}); process.exit(7);`, + ], + command: process.execPath, + env: {}, + }), + passthroughTool: "adb", + clock: new SystemClock(), + knownModels: [options.model], + platform: "android", + }), + ], + filesystem: new MemoryFilesystem(), + logger: new NoopLogger(), + statePath: join(directory, "state.json"), + version: "1.0.0-e2e", + }); + daemons.push(daemon); + return daemon; + } + + it("leases a device on the right worker and execs a real command against it through the gateway", async () => { + const gateway = await startGateway(); + const { secret: tokenA } = await gateway.dispatch( + "token.create", + { role: "worker", label: "worker-a" }, + adminSession(), + ); + const { secret: tokenB } = await gateway.dispatch( + "token.create", + { role: "worker", label: "worker-b" }, + adminSession(), + ); + + await startWorker({ + label: "worker-a", + model: "Pixel-A", + token: tokenA, + stdout: "hello-from-a", + }); + await startWorker({ + label: "worker-b", + model: "Pixel-B", + token: tokenB, + stdout: "hello-from-b", + }); + + // Both uplinks dial on their own schedule outside `startDaemon`'s own returned promise + // (`main.ts` fires `gatewayUplink.start()` without awaiting it) -- wait for the gateway to + // actually see both before leasing. + await vi.waitFor(async () => { + const { workers } = await gateway.dispatch("worker.list", {}, adminSession()); + expect(workers.filter((worker) => worker.connection === "connected")).toHaveLength(2); + }); + + const grant = await gateway.dispatch( + "lease.request", + { model: "Pixel-B", platform: "android", noWait: true }, + agentSession(), + ); + + // ADR §16: the gateway lease id names its worker -- and the worker actually chosen must be + // the one that could serve "Pixel-B" (worker-a's catalog only knows "Pixel-A"). + expect(grant.lease.worker?.label).toBe("worker-b"); + expect(grant.lease.id.startsWith(`${grant.lease.worker?.id}.`)).toBe(true); + + const chunks: string[] = []; + const result = await gateway.dispatch( + "device.exec", + { args: [], leaseId: grant.lease.id, tool: "adb" }, + agentSession({ + onOutput: (_stream, chunk) => { + chunks.push(chunk); + }, + }), + ); + + // The real child process worker-b's own `FakeDriver` builds actually ran, on that worker, + // reached through the gateway's proxy -- not worker-a's, and not simulated. + expect(result.exitCode).toBe(7); + expect(chunks.join("")).toBe("hello-from-b"); + + await gateway.dispatch("lease.release", { leaseId: grant.lease.id }, agentSession()); + }, 30_000); +}); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 44fafe97d..285760f06 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -56,9 +56,14 @@ import { type TcpProbe, } from "../ports/index.js"; import { + createRoutingPolicy, FileDrainStore, + FleetLeaseCoordinator, + FleetLeaseIndex, GatewayDispatcher, + GatewayOwnerRoutedFacts, GatewayService, + isRoutingPolicyName, type GatewayServiceOptions, } from "../gateway/index.js"; import { @@ -518,6 +523,19 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise adminSecret.verify(secret), }); + // ADR 0005 §14/§27: stamped on every requester id this gateway forwards, and what + // `FleetLeaseIndex` recognizes its own leases by when rebuilding from a worker's view. + const gatewayRequesterPrefix = `gw:${instanceId}:`; + const leaseIndex = new FleetLeaseIndex(gatewayRequesterPrefix, logger.child("lease-index")); + if (!isRoutingPolicyName(config.gateway.routing)) { + // Unreachable in production: `loadConfig` already validates `gateway.routing` against this + // same registry's names before a daemon ever starts. Guards the cast below rather than + // trusting `Config`'s own `string` typing (ADR §33: `src/gateway` cannot see `core`'s + // `Config` type, so the contract this value already satisfies cannot be expressed there). + throw new Error(`Unknown gateway.routing policy: ${config.gateway.routing}`); + } + const routing = createRoutingPolicy(config.gateway.routing); + const uplinks = new WebSocketUplinkListenerFactory(); const gatewayService = new GatewayService({ // ADR 0005 §4/§25: only a `worker`-role token opens an uplink. A token of another role is @@ -547,6 +565,30 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise Promise) | undefined; let resolveHttpStarted: (() => void) | undefined; let rejectHttpStarted: ((error: unknown) => void) | undefined; @@ -568,8 +610,10 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise gatewayService.closeLinksForToken(tokenId), config, + coordinator: fleetCoordinator, eventBus, health: () => daemon.health, + leaseIndex, logger: logger.child("gateway"), tokens, workers: gatewayService.workers, @@ -582,7 +626,12 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise + leaseIndex.all().map((entry) => ({ id: entry.gatewayLeaseId, ownerId: entry.ownerId })), logger: logger.child("server"), + ownerRoutedFacts: gatewayOwnerRoutedFacts, resolveRole, version: options.version, // A gateway's "convergence" is starting to accept uplinks and arming the refresh tick. @@ -594,6 +643,8 @@ async function startGatewayDaemon(options: GatewayDaemonOptions): Promise { + fleetCoordinator.dispose(); + gatewayOwnerRoutedFacts.dispose(); await gatewayService.stop(); }, stopAuxiliary: async () => { diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 2ad89674b..cffeec39e 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -65,7 +65,8 @@ interface ServerFrame { | "lease-lost" | "lease.heartbeat" | "output" - | "progress"; + | "progress" + | "started"; } const runningDaemons: DaemonServer[] = []; @@ -569,6 +570,20 @@ describe("DaemonServer", () => { push: "output", }, ]); + + // ADR 0005 §19a: `started` reaches the socket exactly once, keyed by the same frame id. + // Round 5 review: this send site could be deleted with the entire suite green, because + // nothing asserted the frame ever reached a socket at all. + // + // Deliberately not asserted here: that it precedes the first `output`. It does in + // production -- the dispatcher calls `onStarted` synchronously after the spawn returns, and + // a real child's chunks arrive later from `data` events -- but `ScriptedProcessRunner` + // delivers its scripted chunks synchronously *inside* `runCommand`, so this harness sees + // them first and cannot distinguish the two orderings. Claiming the ordering here would be a + // title outrunning its body; `client.test.ts`'s wire test pins it where it is observable. + expect(client.frames().filter((frame) => frame.push === "started")).toEqual([ + { payload: { requestId: "exec-frame" }, push: "started" }, + ]); }); it("routes two commands on one connection by frame id, and pushes to no other connection", async () => { @@ -2981,7 +2996,12 @@ function testConfig( mode: "worker", exec: { timeoutMs: 600_000 }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, eventBuffer: { capacity: 100 }, health: { diff --git a/src/daemon/server.ts b/src/daemon/server.ts index e6c267123..f773697a1 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -81,6 +81,18 @@ interface Connection { * here and nowhere else. */ readonly forcedRole: Role | undefined; + /** + * H3 (round 3 review, narrowed further): set only by `acceptUplink`, and only there -- a + * dedicated fact about *how this connection was accepted*, not derived from `forcedRole`. + * Before this, `#session` read `forcedRole !== undefined` as the proxy for "this is the + * worker's own uplink to its configured gateway", which happened to be true only because + * `acceptUplink` is `#accept`'s one caller that ever sets `forcedRole` at all -- a future + * `#accept(socket, "agent")` (or any other forced role added for an unrelated reason) would + * silently satisfy that same check and reopen ADR §27a's `owner` gate to whatever forced that + * connection, with no test failing to say so. This field is set directly, once, at the one call + * site that is actually the uplink, so a future forced role elsewhere cannot be mistaken for it. + */ + readonly isGatewayUplink: boolean; /** * Lease ids this connection is *currently* explicitly releasing (`lease.release`/ * `lease.release-all`), added right before the dispatched call and consumed by @@ -211,6 +223,25 @@ export interface DaemonServerCommonOptions { * default leaves today's behaviour (no auxiliary frontend at all) unchanged. */ readonly onSocketClaimed?: () => void; + /** + * #118: a gateway's own `OwnerRoutedFacts` (`src/gateway/owner-routed-facts.ts`'s + * `GatewayOwnerRoutedFacts`), replacing the inert one gateway mode has used since #117. Worker + * mode ignores this entirely -- it builds its own `OwnerRoutedFactBus` from the engine's + * registry, exactly as before. Structurally typed (not imported) so this module need not + * depend on `src/gateway`; see that class's own doc comment for why the shapes line up with + * no cast. + */ + readonly ownerRoutedFacts?: OwnerRoutedFacts & { dispose(): void }; + /** + * #118: every lease this daemon currently knows about, for `lease.release-all`'s self-push + * suppression (`#handleRequest`'s `lease.release-all` case below). Worker mode reads its own + * registry directly and never needs this (`this.#engine?.registry` already answers it); a + * gateway has no registry, so it supplies its fleet lease index's own entries here instead -- + * without it, a fleet client's own `lease.release-all` would push every one of its own + * `lease-lost` facts back at itself, since nothing would ever mark them self-initiated. + * Optional so a test exercising neither engine nor gateway leases need not supply one. + */ + readonly leaseSnapshot?: () => readonly { readonly id: string; readonly ownerId: string }[]; } /** @@ -326,7 +357,12 @@ export class DaemonServer { // than wrong. this.#engine = undefined; this.#dispatcher = options.dispatcher; - this.#ownerRoutedFacts = inertOwnerRoutedFacts(); + // #118: a gateway now issues leases of its own, and `GatewayOwnerRoutedFacts` (built by + // `main.ts`, with the fleet's own lease index) is what routes their `lease-lost`/ + // `device-unhealthy`/`device-recovered` facts to the right owner -- see that class's doc + // comment for why a worker's own republished `lease.expired` cannot be routed off its raw + // payload. Falls back to inert only for a gateway test harness that supplies neither. + this.#ownerRoutedFacts = options.ownerRoutedFacts ?? inertOwnerRoutedFacts(); } } @@ -595,10 +631,10 @@ export class DaemonServer { * mismatched range still refuses every operation but `daemon.stop`. */ acceptUplink(connection: IpcConnection): void { - this.#accept(connection, "admin"); + this.#accept(connection, "admin", true); } - #accept(socket: IpcConnection, forcedRole?: Role): void { + #accept(socket: IpcConnection, forcedRole?: Role, isGatewayUplink = false): void { if (this.#stopping) { void socket.close(); return; @@ -608,6 +644,7 @@ export class DaemonServer { closed: false, forcedRole, helloReceived: false, + isGatewayUplink, // Overwritten by `#handleHello` before any dispatched request can read them -- every // path that reaches `#handleRequest` has `connection.helloReceived === true` by // construction (`#dispatchLine` routes to `#handleHello` until then). @@ -947,7 +984,13 @@ export class DaemonServer { // and one granted inside the window is not suppressed, so its holder gets the push it // would have got for any other force-release. Neither can suppress a push for a lease // this principal does not own, which is the property that matters. - const releasing = (this.#engine?.registry.snapshot.leases ?? []) + // #118: a gateway has no `#engine`, so it falls back to `options.leaseSnapshot` (its + // fleet lease index) -- see that option's own doc comment. + const releasing = ( + this.#engine?.registry.snapshot.leases ?? + this.options.leaseSnapshot?.() ?? + [] + ) .filter((lease) => connection.role === "admin" || lease.ownerId === connection.principal) .map((lease) => lease.id); for (const leaseId of releasing) connection.selfInitiatedReleases.add(leaseId); @@ -1092,9 +1135,16 @@ export class DaemonServer { * principal and role -- all that is left of it, since ADR 0004 removed the per-connection * lease state that used to travel alongside. `onProgress` is unset here: only `#requestLease` * needs one, and builds its own session inline so the closure can see that specific call's - * `requestId`. */ + * `requestId`. + * + * `isGatewayUplink` (ADR §27a, H3, round 3 review; narrowed further, see the `Connection` + * field's own doc) reads `connection.isGatewayUplink` directly, not `connection.role` and not + * `connection.forcedRole`: `role` itself is always `"admin"` for such a connection, but so is + * an ordinary HTTP `operator` token's, which is the very confusion this field exists to stop + * propagating into `lease.request`'s `owner` gate. */ #session(connection: Connection): DispatchSession { return { + isGatewayUplink: connection.isGatewayUplink, manageEventSubscription: (subscribe) => this.#manageEventSubscription(connection, subscribe), principal: connection.principal, role: connection.role, @@ -1209,6 +1259,14 @@ export class DaemonServer { if (outputSocket === undefined) return; await this.#pushOutput(outputSocket, requestId, stream, chunk).catch(() => undefined); }, + // ADR 0005 §19a: the process now exists. Fired and forgotten rather than awaited -- + // unlike `onOutput` this carries no backpressure meaning, and the dispatcher calls it + // synchronously between the spawn and the first chunk. Every peer that negotiates + // protocol 5 understands the frame (§31), so this is not a signal anyone opts out of. + onStarted: () => { + if (outputSocket === undefined) return; + void this.#pushStarted(outputSocket, requestId).catch(() => undefined); + }, }); } finally { connection.progressDisposers.delete(disposeOutput); @@ -1238,6 +1296,18 @@ export class DaemonServer { }); } + /** + * ADR 0005 §19a: `started` carries the originating request's frame id, exactly as `output` + * does. It is the one fact a gateway forwarding this command cannot infer for itself -- see + * `startedPushSchema`'s own doc -- so the worker that knows it sends it. + */ + async #pushStarted(socket: IpcConnection, requestId: RequestId): Promise { + return writeFrame(socket, { + push: "started", + payload: this.#parseOutput(PUSH_SCHEMAS.started, { requestId }, "push:started"), + }); + } + /** * Validates a handler's return value against its contract output schema before it goes on * the wire. A mismatch here is always a daemon-side bug (the schema or the mapping is wrong, diff --git a/src/gateway/aggregate.test.ts b/src/gateway/aggregate.test.ts index d1a00bd2e..4a22e43ac 100644 --- a/src/gateway/aggregate.test.ts +++ b/src/gateway/aggregate.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { OPERATIONS } from "../contract/index.js"; import { aggregateCatalog, aggregateStatus } from "./aggregate.js"; +import { FleetLeaseIndex } from "./lease-index.js"; import { deviceFixture, leaseFixture } from "./test-support.js"; import type { WorkerView } from "./worker-registry.js"; @@ -52,6 +53,57 @@ describe("aggregateStatus", () => { expect(status.workers).toEqual([]); }); + // Round 6 review: `aggregateStatus`'s whole `leaseIndex` branch was deletable with a green + // suite -- replacing it with the pre-#118 `{...lease, workerId}` passthrough broke nothing, + // because every case here omitted the optional `leaseIndex` and so exercised only the + // fallback. `lease.list`'s equivalent projection was covered; `status.get`'s was not. + // + // What that left unguarded is the reason the parameter exists: an id an operator reads out of + // `status.get` has to be the id `lease.renew` accepts. A raw worker id answers `UNKNOWN_LEASE`. + it("reports a gateway-issued lease under the id lease.renew accepts, not the worker's own", () => { + const leaseIndex = new FleetLeaseIndex("gw:instance-1:"); + leaseIndex.add({ + gatewayLeaseId: "wrk_a.lease_1", + grantedAt: 1, + ownerId: "agent-1", + requesterId: "gw:instance-1:agent-1", + workerId: "wrk_a", + workerLeaseId: "lease_1", + }); + + const status = aggregateStatus( + [view({ id: "wrk_a", label: "mac-mini-1", leases: [leaseFixture("lease_1", "dev_1")] })], + { health: "running", leaseIndex, queueDepth: 0 }, + ); + + expect(status.leases).toEqual([ + expect.objectContaining({ + id: "wrk_a.lease_1", + requesterId: "gw:instance-1:agent-1", + worker: { id: "wrk_a", label: "mac-mini-1" }, + workerId: "wrk_a", + }), + ]); + // Still the same shape a worker returns (ADR §20) with the projection applied. + expect(() => OPERATIONS["status.get"].output.parse(status)).not.toThrow(); + }); + + // The other half of the same contract: a lease this gateway never issued is a worker's own + // local one, and renaming it would invent a gateway id that `lease.renew` would then reject. + it("leaves a worker's own local lease's id alone", () => { + const leaseIndex = new FleetLeaseIndex("gw:instance-1:"); + + const status = aggregateStatus( + [view({ id: "wrk_a", label: "mac-mini-1", leases: [leaseFixture("lease_1", "dev_1")] })], + { health: "running", leaseIndex, queueDepth: 0 }, + ); + + expect(status.leases).toEqual([ + expect.objectContaining({ id: "lease_1", requesterId: "agent-1", workerId: "wrk_a" }), + ]); + expect(status.leases[0]).not.toHaveProperty("worker"); + }); + it("sums capacity across connected workers", () => { const status = aggregateStatus( [ diff --git a/src/gateway/aggregate.ts b/src/gateway/aggregate.ts index 65294f16f..8812378ae 100644 --- a/src/gateway/aggregate.ts +++ b/src/gateway/aggregate.ts @@ -6,6 +6,7 @@ import type { z } from "zod"; import { OPERATIONS, type Platform } from "../contract/index.js"; +import type { FleetLeaseIndex } from "./lease-index.js"; import type { WorkerView } from "./worker-registry.js"; type StatusOutput = z.infer<(typeof OPERATIONS)["status.get"]["output"]>; @@ -38,6 +39,16 @@ export interface AggregateStatusOptions { readonly health: StatusOutput["daemon"]["health"]; /** The gateway's fleet queue depth -- 0 until #118 gives it a queue. */ readonly queueDepth: number; + /** + * #118: rewrites each view's leases to gateway-facing form (its own id, fleet-level + * `requesterId`, `worker`) for the ones this gateway actually issued -- see + * `FleetLeaseIndex#project`. A caller's own `status.get`-derived lease id must round-trip into + * `lease.renew` the same way `lease.list`'s does; leaving this out (as every caller before + * #118 did, and every `aggregate.test.ts` case that still omits it) reports each worker's raw + * lease record instead, which is still correct for a worker's own local lease -- it only stops + * being correct for one the gateway granted. + */ + readonly leaseIndex?: Pick; } /** @@ -63,7 +74,13 @@ export function aggregateStatus( devices: views.flatMap((view) => view.devices.map((device) => ({ ...device, workerId: view.id })), ), - leases: views.flatMap((view) => view.leases.map((lease) => ({ ...lease, workerId: view.id }))), + leases: views.flatMap((view) => + view.leases.map((lease) => + options.leaseIndex === undefined + ? { ...lease, workerId: view.id } + : options.leaseIndex.project(lease, view.id, view.label), + ), + ), queueDepth: options.queueDepth, workers: [...views], }; diff --git a/src/gateway/boundary.test.ts b/src/gateway/boundary.test.ts index cb8c8611d..69235d7d4 100644 --- a/src/gateway/boundary.test.ts +++ b/src/gateway/boundary.test.ts @@ -14,13 +14,12 @@ const daemonDir = join(srcDir, "daemon"); * platform-agnostic queue and bus modules it reuses; never the registry, capacity, or lifecycle * modules (enforced like `src/contract/boundary.test.ts`)." * - * In this PR the gateway reuses nothing from `core` at all -- the fleet queue arrives with #118 - * -- so the allowance is written as an explicit list rather than a blanket "core is fine": a - * gateway that starts importing `core/registry.js` should fail here, and a later PR adding - * `core/wait-queue.js` should have to say so in this list rather than silently widening the - * boundary. `src/http` is off limits for the same reason (`GatewayTokenStore` is a structural - * interface precisely so the token store need not be imported), as are `src/cli`, `src/mcp` and - * `src/drivers`. + * `drivers`, `http`, `cli`, and `mcp` stay wholesale forbidden -- `src/http` for the same reason + * as always (`GatewayTokenStore` is a structural interface precisely so the token store need not + * be imported). `core` is *not* in this list any more: #118 is the "later PR adding + * `core/wait-queue.js`" the old comment here predicted, and it has to say so explicitly rather + * than silently widening the boundary -- see `ALLOWED_CORE_IMPORTS` below, checked the same way + * `ALLOWED_DAEMON_IMPORTS` already was. * * Named as top-level directories under `src/`, matched against a specifier normalised relative * to `src/` (see `normalizeSpecifier`) rather than against the raw text of the specifier -- a @@ -29,7 +28,7 @@ const daemonDir = join(srcDir, "daemon"); * reaches core as `"../../core/registry.js"`, which does not start with `"../core"`, so the * check silently stopped applying to exactly the files a subdirectory newly reaches. */ -const FORBIDDEN_IMPORT_DIRS = ["core", "drivers", "http", "cli", "mcp"]; +const FORBIDDEN_IMPORT_DIRS = ["drivers", "http", "cli", "mcp"]; /** * The only `src/daemon` module the gateway may import: the transport-facing dispatch contract @@ -40,6 +39,25 @@ const FORBIDDEN_IMPORT_DIRS = ["core", "drivers", "http", "cli", "mcp"]; */ const ALLOWED_DAEMON_IMPORTS = ["daemon/dispatch.js"]; +/** + * #118's fleet queue and its ownership check reuse `core`'s platform-agnostic FIFO + * (`wait-queue.js`) and short critical-section serializer (`serialized-decision.js`) rather than + * forking either -- ADR 0005 §33's "only the platform-agnostic queue and bus modules it reuses". + * `domain.js` and `driver.js` are here too, explicitly, as the doc comment on the old + * (now-removed) blanket `core` entry above asked the PR that widened this list to do: they are + * `wait-queue.js`'s own transitive *type* imports (`DeviceRecord`/`LeaseRecord`/`DeviceSpec` and + * `DeviceRequest`), which the fleet queue and coordinator need to name the same shapes wait-queue + * itself is typed against rather than redeclaring them. Neither module is the registry, capacity, + * or lifecycle engine §33 keeps off limits -- `domain.js` is pure data shapes and a spec-equality + * predicate, `driver.js` is interface declarations only. + */ +const ALLOWED_CORE_IMPORTS = [ + "core/wait-queue.js", + "core/serialized-decision.js", + "core/domain.js", + "core/driver.js", +]; + /** * A relative import specifier, resolved against the directory of the file that wrote it and * expressed relative to `src/` -- e.g. `"../../core/registry.js"` from @@ -105,6 +123,9 @@ describe("gateway module boundary", () => { if (isUnder(normalized, "daemon")) { expect(ALLOWED_DAEMON_IMPORTS).toContain(normalized); } + if (isUnder(normalized, "core")) { + expect(ALLOWED_CORE_IMPORTS).toContain(normalized); + } } }, ); @@ -121,6 +142,47 @@ describe("gateway module boundary", () => { }); }); +/** + * H9 (round 2 review): the reverse direction from the one this file otherwise checks. Before + * this, `src/daemon/error-code.ts` imported `NoCapacityError` from + * `src/gateway/fleet-coordinator.js` just to recognize it in an `instanceof` branch, so every + * worker-mode daemon -- not just gateway mode -- pulled the whole gateway module graph (and + * `src/admin`'s client) into ordinary startup, with nothing here to notice. `main.ts` is the one + * legitimate exception: it is the composition root that wires up whichever mode `config.mode` + * names, and gateway mode's own wiring (`GatewayService`, `FleetLeaseCoordinator`, + * `GatewayOwnerRoutedFacts`, ...) has to live somewhere that can see both. + */ +describe("daemon module boundary (reverse direction, H9)", () => { + const daemonSourceFiles = sourceFilesRecursive(daemonDir).filter( + (path) => path !== join(daemonDir, "main.ts"), + ); + + it("found the daemon's own source files (excluding main.ts, the composition root)", () => { + expect(daemonSourceFiles.length).toBeGreaterThan(0); + }); + + it.each(daemonSourceFiles.map((path) => [path.slice(daemonDir.length + 1), path] as const))( + "%s does not import src/gateway", + (relativePath, filePath) => { + const contents = stripComments(readFileSync(filePath, "utf8")); + const fileDir = dirname(filePath); + + for (const specifier of importSpecifiers(contents)) { + const normalized = normalizeSpecifier(fileDir, specifier); + expect({ + fileName: relativePath, + matchesGateway: isUnder(normalized, "gateway"), + normalized, + }).toEqual({ + fileName: relativePath, + matchesGateway: false, + normalized, + }); + } + }, + ); +}); + describe("sourceFilesRecursive", () => { // M4: the other half of the gap -- a flat `readdirSync` never looked inside a subdirectory at // all, so a module placed under one skipped this whole suite silently rather than failing it. @@ -171,16 +233,21 @@ describe("normalizeSpecifier / isUnder", () => { }); describe("gateway module boundary regression fixtures", () => { - // C2, made concrete: this is exactly the file #118 adds, reduced to the one line that matters. - // Against the pre-fix `specifier.startsWith("../core")` check, this import passes silently -- - // `"../../core/registry.js"` does not start with `"../core"` -- even though it reaches the - // exact module the boundary exists to keep out. + // C2, made concrete: a hypothetical nested module reaching for a forbidden `core` module + // through a longer relative path. Against the pre-fix `specifier.startsWith("../core")` + // check, this import passed silently -- `"../../core/registry.js"` does not start with + // `"../core"` -- even though it reaches exactly the kind of module the boundary exists to + // keep out. `core/registry.js` is the registry itself, never in `ALLOWED_CORE_IMPORTS` (only + // `wait-queue.js`/`serialized-decision.js`/`domain.js`/`driver.js` are, per #118) -- so a + // nested file reaching it is caught the same way the daemon-allowlist gap below is: recognized + // as `core`, and absent from the allowlist that governs it. it("catches a nested module importing core through a longer relative path", () => { const nestedDir = join(gatewayDir, "routing"); const specifier = "../../core/registry.js"; const normalized = normalizeSpecifier(nestedDir, specifier); - expect(FORBIDDEN_IMPORT_DIRS.some((forbidden) => isUnder(normalized, forbidden))).toBe(true); + expect(isUnder(normalized, "core")).toBe(true); + expect(ALLOWED_CORE_IMPORTS).not.toContain(normalized); }); // And the matching allowlist gap: `"../../daemon/dispatcher.js"` does not start with diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index f55a0dfa9..bb7f092a5 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -6,7 +6,18 @@ import type { DispatchSession } from "../daemon/dispatch.js"; import { FakeClock } from "../ports/index.js"; import { GatewayDispatcher, type GatewayTokenStore } from "./dispatcher.js"; import { MemoryDrainStore } from "./drain-store.js"; -import { deviceFixture, leaseFixture, statusFixture } from "./test-support.js"; +import { FleetLeaseCoordinator } from "./fleet-coordinator.js"; +import type { WorkerDirectory, WorkerDispatchTarget } from "./fleet-ports.js"; +import { FleetLeaseIndex } from "./lease-index.js"; +import { createRoutingPolicy } from "./routing.js"; +import { + catalogFixture, + deviceFixture, + grantFixture, + leaseFixture, + ScriptedWorkerClient, + statusFixture, +} from "./test-support.js"; import { WorkerRegistry } from "./worker-registry.js"; const gatewayConfig = { @@ -15,7 +26,12 @@ const gatewayConfig = { downloads: { acceptAndroidLicenses: false, policy: "on-request" as const, timeoutMs: 1 }, eventBuffer: { capacity: 100 }, exec: { timeoutMs: 600_000 }, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, health: { enabled: false, maxConcurrentRecoveries: 1, @@ -65,6 +81,26 @@ class FakeTokens implements GatewayTokenStore { } } +/** Matches `service.test.ts`'s `principal: "gw:instance-1"` -- ADR 0005 §14/§27's own-lease + * prefix is that principal plus a trailing `:`, the same shape `worker-registry.test.ts` uses. */ +const GATEWAY_REQUESTER_PREFIX = "gw:instance-1:"; + +/** A `WorkerDirectory` a test populates by hand -- see `fleet-coordinator.test.ts`'s own copy + * for the fuller doc comment; this file only ever needs one worker at a time. */ +class FakeDirectory implements WorkerDirectory { + readonly clients = new Map(); + + add(workerId: string, client: ScriptedWorkerClient): void { + this.clients.set(workerId, client); + } + + target(workerId: string): WorkerDispatchTarget | undefined { + const client = this.clients.get(workerId); + if (client === undefined) return undefined; + return { client: () => client.asClient(), reachable: true, refresh: async () => {}, workerId }; + } +} + function harness() { const clock = new FakeClock(1_000); const eventBus = new EventBus(clock); @@ -78,18 +114,48 @@ function harness() { const tokens = new FakeTokens(); /** C-2: every id `closeUplinksForToken` was actually called with, in call order. */ const closedUplinkTokens: string[] = []; + const directory = new FakeDirectory(); + const leaseIndex = new FleetLeaseIndex(GATEWAY_REQUESTER_PREFIX); + const coordinator = new FleetLeaseCoordinator({ + clock, + directory, + eventBus, + execTimeoutMs: gatewayConfig.gateway.execTimeoutMs, + leaseRequestTimeoutMs: gatewayConfig.gateway.leaseRequestTimeoutMs, + idGenerator: { + generate: (() => { + let next = 1; + return () => `${next++}`; + })(), + }, + leaseIndex, + routing: createRoutingPolicy("warm-then-free"), + views: workers, + }); const dispatcher = new GatewayDispatcher({ awaitReady: async () => {}, closeUplinksForToken: async (tokenId) => { closedUplinkTokens.push(tokenId); }, config: gatewayConfig, + coordinator, eventBus, health: () => "running", + leaseIndex, tokens, workers, }); - return { clock, closedUplinkTokens, dispatcher, eventBus, tokens, workers }; + return { + clock, + closedUplinkTokens, + coordinator, + directory, + dispatcher, + eventBus, + leaseIndex, + tokens, + workers, + }; } function session(overrides: Partial = {}): DispatchSession { @@ -225,40 +291,77 @@ describe("GatewayDispatcher", () => { // P-1 (third review round): the previous version of `#leaseList` compared a namespaced form // of the session's own principal to each lease's `ownerId` -- a comparison that was false by // construction (see `#leaseList`'s own comment) and so, in practice, indistinguishable from - // simply returning `[]`. This asserts the actual, current contract: a non-admin session sees - // no fleet leases at all, whatever its principal, until #118's own `FleetLeaseIndex` replaces - // this handler. - it("shows a non-admin session no fleet leases at all, regardless of its principal", async () => { + // simply returning `[]`. + // + // Round 6 review: this test's title used to claim a non-admin session sees "no fleet leases at + // all", which #118 -- this PR -- made false when it replaced the handler with `FleetLeaseIndex`: + // such a session now does see leases this gateway issued to it, as the third test below proves. + // What this one actually pins is the baseline the other two build on: a worker's *own local* + // lease is not a fleet lease and is never a candidate, whoever asks. The title says only that + // now (testing rule 1). + it("shows a non-admin session none of a worker's own local leases", async () => { const { dispatcher, workers } = harness(); workers.connected("wrk_1", undefined, undefined); - // `leaseFixture`'s ownerId ("agent-1") is a worker-local principal; this session's own - // principal is deliberately the exact same string, since a principal collision -- not just - // a mismatch -- is the case worth a session leaking a machine's own local lease. workers.refresh("wrk_1", { leases: [leaseFixture("lease_1", "dev_1")] }); + // The worker's lease is a worker-local one -- never indexed by this gateway (only + // `rebuildFromWorker`/an actual grant adds an entry) -- so a non-admin session holds none of + // it, exactly as an unrelated fleet client should. await expect( - dispatcher.dispatch("lease.list", {}, session({ principal: "agent-1", role: "agent" })), + dispatcher.dispatch("lease.list", {}, session({ principal: "someone", role: "agent" })), ).resolves.toEqual({ leases: [] }); }); - // The behavior this round's fix actually changes: the deleted comparison, when fed the one - // input that made it succeed (a lease whose `ownerId` is that session's principal namespaced - // with the gateway's own `gw::` prefix -- the shape a real gateway-issued lease - // would carry once #118 lands, but nothing in this PR ever produces), used to return that - // lease to a non-admin session. This asserts the deliberate regression: `#leaseList` no - // longer has any code path that returns a lease to a non-admin session, matching or not, - // until #118 replaces it with `FleetLeaseIndex`'s real filter. - it("does not resurrect visibility through a namespaced ownerId nothing in this PR can produce", async () => { + // #118 replaced the P2 namespace-comparison this test used to pin with the lease index: a + // non-admin session's `lease.list` now iterates `leaseIndex.all()` rather than scanning every + // worker's raw leases, so a worker's own local lease is never even a candidate -- it cannot + // "match" a session by coincidence of principal spelling, because it is never looked up by + // principal at all. Still worth its own test: this is the case that would tell a correct + // implementation apart from a naive "compare raw principals" one. + it("does not let a gateway session's raw principal match a worker's own local lease owner of the same name", async () => { const { dispatcher, workers } = harness(); workers.connected("wrk_1", undefined, undefined); - const lease = { ...leaseFixture("lease_1", "dev_1"), ownerId: "gw:instance-1:agent-1" }; - workers.refresh("wrk_1", { leases: [lease] }); + // `leaseFixture`'s ownerId ("agent-1") is an un-namespaced *local* principal -- exactly what + // a worker's own agent looks like, and never added to this gateway's lease index. + workers.refresh("wrk_1", { leases: [leaseFixture("lease_1", "dev_1")] }); await expect( dispatcher.dispatch("lease.list", {}, session({ principal: "agent-1", role: "agent" })), ).resolves.toEqual({ leases: [] }); }); + // The positive match: a lease this gateway issued, rebuilt purely from a worker's reported + // view (§30's reconnect path -- see `fleet-coordinator.test.ts` for the admission-path + // equivalent), is rewritten to its gateway id and fleet-level requester and is visible to the + // owner that requested it (ADR §27a: `ownerId` is the real principal, round-tripped -- not + // namespaced, unlike `requesterId`). + it("sees a gateway-issued lease rebuilt from a worker's view, rewritten to its gateway id", async () => { + const { dispatcher, workers } = harness(); + workers.connected("wrk_1", "mac-mini-1", undefined); + const lease = { + ...leaseFixture("lease_1", "dev_1"), + ownerId: "agent-1", + requesterId: `${GATEWAY_REQUESTER_PREFIX}agent-1`, + }; + // `workers.refresh` alone is enough: `FleetLeaseCoordinator` is subscribed to this same + // registry's `onViewsChanged` and rebuilds its lease index from every view it sees, exactly + // as it would from a real `WorkerLink`'s refresh -- nothing in this test drives the index by + // hand. + workers.refresh("wrk_1", { leases: [lease] }); + + await expect( + dispatcher.dispatch("lease.list", {}, session({ principal: "agent-1", role: "agent" })), + ).resolves.toEqual({ + leases: [ + expect.objectContaining({ + id: "wrk_1.lease_1", + requesterId: "agent-1", + worker: { id: "wrk_1", label: "mac-mini-1" }, + }), + ], + }); + }); + it("replays and subscribes to its own bus, which carries the fleet's events", async () => { const { dispatcher, eventBus } = harness(); eventBus.emit("lease.granted", { deviceId: "dev_1", leaseId: "l1", requester: "a" }, "worker"); @@ -326,20 +429,257 @@ describe("GatewayDispatcher", () => { }); }, ); + }); + + describe("lease lifecycle and device.exec (#118)", () => { + it("forwards lease.request through the fleet coordinator and answers UNKNOWN_LEASE for renew/release/exec against an id it never issued", async () => { + const { dispatcher } = harness(); - it.each([ - ["lease.request", { model: "iPhone 17", platform: "ios" }], - ["lease.renew", { leaseId: "lease_1" }], - ["lease.release", { leaseId: "lease_1" }], - ["lease.cancel", {}], - ["lease.release-all", {}], - ["device.exec", { leaseId: "lease_1", tool: "adb", args: ["devices"] }], - ] as const)("%s waits for fleet routing", async (operation, input) => { + // No worker connected at all: a `noWait` request has nowhere to go and is refused + // immediately, rather than the pre-#118 permanent `UNSUPPORTED_IN_GATEWAY_MODE`. A plain + // `DispatchError("NO_CAPACITY", ...)` (H9, round 2 review) -- no gateway-specific error + // class for `daemon/error-code.ts` to import and recognize. + await expect( + dispatcher.dispatch( + "lease.request", + { model: "iPhone 17", noWait: true, platform: "ios" }, + session({ role: "agent" }), + ), + ).rejects.toMatchObject({ code: "NO_CAPACITY" }); + + for (const [operation, input] of [ + ["lease.renew", { leaseId: "wrk_ghost.lease_1" }], + ["lease.release", { leaseId: "wrk_ghost.lease_1" }], + ["device.exec", { args: [], leaseId: "wrk_ghost.lease_1", tool: "adb" }], + ] as const) { + await expect( + dispatcher.dispatch(operation, input, session({ role: "agent" })), + ).rejects.toMatchObject({ code: "UNKNOWN_LEASE" }); + } + }); + + it("answers not-found for lease.cancel and an empty result for lease.release-all with nothing queued or leased", async () => { const { dispatcher } = harness(); await expect( - dispatcher.dispatch(operation as OperationName, input, session()), - ).rejects.toMatchObject({ code: "UNSUPPORTED_IN_GATEWAY_MODE", details: { operation } }); + dispatcher.dispatch("lease.cancel", {}, session({ role: "agent" })), + ).resolves.toEqual({ result: "not-found" }); + await expect(dispatcher.dispatch("lease.release-all", {}, session())).resolves.toEqual({ + leaseIds: [], + }); + }); + + // ADR §27a's whole point: the owner a rebuilt lease authorizes against has to be the real + // principal the worker round-tripped back, not this gateway's own uplink principal -- and it + // has to work on an index built purely by `rebuildFromWorker` (a reconnect), never through + // `coordinator.request` in this process. This is the one place a naive "derive ownerId from + // the connection" implementation and a correct one visibly disagree. + it("authorizes lease.renew for the original requester and forbids everyone else, on a lease rebuilt after reconnect", async () => { + const { dispatcher, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_1", client); + workers.connected("wrk_1", undefined, undefined); + workers.refresh("wrk_1", { + leases: [ + { + ...leaseFixture("lease_1", "dev_1"), + ownerId: "alice-principal", + requesterId: `${GATEWAY_REQUESTER_PREFIX}alice`, + }, + ], + }); + const gatewayLeaseId = "wrk_1.lease_1"; + client.renewLeaseQueue.push({ + kind: "ok", + record: { + ...leaseFixture("lease_1", "dev_1"), + ownerId: "alice-principal", + ttlMs: 1_800_000, + }, + }); + + await expect( + dispatcher.dispatch( + "lease.renew", + { leaseId: gatewayLeaseId }, + session({ principal: "alice-principal", role: "agent" }), + ), + ).resolves.toMatchObject({ id: gatewayLeaseId, requesterId: "alice" }); + + await expect( + dispatcher.dispatch( + "lease.renew", + { leaseId: gatewayLeaseId }, + session({ principal: "mallory-principal", role: "agent" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); + + it("forwards device.exec to the worker that holds the lease, gated on the caller owning it", async () => { + const { coordinator, 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, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "on-request" }, + }); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + const grant = await coordinator.request( + { model: "iPhone 17", platform: "ios" }, + { allowDownload: false, noWait: true, ownerId: "agent-1", requesterId: "agent-1" }, + ); + client.execQueue.push({ exitCode: 3, kind: "ok" }); + + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, + session({ principal: "agent-1", role: "agent" }), + ), + ).resolves.toEqual({ exitCode: 3 }); + + await expect( + dispatcher.dispatch( + "device.exec", + { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, + session({ principal: "someone-else", role: "agent" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); + + // C3 (round 3 review): exercises the gateway's *real* dispatcher end to end + // (`GatewayDispatcher` -> `FleetLeaseCoordinator#exec` -> a scripted worker), unlike + // `http/app.test.ts`'s own "opens the stream when the process starts" test, which drives + // `call.session.onStarted?.()` by hand and so cannot notice a dispatcher that stops calling + // it for a genuinely silent, long-running command. + it("calls onStarted for a silent device.exec from the worker's own started push, with no output and no answer (ADR §19a/§19b/§19e)", async () => { + const { coordinator, 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, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "on-request" }, + }); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const grant = await coordinator.request( + { model: "iPhone 17", platform: "ios" }, + { allowDownload: false, noWait: true, ownerId: "agent-1", requesterId: "agent-1" }, + ); + // §19b's own worked example: `simctl install ` never writes anything while it runs, + // and the worker here never answers at all -- but it does say the process exists, which is + // the fact a transport needs to commit its 200. No clock is advanced below: this asserts + // the relay, not a timer. + client.execQueue.push({ kind: "hang", started: true }); + + let started = false; + void dispatcher.dispatch( + "device.exec", + { args: ["install", "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/path/to.app"], leaseId: grant.lease.id, tool: "simctl" }, + session({ + onStarted: () => { + started = true; + }, + principal: "agent-1", + role: "agent", + }), + ); + await Promise.resolve(); + + expect(started).toBe(true); + }); + + it("lease.request: rejects a non-admin session naming owner with FORBIDDEN, never silently ignoring it (ADR §27a, H7)", 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, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "on-request" }, + }); + // Round 6 review: this harness used to connect `wrk_1` to the registry without adding a + // client for it, so removing the gate under test made the request route to an unreachable + // target, get re-queued by `#staleView`, and fail the test by *timing out* -- an outcome a + // gateway with no gate at all produces just as well. Its H3 sibling below already had the + // fix and said why; this one had been left behind. A worker able and willing to grant, + // plus `noWait`, means an ungated `owner` is caught by the lease actually being issued + // (testing rule 2: fail on a named assertion, not a schedule). + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + await expect( + dispatcher.dispatch( + "lease.request", + { model: "iPhone 17", noWait: true, owner: "someone-else", platform: "ios" }, + session({ principal: "agent-1", role: "agent" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); + + // H3 (round 3 review): §27a's gate here used to be `role !== "admin"`, admitting any HTTP + // `operator` bearer token connected directly to this gateway -- the same over-wide check + // `daemon/dispatcher.ts`'s own `#leaseRequest` shared. `isGatewayUplink` is narrower: it is + // stamped only on a *worker's* connection to its own configured gateway + // (`DaemonServer#acceptUplink`), and nothing forwards into a gateway's own front door the + // way a gateway forwards into a worker -- there is no "gateway of gateways" in ADR 0005. So + // no session this handler is ever called with can carry it, and `owner` is unconditionally + // `FORBIDDEN` here now, admin included: this test pins that a plain admin session (still + // `role: "admin"`, still what an operator token maps to) is refused exactly like an agent's. + it("lease.request: rejects a plain admin session (not the gateway's uplink) naming owner with FORBIDDEN -- no session ever reaching this handler is (ADR §27a, H3)", 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, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "on-request" }, + }); + // A worker able and willing to grant it -- so a gate that let this session's `owner` + // through would be caught by the lease actually being issued, not by an unrelated + // `NO_CAPACITY`/timeout that would pass just as well with no gate at all. + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + await expect( + dispatcher.dispatch( + "lease.request", + { model: "iPhone 17", noWait: true, owner: "agent-7", platform: "ios" }, + session({ principal: "operator-1", role: "admin" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); + + it("lease.request: forwards owner as `ownerId` end to end when the session is the gateway's own uplink (ADR §27a, H3) -- exercising the same field the worker's own dispatcher gates, on this dispatcher's shared handler shape", async () => { + const { directory, dispatcher, leaseIndex, 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, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "on-request" }, + }); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + const grant = await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17", noWait: true, owner: "agent-7", platform: "ios" }, + session({ isGatewayUplink: true, principal: "gw:instance-1", role: "admin" }), + ); + + const gatewayLeaseId = (grant as { lease: { id: string } }).lease.id; + expect((grant as { lease: { ownerId: string } }).lease.ownerId).toBe("agent-7"); + expect(leaseIndex.ownerId(gatewayLeaseId)).toBe("agent-7"); }); }); @@ -352,7 +692,9 @@ describe("GatewayDispatcher", () => { "driver.passthrough": { args: [], tool: "adb" }, "lease.release": { leaseId: "lease_1" }, "lease.renew": { leaseId: "lease_1" }, - "lease.request": { model: "iPhone 17", platform: "ios" }, + // `noWait: true` matters here: with no worker connected, an ordinary "wait" request would + // sit in the fleet queue forever and hang this test rather than answer promptly. + "lease.request": { model: "iPhone 17", noWait: true, platform: "ios" }, "token.create": { role: "agent" }, "token.revoke": { id: "tok_1" }, "worker.drain": { workerId: "wrk_1" }, diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 086792a40..9f712a266 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -9,25 +9,23 @@ * 1. **Answered from the fleet**: `status.get` and `catalog.get` (aggregated, §20/§21), * `worker.*` (§8/§23), `events.*` (the gateway's own bus, which carries every worker's * republished events, §22), `config.get` (the gateway's own config, §34), `token.*` (a - * gateway mints its own credentials, §24). + * gateway mints its own credentials, §24), and -- as of #118 -- the lease *lifecycle* + * (`lease.request`/`renew`/`release`/`cancel`/`release-all`) and `device.exec`, all forwarded + * through `FleetLeaseCoordinator`. * 2. **Refused permanently** (`unsupportedByDesign`): `nuke.run`, `cleanup.run`, `doctor.run` * and `driver.passthrough` (§34) -- operations that act on one machine's devices as a whole. - * 3. **Refused until #118** (`unsupportedUntilRouting`): the lease *lifecycle* -- - * `lease.request`, `renew`, `release`, `cancel`, `release-all` -- and `device.exec`, which - * a gateway proxies to the worker that owns the device (§19b). The fleet queue, routing and - * forwarding are that PR's; this one deliberately makes the fleet visible before it is - * routable. + * 3. *(Formerly "refused until #118" -- the fleet queue, routing, and lease/exec forwarding this + * module now implements. Nothing is left in this population; the type below still enforces + * that every operation but `daemon.stop` is accounted for.)* * - * The read-only members of the lease family -- `lease.list` and `list.get` -- are in the first - * population, not the third: they are the fleet made *visible*, which is this PR's whole point, - * and answering them needs nothing but the views. They read what workers report rather than - * forwarding anything, so #118 replaces their implementation (with its own lease index) without - * changing what a caller sees. + * `lease.list` and `list.get` read what the fleet's views and lease index report rather than + * forwarding anything -- they are the fleet made *visible*, and #118's only change to them is + * rewriting a gateway-issued lease's id/requester to its fleet-facing form (`FleetLeaseIndex#project`) + * so a caller can round-trip it into `lease.renew`; a worker's own local lease is untouched. * - * The last two answer `UNSUPPORTED_IN_GATEWAY_MODE`; `details.operation` and the message say - * which population an answer came from. The table is typed total over the contract minus - * `daemon.stop`, so a newly declared operation is a compile error here until someone decides - * which of the three it belongs to. + * The one population that remains answers `UNSUPPORTED_IN_GATEWAY_MODE`; `details.operation` and + * the message say why. The table is typed total over the contract minus `daemon.stop`, so a + * newly declared operation is a compile error here until someone decides where it belongs. */ import type { z } from "zod"; @@ -42,6 +40,8 @@ import { import type { Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; import { aggregateCatalog, aggregateStatus } from "./aggregate.js"; +import type { FleetLeaseCoordinator } from "./fleet-coordinator.js"; +import type { FleetLeaseIndex } from "./lease-index.js"; import type { WorkerRegistry } from "./worker-registry.js"; type Handler = ( @@ -99,6 +99,30 @@ export interface GatewayDispatcherOptions { /** The gateway's own health, for `status.get`. */ readonly health: () => "starting" | "running" | "failed"; readonly awaitReady: () => Promise; + /** + * #118: admission, dispatch, and lease/exec forwarding. Every lease-lifecycle handler and + * `device.exec` below is a thin translation from contract input to a `coordinator` call; the + * two ownership lookups (`ownerId`, `leaseRequesterId`) and the pending-request lookup + * (`pendingRequestOwner`) it also exposes feed `dispatch()`'s `authorizeLookups` directly, the + * same shape a worker's own `Dispatcher` supplies from its registry and queue. + */ + readonly coordinator: Pick< + FleetLeaseCoordinator, + | "request" + | "cancelPending" + | "renew" + | "release" + | "releaseAll" + | "exec" + | "queueDepth" + | "ownerId" + | "leaseRequesterId" + | "pendingRequestOwner" + >; + /** #118: read-only access for `lease.list`/`list.get`/`status.get`'s lease projection + * (`FleetLeaseIndex#project`/`#all`) -- kept separate from `coordinator` because this + * dispatcher only ever *reads* it, never mutates it. */ + readonly leaseIndex: Pick; } export class GatewayDispatcher { @@ -129,12 +153,12 @@ export class GatewayDispatcher { "doctor.run": unsupportedByDesign("doctor.run"), "driver.passthrough": unsupportedByDesign("driver.passthrough"), - "lease.request": unsupportedUntilRouting("lease.request"), - "lease.renew": unsupportedUntilRouting("lease.renew"), - "lease.release": unsupportedUntilRouting("lease.release"), - "lease.cancel": unsupportedUntilRouting("lease.cancel"), - "lease.release-all": unsupportedUntilRouting("lease.release-all"), - "device.exec": unsupportedUntilRouting("device.exec"), + "lease.request": this.#leaseRequest, + "lease.renew": this.#leaseRenew, + "lease.release": this.#leaseRelease, + "lease.cancel": this.#leaseCancel, + "lease.release-all": this.#leaseReleaseAll, + "device.exec": this.#deviceExec, // "daemon.stop" is absent for the same reason it is absent from the worker's table: the // transport intercepts it ahead of any dispatch (ADR 0003 §6's frozen exception). }; @@ -147,10 +171,14 @@ export class GatewayDispatcher { ): Promise> { return runDispatch(operation, rawInput, session, { handlers: this.#handlers, - // No `authorizeLookups`: the gateway holds no leases and no pending requests of its own - // in this PR, so both lookups answer `undefined`, which every `authorize` hook treats as - // authorized -- and every operation carrying one is refused here anyway. #118 supplies - // the real lookups along with the lease index they read. + // #118: `ownsLease`/`device.exec`'s own hook and `lease.cancel`'s resolve these against + // the fleet's own lease index and pending-request queue -- the same shape a worker's own + // `Dispatcher` supplies from its registry and queue, read through `coordinator` instead. + authorizeLookups: { + leaseRequesterId: (id) => this.options.coordinator.leaseRequesterId(id), + ownerId: (id) => this.options.coordinator.ownerId(id), + pendingRequestOwner: (id) => this.options.coordinator.pendingRequestOwner(id), + }, awaitReady: () => this.options.awaitReady(), onOutputMismatch: (operationName, issues) => { this.#logger.error("Operation output failed contract validation", { @@ -166,9 +194,9 @@ export class GatewayDispatcher { #statusGet: Handler<"status.get"> = () => aggregateStatus(this.options.workers.views(), { health: this.options.health(), - // ADR 0005 §20: the *gateway's* queue depth. It has no queue until #118, and 0 is the - // honest answer for a queue that cannot hold anything -- not a placeholder. - queueDepth: 0, + // ADR 0005 §20: the gateway's own fleet queue depth. + queueDepth: this.options.coordinator.queueDepth, + leaseIndex: this.options.leaseIndex, }); #catalogGet: Handler<"catalog.get"> = (input) => @@ -226,26 +254,37 @@ export class GatewayDispatcher { }); /** - * Every lease the fleet's views report, each carrying its `workerId` (ADR 0005 §20), for an - * admin session. A non-admin session sees none of them. - * - * P-1 (third review round): P2's version of this handler compared a namespaced form of the - * session's own principal (`gatewayRequesterPrefix` + `session.principal`) against each - * lease's `ownerId` -- but on a worker, `ownerId` is the *raw*, un-namespaced local principal - * (`daemon/dispatcher.ts`'s own `lease.list`), and the gateway's own principal at `hello` is - * `gw:` with no `:` suffix (`GatewayService`). A string ending in - * `:` can therefore never equal `gw:`, so that comparison returned - * `[]` for every non-admin session *by construction* -- not "until #118", as its comment - * claimed -- and nothing exercised it except a test that hand-built an `ownerId` no code path - * actually produces. #118 replaces this handler outright with its own `FleetLeaseIndex`, - * filtered by `ownerId` for the real, routed case; this handler is deliberately left inert - * rather than growing a second, competing namespacing scheme #118 would then have to undo. - * Same observable behavior as before (`[]`), no comparison pretending to be live. + * ADR 0005 §14/§20: a non-admin session sees only the fleet leases *it* owns -- resolved + * through the lease index by `ownerId`, never by scanning every worker's raw leases and + * comparing `ownerId` to `session.principal` directly. That comparison would let an agent + * token on the gateway that happens to name itself the same as some worker's own local agent + * see that machine's local lease (`session.principal` is client-chosen and unverified, per + * `daemon/server.ts`'s `hello` handling) -- the index only ever holds leases this gateway + * itself issued, so it cannot produce that collision. An admin session sees the whole fleet, + * which is what `GET /v1/leases` is for. */ #leaseList: Handler<"lease.list"> = (_input, session) => ({ - leases: session.role === "admin" ? this.#fleetLeases() : [], + leases: + session.role === "admin" ? this.#fleetLeases() : this.#ownedFleetLeases(session.principal), }); + /** Every lease this gateway issued to `ownerId`, projected to its fleet-facing form. Looks up + * each entry's current record from the owning worker's view rather than caching one on the + * index itself, so a renewed TTL/`lastRenewedAt` is always current. An entry whose worker view + * (or the specific lease on it) is momentarily missing -- a race with a reconnect rebuild, or + * a worker that just disconnected -- is skipped rather than fabricated. */ + #ownedFleetLeases(ownerId: string) { + const leases = []; + for (const entry of this.options.leaseIndex.all()) { + if (entry.ownerId !== ownerId) continue; + const view = this.options.workers.view(entry.workerId); + const raw = view?.leases.find((lease) => lease.id === entry.workerLeaseId); + if (view === undefined || raw === undefined) continue; + leases.push(this.options.leaseIndex.project(raw, view.id, view.label)); + } + return leases; + } + /** * The admin inspection of the fleet. `devices` and `leases` are the aggregate with * `workerId`; `rules` is empty, because cleanup rules are a machine's own configuration and a @@ -266,10 +305,118 @@ export class GatewayDispatcher { } }; + /** Every lease every worker's view reports, each projected through the lease index -- rewritten + * to its gateway id/requester/`worker` for a lease this gateway issued (test: "lease.list + * rewrites ids only for gateway-issued leases"), passed through with only `workerId` added for + * a worker's own local lease. Admin-only visibility (`list.get`, and `#leaseList` for an admin + * session): a non-admin session never reaches this, see `#ownedFleetLeases` above. */ #fleetLeases() { return this.options.workers .views() - .flatMap((view) => view.leases.map((lease) => ({ ...lease, workerId: view.id }))); + .flatMap((view) => + view.leases.map((lease) => this.options.leaseIndex.project(lease, view.id, view.label)), + ); + } + + /** + * ADR 0005 §15: "the gateway's `lease.defaultTtlMs` fills in a request that names no `ttlMs` + * and its `lease.maxTtlMs` caps what its own clients may ask for, both before anything is + * dispatched". `owner` (§27a, narrowed round 3 review H3) is read only from `session. + * isGatewayUplink` -- never merely `role === "admin"`, which HTTP's `operator` token also maps + * onto (`dispatcher-session.ts`), the same over-wide gate `daemon/dispatcher.ts`'s own + * `#leaseRequest` used to share with this one. + * + * Unlike the worker, nothing ever forwards *into* a gateway's own front door the way this + * gateway forwards into a worker -- there is no "gateway of gateways" in ADR 0005, so no + * session reaching this handler is ever the uplink `isGatewayUplink` identifies (that flag is + * stamped only on a worker's own `DaemonServer#acceptUplink` connection, never on a gateway's). + * The practical effect is what the user's decision asked for stated plainly: `owner` is + * unconditionally `FORBIDDEN` here, admin included -- a fleet client's own principal + * (`session.principal`, the default below) is already the correct, un-spoofable owner for + * anything this gateway itself issues. + */ + // fallow-ignore-next-line complexity -- one transaction, moved verbatim from the worker's own #leaseRequest shape. + #leaseRequest: Handler<"lease.request"> = async (input, session) => { + this.#requireTtlWithinCap(input.ttlMs); + if (input.owner !== undefined && session.isGatewayUplink !== true) { + throw new DispatchError( + "FORBIDDEN", + "Only the gateway's own uplink session may set lease.request's `owner` field", + ); + } + return this.options.coordinator.request( + { + model: input.model, + platform: input.platform, + ...(input.osVersion === undefined ? {} : { osVersion: input.osVersion }), + ...(input.full ? { full: true } : {}), + }, + { + allowDownload: input.allowDownload ?? false, + noWait: input.noWait ?? false, + ownerId: input.owner ?? session.principal, + requesterId: input.requesterId ?? session.principal, + ...(session.onProgress === undefined ? {} : { onProgress: session.onProgress }), + ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }), + // Always explicit past this point (§15): a request that named none is filled in here, + // before dispatch, rather than left for whichever worker happens to grant it to default + // on its own -- which could differ fleet to fleet. + ttlMs: input.ttlMs ?? this.options.config.lease.defaultTtlMs, + }, + ); + }; + + #leaseCancel: Handler<"lease.cancel"> = async (input, session) => { + const requesterId = input.requesterId ?? session.principal; + const result = await this.options.coordinator.cancelPending(requesterId); + return { result }; + }; + + /** ADR §15's cap applies here too -- "what its own clients may ask for" is any `ttlMs` a + * fleet client names, renew included, not only the initial request. */ + #leaseRenew: Handler<"lease.renew"> = async (input) => { + this.#requireTtlWithinCap(input.ttlMs); + return this.options.coordinator.renew(input.leaseId, input.ttlMs); + }; + + #leaseRelease: Handler<"lease.release"> = async (input) => { + await this.options.coordinator.release(input.leaseId); + return { leaseId: input.leaseId }; + }; + + #leaseReleaseAll: Handler<"lease.release-all"> = async () => { + const leaseIds = await this.options.coordinator.releaseAll(); + return { leaseIds: [...leaseIds] }; + }; + + /** ADR §19b: proxied to the worker that owns the device, over the same uplink as everything + * else. Ownership was already checked once, at the gateway (this operation's own `authorize` + * hook, via `leaseRequesterId`/`ownerId` above) -- the worker checks it again, against the + * namespaced requester `FleetLeaseCoordinator#exec` forwards (§19a'). */ + #deviceExec: Handler<"device.exec"> = async (input, session) => + this.options.coordinator.exec( + { + leaseId: input.leaseId, + tool: input.tool, + args: input.args, + ...(input.stdin === undefined ? {} : { stdin: input.stdin }), + }, + session, + ); + + /** + * ADR §15/§4's cap, applied identically to a request and a renew. Lives here rather than in + * the contract schema for the same reason the worker's own copy does: `lease.maxTtlMs` is a + * daemon config value the contract module cannot see. + */ + #requireTtlWithinCap(ttlMs: number | undefined): void { + const maxTtlMs = this.options.config.lease.maxTtlMs; + if (ttlMs !== undefined && ttlMs > maxTtlMs) { + throw new DispatchError( + "BAD_REQUEST", + `ttlMs ${String(ttlMs)} exceeds lease.maxTtlMs (${String(maxTtlMs)})`, + ); + } } #requireTokens(): GatewayTokenStore { @@ -290,14 +437,3 @@ function unsupportedByDesign(operation: OperationName): ErasedHandler { ); }; } - -/** Answered once #118 gives the gateway a queue, a routing policy, and lease forwarding. */ -function unsupportedUntilRouting(operation: OperationName): ErasedHandler { - return () => { - throw new DispatchError( - "UNSUPPORTED_IN_GATEWAY_MODE", - `${operation} is not available on a gateway yet; fleet routing implements it`, - { operation }, - ); - }; -} diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts new file mode 100644 index 000000000..74b330d9c --- /dev/null +++ b/src/gateway/fleet-coordinator.test.ts @@ -0,0 +1,1597 @@ +import { describe, expect, it } from "vitest"; + +import { EventBus } from "../bus/index.js"; +import { SimlockError } from "../contract/index.js"; +import { DispatchError } from "../daemon/dispatch.js"; +import { FakeClock, type Logger } from "../ports/index.js"; +import type { WorkerDirectory, WorkerDispatchTarget } from "./fleet-ports.js"; +import { FleetLeaseCoordinator } from "./fleet-coordinator.js"; +import { FleetLeaseIndex } from "./lease-index.js"; +import { RequesterAlreadyLeasedError } from "./queue.js"; +import { createRoutingPolicy, type RoutingPolicy } from "./routing.js"; +import { + catalogFixture, + deviceFixture, + grantFixture, + noCapacityError, + ScriptedWorkerClient, + statusFixture, +} from "./test-support.js"; +import { WorkerRegistry } from "./worker-registry.js"; + +const GATEWAY_PREFIX = "gw:instance-1:"; + +/** A `WorkerDirectory` a test populates by hand: one `ScriptedWorkerClient` per worker id, with + * `reachable` and the `refresh()` call count independently controllable. */ +class FakeDirectory implements WorkerDirectory { + readonly clients = new Map(); + readonly unreachable = new Set(); + /** C1 (round 2 review): a worker id in here answers `reachable: true` but `client()` + * `undefined` -- the real window `WorkerLink#reachable`/`#client` can disagree in, between a + * reconnecting link's `#closed` clearing and its own handshake finishing (`#client` is not + * assigned until `start()` completes). Distinct from `unreachable` above, which models + * `reachable: false` instead -- a different code path in `#attempt`/`#forwardToWorker` that no + * test previously exercised the *first* of the two ways. */ + readonly reachableButNoClient = new Set(); + readonly refreshCalls: string[] = []; + + add(workerId: string, client: ScriptedWorkerClient): void { + this.clients.set(workerId, client); + } + + target(workerId: string): WorkerDispatchTarget | undefined { + const client = this.clients.get(workerId); + if (client === undefined) return undefined; + const reachable = !this.unreachable.has(workerId); + const hasClient = reachable && !this.reachableButNoClient.has(workerId); + return { + client: () => (hasClient ? client.asClient() : undefined), + reachable, + refresh: async () => { + this.refreshCalls.push(workerId); + }, + workerId, + }; + } +} + +/** Records every `warn` call -- for H6's own test, which asserts a mismatched ownerId echo is + * logged rather than silently swallowed. */ +class RecordingLogger implements Logger { + readonly warnings: Array<{ message: string; fields?: Record }> = []; + + debug(): void {} + info(): void {} + warn(message: string, fields?: Record): void { + this.warnings.push(fields === undefined ? { message } : { fields, message }); + } + error(): void {} + child(): Logger { + return this; + } +} + +function harness( + overrides: { + readonly execTimeoutMs?: number; + readonly leaseRequestTimeoutMs?: number; + readonly logger?: Logger; + /** Built with the registry so a stub can change the views from inside the dispatch walk -- + * the one way to reach `#dispatch`'s re-entrancy guard. Defaults to the real policy. */ + readonly routing?: (workers: WorkerRegistry) => RoutingPolicy; + } = {}, +) { + const clock = new FakeClock(1_000); + const eventBus = new EventBus(clock); + const workers = new WorkerRegistry({ + clock, + eventBus, + // ADR §15: the gateway's own cap, which `WorkerRegistry` warns against when a worker + // reports a lower one. Nothing in this file exercises that warning -- the value only has + // to exist, and is set high enough that no fixture here trips it. + leaseMaxTtlMs: 4 * 60 * 60_000, + retentionMs: 24 * 60 * 60_000, + }); + const directory = new FakeDirectory(); + const leaseIndex = new FleetLeaseIndex(GATEWAY_PREFIX); + const coordinator = new FleetLeaseCoordinator({ + clock, + directory, + eventBus, + // Deliberately large by default -- P5's own test overrides this to something the FakeClock + // can advance past inside the test, without every other test in this file needing to know + // gateway.execTimeoutMs exists. + execTimeoutMs: overrides.execTimeoutMs ?? 11 * 60_000, + idGenerator: { + generate: (() => { + let next = 1; + return () => `${next++}`; + })(), + }, + leaseIndex, + // Deliberately large by default -- P2's own test overrides this the same way P5 does for + // execTimeoutMs above. + leaseRequestTimeoutMs: overrides.leaseRequestTimeoutMs ?? 5 * 60_000, + ...(overrides.logger === undefined ? {} : { logger: overrides.logger }), + routing: overrides.routing?.(workers) ?? createRoutingPolicy("warm-then-free"), + views: workers, + }); + return { clock, coordinator, directory, eventBus, leaseIndex, workers }; +} + +/** Connects a worker with a catalog, capacity, and devices a test can override -- everything + * defaults to "eligible for an iOS iPhone 17 request with free capacity". */ +function connectWorker( + workers: WorkerRegistry, + workerId: string, + overrides: { + readonly label?: string; + readonly models?: readonly string[]; + readonly platform?: "ios" | "android"; + readonly capacity?: ReturnType["capacity"]; + readonly devices?: ReturnType[]; + } = {}, +): void { + workers.connected(workerId, overrides.label, "0.3.0"); + workers.refresh(workerId, { + capacity: overrides.capacity ?? statusFixture().capacity, + catalog: catalogFixture([ + { + models: [...(overrides.models ?? ["iPhone 17"])], + platform: overrides.platform ?? "ios", + runtimes: ["26.0"], + }, + ]).platforms, + devices: overrides.devices ?? [], + downloads: { policy: "on-request" }, + health: "running", + leases: [], + queueDepth: 0, + }); +} + +/** Flushes enough microtasks for `SerializedDecision.run`'s chain (admission) and a fire-and- + * forget dispatch attempt's own synchronous-until-the-RPC portion to have run, without waiting on + * a real timer -- everything in this module is driven by `FakeClock` and in-memory promises, so + * there is nothing a real clock tick would advance that this does not already cover. */ +async function tick(times = 8): Promise { + for (let iteration = 0; iteration < times; iteration += 1) await Promise.resolve(); +} + +const REQUEST = { model: "iPhone 17", osVersion: "26.0", platform: "ios" as const }; + +function requestOptions(overrides: Partial[1]> = {}) { + return { + allowDownload: false, + noWait: false, + ownerId: "agent-1", + requesterId: "agent-1", + ...overrides, + }; +} + +describe("FleetLeaseCoordinator dispatch", () => { + it("grants a queued request from whichever worker frees first -- never dispatching to the one routing did not prefer", async () => { + const { coordinator, directory, workers } = harness(); + const clientA = new ScriptedWorkerClient(); + const clientB = new ScriptedWorkerClient(); + directory.add("wrk_a", clientA); + directory.add("wrk_b", clientB); + // Both start at zero free capacity, so the first look finds nobody and the request waits. + // Worker A offers *more* running capacity than B -- if both had free room, routing would + // prefer A (more free capacity wins the tie-break). + const noFree = { ...statusFixture().capacity.android, maxRunning: 0, running: 0 }; + connectWorker(workers, "wrk_a", { + capacity: { ...statusFixture().capacity, ios: { ...noFree, maxRunning: 5, running: 5 } }, + }); + connectWorker(workers, "wrk_b", { + capacity: { ...statusFixture().capacity, ios: noFree }, + }); + + const grantPromise = coordinator.request(REQUEST, requestOptions()); + await tick(); + expect(coordinator.queueDepth).toBe(1); + + // Worker B frees up (A stays saturated) -- the pass-over that grants it. + clientB.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + workers.refresh("wrk_b", { + capacity: { ...statusFixture().capacity, ios: { ...noFree, maxRunning: 5, running: 0 } }, + }); + + const grant = await grantPromise; + expect(grant.lease.worker?.id).toBe("wrk_b"); + expect(clientA.calls.filter((call) => call.startsWith("lease.request"))).toEqual([]); + expect(clientB.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + }); + + it("issues exactly one lease.request for a waiter still in flight, even when another worker's view changes mid-flight", async () => { + const { coordinator, directory, workers } = harness(); + const clientA = new ScriptedWorkerClient(); + const clientB = new ScriptedWorkerClient(); + directory.add("wrk_a", clientA); + directory.add("wrk_b", clientB); + // Worker A never answers -- the attempt this waiter is dispatched to stays in flight. + clientA.requestLeaseQueue.push({ kind: "hang" }); + + // No worker connected yet: admission's own first look finds nobody, so this waiter genuinely + // enters the queue (`queue.list()`) rather than settling on the fast admission-time path -- + // exactly the shape a *second* dispatch pass (triggered below) would otherwise re-scan. + void coordinator.request(REQUEST, requestOptions()); + await tick(); + expect(coordinator.queueDepth).toBe(1); + + connectWorker(workers, "wrk_a"); + await tick(); + expect(clientA.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + + // Worker B connects (also eligible for this request) *while A's attempt is still hanging* -- + // with strictly *more* free capacity than A, so routing would prefer B outright on a second + // look. A dispatch loop that only checks `waiter.state !== "queued"` (and one that never + // left the waiter `processing` in the first place, i.e. `#beginAttempt` calling + // `queue.markProcessing` before the RPC starts) would pick the same still-visible waiter up + // again here and send it to B. Round 2 review (C2): this test alone proves the state check + // is what suppresses the second dispatch, not a second guard beside it -- reverting just + // `queue.markProcessing(waiter)` in `#beginAttempt` (leaving the state check in `#dispatch` + // untouched) makes this assertion fail. + connectWorker(workers, "wrk_b", { + capacity: { + ...statusFixture().capacity, + ios: { ...statusFixture().capacity.ios, maxRunning: 10 }, + }, + }); + await tick(); + + expect(clientB.calls.filter((call) => call.startsWith("lease.request"))).toEqual([]); + }); + + it("dispatches at most one queued waiter per worker per pass, rather than sending every queued waiter at a single over-reporting worker at once (H6, round 3 review)", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + // Exactly one grant scripted -- every other forwarded lease.request answers + // `requestLeaseDefault`'s own NO_CAPACITY, modelling a worker whose reported free capacity + // (two full slots below) does not match what it can actually grant right now. + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + // Three requests queue up before any worker is connected -- all genuinely `queued`, not + // settled at admission. + const p1 = coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-1", requesterId: "agent-1" }), + ); + const p2 = coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-2", requesterId: "agent-2" }), + ); + const p3 = coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-3", requesterId: "agent-3" }), + ); + await tick(); + expect(coordinator.queueDepth).toBe(3); + + // `connectWorker`'s default capacity reports two free iOS slots -- on paper, room for two of + // the three queued waiters above. Without the per-pass cap, `#dispatch`'s single pass would + // run `routing.select` against this same unchanged view for every one of the three, pick + // worker A for every one of them, and fire three concurrent `lease.request`s in this one pass. + connectWorker(workers, "wrk_a"); + await tick(); + + // Capped at one dispatch *per pass* -- but C1 (round 3 review) guarantees a fresh pass the + // moment p1's own attempt settles, so p2 gets its own look right behind it (in this same + // tick), rather than being stranded until "the next real view change" this test used to have + // to wait forever for. p2's attempt still reads the same stale view (routing has no way to + // know p1 already used the worker's one real slot) and is refused NO_CAPACITY in turn -- + // exactly the self-limiting RPC storm the module doc describes, not a second bug. + const leaseRequests = client.calls.filter((call) => call.startsWith("lease.request")); + expect(leaseRequests).toHaveLength(2); + expect(leaseRequests[1]).toContain("agent-2"); + + await expect(p1).resolves.toBeDefined(); + // p2's own attempt above already failed and re-queued it -- it is genuinely `queued` again, + // not stuck `processing`. p3 was passed over by that *same* pass (only one worker, already + // claimed for it once p2 claimed it) and is waiting for its own turn next -- neither granted + // nor rejected, and never even attempted yet. + const outcome = await Promise.race([ + Promise.allSettled([p2, p3]).then(() => "settled" as const), + tick(6).then(() => "still-pending" as const), + ]); + expect(outcome).toBe("still-pending"); + expect(coordinator.queueDepth).toBe(2); + // p2's own stale-view retry really ran the ordinary NO_CAPACITY path (refreshing the + // worker's view), not merely stayed queued from before. + expect(directory.refreshCalls).toEqual(["wrk_a"]); + }); + + it("gives a waiter passed over by the per-pass cap a guaranteed next look once the claiming attempt settles terminally, even when that failure produces no worker-side event at all (C1, round 3 review)", async () => { + // The finding's own reproduction: a terminal failure other than an immediate NO_CAPACITY + // (WORKER_UNREACHABLE here, via `leaseRequestTimeoutMs`) hits `#attempt`'s `queue.reject` + // branch directly -- no `refresh()`, no worker event, nothing that `#staleView`'s own + // self-heal depends on. Before this fix, nothing else ever scheduled another `#dispatch` + // pass, so a waiter passed over in the same pass (H6's per-worker-per-pass cap) stalled + // forever, reachable only by the unrelated 30s worker-refresh tick. + const { clock, coordinator, directory, workers } = harness({ leaseRequestTimeoutMs: 5_000 }); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + // w1's own forwarded RPC never answers at all. + client.requestLeaseQueue.push({ kind: "hang" }); + // w2's own eventual attempt, once it gets its turn. + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + const w1 = coordinator + .request(REQUEST, requestOptions({ ownerId: "agent-1", requesterId: "agent-1" })) + .catch((error: unknown) => error); + const w2 = coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-2", requesterId: "agent-2" }), + ); + await tick(); + expect(coordinator.queueDepth).toBe(2); + + connectWorker(workers, "wrk_a"); + await tick(); + // H6's own per-pass cap: only w1 was attempted this pass, w2 passed over. + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + + // w1's RPC settles terminally with WORKER_UNREACHABLE, never an immediate NO_CAPACITY -- so + // `#staleView`'s own refresh-triggered self-heal never runs for it, and this test never + // triggers any worker-view change of its own either. + clock.advance(5_000); + const w1Error = await w1; + expect(w1Error).toBeInstanceOf(DispatchError); + expect((w1Error as DispatchError).code).toBe("WORKER_UNREACHABLE"); + + const outcome = await Promise.race([ + w2.then( + () => "resolved" as const, + () => "resolved" as const, + ), + tick(6).then(() => "still-pending" as const), + ]); + expect(outcome).toBe("resolved"); + const w2Grant = await w2; + expect(w2Grant.lease.worker?.id).toBe("wrk_a"); + // The self-heal here is `#attempt`'s own guaranteed next pass, not a worker-view refresh. + expect(directory.refreshCalls).toEqual([]); + }); + + it("re-dispatches a waiter whose attempt found a reachable-but-not-yet-connected target, instead of parking it forever", async () => { + // C1 (round 2 review): the routine trigger is a worker reconnect -- `GatewayService#accept` + // sets the new link in `#links` and calls `start()` before the handshake's `#client` is + // assigned, so `directory.target(id)` answers `reachable: true` with `client()` still + // `undefined` for a real window. `FakeDirectory#reachableButNoClient` reproduces exactly + // that window without a real `WorkerLink`. + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + directory.reachableButNoClient.add("wrk_a"); + + const grantPromise = coordinator.request(REQUEST, requestOptions()); + await tick(); + + // The attempt found no client to call at all -- nothing was ever sent to the worker, and the + // waiter is back in the queue, not stuck `processing`. + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toEqual([]); + expect(coordinator.queueDepth).toBe(1); + + // The handshake finishes and a later view change re-runs dispatch, exactly as a real + // `WorkerLink#start()` completing (or any subsequent refresh) would trigger. On the pre-fix + // code this waiter is invisible to `#dispatch` forever from here on: its own leaked + // dispatch-target mark keeps failing `#dispatch`'s guard even though its queue state is + // genuinely `queued` again. + directory.reachableButNoClient.delete("wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + workers.refresh("wrk_a", {}); // any refresh re-runs dispatch, exactly as a real one would + + const grant = await grantPromise; + expect(grant.lease.worker?.id).toBe("wrk_a"); + expect(coordinator.queueDepth).toBe(0); + }); + + it("leaves a request queued after a stale-view NO_CAPACITY even when the caller asked noWait: true, and refreshes that worker's view", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ error: noCapacityError(), kind: "error" }); + + const grantPromise = coordinator.request(REQUEST, requestOptions({ noWait: true })); + let settled = false; + void grantPromise.then( + () => { + settled = true; + }, + () => { + settled = true; + }, + ); + + await tick(); + + expect(settled).toBe(false); + expect(coordinator.queueDepth).toBe(1); + expect(directory.refreshCalls).toEqual(["wrk_a"]); + + // The refreshed view now has capacity, and this time the worker grants it. + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + workers.refresh("wrk_a", {}); // any refresh re-runs dispatch, exactly as a real one would + + const grant = await grantPromise; + expect(grant.lease.worker?.id).toBe("wrk_a"); + }); + + it("terminally rejects, rather than re-queuing, a NO_CAPACITY that arrives after progress already fired (P1, round 2 review)", async () => { + // ADR §11: "an *immediate* NO_CAPACITY is the only answer that leaves it queued" -- one + // reached *after* a progress push means device work had already begun (the worker's own + // `#evictManaged` failure path can answer this way, after `provisioning`/`reclaiming`), so + // this request was already dispatched and a NO_CAPACITY past that point is its own terminal + // failure, not a stale view to retry. + const { coordinator, directory, eventBus, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + error: noCapacityError(), + kind: "error", + progress: [{ etaMs: 5_000, stage: "reclaiming" }], + }); + const dispatched: unknown[] = []; + eventBus.subscribe("request.dispatched", (envelope) => dispatched.push(envelope.payload)); + + const rejection = await coordinator + .request(REQUEST, requestOptions()) + .catch((error: unknown) => error); + + // It really was announced -- proving this is the "already dispatched" branch, not the + // ordinary immediate-refusal one. + expect(dispatched).toHaveLength(1); + expect(rejection).toBeInstanceOf(DispatchError); + expect((rejection as DispatchError).code).toBe("NO_CAPACITY"); + expect(coordinator.queueDepth).toBe(0); + expect(directory.refreshCalls).toEqual([]); + }); + + it("bounds a forwarded lease.request against gateway.leaseRequestTimeoutMs when the worker never answers at all (P2, round 2 review)", async () => { + // ADR §10: timeoutMs/QUEUE_TIMEOUT and lease.cancel are enforced on the gateway's own queue + // -- which only holds while a waiter is `queued`, never while it is `processing` a forwarded + // RPC. Before this fix, a forwarded `lease.request` had no timeout of its own, so a worker + // whose handler wedged left the request `processing` forever: neither a deadline nor + // `lease.cancel` could ever reach it again. + const { clock, coordinator, directory, workers } = harness({ leaseRequestTimeoutMs: 5_000 }); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ kind: "hang" }); + + const rejection = coordinator + .request(REQUEST, requestOptions()) + .catch((error: unknown) => error); + await tick(); + // Not stuck forever, and not answerable by a stale-view refresh either -- the waiter must + // come back to a state the queue's own machinery can act on. + expect(coordinator.queueDepth).toBe(0); + expect(directory.refreshCalls).toEqual([]); + + clock.advance(5_000); + const error = await rejection; + + expect(error).toBeInstanceOf(DispatchError); + expect((error as DispatchError).code).toBe("WORKER_UNREACHABLE"); + expect(coordinator.queueDepth).toBe(0); + }); + + it("does not emit request.dispatched for a progress push that arrives after gateway.leaseRequestTimeoutMs already rejected the waiter (P4, round 3 review)", async () => { + // H4's own reasoning, applied to the sibling timeout P2 added in the same round and left + // undetached: `#withLeaseRequestTimeout` settling `WORKER_UNREACHABLE` only stops the + // returned promise from being awaited -- the worker's own still-pending `lease.request` RPC + // is never cancelled, and its `onProgress` closure stays live for as long as the worker cares + // to keep pushing. `docs/EVENTS.md` defines `request.dispatched` as "the gateway's fleet queue + // sent a queued request to a worker ... and the worker took it" -- a false past-tense fact for + // a request the caller has already been told is `WORKER_UNREACHABLE`. + const { clock, coordinator, directory, eventBus, workers } = harness({ + leaseRequestTimeoutMs: 5_000, + }); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ kind: "hang" }); + const events: string[] = []; + eventBus.subscribe("request.dispatched", () => events.push("request.dispatched")); + eventBus.subscribe("lease.rejected", () => events.push("lease.rejected")); + + const rejection = coordinator + .request(REQUEST, requestOptions()) + .catch((error: unknown) => error); + await tick(); + + clock.advance(5_000); + const error = await rejection; + expect((error as DispatchError).code).toBe("WORKER_UNREACHABLE"); + expect(events).toEqual([]); + + // The worker, unaware this gateway already gave up, pushes progress on the RPC it still + // thinks is live -- exactly as `client.exec`'s own late `onOutput` chunk does in H4's test. + client.lastRequestLeaseOptions?.onProgress?.({ etaMs: 5_000, stage: "provisioning" }); + await tick(); + + expect(events).toEqual([]); + }); + + it("answers REQUESTER_ALREADY_LEASED naming the existing lease id, for an index built purely via rebuildFromWorker", async () => { + const { coordinator, leaseIndex } = harness(); + // Simulates a gateway restart's reconnect rebuild (§30): this lease was never granted + // through `coordinator.request` in this process at all. + leaseIndex.rebuildFromWorker("wrk_a", [ + { + grantedAt: 1, + id: "lse_1", + ownerId: "agent-9", + requesterId: `${GATEWAY_PREFIX}agent-9`, + }, + ]); + + const rejection = await coordinator + .request(REQUEST, requestOptions({ ownerId: "agent-9", requesterId: "agent-9" })) + .catch((error: unknown) => error); + + expect(rejection).toBeInstanceOf(RequesterAlreadyLeasedError); + expect((rejection as RequesterAlreadyLeasedError).existingLeaseId).toBe("wrk_a.lse_1"); + }); + + it("passes over a request no worker can serve instead of blocking behind it, and never lets a brand-new admission jump an older, equally-eligible waiter still queued behind it (C2, round 3 review)", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_ios", client); + // `oldFirst`'s own attempt claims the worker for the whole test and never settles -- what + // matters here is which *other* waiter gets a look at the worker's nominal second slot next, + // not what `oldFirst` itself resolves to. + client.requestLeaseQueue.push({ kind: "hang" }); + + // Admitted oldest first: an unserviceable android request, then two genuinely iOS-eligible + // waiters -- all enter the queue before any worker connects. The round 3 review's own + // title-vs-body finding (C2): the previous version of this test had only one iOS-eligible + // waiter, so its title's ordering claim asserted nothing a reader could not already get from + // the "passed over" half alone -- `oldSecond` and `newPromise` below are what actually exercise it. + const androidPromise = coordinator.request( + { model: "Pixel 9", platform: "android" }, + requestOptions({ ownerId: "agent-android", requesterId: "agent-android" }), + ); + const oldFirstPromise = coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-old-1", requesterId: "agent-old-1" }), + ); + const oldSecondPromise = coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-old-2", requesterId: "agent-old-2" }), + ); + await tick(); + expect(coordinator.queueDepth).toBe(3); + + // The one worker that connects can only ever serve iOS -- an android-then-iOS dispatch loop + // that gives up (or blocks) on android's own "no worker" answer would never reach either iOS + // waiter behind it in this same pass. Its reported capacity (two free slots) is on paper room + // for both `oldFirst` and `oldSecond`, but H6's own per-worker-per-pass cap intentionally + // leaves `oldSecond` passed over here -- genuinely `queued`, not the bug this test targets. + connectWorker(workers, "wrk_ios", { platform: "ios", models: ["iPhone 17"] }); + await tick(); + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + + let androidSettled = false; + void androidPromise.then( + () => { + androidSettled = true; + }, + () => { + androidSettled = true; + }, + ); + await tick(); + expect(androidSettled).toBe(false); + + // A brand-new iOS waiter arrives after `oldSecond`, with no worker-view change since -- + // `routing.select` is a pure function of the current views, so the very same stale view that + // already left `oldSecond` queued still nominally reports the same free capacity. ADR + // §10/§11's FIFO is oldest-first: that capacity belongs to `oldSecond`, which has been queued + // and eligible the whole time, never to a brand-new admission that only got a look because + // `#admit` took its own out-of-order peek instead of deferring to `#dispatch`. + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const newPromise = coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-new", requesterId: "agent-new" }), + ); + await tick(); + + // The second `lease.request` this test ever sends must be `oldSecond`'s own, not the + // brand-new admission's -- regardless of what either eventually settles to. + const leaseRequests = client.calls.filter((call) => call.startsWith("lease.request")); + expect(leaseRequests.length).toBeGreaterThanOrEqual(2); + expect(leaseRequests[1]).toContain("agent-old-2"); + + const oldSecondGrant = await oldSecondPromise; + expect(oldSecondGrant.lease.worker?.id).toBe("wrk_ios"); + expect(androidSettled).toBe(false); + void oldFirstPromise; + void newPromise; + }); + + it("indexes a fresh grant under the ownerId it forwarded, not the worker's own echo of it, and logs a mismatch (H6)", async () => { + const logger = new RecordingLogger(); + const { coordinator, directory, leaseIndex, workers } = harness({ logger }); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + grant: grantFixture({ + lease: { + ...grantFixture().lease, + // A worker that ignores or rewrites the field it was asked to store verbatim -- + // exactly the case this gateway must not trust for a fresh grant, even though + // `FleetLeaseIndex#rebuildFromWorker` (the reconnect path) has no better source and + // must trust it there. + ownerId: "worker-rewrote-this", + }, + }), + kind: "grant", + }); + + const grant = await coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-1", requesterId: "agent-1" }), + ); + + expect(leaseIndex.ownerId(grant.lease.id)).toBe("agent-1"); + expect(grant.lease.ownerId).toBe("agent-1"); + expect( + logger.warnings.some( + (entry) => + entry.fields?.echoedOwnerId === "worker-rewrote-this" && + entry.fields.forwardedOwnerId === "agent-1", + ), + ).toBe(true); + }); + + // C4 (round 2 review): the test below titled around "the worker's first progress push" + // asserted nothing that a progress push specifically causes -- the grant path emits + // `request.dispatched` right after `client.requestLease` resolves regardless of whether + // `progress` fired first, so deleting `announceDispatched()` from `#attempt`'s `onProgress` + // callback entirely left every test in this file passing. This one scripts a request that is + // genuinely dispatched (a `progress` push fires) and then never settles at all, so the *only* + // way `request.dispatched` can appear is the progress-driven call -- proving it fires before, + // not merely alongside, settlement (there is none, ever, in this scenario). + it("emits request.dispatched on the worker's first progress push even when the request never settles at all (§11, C4 round 2 review)", async () => { + const { coordinator, eventBus, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + kind: "hang", + progress: [{ etaMs: 5_000, stage: "provisioning" }], + }); + const dispatched: unknown[] = []; + eventBus.subscribe("request.dispatched", (envelope) => dispatched.push(envelope.payload)); + + let settled = false; + void coordinator.request(REQUEST, requestOptions()).then( + () => { + settled = true; + }, + () => { + settled = true; + }, + ); + await tick(); + + expect(settled).toBe(false); + expect(dispatched).toEqual([ + { + model: "iPhone 17", + platform: "ios", + queuedMs: expect.any(Number) as number, + reason: "free-capacity", + requestId: expect.any(String) as string, + requesterId: "agent-1", + workerId: "wrk_a", + }, + ]); + }); + + // H10 (round 2 review): `request.dispatched` had no test at all -- not its payload, not + // emit-once, not §11's "first progress push counts as dispatched" rule. `progress` on + // `RequestLeaseOutcome` (`test-support.ts`) was added for exactly this and was dead code until + // these three tests started using it. + it("emits request.dispatched exactly once, on the worker's first progress push, not again when the grant lands afterward (§11)", async () => { + const { coordinator, directory, eventBus, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + grant: grantFixture(), + kind: "grant", + progress: [ + { etaMs: 5_000, stage: "provisioning" }, + { etaMs: 1_000, stage: "booting" }, + ], + }); + const dispatched: unknown[] = []; + eventBus.subscribe("request.dispatched", (envelope) => dispatched.push(envelope.payload)); + + const grant = await coordinator.request(REQUEST, requestOptions()); + + // C2 (round 2 review): the full self-contained payload `docs/EVENTS.md` specifies -- not + // just the gateway-internal `requestId`/`workerId` pair. + expect(dispatched).toEqual([ + { + model: "iPhone 17", + platform: "ios", + queuedMs: expect.any(Number) as number, + reason: "free-capacity", + requestId: expect.any(String) as string, + requesterId: "agent-1", + workerId: "wrk_a", + }, + ]); + // Sanity: the request really did land where the event says it did. + expect(grant.lease.worker?.id).toBe("wrk_a"); + }); + + it("emits request.dispatched when a grant lands with no progress push at all -- the ADR §11 rule's other half", async () => { + const { coordinator, directory, eventBus, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const dispatched: unknown[] = []; + eventBus.subscribe("request.dispatched", (envelope) => dispatched.push(envelope.payload)); + + await coordinator.request(REQUEST, requestOptions()); + + expect(dispatched).toEqual([ + { + model: "iPhone 17", + platform: "ios", + queuedMs: expect.any(Number) as number, + reason: "free-capacity", + requestId: expect.any(String) as string, + requesterId: "agent-1", + workerId: "wrk_a", + }, + ]); + }); + + it("reports request.dispatched's reason as warm-hit when routing picked the worker for an unleased ready device, and queuedMs as the real wait (C2, round 2 review)", async () => { + const { clock, coordinator, directory, eventBus, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + // No free capacity yet -- the request genuinely queues instead of settling on the fast + // admission-time path, so `queuedMs` has something real to measure. + const noFree = { ...statusFixture().capacity.ios, maxRunning: 0, running: 0 }; + connectWorker(workers, "wrk_a", { capacity: { ...statusFixture().capacity, ios: noFree } }); + const dispatched: unknown[] = []; + eventBus.subscribe("request.dispatched", (envelope) => dispatched.push(envelope.payload)); + + const grantPromise = coordinator.request(REQUEST, requestOptions()); + await tick(); + expect(coordinator.queueDepth).toBe(1); + + clock.advance(2_500); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + // The worker now reports the requested device itself sitting ready -- a warm hit, not a + // free-capacity pick, once capacity frees up too. + workers.refresh("wrk_a", { + capacity: { ...statusFixture().capacity, ios: { ...noFree, maxRunning: 5 } }, + devices: [deviceFixture("dev_1", "ready")], + }); + + await grantPromise; + + expect(dispatched).toEqual([ + { + model: "iPhone 17", + platform: "ios", + queuedMs: 2_500, + reason: "warm-hit", + requestId: expect.any(String) as string, + requesterId: "agent-1", + workerId: "wrk_a", + }, + ]); + }); + + it("does not emit request.dispatched for a stale-view NO_CAPACITY -- the request stayed queued, never actually dispatched", async () => { + const { coordinator, directory, eventBus, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ error: noCapacityError(), kind: "error" }); + const dispatched: unknown[] = []; + eventBus.subscribe("request.dispatched", (envelope) => dispatched.push(envelope.payload)); + + void coordinator.request(REQUEST, requestOptions({ noWait: true })); + await tick(); + + expect(dispatched).toEqual([]); + }); + + it("forwards device.exec with the namespaced requesterId reaching the scripted worker client", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + grant: grantFixture({ + lease: { + ...grantFixture().lease, + id: "lse_9", + ownerId: "agent-1", + requesterId: `${GATEWAY_PREFIX}agent-1`, + }, + }), + kind: "grant", + }); + + const grant = await coordinator.request(REQUEST, requestOptions()); + client.execQueue.push({ exitCode: 0, kind: "ok" }); + + await coordinator.exec( + { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, + { manageEventSubscription: () => undefined, principal: "agent-1", role: "agent" }, + ); + + expect(client.calls).toContain(`device.exec:${GATEWAY_PREFIX}agent-1`); + }); + + // C3 (round 2 review): `session.onStarted` used to fire before `client.exec` even went out -- + // committing an HTTP caller's `200` before this gateway had any idea whether the worker would + // accept the command at all, including a worker-side `FORBIDDEN` (§19a', the one place `admin` + // does not bypass ownership) and the driver's own `PASSTHROUGH_REFUSED` / a bad `tool`. These + // two tests exercise `FleetLeaseCoordinator#exec` itself, the actual chokepoint -- not just + // `http/app.ts`'s own route logic, which was already correct given whatever a dispatcher told + // it (see `http/app.test.ts`'s "answers a failure that lands before any output with its own + // status, not a stream"). + it("announces started from the worker's own push, before any output, and never before client.exec is sent (ADR §19a)", async () => { + // The signal is the worker's `started` frame and nothing else -- not the first output chunk + // (which cannot fire for a silent command) and not a timer (which cannot tell a slow worker + // from a refusing one). This asserts the ordering that matters to a transport: `started` + // lands before the first chunk, and never before the forward actually goes out. + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const grant = await coordinator.request(REQUEST, requestOptions()); + client.execQueue.push({ + exitCode: 0, + kind: "ok", + output: [{ chunk: "hi", stream: "stdout" }], + started: true, + }); + + const order: string[] = []; + await coordinator.exec( + { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, + { + manageEventSubscription: () => undefined, + onOutput: () => { + order.push("output"); + }, + onStarted: () => { + order.push("started"); + }, + principal: "agent-1", + role: "agent", + }, + ); + + expect(order).toEqual(["started", "output"]); + expect(client.calls).toContain(`device.exec:${GATEWAY_PREFIX}agent-1`); + }); + + it("never calls onStarted for a worker-side FORBIDDEN that produced no output at all -- the HTTP route must still be free to answer 403, not a committed 200 (C3, round 2 review)", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + grant: grantFixture({ + lease: { + ...grantFixture().lease, + id: "lse_9", + ownerId: "agent-1", + requesterId: `${GATEWAY_PREFIX}agent-1`, + }, + }), + kind: "grant", + }); + const grant = await coordinator.request(REQUEST, requestOptions()); + // §19a': the worker's own ownership check disagreeing with what this gateway forwarded -- + // exactly the answer that must still reach an HTTP caller as its own status code, not as an + // already-committed 200 + SSE `error`. + client.execQueue.push({ + error: new SimlockError("FORBIDDEN", "domain", "Lease belongs to a different requester", {}), + kind: "error", + }); + + let started = false; + const rejection = await coordinator + .exec( + { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, + { + manageEventSubscription: () => undefined, + onStarted: () => { + started = true; + }, + principal: "agent-1", + role: "agent", + }, + ) + .catch((error: unknown) => error); + + expect(rejection).toBeInstanceOf(DispatchError); + expect((rejection as DispatchError).code).toBe("FORBIDDEN"); + expect(started).toBe(false); + }); + + it("a noWait request refused while other requests are queued emits no lease.queued and no queued progress -- it never entered the queue (ADR §10, architecture rule 10)", async () => { + // `noWait` used to be enforced twice: once in `#admit`'s own direct look and once after an + // enqueue-then-dispatch. The second path committed queue membership *before* it knew the + // answer, and `WaitQueue#enqueue` pushes a `queued` progress frame and `#enqueue` emits + // `lease.queued` -- so the same request produced different observable facts depending on + // whether *unrelated* requests happened to be queued at the time. ADR §10 requires "the same + // codes and progress states a worker uses", and a worker's own `#defer` rejects a `noWait` + // waiter before it enqueues. + const { coordinator, directory, eventBus, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + + // Occupy the worker and leave a waiter in the queue, so the queue is non-empty. + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + await coordinator.request(REQUEST, requestOptions()); + void coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-2", requesterId: "agent-2" }), + ); + await tick(); + expect(coordinator.queueDepth).toBe(1); + + const events: string[] = []; + eventBus.subscribe("lease.queued", () => events.push("lease.queued")); + eventBus.subscribe("lease.rejected", () => events.push("lease.rejected")); + const progress: string[] = []; + + await expect( + coordinator.request( + REQUEST, + requestOptions({ + noWait: true, + onProgress: (update) => progress.push(update.stage), + ownerId: "agent-3", + requesterId: "agent-3", + }), + ), + ).rejects.toMatchObject({ code: "NO_CAPACITY" }); + + expect(events).toEqual(["lease.rejected"]); + expect(progress).toEqual([]); + expect(coordinator.queueDepth).toBe(1); + }); + + it("a noWait request bounced back by a stale view stays queued even with other requests queued -- §11's exception does not depend on queue depth", async () => { + // §11: "an immediate NO_CAPACITY is the only answer that leaves it queued", and `#staleView` + // applies that unconditionally, "even for a caller that asked noWait: true". Deciding on + // `waiter.state === "queued"` could not tell "never attempted" from "attempted and bounced + // back inside the same pass", so the answer flipped with unrelated queue depth. + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + await coordinator.request(REQUEST, requestOptions()); + void coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-2", requesterId: "agent-2" }), + ); + await tick(); + expect(coordinator.queueDepth).toBe(1); + + // A second worker the views advertise but the directory cannot resolve: routing picks it, + // `#attempt` finds no client, and `#staleView` bounces the waiter straight back -- all + // synchronously, inside the admission's own pass. + connectWorker(workers, "wrk_b"); + + let settled = "pending"; + void coordinator + .request( + REQUEST, + requestOptions({ noWait: true, ownerId: "agent-3", requesterId: "agent-3" }), + ) + .then( + () => (settled = "granted"), + () => (settled = "rejected"), + ); + await tick(); + + expect(settled).toBe("pending"); + expect(coordinator.queueDepth).toBe(2); + }); + + it("relays the worker's own started push for a silent, long-running command -- no output, no answer, still a 200 through a gateway (ADR §19a/§19b/§19e)", async () => { + // ADR §19e/§19b: "a command that prints nothing for nine minutes still gets its 200 and its + // keepalives" -- `simctl install ` (§19b's own worked example) is exactly such a + // command. Deferring `onStarted` to the first output chunk never fires for one, so a + // gateway-fronted caller got no `200`, no keepalives, and eventually a `504` instead of the + // stream's own terminal `EXEC_TIMEOUT`. The worker knows the moment and now sends it, so + // this asserts the relay and nothing about timing: no clock is advanced anywhere below. + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const grant = await coordinator.request(REQUEST, requestOptions()); + // The process exists on the worker -- it says so -- and then writes nothing and never + // settles, which is the whole shape of a silent long-running command. + client.execQueue.push({ kind: "hang", started: true }); + + let started = false; + void coordinator.exec( + { args: ["install", "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/path/to.app"], leaseId: grant.lease.id, tool: "simctl" }, + { + manageEventSubscription: () => undefined, + onStarted: () => { + started = true; + }, + principal: "agent-1", + role: "agent", + }, + ); + await tick(); + + expect(started).toBe(true); + }); + + it("does not announce started for a command the worker refuses before any process exists -- a pre-process refusal keeps its own real status (ADR §19a′)", async () => { + const { clock, coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const grant = await coordinator.request(REQUEST, requestOptions()); + client.execQueue.push({ + error: new SimlockError("FORBIDDEN", "domain", "Lease belongs to a different requester", {}), + kind: "error", + }); + + let started = false; + const rejection = await coordinator + .exec( + { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, + { + manageEventSubscription: () => undefined, + onStarted: () => { + started = true; + }, + principal: "agent-1", + role: "agent", + }, + ) + .catch((error: unknown) => error); + + expect(rejection).toBeInstanceOf(DispatchError); + expect((rejection as DispatchError).code).toBe("FORBIDDEN"); + expect(started).toBe(false); + + // There is no timer to fire any more -- advancing the clock well past where one used to be + // must not fire a stray `onStarted` for a call that is already over. + clock.advance(10_000); + expect(started).toBe(false); + }); + + it("times out a forwarded device.exec after gateway.execTimeoutMs when the worker never answers at all (P5)", async () => { + const { clock, coordinator, directory, workers } = harness({ execTimeoutMs: 5_000 }); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + grant: grantFixture({ + lease: { + ...grantFixture().lease, + id: "lse_9", + ownerId: "agent-1", + requesterId: `${GATEWAY_PREFIX}agent-1`, + }, + }), + kind: "grant", + }); + const grant = await coordinator.request(REQUEST, requestOptions()); + client.execQueue.push({ kind: "hang" }); + + const rejection = coordinator + .exec( + { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, + { manageEventSubscription: () => undefined, principal: "agent-1", role: "agent" }, + ) + .catch((error: unknown) => error); + await tick(); + clock.advance(5_000); + + const error = await rejection; + expect(error).toBeInstanceOf(DispatchError); + expect((error as DispatchError).code).toBe("EXEC_TIMEOUT"); + }); + + it("stops relaying a worker's device.exec output once gateway.execTimeoutMs has already rejected the call (H4, round 3 review)", async () => { + const { clock, coordinator, directory, workers } = harness({ execTimeoutMs: 5_000 }); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + grant: grantFixture({ + lease: { + ...grantFixture().lease, + id: "lse_9", + ownerId: "agent-1", + requesterId: `${GATEWAY_PREFIX}agent-1`, + }, + }), + kind: "grant", + }); + const grant = await coordinator.request(REQUEST, requestOptions()); + // Never settles -- exactly the "worker never answers at all" case `EXEC_TIMEOUT` exists for + // -- but the underlying RPC is never cancelled, so a real worker's own `onOutput` pushes can + // still arrive on it after this gateway has already given up. + client.execQueue.push({ kind: "hang" }); + + const relayed: Array<{ stream: string; chunk: string }> = []; + const rejection = coordinator + .exec( + { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, + { + manageEventSubscription: () => undefined, + onOutput: (stream, chunk) => { + relayed.push({ chunk, stream }); + }, + principal: "agent-1", + role: "agent", + }, + ) + .catch((error: unknown) => error); + await tick(); + clock.advance(5_000); + const error = await rejection; + expect((error as DispatchError).code).toBe("EXEC_TIMEOUT"); + + // The worker, unaware this gateway already timed the call out, keeps streaming -- this is + // exactly the closure `client.exec` was given, invoked exactly as the worker's own RPC + // handling would invoke it in production, well after `EXEC_TIMEOUT` already settled. + client.lastExecOptions?.onOutput?.({ chunk: "late output", stream: "stdout" }); + await tick(); + + expect(relayed).toEqual([]); + }); + + // Round 6 review: `#raceTimeout`'s own doc claims no late frame "reaches `session.onOutput` + // (or spuriously fires `onStarted`) once that has happened", but only the `onOutput` half was + // tested -- both `detached` guards were deletable with the whole suite green. HTTP survives a + // spurious `onStarted` only because `OutputRelay` swallows it, which is the transport saving + // this class again: exactly the reasoning H4 rejected for `onOutput`. + it("does not announce started from a worker frame that arrives after gateway.execTimeoutMs already rejected the call (H4, round 6 review)", async () => { + const { clock, coordinator, directory, workers } = harness({ execTimeoutMs: 5_000 }); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const grant = await coordinator.request(REQUEST, requestOptions()); + client.execQueue.push({ kind: "hang" }); + + let startedCount = 0; + const rejection = coordinator + .exec( + { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, + { + manageEventSubscription: () => undefined, + onStarted: () => { + startedCount += 1; + }, + principal: "agent-1", + role: "agent", + }, + ) + .catch((error: unknown) => error); + await tick(); + clock.advance(5_000); + const error = await rejection; + expect((error as DispatchError).code).toBe("EXEC_TIMEOUT"); + + // The worker finally spawns the process and says so -- the same closure `client.exec` was + // given, well after this gateway answered `EXEC_TIMEOUT`. + client.lastExecOptions?.onStarted?.(); + await tick(); + + expect(startedCount).toBe(0); + }); + + it("announces started once even if the worker sends the frame more than once", async () => { + // A `started` push is request-scoped and should arrive once, but nothing on the wire stops a + // worker from sending it twice, and a transport that has already chosen its response shape + // cannot un-choose it. The dedupe is what makes the signal idempotent for every consumer. + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const grant = await coordinator.request(REQUEST, requestOptions()); + client.execQueue.push({ exitCode: 0, kind: "ok", started: true }); + + let startedCount = 0; + await coordinator.exec( + { args: ["devices"], leaseId: grant.lease.id, tool: "adb" }, + { + manageEventSubscription: () => undefined, + onStarted: () => { + startedCount += 1; + }, + principal: "agent-1", + role: "agent", + }, + ); + client.lastExecOptions?.onStarted?.(); + await tick(); + + expect(startedCount).toBe(1); + }); + + // Round 6 review: `#dispatch`'s re-entrancy guard and its `#passRequested` deferral were + // deletable with the whole suite green, and instrumenting the `#dispatchDepth > 0` branch + // showed *zero* hits across every test in the repo -- round 4 finding 6's fix ("defer instead + // of dropping") was a green light wired to nothing. + // + // It takes a synchronous view change raised from inside the walk to reach, which no production + // path does today (`WorkerLink#refresh` mutates only past its first await). That is precisely + // why it needs a test rather than deletion: the guard exists so that a future caller which + // *does* mutate synchronously cannot silently reintroduce C1's stall, and nothing but this + // test would notice if the deferral were removed again. + it("runs another pass for a view change raised from inside the walk, rather than dropping it (round 4 finding 6, round 6 review)", async () => { + // Call 1 is the admission look (worker still carries the wrong model, so the real policy + // refuses and the waiter queues). Call 2 is the pass the single refresh below triggers -- + // that is the one that injects. Call 3 can only happen if the nested change was deferred + // rather than dropped. + let selectCalls = 0; + const { coordinator, directory, workers } = harness({ + routing: (registry) => { + const real = createRoutingPolicy("warm-then-free"); + return { + select(request, workerViews) { + selectCalls += 1; + if (selectCalls === 2) { + // A view change *during* the walk: re-enters `#dispatch`, which cannot run a pass + // now (one is already walking a snapshot) and must therefore remember to run one + // when this one unwinds. + registry.refresh("wrk_a", {}); + // ...and this waiter finds nothing this pass, so only that next pass can serve it. + return undefined; + } + return real.select(request, workerViews); + }, + }; + }, + }); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + // Connected, but carrying a model this request cannot use -- so the waiter queues, and the + // worker is already fully connected. That matters: `connectWorker` raises *two* view changes + // (`connected`, then `refresh`), and a second top-level dispatch would serve the waiter on + // its own, masking whether the deferred pass did anything at all. Getting the worker + // connected before the request leaves exactly one trigger below. + connectWorker(workers, "wrk_a", { models: ["iPhone 16"] }); + const grantPromise = coordinator.request(REQUEST, requestOptions()); + await tick(); + expect(coordinator.queueDepth).toBe(1); + + // The single trigger: one refresh that makes the worker eligible. Pass 1 refuses the waiter + // and raises a nested view change; only the deferred pass 2 can dispatch it. Asserted on the + // forwarded RPC rather than by awaiting the grant, so dropping the deferral fails here on a + // named assertion instead of by timing out (testing rule 2). + workers.refresh("wrk_a", { + capacity: statusFixture().capacity, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + devices: [], + downloads: { policy: "on-request" }, + health: "running", + leases: [], + queueDepth: 0, + }); + await tick(); + + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + // Three looks: admission, the injecting pass, and the deferred pass that actually dispatched. + expect(selectCalls).toBe(3); + const grant = await grantPromise; + expect(grant.lease.worker?.id).toBe("wrk_a"); + expect(coordinator.queueDepth).toBe(0); + }); + + it("rejects a no-wait request immediately with NO_CAPACITY when no worker is eligible at all", async () => { + const { coordinator } = harness(); + + await expect( + coordinator.request(REQUEST, requestOptions({ noWait: true })), + ).rejects.toMatchObject({ code: "NO_CAPACITY" }); + }); + + it("forwards a worker's own terminal refusal verbatim, as the worker's own error code", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ + error: new SimlockError("RUNTIME_MISSING", "domain", "no such runtime", { + downloadable: false, + osVersion: "99.0", + platform: "ios", + }), + kind: "error", + }); + + const rejection = await coordinator + .request(REQUEST, requestOptions()) + .catch((error: unknown) => error); + expect(rejection).toBeInstanceOf(DispatchError); + expect((rejection as DispatchError).code).toBe("RUNTIME_MISSING"); + }); + + it("maps a transport failure on lease.request to WORKER_UNREACHABLE, never the uplink client's own error code verbatim (P4)", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + // What the admin client's own wire rejects an in-flight call with when *its* connection to + // the worker dies mid-call (`src/simlock-client/wire.ts`) -- `kind: "transport"` names the + // uplink itself, not a worker fact, and forwarding it verbatim would tell the fleet client + // its own connection to *this gateway* was lost, which never happened. + client.requestLeaseQueue.push({ + error: new SimlockError( + "DAEMON_CONNECTION_LOST", + "transport", + "Daemon connection is closed", + {}, + ), + kind: "error", + }); + + const rejection = await coordinator + .request(REQUEST, requestOptions()) + .catch((error: unknown) => error); + expect(rejection).toBeInstanceOf(DispatchError); + expect((rejection as DispatchError).code).toBe("WORKER_UNREACHABLE"); + expect((rejection as DispatchError).details).toMatchObject({ workerId: "wrk_a" }); + }); + + it("maps a transport failure on a forwarded lease.renew to WORKER_UNREACHABLE the same way (P4)", async () => { + const { coordinator, directory, workers, leaseIndex } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + leaseIndex.add({ + gatewayLeaseId: "wrk_a.lse_1", + grantedAt: 1, + ownerId: "agent-1", + requesterId: "agent-1", + workerId: "wrk_a", + workerLeaseId: "lse_1", + }); + client.renewLeaseQueue.push({ + error: new SimlockError( + "DAEMON_CONNECTION_LOST", + "transport", + "Daemon connection is closed", + {}, + ), + kind: "error", + }); + + const rejection = await coordinator + .renew("wrk_a.lse_1", undefined) + .catch((error: unknown) => error); + expect(rejection).toBeInstanceOf(DispatchError); + expect((rejection as DispatchError).code).toBe("WORKER_UNREACHABLE"); + }); + + it("reports a non-SimlockError from a forwarded renew as INTERNAL, never as WORKER_UNREACHABLE (H1, round 2 review)", async () => { + // A raw TypeError here is this coordinator's own bug, not a fact about the worker -- every + // real transport failure already arrives as a `kind: "transport"` SimlockError (the test + // above). Answering WORKER_UNREACHABLE for a value like this would misreport a gateway-side + // crash as "the machine is unreachable". + const { coordinator, directory, workers, leaseIndex } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + leaseIndex.add({ + gatewayLeaseId: "wrk_a.lse_1", + grantedAt: 1, + ownerId: "agent-1", + requesterId: "agent-1", + workerId: "wrk_a", + workerLeaseId: "lse_1", + }); + client.renewLeaseQueue.push({ error: new TypeError("boom"), kind: "error" }); + + const rejection = await coordinator + .renew("wrk_a.lse_1", undefined) + .catch((error: unknown) => error); + expect(rejection).toBeInstanceOf(DispatchError); + expect((rejection as DispatchError).code).toBe("INTERNAL"); + }); + + it("reports a non-SimlockError from a forwarded lease.request as INTERNAL too, the same shape of failure #attempt answers directly (H1, round 2 review)", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ error: new TypeError("boom"), kind: "error" }); + + const rejection = await coordinator + .request(REQUEST, requestOptions()) + .catch((error: unknown) => error); + expect(rejection).toBeInstanceOf(DispatchError); + expect((rejection as DispatchError).code).toBe("INTERNAL"); + }); + + it("drops its own index entry when the worker answers UNKNOWN_LEASE to a release, instead of leaving a zombie behind (C3)", async () => { + const { coordinator, directory, workers, leaseIndex } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + leaseIndex.add({ + gatewayLeaseId: "wrk_a.lse_1", + grantedAt: 1, + ownerId: "agent-1", + requesterId: "agent-1", + workerId: "wrk_a", + workerLeaseId: "lse_1", + }); + client.releaseLeaseQueue.push({ + error: new SimlockError("UNKNOWN_LEASE", "domain", "Unknown lease: lse_1", { + leaseId: "lse_1", + }), + kind: "error", + }); + + await expect(coordinator.release("wrk_a.lse_1")).rejects.toMatchObject({ + code: "UNKNOWN_LEASE", + }); + + // The gateway's own record was provably wrong (the worker has no idea what this lease is) -- + // it must not survive to block `agent-1`'s next request with REQUESTER_ALREADY_LEASED + // naming a lease that exists nowhere. + expect(leaseIndex.resolve("wrk_a.lse_1")).toBeUndefined(); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + await expect(coordinator.request(REQUEST, requestOptions())).resolves.toBeDefined(); + }); + + it("drops its own index entry when the worker answers UNKNOWN_LEASE to a renew too (C3)", async () => { + const { coordinator, directory, workers, leaseIndex } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + leaseIndex.add({ + gatewayLeaseId: "wrk_a.lse_1", + grantedAt: 1, + ownerId: "agent-1", + requesterId: "agent-1", + workerId: "wrk_a", + workerLeaseId: "lse_1", + }); + client.renewLeaseQueue.push({ + error: new SimlockError("UNKNOWN_LEASE", "domain", "Unknown lease: lse_1", { + leaseId: "lse_1", + }), + kind: "error", + }); + + await expect(coordinator.renew("wrk_a.lse_1", undefined)).rejects.toMatchObject({ + code: "UNKNOWN_LEASE", + }); + expect(leaseIndex.resolve("wrk_a.lse_1")).toBeUndefined(); + }); + + it("release-all treats a worker's UNKNOWN_LEASE as already-released rather than a failure that blocks every future call (C3)", async () => { + const { coordinator, directory, workers, leaseIndex } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + leaseIndex.add({ + gatewayLeaseId: "wrk_a.lse_zombie", + grantedAt: 1, + ownerId: "agent-1", + requesterId: "agent-1", + workerId: "wrk_a", + workerLeaseId: "lse_zombie", + }); + client.releaseLeaseQueue.push({ + error: new SimlockError("UNKNOWN_LEASE", "domain", "Unknown lease: lse_zombie", { + leaseId: "lse_zombie", + }), + kind: "error", + }); + + // Without C3's fix this single zombie entry throws on *every* future release-all -- proven + // by calling it twice. + await expect(coordinator.releaseAll()).resolves.toEqual(["wrk_a.lse_zombie"]); + expect(leaseIndex.resolve("wrk_a.lse_zombie")).toBeUndefined(); + await expect(coordinator.releaseAll()).resolves.toEqual([]); + }); + + it("does not evict a lease on one worker when only a different worker's view changes repeatedly (C1, round 2 review)", async () => { + // Reproduces the round 2 finding exactly: a grant lands on wrk_a, but wrk_a's own cached + // view never gets refreshed with the new lease in this test (nothing here calls + // `workers.refresh("wrk_a", { leases: [...] })`, exactly the race where a real + // `WorkerLink`'s post-grant refresh is still in flight). Unrelated churn on wrk_b must never + // be able to evict wrk_a's lease -- before the fix, `#onViewsChanged` reconciled *every* + // view (including wrk_a's stale, lease-less one) on every notification, so two view changes + // on wrk_b alone were enough to walk wrk_a's entry through both halves of + // `rebuildFromWorker`'s two-consecutive-misses rule and forget it. + const { coordinator, directory, workers, leaseIndex } = harness(); + const clientA = new ScriptedWorkerClient(); + const clientB = new ScriptedWorkerClient(); + directory.add("wrk_a", clientA); + directory.add("wrk_b", clientB); + connectWorker(workers, "wrk_a"); + connectWorker(workers, "wrk_b"); + clientA.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + const grant = await coordinator.request(REQUEST, requestOptions()); + expect(grant.lease.worker?.id).toBe("wrk_a"); + // wrk_a's own view still reports no leases at all -- the stale-cache race this finding + // describes, not a hypothetical. + expect(workers.view("wrk_a")?.leases).toEqual([]); + + // Two unrelated view changes on wrk_b -- neither one is about wrk_a. + workers.refresh("wrk_b", {}); + workers.refresh("wrk_b", {}); + + expect(leaseIndex.resolve(grant.lease.id)).toBeDefined(); + expect(leaseIndex.existingLeaseId("agent-1")).toBe(grant.lease.id); + }); + + it("release-all attaches the leases it already released to a later failure's own details (H8)", async () => { + const { coordinator, directory, workers, leaseIndex } = harness(); + const clientA = new ScriptedWorkerClient(); + const clientB = new ScriptedWorkerClient(); + directory.add("wrk_a", clientA); + directory.add("wrk_b", clientB); + connectWorker(workers, "wrk_a"); + connectWorker(workers, "wrk_b"); + leaseIndex.add({ + gatewayLeaseId: "wrk_a.lse_1", + grantedAt: 1, + ownerId: "agent-1", + requesterId: "agent-1", + workerId: "wrk_a", + workerLeaseId: "lse_1", + }); + leaseIndex.add({ + gatewayLeaseId: "wrk_b.lse_1", + grantedAt: 1, + ownerId: "agent-2", + requesterId: "agent-2", + workerId: "wrk_b", + workerLeaseId: "lse_1", + }); + clientA.releaseLeaseQueue.push({ kind: "ok" }); + directory.unreachable.add("wrk_b"); + + const rejection = await coordinator.releaseAll().catch((error: unknown) => error); + expect(rejection).toBeInstanceOf(DispatchError); + expect((rejection as DispatchError).code).toBe("WORKER_UNREACHABLE"); + expect((rejection as DispatchError).details).toMatchObject({ + releasedLeaseIds: ["wrk_a.lse_1"], + }); + // What already succeeded stays released regardless of the answer's own shape. + expect(leaseIndex.resolve("wrk_a.lse_1")).toBeUndefined(); + expect(leaseIndex.resolve("wrk_b.lse_1")).toBeDefined(); + }); +}); diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts new file mode 100644 index 000000000..7e4e0680e --- /dev/null +++ b/src/gateway/fleet-coordinator.ts @@ -0,0 +1,1038 @@ +/** + * `FleetLeaseCoordinator`: admission, the fleet-wide one-lease rule, dispatch, and lease/exec + * forwarding (ADR 0005 §10-§16, §19a-§19c, §27, §27a). Much smaller than the worker's own + * `LeaseAcquisitionCoordinator` -- there is no provisioning, no eviction, and no driver to ask: a + * worker either grants a forwarded `lease.request` immediately or refuses it, because every + * dispatch is `noWait` (§12). + * + * ## The dispatch race (see the module's own tests for the one that catches a naive fix) + * + * Dispatch re-runs on every worker-view change (`FleetViews#onViewsChanged`) and once more per + * settled attempt. (C1/C2, round 3 review: `#attempt` now calls `#dispatch()` itself, right after + * `#settleGrant` and right after its own terminal `reject` -- see `#attempt`'s own doc for why + * this was previously false. `#admit` has no look of its own at all: it hands the + * brand-new waiter to that same walk as its `candidate` -- see `#admit`'s own doc, and + * architecture rule 10.) A waiter whose forwarded `lease.request` is still in + * flight to worker A must never be picked up by a second pass and sent to worker B too -- if both granted, one requester + * would hold two devices on two machines, and the fleet-wide admission check cannot catch it + * (it runs once, at admission, before either RPC). `#beginAttempt` calls `queue.markProcessing` + * *before* issuing the RPC, taking the waiter out of `queued` state, so `#dispatch`'s own + * `queue.list()` scan skips it for the whole in-flight window; the waiter only becomes `queued` + * again (via `#enqueue`, from `#staleView`) once that attempt has fully settled. There used to be + * a second guard here too -- a `Map` keyed by in-flight target -- but once + * every exit from `#attempt` clears its waiter's processing state in exactly one place (the + * `finally` below), the two checks can never disagree: nothing can observe a waiter that is both + * `queued` and mid-attempt. Keeping a guard with no state it can ever catch was worse than + * deleting it (round 2 review, C1/C2) -- if a future change reintroduces that race, the fix is a + * new guard proven by a new failing test, not resurrecting one that only ever watched itself. + * + * ## Two different fields, two different rules + * + * The fleet-wide "already leased" admission check keys on **`requesterId`** (§14) and runs + * inside one `SerializedDecision.run` together with the enqueue (`request` below), so two + * concurrent requests for one requester cannot both pass before either is admitted. Ownership + * authorization for `lease.renew`/`lease.release`/`device.exec` keys on **`ownerId`** instead + * (§26) -- the gateway's own inbound principal, resolved by `GatewayDispatcher`'s + * `authorizeLookups` from `ownerId()`/`leaseRequesterId()` below, never by this class directly. + * + * ## What this class does not do + * + * `WORKER_UNREACHABLE` retry/backoff semantics and "dispatched, then uplink lost" recovery are + * #119's (ADR §28/§29) -- every forward in this class funnels through `#forwardToWorker`, the one + * chokepoint #119 can wrap without touching every call site. This class answers + * `WORKER_UNREACHABLE` when a target is not reachable *right now*, and nothing more. + */ +import type { EventBus, EventMap } from "../bus/index.js"; +import type { LeaseGrant, LeaseRecord, SimlockAdminClient } from "../admin/index.js"; +import { isSimlockError, type AnySimlockError, type Platform } from "../contract/index.js"; +import { DispatchError, type DispatchSession } from "../daemon/dispatch.js"; +import type { DeviceRequest } from "../core/driver.js"; +import { SerializedDecision } from "../core/serialized-decision.js"; +import type { Clock, IdGenerator, Logger } from "../ports/index.js"; +import { NoopLogger } from "../ports/index.js"; +import type { WorkerDirectory } from "./fleet-ports.js"; +import type { FleetViews } from "./fleet-ports.js"; +import { type FleetLeaseEntry, type FleetLeaseIndex } from "./lease-index.js"; +import type { WorkerView } from "./worker-registry.js"; +import { + FleetQueue, + RequestCancelledError, + RequesterAlreadyLeasedError, + type FleetLeaseGrant, + type FleetLeaseRecord, + type FleetWaiter, + type LeaseRequestOptions, +} from "./queue.js"; +import type { RoutableRequest, RoutingDecision, RoutingPolicy } from "./routing.js"; + +export interface FleetExecInput { + readonly leaseId: string; + readonly tool: string; + readonly args: readonly string[]; + readonly stdin?: string; +} + +export interface FleetLeaseCoordinatorOptions { + readonly clock: Clock; + readonly idGenerator: IdGenerator; + readonly eventBus: Pick; + readonly directory: WorkerDirectory; + readonly views: FleetViews; + readonly routing: RoutingPolicy; + readonly leaseIndex: FleetLeaseIndex; + /** ADR §19e (P5, round 2 review): `gateway.execTimeoutMs`, the backstop for a forwarded + * `device.exec` whose worker never answers at all -- the worker's own `exec.timeoutMs` is + * authoritative for an ordinary timeout (it owns the process and can kill it) and is expected + * to fire first, since the gateway's default is deliberately the longer of the two. */ + readonly execTimeoutMs: number; + /** P2 (round 2 review): `gateway.leaseRequestTimeoutMs` -- bounds a forwarded `lease.request`, + * the one uplink call that used to have no timeout of its own. See + * `#withLeaseRequestTimeout`'s own doc comment. */ + readonly leaseRequestTimeoutMs: number; + readonly logger?: Logger; +} + +type FleetEventName = "lease.requested" | "lease.queued" | "lease.rejected" | "request.dispatched"; + +export class FleetLeaseCoordinator { + readonly #queue: FleetQueue; + readonly #decisions = new SerializedDecision(); + readonly #logger: Logger; + #knownWorkerIds = new Set(); + /** C1 (round 2 review): the `view.leases` array reference this coordinator last reconciled + * into `leaseIndex` for each worker, keyed by worker id. `onViewsChanged` fires for *every* + * worker-view mutation on the whole registry (`connected`, `refresh`, `disconnected`, + * `setDrained`, `remove`, `pruneExpired` -- see `FleetViews#onViewsChanged`'s own doc), not + * just a change to the worker being reconciled, so calling `rebuildFromWorker` for every view + * on every notification bumped a worker's reconciliation generation without a new snapshot + * ever having arrived for it (see `#onViewsChanged`'s own doc for the eviction this caused). + * `WorkerRegistry` only ever replaces a view's `leases` array when a snapshot naming `leases` + * actually lands for that specific worker (`refresh`'s partial-update contract; `connected` and + * `disconnected` never touch it) -- so this reference is exactly "a new snapshot for this + * worker arrived" and nothing else, with no need to widen `FleetViews` to carry worker + * identity on the notification itself. */ + readonly #lastReconciledLeases = new Map(); + readonly #unsubscribeViews: () => void; + /** C2 (round 2 review): when each waiter was created (`#queue.create`, in `request` below), + * for `request.dispatched`'s `queuedMs` field -- a `WeakMap` rather than a `Map` + * so a waiter that never gets there (rejected at admission, cancelled, timed out) needs no + * explicit clean-up call on every one of those exits to avoid an unbounded leak; the entry is + * reclaimable the moment nothing else still references the waiter. */ + readonly #createdAt = new WeakMap(); + /** C1 (round 3 review): re-entrancy guard for `#dispatch` -- see its own doc comment. */ + #dispatchDepth = 0; + /** Set when a pass is requested while one is already running; the running pass then repeats + * rather than dropping it (round 4 review, finding 6). */ + #passRequested = false; + + constructor(private readonly options: FleetLeaseCoordinatorOptions) { + this.#logger = options.logger ?? new NoopLogger(); + this.#queue = new FleetQueue({ + clock: options.clock, + idGenerator: options.idGenerator, + // The rejection itself already happened inside `WaitQueue#armTimeout` by the time this + // fires (see `queue.ts`); this only reports the gateway's own fact for it. + onTimeout: (waiter) => + this.#emit("lease.rejected", { requestSpec: waiter.request, reason: "timeout" }), + }); + this.#unsubscribeViews = options.views.onViewsChanged(() => this.#onViewsChanged()); + } + + get queueDepth(): number { + return this.#queue.depth; + } + + // fallow-ignore-next-line unused-class-member -- reached only through `GatewayDispatcher`'s `Pick`-typed `coordinator` option (`authorizeLookups.ownerId`); the audit cannot follow a call through a structural type. + ownerId(gatewayLeaseId: string): string | undefined { + return this.options.leaseIndex.ownerId(gatewayLeaseId); + } + + // fallow-ignore-next-line unused-class-member -- see `ownerId` above; reached via `authorizeLookups.leaseRequesterId`. + leaseRequesterId(gatewayLeaseId: string): string | undefined { + return this.options.leaseIndex.leaseRequesterId(gatewayLeaseId); + } + + // fallow-ignore-next-line unused-class-member -- see `ownerId` above; reached via `authorizeLookups.pendingRequestOwner`. + pendingRequestOwner(requesterId: string): string | undefined { + return this.#queue.findPendingWaiter(requesterId)?.options.ownerId; + } + + /** + * Admits a request and returns the eventual grant. The one-lease check and the enqueue commit + * together, inside `SerializedDecision.run`, so two concurrent requests for the same + * `requesterId` can never both be admitted (see the module doc's "two different fields"). + * Everything past admission -- reaching a worker at all -- is I/O and stays outside it. + */ + async request( + deviceRequest: DeviceRequest, + options: LeaseRequestOptions, + ): Promise { + const waiter = await this.#decisions.run(async () => { + const existingLeaseId = this.options.leaseIndex.existingLeaseId(options.requesterId); + if (existingLeaseId !== undefined || this.#queue.hasPendingRequester(options.requesterId)) { + this.#emit("lease.rejected", { requestSpec: deviceRequest, reason: "already-leased" }); + throw new RequesterAlreadyLeasedError(options.requesterId, existingLeaseId); + } + const created = this.#queue.create(deviceRequest, options); + this.#createdAt.set(created, this.options.clock.now()); + this.#emit("lease.requested", { + requestSpec: deviceRequest, + requester: options.requesterId, + waitPolicy: options.noWait === true ? "no-wait" : "wait", + }); + return created; + }); + this.#admit(waiter); + return waiter.promise; + } + + // fallow-ignore-next-line unused-class-member -- reached only through `GatewayDispatcher`'s `Pick`-typed `coordinator` option (`#leaseCancel`); the audit cannot follow a call through a structural type. + async cancelPending(requesterId: string): Promise<"cancelled" | "not-found" | "not-cancellable"> { + return this.#decisions.run(async () => { + const waiter = this.#queue.findPendingWaiter(requesterId); + if (waiter === undefined) return "not-found"; + if (waiter.state !== "queued") return "not-cancellable"; + if (this.#queue.reject(waiter, new RequestCancelledError(waiter.id))) { + this.#emit("lease.rejected", { requestSpec: waiter.request, reason: "cancelled" }); + } + return "cancelled"; + }); + } + + async renew(gatewayLeaseId: string, ttlMs: number | undefined): Promise { + const entry = this.#requireEntry(gatewayLeaseId); + let record: LeaseRecord; + try { + record = await this.#forwardToWorker(entry.workerId, (client) => + client.renewLease({ + leaseId: entry.workerLeaseId, + ...(ttlMs === undefined ? {} : { ttlMs }), + }), + ); + } catch (error: unknown) { + this.#forgetIfUnknownToWorker(gatewayLeaseId, error); + throw error; + } + return this.#projectRecord(record, entry); + } + + async release(gatewayLeaseId: string): Promise { + const entry = this.#requireEntry(gatewayLeaseId); + try { + await this.#forwardToWorker(entry.workerId, (client) => + client.releaseLease({ leaseId: entry.workerLeaseId }), + ); + } catch (error: unknown) { + this.#forgetIfUnknownToWorker(gatewayLeaseId, error); + throw error; + } + // Removed immediately rather than waiting on the relayed `lease.released` fact to make the + // round trip back over the uplink: the release just succeeded, on this same call, so there + // is nothing left to learn from that event. `removeByWorkerLease` still runs when it arrives + // (idempotent -- see `FleetLeaseIndex`), which is what covers a release the worker's own + // TTL or a local operator caused instead. + this.options.leaseIndex.remove(gatewayLeaseId); + } + + /** + * ADR §34: releases only the leases this gateway issued, across every connected worker, and + * never a worker's own local leases. A worker that cannot be reached is reported, naming it, + * while every other worker's releases still complete -- what has already succeeded by the time + * one fails stays released. + * + * H8 (round 2 review): the thrown error's `details.releasedLeaseIds` names everything that did + * succeed before the failure, rather than leaving the operator to guess (§34's own "leaves the + * operator guessing" is exactly the thing this closes) -- `lease.release-all`'s output shape + * (`{ leaseIds }`) still has no room to carry a partial result on its *success* path, so this is + * the one channel available on the answer that does exist. #119, which owns `WORKER_UNREACHABLE` + * retry/backoff, may still want to widen the output shape itself. + */ + async releaseAll(): Promise { + const released: string[] = []; + let firstFailure: unknown; + for (const entry of this.options.leaseIndex.all()) { + try { + await this.#forwardToWorker(entry.workerId, (client) => + client.releaseLease({ leaseId: entry.workerLeaseId }), + ); + this.options.leaseIndex.remove(entry.gatewayLeaseId); + released.push(entry.gatewayLeaseId); + } catch (error: unknown) { + if (this.#forgetIfUnknownToWorker(entry.gatewayLeaseId, error)) { + // C3: the worker already agrees this lease does not exist -- that is not a failure to + // report, it is the release this call asked for, already true. Skip it (not a + // `firstFailure`) rather than making a single zombie entry fail every future + // `release-all` forever. + released.push(entry.gatewayLeaseId); + continue; + } + firstFailure ??= error; + } + } + if (firstFailure !== undefined) { + throw this.#withReleasedDetails(firstFailure, released); + } + return released; + } + + /** + * C3 (round 2 review): a worker answering `UNKNOWN_LEASE` to a release or renew is telling this + * gateway its own index entry is wrong -- the one source of truth for removal + * (`lease.released`/`lease.expired`) never fires for a lease the worker has no record of at + * all, so without this the entry is immortal: every future request from the same requester is + * refused `REQUESTER_ALREADY_LEASED` naming a lease that exists nowhere, and (`releaseAll`) + * every future `lease.release-all` fails on it forever. Returns whether it acted, so a caller + * (`releaseAll`) can fold that lease into its own success accounting instead of its failure one. + */ + #forgetIfUnknownToWorker(gatewayLeaseId: string, error: unknown): boolean { + if (!(error instanceof DispatchError) || error.code !== "UNKNOWN_LEASE") return false; + this.options.leaseIndex.remove(gatewayLeaseId); + return true; + } + + #withReleasedDetails(error: unknown, released: readonly string[]): unknown { + if (!(error instanceof DispatchError)) return error; + const baseDetails = + typeof error.details === "object" && error.details !== null ? error.details : {}; + return new DispatchError(error.code, error.message, { + ...baseDetails, + releasedLeaseIds: released, + }); + } + + async exec( + input: FleetExecInput, + session: DispatchSession, + ): Promise<{ readonly exitCode: number }> { + const entry = this.#requireEntry(input.leaseId); + // ADR §19b/§27: the worker checks this *namespaced* requester against the lease in front of + // it (§19a'), so it must be built from the lease's own recorded requester -- never from + // whatever `device.exec`'s own optional `requesterId` said, which the gateway's own + // `authorize` hook (via `leaseRequesterId` above) has already resolved by the time this + // handler runs. + const namespacedRequesterId = `${this.options.leaseIndex.requesterPrefix}${entry.requesterId}`; + // ADR §19a/§19e: `session.onStarted` means "the process now exists", and a transport chooses + // its response shape on it -- HTTP commits its `200` and starts an SSE stream, so every + // failure that can happen *before* a process exists (§19a''s `FORBIDDEN` when the worker's own + // ownership check disagrees with this gateway's index, the driver's `PASSTHROUGH_REFUSED` / + // `UNKNOWN_PASSTHROUGH_TOOL`) has to reach the caller as its own status code instead. + // + // This gateway cannot infer that moment: it holds no driver refusal list and does not + // duplicate the worker-side ownership check. Two earlier attempts to infer it each broke one + // half of the contract -- announcing before the forward went out turned a `FORBIDDEN` between + // two fleet agents into a `200` + SSE `error` (round 2), and deferring to the first relayed + // `output` chunk left a *silent* long-running command (§19b's own worked example, + // `simctl install `) with no `200` and no keepalives at all (round 3), then a timed + // grace window put the first failure back for any refusal slower than the guess (round 4). + // + // So the worker sends the fact instead of the gateway guessing it. Its dispatcher already + // computes this exact moment -- it spawns the child and then calls `onStarted` -- and ADR + // §19a's request-scoped push family carries it (`started`, see `contract/pushes.ts`). + // Relaying it is all this needs. + // + // `started` is part of protocol 5, not an addition on top of it: 5 has never shipped (`main` + // advertises 3; 4 and 5 both land with this stack), so it releases as one version carrying + // `device.exec`, its `output` family, `status.get`'s `mode`, the gateway surface and this + // frame together. Nothing will ever advertise 5 without it, which is exactly why the grace + // timer could be deleted outright rather than kept as a fallback -- there is no peer to fall + // back for, and a second path to this signal would be the duplication architecture rule 10 + // forbids. A worker older than protocol 5 negotiates nothing and is `incompatible` by range + // (§31), so it is never dispatched to at all. + let started = false; + const announceStarted = (): void => { + if (started) return; + started = true; + session.onStarted?.(); + }; + // H4 (round 3 review): `#withExecTimeout` settling `EXEC_TIMEOUT` only stops *this* call's + // returned promise from being awaited any further -- the worker's own `client.exec` RPC is + // never cancelled, and its `onOutput` closure below stays live for as long as the worker + // keeps sending chunks, relaying every one of them into `session.onOutput` long after the + // caller has already been told this command timed out. Nothing here made that safe; it was + // HTTP's own `OutputRelay.drop()` that happened to swallow a push arriving after an SSE + // response had already ended, which is the transport saving this class, not this class + // cancelling anything -- a future non-HTTP frontend has no such backstop. `detached` is + // flipped by `#withExecTimeout`'s own `onTimeout` hook, right as it decides to reject, so no + // late chunk reaches `session.onOutput` (or spuriously fires `onStarted`) once that has + // happened. + let detached = false; + return this.#forwardToWorker(entry.workerId, async (client) => { + // ADR §19e (P5, round 2 review): `gateway.execTimeoutMs` is the backstop for "the worker + // never answers at all" -- the worker's own `exec.timeoutMs` is authoritative for an + // ordinary timeout and is expected to answer first (the gateway's default is deliberately + // the longer of the two), so this only ever fires when nothing else would have. + return this.#withExecTimeout( + client.exec( + { + leaseId: entry.workerLeaseId, + tool: input.tool, + args: [...input.args], + ...(input.stdin === undefined ? {} : { stdin: input.stdin }), + requesterId: namespacedRequesterId, + }, + { + onOutput: (chunk) => { + if (detached) return; + void session.onOutput?.(chunk.stream, chunk.chunk); + }, + // The worker's own "the process exists" fact, relayed verbatim -- the only thing + // that announces `started` here, so there is exactly one path to it. + onStarted: () => { + if (detached) return; + announceStarted(); + }, + }, + ), + entry.workerId, + () => { + detached = true; + }, + ); + }); + } + + /** + * Races a forwarded `device.exec` against `gateway.execTimeoutMs` (ADR §19e). Before this, + * `exec` awaited `client.exec` unbounded -- a worker that never answers at all (the case this + * config value exists for, not an ordinary command timeout the worker's own `exec.timeoutMs` + * already covers) hung the call and its SSE stream forever, and nothing here read the config + * value the schema, validator, and docs already described. + * + * `onTimeout` (H4, round 3 review) is `#raceTimeout`'s own detach hook -- see `exec`'s own + * `detached` flag for why: a client that only stops *awaiting* the worker's answer, without + * also telling `exec`'s `onOutput` closure to stop relaying, would keep forwarding late chunks + * to `session.onOutput` for as long as the worker cared to keep sending them. + */ + #withExecTimeout( + promise: Promise, + workerId: string, + onTimeout: () => void, + ): Promise { + return this.#raceTimeout( + promise, + this.options.execTimeoutMs, + () => + new DispatchError( + "EXEC_TIMEOUT", + `Worker ${workerId} did not answer device.exec within gateway.execTimeoutMs (${String(this.options.execTimeoutMs)}ms)`, + ), + onTimeout, + ); + } + + /** + * P2 (round 2 review): races a forwarded `lease.request` against + * `gateway.leaseRequestTimeoutMs`. Before this, the one uplink call this class makes with no + * bound of its own left a waiter `processing` -- a state neither `WaitQueue#armTimeout` (it + * declines to reject a `processing` waiter) nor `cancelPending` (`not-cancellable`) can reach + * -- for as long as a wedged worker cared to hold it, with `timeoutMs`/`lease.cancel` + * unenforceable the whole time (ADR §10). Expiry maps to `WORKER_UNREACHABLE`: not a fact + * about this worker's capacity (a real answer might still have been a grant), but the same + * "not reachable right now" story `#forwardToWorker`'s pre-flight check already answers that + * code for. + * + * If the worker does eventually answer after this already gave up, that answer is discarded + * here exactly as `#withExecTimeout`'s own doc describes -- a grant landing late becomes an + * orphan lease on the worker (this gateway rejected the waiter and issued nothing to release + * it by), the same class of gap H2/H8 already name for the RPCs this class does track state + * for. A genuinely wedged worker is rare enough, and `leaseRequestTimeoutMs` generous enough, + * that this is left as a known consequence rather than built out here. + * + * `onTimeout` (P4, round 3 review): the same detach hook `#withExecTimeout` already takes, for + * the same reason -- see `#attempt`'s own `detached` flag. + */ + #withLeaseRequestTimeout( + promise: Promise, + workerId: string, + onTimeout: () => void, + ): Promise { + return this.#raceTimeout( + promise, + this.options.leaseRequestTimeoutMs, + () => + new DispatchError( + "WORKER_UNREACHABLE", + `Worker ${workerId} did not answer lease.request within gateway.leaseRequestTimeoutMs (${String(this.options.leaseRequestTimeoutMs)}ms)`, + { workerId }, + ), + onTimeout, + ); + } + + /** + * Mirrors `WorkerLink#withTimeout`'s race-and-cancel shape: whichever of the timer or + * `promise` settles first wins, and the other is inert from then on (the timer is cancelled on + * a real answer; a promise that eventually does settle after the timer already fired is simply + * ignored, not delivered late). + * + * That "ignored, not delivered late" is true of `promise`'s own eventual resolution -- it is + * *not* true, on its own, of anything a callback reachable from `promise` keeps doing after the + * timer wins (H4, round 3 review): `client.exec`'s `onOutput` closure is exactly such a + * callback, invoked directly by the worker's own RPC handling, entirely outside this promise's + * settlement. `onTimeout`, when given, runs synchronously the moment the timer decides to + * reject -- before `buildTimeoutError` is even called -- so a caller with such a callback can + * flip its own "stop relaying" flag in the same tick its timeout error is built, rather than + * relying on a downstream transport (HTTP's `OutputRelay.drop()`) to swallow what this class + * itself never stopped producing. + */ + #raceTimeout( + promise: Promise, + timeoutMs: number, + buildTimeoutError: () => DispatchError, + onTimeout?: () => void, + ): Promise { + return new Promise((resolve, reject) => { + let settled = false; + const timer = this.options.clock.setTimer(timeoutMs, () => { + if (settled) return; + settled = true; + onTimeout?.(); + reject(buildTimeoutError()); + }); + promise.then( + (value) => { + if (settled) return; + settled = true; + this.options.clock.cancel(timer); + resolve(value); + }, + (error: unknown) => { + if (settled) return; + settled = true; + this.options.clock.cancel(timer); + reject(error); + }, + ); + }); + } + + /** Unsubscribes from worker-view changes and rejects every still-pending waiter -- a gateway + * restart loses in-flight requests exactly as a worker restart does (ADR §30), so this makes + * that explicit rather than leaving them to hang on a coordinator nothing will ever drive + * again. */ + dispose(): void { + this.#unsubscribeViews(); + this.#queue.cancelAll(() => new DispatchError("DAEMON_STOPPING", "Gateway is stopping")); + } + + // ---- admission and dispatch ---------------------------------------------------------------- + + /** + * A brand-new waiter's admission. **Architecture rule 10: `noWait` is enforced in exactly one + * place.** Every admission goes through `#dispatch`'s one ordered walk, carrying this waiter + * as its `candidate` -- there is no second, out-of-order look of its own. + * + * There used to be two paths here: a direct `routing.select` when the queue was empty, and an + * enqueue-then-dispatch when it was not. They answered the same question and drifted, exactly + * as rule 10 describes. Four consecutive review rounds each found a fresh defect in that + * disagreement, ending with a request that answered `NO_CAPACITY` immediately or waited in the + * queue depending on whether *unrelated* requests happened to be queued at the time. + * + * Queue membership is committed only once the waiter is actually going to wait. That ordering + * is load-bearing rather than tidy: `WaitQueue#enqueue` pushes a `queued` progress frame to + * the caller and `#enqueue` emits `lease.queued`, and a `noWait` request that is about to be + * refused must produce neither. ADR §10 requires "the same codes and progress states a worker + * uses", and the worker's own `#defer` rejects a `noWait` waiter *before* it enqueues. + * + * H9 (round 2 review): throws a plain `DispatchError("NO_CAPACITY", ...)` rather than a + * fleet-native error class -- `DispatchError`'s own code is used verbatim by + * `daemon/error-code.ts#classifyError`'s first branch, so no gateway-specific class or import + * is needed there to answer the same code the worker's own `NoCapacityError` answers. Before + * this, `src/daemon` (every worker-mode daemon, not just gateway mode) imported that class + * from `src/gateway/fleet-coordinator.js` just to recognize it, pulling the whole gateway + * module graph into ordinary worker startup with no boundary test covering that direction. + */ + #admit(waiter: FleetWaiter): void { + // Attempted -- including attempted and bounced straight back by a stale view, which §11 + // keeps queued even for a `noWait` caller (`#staleView` has already re-enqueued it). + if (this.#dispatch(waiter)) return; + if (waiter.options.noWait === true) { + this.#reject( + waiter, + new DispatchError("NO_CAPACITY", "No worker in the fleet can currently serve this request"), + "no-wait", + ); + return; + } + this.#enqueue(waiter); + } + + /** + * ADR §11: re-run on every worker-view change. Every already-queued waiter not currently in + * flight gets one more look, oldest first; one no eligible worker can serve is passed over, + * not blocked on -- there is no early exit from this loop. + * + * H6 (round 3 review): `routing.select` reads the same unchanged `views()` snapshot for every + * waiter in this loop, so a worker whose view over-reports free capacity relative to what it + * can actually grant right now used to look equally eligible to every one of them -- N queued + * waiters could all pick that one worker in a single pass, and every one past the first came + * back `NO_CAPACITY`, each triggering its own `#staleView` refresh. Self-limiting once the + * refresh lands (the module doc's "the dispatch race"), but an over-reporting view that never + * corrects itself between passes turns this into an RPC storm scaling with queue depth. Once a + * worker is claimed by a waiter this pass, it drops out of the pool the rest of the pass sees: + * at most one dispatch per worker per pass. A waiter left without a worker this way is not + * rejected -- it stays `queued` for the next pass. C1 (round 3 review): that next pass is + * guaranteed now, not merely hoped for -- `#attempt` runs one itself the moment *any* attempt + * settles (a grant via `#settleGrant`, or a terminal rejection), on top of the existing + * worker-view trigger, so a waiter passed over here always gets looked at again once whatever + * claimed its worker this pass is done with it, the same "passed over, not blocked on" contract + * this method already promises for a request no worker can serve at all. Before this, only a + * worker's own event stream (a `lease.rejected`/`lease.expired` push, or the 30s refresh tick) + * ever re-ran this method -- several of `#attempt`'s own terminal branches + * (`WORKER_UNREACHABLE`, `INTERNAL`, a target that disappeared between routing and dispatch) + * produce no such push at all, so a waiter passed over in the same pass as one of those had + * nothing left to schedule another look. + * + * `#dispatchDepth` guards against this method ever running re-entrantly on the same call stack + * (defensive: `#beginAttempt`'s own `#attempt` is `void`-async and every await point in it is + * genuinely asynchronous -- see `#raceTimeout` -- so a nested synchronous call back into this + * method should not be reachable today, but nothing about that is enforced by a type). A nested + * call is *deferred*, not dropped: it sets `#passRequested` and the running call walks again + * once it unwinds. Dropping it was C1's own stall reintroduced by the guard meant to prevent + * recursion -- the outer walk iterates a snapshot and has already claimed workers, so a waiter + * freed mid-pass would never be reconsidered (round 4 review, finding 6). + * + * `candidate` is a brand-new waiter with no queue membership yet; it walks last and the return + * value says whether it was attempted. See `#dispatchPass`. + * + * The deferred passes above deliberately carry **no** candidate, and that is not a dropped + * one (round 5 review): a nested `#dispatch` can only be raised from inside a `#beginAttempt`, + * `#dispatchPass` re-reads `views.views()` per waiter rather than once per pass, and the + * candidate walks last. So every view change a deferred pass exists to react to was already + * raised *before* the candidate's own iteration read the views, and was already visible to it. + * There is no state a second pass could show the candidate that its first look did not have, + * which is why re-offering it there would add a branch no test can fail for the right reason. + */ + #dispatch(candidate?: FleetWaiter): boolean { + if (this.#dispatchDepth > 0) { + // Round 4 review: a nested pass used to be *dropped*. The outer walk iterates a snapshot + // and has already claimed workers, so a waiter freed mid-pass would never be reconsidered + // -- C1's stall, reintroduced silently by the guard meant to prevent recursion. Defer + // instead of dropping: the outer call runs another pass once this one unwinds. + this.#passRequested = true; + return false; + } + this.#dispatchDepth += 1; + let candidateAttempted = false; + try { + candidateAttempted = this.#dispatchPass(candidate); + while (this.#passRequested) { + this.#passRequested = false; + this.#dispatchPass(); + } + } finally { + this.#dispatchDepth -= 1; + this.#passRequested = false; + } + return candidateAttempted; + } + + /** + * One ordered, oldest-first walk -- the single place a waiter is matched to a worker. + * + * `candidate` is a brand-new waiter that has no queue membership yet (`#admit`'s). It walks + * **last**, because it is the newest: that is what keeps ADR §10's single fleet FIFO honest, + * since an admission can never take a slot an already-queued waiter would have had. Returns + * whether the candidate was attempted, which is what lets `#admit` tell "nothing could serve + * it" from "it was attempted and bounced straight back by a stale view" -- §11 keeps the + * second one queued even for a `noWait` caller, and `waiter.state` alone cannot distinguish + * them (round 4 review, finding 2). + */ + #dispatchPass(candidate?: FleetWaiter): boolean { + let candidateAttempted = false; + const claimedThisPass = new Set(); + const waiters = + candidate === undefined ? this.#queue.list() : [...this.#queue.list(), candidate]; + for (const waiter of waiters) { + // The candidate is not in the queue yet, so it has no `queued` state to check. + if (waiter !== candidate && waiter.state !== "queued") continue; + const eligibleWorkers = this.options.views + .views() + .filter((worker) => !claimedThisPass.has(worker.id)); + const decision = this.options.routing.select(routable(waiter), eligibleWorkers); + if (decision === undefined) continue; + claimedThisPass.add(decision.workerId); + if (waiter === candidate) candidateAttempted = true; + this.#beginAttempt(waiter, decision); + } + return candidateAttempted; + } + + /** + * H2 (round 2 review): `markProcessing`'s own `false` return -- the waiter is already terminal + * -- used to be ignored, issuing the RPC anyway. Masked in practice by every caller + * (`#admit`/`#dispatch`) only ever reaching this with a live waiter today, but nothing enforced + * that: a grant landing for a waiter that settled a moment earlier would still be indexed by + * `#settleGrant` while `queue.resolve` quietly answers `false`, leaving an orphan lease no + * client holds a reference to release. + */ + #beginAttempt(waiter: FleetWaiter, decision: RoutingDecision): void { + if (!this.#queue.markProcessing(waiter)) return; + void this.#attempt(waiter, decision); + } + + /** + * Every exit from this method leaves `waiter` either terminal (`resolve`/`reject`, inside + * `#settleGrant`/the catch below) or back in `queued` (`#staleView`'s `#enqueue`) -- never + * stuck `processing` with nothing left to drive it, and never in two places disagreeing about + * which. C1 (round 2 review): the first early return used to skip straight to `#staleView` + * without first clearing a separate `#dispatchTargets` mark this method used to set -- the mark + * survived the re-queue, and `#dispatch`'s guard on it then skipped this waiter forever. Since + * `queue.markProcessing`/`#enqueue` (`WaitQueue`'s own state, not a second map this class kept + * beside it) is now the *only* bookkeeping a waiter's in-flight-ness lives in, every branch + * below already leaves it in one of exactly those states on its own -- there is no second + * clear-up step left to forget. + * + * C1 (round 3 review): the two branches that leave `waiter` *terminal* -- `#settleGrant`, and + * the catch block's own `queue.reject` -- also each call `#dispatch()` themselves, right after. + * `#staleView`'s own branches (the unreachable-target check above, and the catch's immediate + * `NO_CAPACITY`) do not need to: both already call a worker's `refresh()`, and a real snapshot + * landing for it fires `#onViewsChanged` -> `#dispatch()` regardless of whether the numbers + * actually changed. The terminal branches have no such follow-up of their own -- a worker this + * class gave up on (`WORKER_UNREACHABLE`, `INTERNAL`) or was refused for a reason genuinely + * unrelated to capacity (any other worker-side code) may still be exactly the worker a different + * queued waiter needs, and nothing else would ever schedule that second look. + */ + async #attempt(waiter: FleetWaiter, decision: RoutingDecision): Promise { + const workerId = decision.workerId; + const target = this.options.directory.target(workerId); + const client = target?.reachable === true ? target.client() : undefined; + if (client === undefined) { + // The view named a worker that is no longer reachable by the time we got here -- the same + // "stale, not wrong" story as a worker's own `NO_CAPACITY`, just discovered a step earlier. + this.#staleView(waiter, workerId); + return; + } + + const namespacedRequesterId = `${this.options.leaseIndex.requesterPrefix}${waiter.options.requesterId}`; + let announced = false; + const announceDispatched = (): void => { + if (announced) return; + announced = true; + // C2 (round 2 review): the full payload `docs/EVENTS.md` always specified for this row -- + // see `bus/index.ts`'s own doc comment on why it was narrowed and then restored. + const createdAt = this.#createdAt.get(waiter); + this.#emit("request.dispatched", { + model: waiter.request.model, + platform: waiter.request.platform, + queuedMs: createdAt === undefined ? 0 : Math.max(0, this.options.clock.now() - createdAt), + reason: decision.reason, + requestId: waiter.id, + requesterId: waiter.options.requesterId, + workerId, + }); + }; + + // P4 (round 3 review): H4's own reasoning applies verbatim here -- `#withLeaseRequestTimeout` + // settling `WORKER_UNREACHABLE` only stops *this* call's returned promise from being awaited + // any further, not the worker's own still-pending `lease.request` RPC, whose `onProgress` + // closure below stays live for as long as the worker keeps pushing progress. Before this, + // a late `progress` push after the timeout had already rejected the waiter still called + // `announceDispatched()` and emitted `request.dispatched` for a request this gateway had + // already told its caller was `WORKER_UNREACHABLE` -- a false past-tense fact against + // `docs/EVENTS.md`'s own "and the worker took it". Same mechanism as `exec`'s `detached`, not + // a second bespoke one: flipped by `#withLeaseRequestTimeout`'s own `onTimeout` hook, checked + // here before either `announceDispatched()` or `notifyProgress` run. + let detached = false; + let grant: LeaseGrant; + try { + grant = await this.#withLeaseRequestTimeout( + client.requestLease( + { + platform: waiter.request.platform, + model: waiter.request.model, + ...(waiter.request.osVersion === undefined + ? {} + : { osVersion: waiter.request.osVersion }), + ...(waiter.request.full === true ? { full: true } : {}), + requesterId: namespacedRequesterId, + // ADR §27a (narrowed, round 3 review, H3): only the worker's own gateway-uplink + // session may set `owner` -- and this RPC always travels over exactly that + // connection (`WorkerLink#connect`, via `acceptUplink` on the worker's own end, see + // `session.isGatewayUplink`'s doc). The worker stores this verbatim as the lease's + // `ownerId` instead of deriving it from the connection -- see + // `daemon/dispatcher.ts`'s `#leaseRequest`. + owner: waiter.options.ownerId, + allowDownload: waiter.options.allowDownload ?? false, + // ADR §12: worker queues never hold gateway traffic. Every dispatch is `noWait` + // regardless of what the original caller asked the gateway for -- the *gateway's + // own* queue is where a "wait" request actually waits. + noWait: true, + ...(waiter.options.ttlMs === undefined ? {} : { ttlMs: waiter.options.ttlMs }), + }, + { + onProgress: (progress) => { + if (detached) return; + // ADR §11: "the first `progress` push" is one of the two signals a request is + // this worker's now -- device work having started means it is committed here even + // before the grant itself arrives. + announceDispatched(); + this.#queue.notifyProgress(waiter, progress); + }, + }, + ), + workerId, + () => { + detached = true; + }, + ); + } catch (error: unknown) { + // P1 (round 2 review): "an *immediate* NO_CAPACITY is the only answer that leaves it + // queued ... the request waits" (§11) -- `announced` is exactly the "work has begun" + // distinction the ADR draws, already maintained above for `request.dispatched`. A worker + // can answer `NO_CAPACITY` *after* pushing progress (its own `#evictManaged` failure path, + // reached from a `noWait` waiter's `#defer`, runs after `provisioning`/`reclaiming`), and + // that is this request's own terminal failure -- not a stale view to retry, because device + // work already started means the request was this worker's (§11's own wording). Re-queuing + // it anyway silently reversed a dispatch the caller had already been told about. + if (isSimlockError(error) && error.code === "NO_CAPACITY" && !announced) { + this.#staleView(waiter, workerId); + return; + } + // C1 (round 3 review): this waiter's own outcome is terminal, but the worker it just gave + // up (or never actually reached) may still be free for whoever else is queued behind it -- + // and unlike `#staleView`'s branch above, nothing else here schedules another look at them. + // `WORKER_UNREACHABLE`/`INTERNAL` in particular produce no worker-side event at all, so + // without this a waiter passed over in this same pass had nothing left to wake it until the + // next real worker-view change (the 30s refresh tick, at best). + this.#queue.reject(waiter, this.#classifyLeaseRequestError(error, workerId)); + this.#dispatch(); + return; + } + + announceDispatched(); + this.#settleGrant(waiter, workerId, grant); + // C1 (round 3 review): see the catch branch above -- a grant settling this waiter is just as + // much a reason for whoever else is queued to get another look, not only a terminal failure. + this.#dispatch(); + } + + /** + * A terminal failure past `#attempt`'s `NO_CAPACITY`/stale-view check is the worker's own fact + * (it already emitted its own `lease.rejected`, relayed onto this bus with `workerId` added by + * `WorkerLink`) -- this class does not emit a second one for it (see the module doc, "two + * different fields", and events.md's post-commit rule apply equally to not inventing a + * duplicate fact). Only the error code is preserved so the caller sees what the worker actually + * said, with three exceptions: + * + * - a transport failure (the uplink itself, not the worker's own answer) -- ADR §28/§29 name + * `WORKER_UNREACHABLE` for that, not whatever the client's own connection loss happens to be + * called (`daemon/dispatch.js`'s `SimlockError.kind` is what tells the two apart); + * - `#withLeaseRequestTimeout`'s own `DispatchError` (P2, round 2 review) -- never a + * `SimlockError`, since it never reached the worker at all -- forwarded as-is; + * - anything else that is neither of those (H1, round 2 review): not a fact about the worker, + * since every real transport failure already arrives as a `kind: "transport"` `SimlockError`, + * so this is a bug in this coordinator's own request-building code. `WORKER_UNREACHABLE` + * used to answer this case too, misreporting a gateway-side crash as "the machine is + * unreachable"; `INTERNAL` is what `#forwardToWorker`'s matching branch answers for the same + * shape of failure. + */ + #classifyLeaseRequestError(error: unknown, workerId: string): DispatchError { + if (error instanceof DispatchError) return error; + if (isSimlockError(error)) return this.#classifyRelayedError(error, workerId); + return new DispatchError( + "INTERNAL", + `Unexpected error forwarding lease.request to worker ${workerId}`, + { workerId }, + ); + } + + /** ADR §11: "an immediate `NO_CAPACITY` is the only answer that leaves it queued ... the + * request waits" -- unconditionally, even for a caller that asked `noWait: true` (the one + * explicit exception the ADR calls out), because this is a stale view, not a real refusal. */ + #staleView(waiter: FleetWaiter, workerId: string): void { + this.#enqueue(waiter); + const target = this.options.directory.target(workerId); + void target?.refresh().catch((error: unknown) => { + this.#logger.debug("Failed to refresh a worker's view after a stale-view NO_CAPACITY", { + workerId, + message: error instanceof Error ? error.message : String(error), + }); + }); + } + + /** + * H6 (round 2 review): the entry's `ownerId` comes from `waiter.options.ownerId` -- what this + * gateway itself forwarded as `owner` in the `lease.request` a moment ago -- never from the + * worker's own echo of it (`grant.lease.ownerId`). Everything this gateway authorizes + * afterwards (`lease.renew`/`release`/`device.exec`) keys on the index's `ownerId`, so a worker + * that ignored or rewrote the field would otherwise redefine ownership at the gateway; the + * rebuild path (`FleetLeaseIndex#rebuildFromWorker`) has no better source and must trust the + * worker, but this path already knows the answer. A mismatched echo is logged -- it means + * either a worker bug or something worth knowing about, never silently swallowed. + */ + #settleGrant(waiter: FleetWaiter, workerId: string, grant: LeaseGrant): void { + const gatewayLeaseId = `${workerId}.${grant.lease.id}`; + if (grant.lease.ownerId !== waiter.options.ownerId) { + this.#logger.warn("Worker echoed an ownerId different from the one the gateway forwarded", { + echoedOwnerId: grant.lease.ownerId, + forwardedOwnerId: waiter.options.ownerId, + gatewayLeaseId, + workerId, + }); + } + const entry: FleetLeaseEntry = { + gatewayLeaseId, + grantedAt: grant.lease.grantedAt, + ownerId: waiter.options.ownerId, + requesterId: waiter.options.requesterId, + workerId, + workerLeaseId: grant.lease.id, + }; + this.options.leaseIndex.add(entry); + const fleetGrant: FleetLeaseGrant = { + device: grant.device, + environment: grant.environment, + lease: this.#projectRecord(grant.lease, entry), + timing: grant.timing, + }; + this.#queue.resolve(waiter, fleetGrant); + } + + #enqueue(waiter: FleetWaiter): void { + const alreadyQueued = this.#queue.isQueued(waiter); + if (this.#queue.enqueue(waiter) && !alreadyQueued) { + this.#emit("lease.queued", { queuePosition: this.#queue.depth, requestId: waiter.id }); + } + } + + #reject(waiter: FleetWaiter, error: Error, reason: "no-wait" | "cancelled" | "timeout"): void { + if (this.#queue.reject(waiter, error)) { + this.#emit("lease.rejected", { requestSpec: waiter.request, reason }); + } + } + + // ---- forwarding and views ------------------------------------------------------------------- + + /** The one chokepoint every forwarded operation funnels through -- #119's seam for + * `WORKER_UNREACHABLE` retry/backoff, without touching `renew`/`release`/`releaseAll`/`exec` + * individually. */ + async #forwardToWorker( + workerId: string, + fn: (client: SimlockAdminClient) => Promise, + ): Promise { + const target = this.options.directory.target(workerId); + const client = target?.reachable === true ? target.client() : undefined; + if (client === undefined) { + throw new DispatchError("WORKER_UNREACHABLE", `Worker ${workerId} is not reachable`, { + workerId, + }); + } + try { + return await fn(client); + } catch (error: unknown) { + if (isSimlockError(error)) throw this.#classifyRelayedError(error, workerId); + // H1 (round 2 review): rethrown unchanged before this fix, which let a `TypeError` in this + // coordinator's own request-building code surface exactly as if the worker itself had + // produced it -- no code, no `kind`, nothing a caller could branch on the way it could on + // every other failure this class answers. Every real transport failure already arrives as + // a `kind: "transport"` `SimlockError` (handled above), so anything else here is this + // gateway's own bug, not a fact about the worker -- `INTERNAL` names that, consistent with + // `#attempt`'s matching branch for the one forward this chokepoint does not cover + // (`lease.request`, bound by `#withLeaseRequestTimeout` instead). + if (error instanceof DispatchError) throw error; + throw new DispatchError( + "INTERNAL", + `Unexpected error forwarding a call to worker ${workerId}`, + { workerId }, + ); + } + } + + /** + * P4 (round 2 review): `error.code` was preserved verbatim for every `SimlockError`, which + * answered a fleet client its own `DAEMON_CONNECTION_LOST` whenever the uplink itself died + * mid-call -- naming *this coordinator's* session to the worker, not the worker's own fact. + * `kind: "transport"` is what the admin client's wire (`src/simlock-client/wire.ts`) stamps on + * every rejection caused by the connection dying under an in-flight call, so it is what + * distinguishes that case from an ordinary domain refusal (`RUNTIME_MISSING`, + * `REQUESTER_ALREADY_LEASED`, ...), which is forwarded byte for byte -- ADR §28/§29 name + * `WORKER_UNREACHABLE` for exactly the transport case, and `#forwardToWorker`'s "not reachable + * right now" branch above already answers that same code for the pre-flight version of it. + */ + #classifyRelayedError(error: AnySimlockError, workerId: string): DispatchError { + if (error.kind === "transport") { + return new DispatchError("WORKER_UNREACHABLE", error.message, { workerId }); + } + return new DispatchError(error.code, error.message, error.details); + } + + #requireEntry(gatewayLeaseId: string): FleetLeaseEntry { + const entry = this.options.leaseIndex.resolve(gatewayLeaseId); + if (entry === undefined) { + throw new DispatchError("UNKNOWN_LEASE", `Unknown lease: ${gatewayLeaseId}`, { + leaseId: gatewayLeaseId, + }); + } + return entry; + } + + #projectRecord< + Record extends { readonly id: string; readonly requesterId: string; readonly ownerId: string }, + >( + record: Record, + entry: FleetLeaseEntry, + ): Record & { readonly worker?: { readonly id: string; readonly label?: string } } { + const workerLabel = this.options.views.view(entry.workerId)?.label; + return { + ...record, + id: entry.gatewayLeaseId, + // H6 (round 2 review): the index's own `ownerId` (trusted -- see `#settleGrant`), never + // this record's raw `ownerId` as a worker's own RPC answer echoed it back. + ownerId: entry.ownerId, + requesterId: entry.requesterId, + ...(workerLabel === undefined + ? { worker: { id: entry.workerId } } + : { worker: { id: entry.workerId, label: workerLabel } }), + }; + } + + /** + * §30's reconnect rebuild, and its own upkeep on every worker-view change: reconciles each + * worker's entries against its current view -- adding any gateway-issued lease the index does + * not already know and, a generation later, forgetting one the view has stopped reporting at + * all (see `FleetLeaseIndex#rebuildFromWorker`'s own doc comment, C3 round 2 review) -- forgets + * a worker's entries entirely once its view has disappeared (`worker.remove`, or retention), + * then runs a dispatch pass. + * + * C1 (round 2 review): `rebuildFromWorker` runs *only* for a worker whose `view.leases` + * reference actually changed since the last time this method reconciled it -- see + * `#lastReconciledLeases`'s own doc. Before this fix, every view was reconciled on *every* + * notification regardless of which worker it was about: two view changes on worker B alone + * bumped worker A's reconciliation generation twice against A's own byte-identical, stale + * cached snapshot, which is enough for `rebuildFromWorker`'s two-consecutive-misses rule to + * evict a lease on A that was never actually missing from a real snapshot at all -- silently + * violating ADR §14 (the fleet-wide one-lease check reads this same index) and losing the + * `lease-lost` push `GatewayOwnerRoutedFacts` would otherwise emit for it. + */ + #onViewsChanged(): void { + const views = this.options.views.views(); + const currentIds = new Set(views.map((view) => view.id)); + for (const view of views) { + if (this.#lastReconciledLeases.get(view.id) === view.leases) continue; + this.options.leaseIndex.rebuildFromWorker(view.id, view.leases); + this.#lastReconciledLeases.set(view.id, view.leases); + } + for (const workerId of this.#knownWorkerIds) { + if (!currentIds.has(workerId)) { + this.options.leaseIndex.forgetWorker(workerId); + this.#lastReconciledLeases.delete(workerId); + } + } + this.#knownWorkerIds = currentIds; + this.#dispatch(); + } + + #emit(event: Event, payload: EventMap[Event]): void { + this.options.eventBus.emit(event, payload, "fleet-lease-coordinator"); + } +} + +function routable(waiter: FleetWaiter): RoutableRequest { + return { + platform: waiter.request.platform as Platform, + model: waiter.request.model, + ...(waiter.request.osVersion === undefined ? {} : { osVersion: waiter.request.osVersion }), + allowDownload: waiter.options.allowDownload ?? false, + }; +} diff --git a/src/gateway/fleet-ports.ts b/src/gateway/fleet-ports.ts index d0f6d3f86..b2e074ef9 100644 --- a/src/gateway/fleet-ports.ts +++ b/src/gateway/fleet-ports.ts @@ -1,16 +1,14 @@ /** - * `src/gateway/fleet-ports.ts` -- the seam #118 (fleet queue, routing, forwarding) codes - * against, declared here so that PR can be written while this one's internals are still - * being revised. + * `src/gateway/fleet-ports.ts` -- the seam #118 (`FleetLeaseCoordinator`, in + * `fleet-coordinator.ts`) codes against instead of importing `WorkerLink`/`WorkerRegistry`/ + * `GatewayService` directly, so a change *behind* one of these shapes (a call timeout, the + * drain-flag split, a truncation guard) is not a change the coordinator has to see. * - * Nothing here has an implementation of its own: `WorkerLink`, `WorkerRegistry` and - * `GatewayService` satisfy these shapes, and the point is that #118 never imports those - * classes directly -- so a change *behind* one of these shapes (a call timeout, the - * drain-flag split, a truncation guard) is not a change #118 has to see. - * - * Declared before its consumer exists, so `fallow` is told that is deliberate -- the same - * annotation `DrainStore` already carries in `index.ts`. #118 owns these shapes once it - * lands: if one is wrong, that PR changes it rather than working around it. + * Nothing here has an implementation of its own: `WorkerLink` satisfies `WorkerDispatchTarget`, + * `WorkerRegistry` satisfies `FleetViews`, and `GatewayService` satisfies `WorkerDirectory`. + * These shapes are #118's now: `refresh()` on `WorkerDispatchTarget` is this PR's own addition + * (see its doc comment) -- the seam changes here, not around it, when one of these shapes turns + * out to be missing something the coordinator needs. */ import type { SimlockAdminClient } from "../admin/index.js"; import type { WorkerView } from "./worker-registry.js"; @@ -32,10 +30,22 @@ export interface WorkerDispatchTarget { readonly workerId: string; readonly reachable: boolean; client(): SimlockAdminClient | undefined; + /** + * Added by #118. Forces this worker's view to be re-read now, rather than waiting for the + * next lease event or the periodic tick. Called after a stale-view `NO_CAPACITY` (ADR §11: + * "it means the view was stale, so the gateway refreshes that worker's view and the request + * waits") -- without it, a request that lost a race to a stale view would sit queued for up + * to the periodic tick's whole interval before the gateway even tried to find out whether the + * view was right. `WorkerLink` already does this same refresh for every other trigger this + * interface's other members are read from (a lease event, the periodic tick); this is the one + * more call site, and `WorkerLink#refresh` already accepts being called with no arguments. + * Never rejects, mirroring `WorkerLink#refresh`'s own best-effort contract. + */ + refresh(): Promise; } -/** Resolves a worker id to its live link. `GatewayService` satisfies this. */ -// fallow-ignore-next-line unused-type -- #118's seam; declared before its consumer exists. +/** Resolves a worker id to its live link. `GatewayService` satisfies this; + * `FleetLeaseCoordinator` is the consumer. */ export interface WorkerDirectory { target(workerId: string): WorkerDispatchTarget | undefined; } @@ -48,7 +58,6 @@ export interface WorkerDirectory { * it. Listeners are called *after* the change is committed (and after the corresponding event * is emitted), per `events.md`'s post-commit rule; the returned function unsubscribes. */ -// fallow-ignore-next-line unused-type -- #118's seam; declared before its consumer exists. export interface FleetViews { views(): readonly WorkerView[]; view(workerId: string): WorkerView | undefined; diff --git a/src/gateway/index.ts b/src/gateway/index.ts index 0ae9c86a8..63b2e71a4 100644 --- a/src/gateway/index.ts +++ b/src/gateway/index.ts @@ -19,9 +19,19 @@ export { GatewayDispatcher } from "./dispatcher.js"; // fallow-ignore-next-line unused-type -- public option shape for anyone composing a gateway; `main.ts` builds one inline. export type { GatewayTokenStore } from "./dispatcher.js"; export { GatewayService, type GatewayServiceOptions } from "./service.js"; -// fallow-ignore-next-line unused-type -- #118's seam; declared before its consumer exists. +// fallow-ignore-next-line unused-type -- public seam types (WorkerLink/WorkerRegistry/GatewayService satisfy them); #118's FleetLeaseCoordinator imports them directly from fleet-ports.js rather than through this barrel, so a custom implementation is this re-export's only consumer. export type { FleetViews } from "./fleet-ports.js"; -// fallow-ignore-next-line unused-type -- #118's seam; declared before its consumer exists. +// fallow-ignore-next-line unused-type -- see FleetViews above. export type { WorkerDirectory } from "./fleet-ports.js"; -// fallow-ignore-next-line unused-type -- #118's seam; declared before its consumer exists. +// fallow-ignore-next-line unused-type -- see FleetViews above. export type { WorkerDispatchTarget } from "./fleet-ports.js"; +export { FleetLeaseCoordinator } from "./fleet-coordinator.js"; +export { FleetLeaseIndex } from "./lease-index.js"; +// fallow-ignore-next-line unused-type -- public record shape for FleetLeaseIndex's own consumers; no current caller outside src/gateway needs the type by name. +export type { FleetLeaseEntry } from "./lease-index.js"; +export { createRoutingPolicy, isRoutingPolicyName } from "./routing.js"; +// fallow-ignore-next-line unused-export -- public registry surface (mirrors capacityStrategyNames); routing.test.ts imports it directly from routing.js, not through this barrel. +export { DEFAULT_ROUTING_POLICY, routingPolicyNames } from "./routing.js"; +// fallow-ignore-next-line unused-type -- public shape for a caller implementing its own routing policy; no current one exists outside routing.ts. +export type { RoutingPolicy, RoutingPolicyName } from "./routing.js"; +export { GatewayOwnerRoutedFacts } from "./owner-routed-facts.js"; diff --git a/src/gateway/lease-index.test.ts b/src/gateway/lease-index.test.ts new file mode 100644 index 000000000..13a2bcf21 --- /dev/null +++ b/src/gateway/lease-index.test.ts @@ -0,0 +1,311 @@ +import { describe, expect, it } from "vitest"; + +import type { Logger } from "../ports/index.js"; +import { FleetLeaseIndex, type WorkerReportedLease } from "./lease-index.js"; + +const PREFIX = "gw:instance-1:"; + +/** Records every `warn` call. */ +class RecordingLogger implements Logger { + readonly warnings: Array<{ message: string; fields?: Record }> = []; + + debug(): void {} + info(): void {} + warn(message: string, fields?: Record): void { + this.warnings.push(fields === undefined ? { message } : { fields, message }); + } + error(): void {} + child(): Logger { + return this; + } +} + +function reported(id: string, overrides: Partial = {}): WorkerReportedLease { + return { + grantedAt: 1, + id, + ownerId: "alice-principal", + requesterId: `${PREFIX}alice`, + ...overrides, + }; +} + +function entry(overrides: Partial[0]> = {}) { + return { + gatewayLeaseId: "wrk_1.lse_1", + grantedAt: 1, + ownerId: "alice-principal", + requesterId: "alice", + workerId: "wrk_1", + workerLeaseId: "lse_1", + ...overrides, + }; +} + +describe("FleetLeaseIndex", () => { + describe("add / resolve / lookups", () => { + it("resolves an entry by gateway id, by (workerId, workerLeaseId), by ownerId and by requesterId", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add(entry()); + + expect(index.resolve("wrk_1.lse_1")).toEqual(entry()); + expect(index.findByWorkerLease("wrk_1", "lse_1")).toEqual(entry()); + expect(index.findByWorkerLease("wrk_1", "lse_other")).toBeUndefined(); + expect(index.ownerId("wrk_1.lse_1")).toBe("alice-principal"); + expect(index.leaseRequesterId("wrk_1.lse_1")).toBe("alice"); + expect(index.existingLeaseId("alice")).toBe("wrk_1.lse_1"); + expect(index.all()).toEqual([entry()]); + }); + + it("replaces rather than duplicates when the same gateway id is added twice", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add(entry()); + index.add(entry({ ownerId: "someone-else" })); + + expect(index.all()).toHaveLength(1); + expect(index.ownerId("wrk_1.lse_1")).toBe("someone-else"); + }); + }); + + describe("remove / removeByWorkerLease", () => { + it("remove forgets an entry by gateway id and is a no-op for an unknown one", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add(entry()); + + expect(index.remove("wrk_1.lse_1")).toEqual(entry()); + expect(index.resolve("wrk_1.lse_1")).toBeUndefined(); + expect(index.existingLeaseId("alice")).toBeUndefined(); + expect(index.remove("wrk_1.lse_1")).toBeUndefined(); + }); + + it("removeByWorkerLease finds and forgets atomically, returning the entry it removed", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add(entry()); + + const removed = index.removeByWorkerLease("wrk_1", "lse_1"); + expect(removed).toEqual(entry()); + expect(index.resolve("wrk_1.lse_1")).toBeUndefined(); + expect(index.removeByWorkerLease("wrk_1", "lse_1")).toBeUndefined(); + }); + + it("does not let removing one requester's entry evict a different entry that raced it onto the same requester slot", () => { + // `#byRequester` is keyed by requesterId, one entry deep -- removing an id only clears the + // requester slot when it still points at *that* gateway id, which is what protects a + // requester who released and immediately re-leased from having the new lease's admission + // slot wiped by the old one's removal landing late. + const index = new FleetLeaseIndex(PREFIX); + index.add(entry({ gatewayLeaseId: "wrk_1.lse_1", workerLeaseId: "lse_1" })); + index.remove("wrk_1.lse_1"); + index.add(entry({ gatewayLeaseId: "wrk_1.lse_2", workerLeaseId: "lse_2" })); + + // A late `remove` for the first (already-gone) id must not disturb the second. + index.remove("wrk_1.lse_1"); + expect(index.existingLeaseId("alice")).toBe("wrk_1.lse_2"); + }); + }); + + describe("rebuildFromWorker: additions", () => { + it("adds every gateway-issued lease a snapshot reports that the index does not already know", () => { + const index = new FleetLeaseIndex(PREFIX); + index.rebuildFromWorker("wrk_1", [ + reported("lse_1"), + reported("lse_2", { requesterId: `${PREFIX}bob`, ownerId: "bob-principal" }), + ]); + + expect(index.resolve("wrk_1.lse_1")).toMatchObject({ + ownerId: "alice-principal", + requesterId: "alice", + }); + expect(index.resolve("wrk_1.lse_2")).toMatchObject({ + ownerId: "bob-principal", + requesterId: "bob", + }); + }); + + it("skips a worker's own local lease -- one whose requesterId does not carry this gateway's prefix", () => { + const index = new FleetLeaseIndex(PREFIX); + index.rebuildFromWorker("wrk_1", [reported("lse_local", { requesterId: "local-agent" })]); + + expect(index.resolve("wrk_1.lse_local")).toBeUndefined(); + expect(index.all()).toEqual([]); + }); + + it("does not overwrite an entry it already has with the same snapshot's own copy", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add(entry({ ownerId: "granted-owner" })); + + // A worker's own view reports the same lease with a *different* ownerId -- if this ever + // happened it would be the worker disagreeing with what the gateway itself granted, not + // new information the rebuild should trust over the grant. + index.rebuildFromWorker("wrk_1", [reported("lse_1", { ownerId: "different-owner" })]); + + expect(index.ownerId("wrk_1.lse_1")).toBe("granted-owner"); + }); + }); + + describe("rebuildFromWorker: reconciliation (C3, round 2 review)", () => { + it("removes an entry missing for two consecutive snapshots -- the worker restarted or expired the lease while the uplink was down", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add(entry()); + + // First snapshot after reconnect: the worker no longer reports this lease at all. Without + // C3's fix this is where the old upsert-only index would stop -- the entry survives + // forever, and `agent-1`'s next request is refused REQUESTER_ALREADY_LEASED against a + // lease that exists nowhere. + index.rebuildFromWorker("wrk_1", []); + expect(index.resolve("wrk_1.lse_1")).toBeDefined(); + expect(index.existingLeaseId("alice")).toBe("wrk_1.lse_1"); + + // Second consecutive snapshot still does not report it -- now it is forgotten. + index.rebuildFromWorker("wrk_1", []); + expect(index.resolve("wrk_1.lse_1")).toBeUndefined(); + expect(index.existingLeaseId("alice")).toBeUndefined(); + }); + + it("does not evict an entry that reappears in the very next snapshot -- the one-generation grace window a grant racing a refresh needs", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add(entry()); + + // A single missed snapshot -- the exact shape of a refresh that started before this + // gateway's own grant landed on the worker (the race `rebuildFromWorker`'s own doc comment + // describes) -- must not be enough to evict on its own. + index.rebuildFromWorker("wrk_1", []); + expect(index.resolve("wrk_1.lse_1")).toBeDefined(); + + // The lease is reported again on the very next snapshot: the miss really was a one-off, + // and the entry survives indefinitely from here, not just for one more generation. + index.rebuildFromWorker("wrk_1", [reported("lse_1")]); + expect(index.resolve("wrk_1.lse_1")).toBeDefined(); + + index.rebuildFromWorker("wrk_1", []); + expect(index.resolve("wrk_1.lse_1")).toBeDefined(); + index.rebuildFromWorker("wrk_1", []); + expect(index.resolve("wrk_1.lse_1")).toBeUndefined(); + }); + + it("never removes an entry attributed to a different worker", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add( + entry({ gatewayLeaseId: "wrk_1.lse_1", workerId: "wrk_1", workerLeaseId: "lse_1" }), + ); + index.add( + entry({ gatewayLeaseId: "wrk_2.lse_1", workerId: "wrk_2", workerLeaseId: "lse_1" }), + ); + + index.rebuildFromWorker("wrk_1", []); + index.rebuildFromWorker("wrk_1", []); + + expect(index.resolve("wrk_1.lse_1")).toBeUndefined(); + expect(index.resolve("wrk_2.lse_1")).toBeDefined(); + }); + }); + + describe("removeByWorkerLease resurrection (C1, round 2 review)", () => { + it("logs when a snapshot re-reports a lease removeByWorkerLease just forgot, instead of silently resurrecting it unremarked", () => { + const logger = new RecordingLogger(); + const index = new FleetLeaseIndex(PREFIX, logger); + index.add(entry()); + + // The worker's own relayed `lease.expired`/`lease.released` forgets it... + index.removeByWorkerLease("wrk_1", "lse_1"); + expect(index.resolve("wrk_1.lse_1")).toBeUndefined(); + + // ...but a snapshot that started gathering data before that fact landed completes after + // it and still reports the same worker lease id. The worker is the source of truth, so + // the entry is still re-added (a caller must not lose a lease the worker still holds)... + index.rebuildFromWorker("wrk_1", [reported("lse_1")]); + expect(index.resolve("wrk_1.lse_1")).toBeDefined(); + + // ...but this is not an ordinary addition, and round 2 flagged silently swallowing it. + expect( + logger.warnings.some( + (warning) => + warning.fields?.gatewayLeaseId === "wrk_1.lse_1" && warning.fields.workerId === "wrk_1", + ), + ).toBe(true); + }); + + it("does not warn for an ordinary addition that was never removed by a relayed event", () => { + const logger = new RecordingLogger(); + const index = new FleetLeaseIndex(PREFIX, logger); + + index.rebuildFromWorker("wrk_1", [reported("lse_1")]); + + expect(logger.warnings).toEqual([]); + }); + }); + + describe("forgetWorker", () => { + it("drops every entry attributed to the forgotten worker, and no other", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add( + entry({ gatewayLeaseId: "wrk_1.lse_1", workerId: "wrk_1", workerLeaseId: "lse_1" }), + ); + index.add( + entry({ + gatewayLeaseId: "wrk_2.lse_1", + workerId: "wrk_2", + workerLeaseId: "lse_1", + requesterId: "bob", + }), + ); + + index.forgetWorker("wrk_1"); + + expect(index.resolve("wrk_1.lse_1")).toBeUndefined(); + expect(index.existingLeaseId("alice")).toBeUndefined(); + expect(index.resolve("wrk_2.lse_1")).toBeDefined(); + }); + + it("starts reconciliation over for a worker id that reconnects after being forgotten, rather than inheriting a stale generation", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add(entry()); + index.rebuildFromWorker("wrk_1", []); // one miss recorded, entry still protected + index.forgetWorker("wrk_1"); // the worker's view disappeared entirely (retention) + + // The same worker id reconnects and immediately reports the lease again (a worker that + // never actually lost it -- only the gateway's view of it lapsed). A stale one-miss + // generation surviving `forgetWorker` would have no way to hurt this case since the entry + // itself is gone too, but the fresh add below must not be evicted by leftover bookkeeping. + index.rebuildFromWorker("wrk_1", [reported("lse_1")]); + index.rebuildFromWorker("wrk_1", [reported("lse_1")]); + expect(index.resolve("wrk_1.lse_1")).toBeDefined(); + }); + }); + + describe("project", () => { + it("rewrites a recognized lease's id/requesterId and attaches worker, passing through an unrecognized one with only workerId added", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add(entry()); + + const projected = index.project( + { id: "lse_1", requesterId: `${PREFIX}alice` }, + "wrk_1", + "Alice's Mac", + ); + expect(projected).toEqual({ + id: "wrk_1.lse_1", + requesterId: "alice", + workerId: "wrk_1", + worker: { id: "wrk_1", label: "Alice's Mac" }, + }); + + const passthrough = index.project( + { id: "lse_local", requesterId: "local-agent" }, + "wrk_1", + undefined, + ); + expect(passthrough).toEqual({ + id: "lse_local", + requesterId: "local-agent", + workerId: "wrk_1", + }); + }); + }); + + describe("requesterPrefix", () => { + it("exposes exactly the prefix it was constructed with", () => { + expect(new FleetLeaseIndex(PREFIX).requesterPrefix).toBe(PREFIX); + }); + }); +}); diff --git a/src/gateway/lease-index.ts b/src/gateway/lease-index.ts new file mode 100644 index 000000000..0f9407d70 --- /dev/null +++ b/src/gateway/lease-index.ts @@ -0,0 +1,303 @@ +import type { Logger } from "../ports/index.js"; +import { NoopLogger } from "../ports/index.js"; + +/** + * `FleetLeaseIndex`: the gateway's own record of which leases *it* issued (ADR 0005 §14, §16, + * §27a, §30). Nothing here is persisted -- like every worker view, it is rebuilt from what a + * worker reports (`rebuildFromWorker`) whenever the gateway can see it, which is what makes a + * gateway restart lose nothing a worker restart would not also lose (Decision 5). + * + * A gateway lease id is minted once, at grant, as `${workerId}.${workerLeaseId}` (§16) and never + * re-derived by splitting the string back apart -- every lookup in this class goes through the + * map this index keeps, keyed by the id it minted or by the `(workerId, workerLeaseId)` pair a + * relayed worker event carries. The "split on the first `.`" the ADR describes is what makes the + * id *routable in principle* (a worker id is a UUID, so it can never itself contain the + * separator); nothing in this codebase needs to actually perform that split, because this index + * always has the structured pair already. + */ + +/** One lease this gateway knows it issued. `requesterId`/`ownerId` are the *fleet-level* + * identities -- `requesterId` with no `gw::` prefix (what the client itself used), + * `ownerId` the real principal ADR §27a rescued from a round trip through the worker. */ +export interface FleetLeaseEntry { + readonly gatewayLeaseId: string; + readonly workerId: string; + readonly workerLeaseId: string; + readonly requesterId: string; + readonly ownerId: string; + readonly grantedAt: number; +} + +/** The subset of a worker-reported lease record this index needs to recognize and rebuild its + * own entries from (`WorkerView.leases`'s element shape, structurally). */ +export interface WorkerReportedLease { + readonly id: string; + readonly requesterId: string; + readonly ownerId: string; + readonly grantedAt: number; +} + +/** A lease record projected for a fleet client: rewritten to the gateway's id and fleet-level + * requester, with `worker` attached, when the index recognizes it; passed through unchanged + * (plus `workerId`) when it does not -- a worker's own local lease, which this gateway never + * issued and has no business renaming (test: "lease.list rewrites ids only for gateway-issued + * leases; a worker's own local lease keeps its raw id"). */ +export type ProjectedLease = Lease extends { + readonly id: string; + readonly requesterId: string; +} + ? Lease & { + readonly workerId: string; + readonly worker?: { readonly id: string; readonly label?: string }; + } + : never; + +export class FleetLeaseIndex { + readonly #byGatewayId = new Map(); + readonly #byRequester = new Map(); + readonly #byWorkerLease = new Map(); + /** C3 (round 2 review): one strictly-increasing counter per worker, bumped on every + * `rebuildFromWorker` call for that worker -- what lets reconciliation (below) tell "missing + * from this snapshot" apart from "missing for a whole extra snapshot in a row" without + * comparing clocks across two processes. */ + readonly #generation = new Map(); + /** C3: the generation at which an entry attributed to a still-known worker was first found + * absent from a `rebuildFromWorker` snapshot. Cleared the moment the entry is reported again + * (the race this guards against is a one-snapshot fluke, not a real disappearance), and read + * again by the *next* `rebuildFromWorker` call for that worker: still absent one full + * generation later is what promotes "missing" to "gone" (see `rebuildFromWorker`'s own doc). */ + readonly #missingSince = new Map(); + /** C1 (round 2 review): gateway lease ids `removeByWorkerLease` just forgot -- an ordinary + * worker-relayed `lease.expired`/`lease.released` -- kept around only long enough to flag the + * one thing that should never legitimately happen next: the *same* id reappearing in a + * `rebuildFromWorker` snapshot moments later. That can only mean a snapshot that started + * gathering data before the relayed fact landed is completing after it, stale by the time it + * arrives; a worker never reissues a lease id, so this is not a real re-grant to admit + * quietly. Bounded (see `#noteRemovedByEvent`) so a long-running gateway's memory does not grow + * with every release it has ever relayed. */ + readonly #removedByEvent = new Map(); + /** How many recently-event-removed ids `#removedByEvent` remembers before evicting the + * oldest -- generous relative to how many leases could plausibly be mid-flight across the + * fleet at once, small relative to a gateway's uptime. */ + static readonly #removedByEventCapacity = 200; + + constructor( + private readonly gatewayRequesterPrefix: string, + private readonly logger: Logger = new NoopLogger(), + ) {} + + /** `gw::` -- what marks a requester id as this gateway's own + * (§14/§27). Exposed so `FleetLeaseCoordinator` namespaces outgoing requester ids with the + * exact same value this index recognizes them by. */ + get requesterPrefix(): string { + return this.gatewayRequesterPrefix; + } + + /** Every entry, for `lease.release-all` (§34's own-leases-only filter) and for a caller + * reconciling worker ids that disappeared entirely (`forgetWorker`). */ + all(): readonly FleetLeaseEntry[] { + return [...this.#byGatewayId.values()]; + } + + resolve(gatewayLeaseId: string): FleetLeaseEntry | undefined { + return this.#byGatewayId.get(gatewayLeaseId); + } + + findByWorkerLease(workerId: string, workerLeaseId: string): FleetLeaseEntry | undefined { + const gatewayLeaseId = this.#byWorkerLease.get(workerKey(workerId, workerLeaseId)); + return gatewayLeaseId === undefined ? undefined : this.#byGatewayId.get(gatewayLeaseId); + } + + ownerId(gatewayLeaseId: string): string | undefined { + return this.resolve(gatewayLeaseId)?.ownerId; + } + + /** The fleet-level requester a gateway lease is attributed to -- `roles.ts`'s + * `AuthorizeContext.leaseRequesterId`, for `device.exec`'s admin-vs-agent gate. */ + leaseRequesterId(gatewayLeaseId: string): string | undefined { + return this.resolve(gatewayLeaseId)?.requesterId; + } + + /** ADR §14: the fleet-wide one-lease-per-requester check, keyed on `requesterId` (never + * `ownerId` -- see the module doc on the distinction). `undefined` means "no lease", so a + * caller gets the existing id to report (`RequesterAlreadyLeasedError`) in the same lookup + * that answers the boolean question. */ + existingLeaseId(requesterId: string): string | undefined { + return this.#byRequester.get(requesterId); + } + + /** Records a lease this gateway just granted. Idempotent by `gatewayLeaseId`: granting twice + * under the same id (it never happens outside a test) replaces rather than duplicates. */ + add(entry: FleetLeaseEntry): void { + this.#byGatewayId.set(entry.gatewayLeaseId, entry); + this.#byRequester.set(entry.requesterId, entry.gatewayLeaseId); + this.#byWorkerLease.set(workerKey(entry.workerId, entry.workerLeaseId), entry.gatewayLeaseId); + } + + /** Forgets one lease by its gateway id -- the gateway's own `lease.release` completing. */ + remove(gatewayLeaseId: string): FleetLeaseEntry | undefined { + const entry = this.#byGatewayId.get(gatewayLeaseId); + if (entry === undefined) return undefined; + this.#forget(entry); + return entry; + } + + /** + * Finds and forgets a lease by the `(workerId, workerLeaseId)` pair a relayed worker event + * carries (`lease.expired`/`lease.released`, republished with `workerId` added). Atomic -- + * look up and remove in one call -- so `GatewayOwnerRoutedFacts` can resolve the fleet + * `ownerId`/gateway lease id for its translated push *before* the entry is gone, with no + * ordering dependency on which of two independent bus subscriptions runs first (finding 4: + * "do not trust a relayed event's `ownerId`" only holds if the lookup and the forget are one + * step, not two). + */ + removeByWorkerLease(workerId: string, workerLeaseId: string): FleetLeaseEntry | undefined { + const entry = this.findByWorkerLease(workerId, workerLeaseId); + if (entry === undefined) return undefined; + this.#forget(entry); + this.#noteRemovedByEvent(entry.gatewayLeaseId); + return entry; + } + + /** Records `gatewayLeaseId` as just forgotten by a relayed worker event, for `#addReported`'s + * resurrection check -- see `#removedByEvent`'s own doc. Evicts the oldest entry once the + * bound is hit; `Map` iterates insertion order, so its first key is always the oldest. */ + #noteRemovedByEvent(gatewayLeaseId: string): void { + this.#removedByEvent.set(gatewayLeaseId, true); + if (this.#removedByEvent.size <= FleetLeaseIndex.#removedByEventCapacity) return; + const oldest = this.#removedByEvent.keys().next().value; + if (oldest !== undefined) this.#removedByEvent.delete(oldest); + } + + /** + * Adds every gateway-issued lease a worker's current view reports that this index does not + * already know (ADR §30's reconnect rebuild; also the ordinary per-refresh path, since + * `WorkerView.leases` is always the worker's complete current set, not a delta). Recognizes + * "gateway-issued" by `requesterId`'s prefix (§14) -- a worker's own local lease never carries + * it and is silently skipped, exactly as it must be for `hasLease`'s admission check to mean + * anything. + * + * Reconciling, not upsert-only (C3, round 2 review): an entry attributed to this worker that + * this snapshot does not mention is removed too, so a worker that lost a gateway-issued lease + * out of band -- restarted, or expired it while the uplink was down -- does not leave an + * immortal entry behind that no relayed `lease.released`/`lease.expired` will ever arrive to + * clear (removal used to have exactly one source of truth, that relayed fact; a worker that + * forgot the lease before reconnecting can never produce one). `removeByWorkerLease` is still + * what clears the ordinary case -- a relayed fact arriving for a lease this snapshot has + * already dropped is simply a no-op there. + * + * The race the old upsert-only comment warned about is real and still handled: a lease this + * gateway granted a moment ago could be missing from a `WorkerLink` refresh that started + * *before* the grant landed on the worker, and removing on that stale a snapshot would evict a + * lease that is very much still held. Protected by a watermark instead of never removing -- + * `#generation`/`#missingSince` (see their own doc comments) require an entry to be missing + * from *two* consecutive snapshots for this worker before it is forgotten, so a single + * unlucky race is always caught by the very next rebuild (the next periodic refresh, or the one + * this class's own caller re-runs after every worker-view change) rather than evicting on the + * first miss. + */ + rebuildFromWorker(workerId: string, leases: readonly WorkerReportedLease[]): void { + const generation = (this.#generation.get(workerId) ?? 0) + 1; + this.#generation.set(workerId, generation); + const reported = this.#addReported(workerId, leases); + this.#reconcileMissing(workerId, generation, reported); + } + + /** `rebuildFromWorker`'s addition half: adds every gateway-issued lease this snapshot reports + * that the index does not already know, and returns the full set of gateway ids it saw (used + * to know which of this worker's *existing* entries this snapshot did not mention). */ + #addReported(workerId: string, leases: readonly WorkerReportedLease[]): ReadonlySet { + const reported = new Set(); + for (const lease of leases) { + if (!lease.requesterId.startsWith(this.gatewayRequesterPrefix)) continue; + const gatewayLeaseId = `${workerId}.${lease.id}`; + reported.add(gatewayLeaseId); + this.#missingSince.delete(gatewayLeaseId); + if (this.#byGatewayId.has(gatewayLeaseId)) continue; + // C1 (round 2 review): this id was forgotten moments ago by the worker's own relayed + // `lease.expired`/`lease.released` -- reappearing in a snapshot now means that snapshot + // was gathered before the relayed fact landed and is only completing late (see + // `#removedByEvent`'s own doc). Logged, not skipped: the worker is the source of truth for + // its own leases, so refusing to re-add would risk permanently hiding a lease the worker + // still genuinely holds on the rare chance this read is right instead of the fact. + if (this.#removedByEvent.delete(gatewayLeaseId)) { + this.logger.warn( + "A worker-reported lease reappeared right after its own relayed expiry/release -- likely a stale snapshot racing the event", + { gatewayLeaseId, workerId }, + ); + } + this.add({ + gatewayLeaseId, + grantedAt: lease.grantedAt, + ownerId: lease.ownerId, + requesterId: lease.requesterId.slice(this.gatewayRequesterPrefix.length), + workerId, + workerLeaseId: lease.id, + }); + } + return reported; + } + + /** `rebuildFromWorker`'s removal half: forgets an existing entry for `workerId` that this + * snapshot did not report, but only once it has failed to appear in *two* consecutive + * snapshots (see `#missingSince`'s own doc comment for why one miss is not enough). */ + #reconcileMissing(workerId: string, generation: number, reported: ReadonlySet): void { + for (const entry of this.all()) { + if (entry.workerId !== workerId || reported.has(entry.gatewayLeaseId)) continue; + const firstMissedAt = this.#missingSince.get(entry.gatewayLeaseId); + if (firstMissedAt === undefined) { + this.#missingSince.set(entry.gatewayLeaseId, generation); + } else if (firstMissedAt < generation) { + this.#forget(entry); + } + } + } + + /** Drops every entry attributed to a worker the gateway has forgotten entirely (its view was + * removed -- `worker.remove`, or retention). A worker's view carrying no leases is not this: + * that is the ordinary release/expiry path above. Also drops that worker's own `#generation` + * counter (`#forget`, above, already clears each entry's own `#missingSince`) -- a worker id + * that reconnects after this is a fresh start for reconciliation, not a continuation of one + * that was, at the time, about a worker this index no longer has any record of at all. */ + forgetWorker(workerId: string): void { + for (const entry of this.all()) { + if (entry.workerId === workerId) this.#forget(entry); + } + this.#generation.delete(workerId); + } + + /** Projects a worker-reported lease for a fleet client: rewritten when this index recognizes + * it (by `(workerId, lease.id)`), passed through with only `workerId` added otherwise. */ + project( + lease: Lease, + workerId: string, + workerLabel: string | undefined, + ): ProjectedLease { + const entry = this.findByWorkerLease(workerId, lease.id); + if (entry === undefined) { + return { ...lease, workerId } as ProjectedLease; + } + return { + ...lease, + id: entry.gatewayLeaseId, + requesterId: entry.requesterId, + workerId, + ...(workerLabel === undefined + ? { worker: { id: workerId } } + : { worker: { id: workerId, label: workerLabel } }), + } as ProjectedLease; + } + + #forget(entry: FleetLeaseEntry): void { + this.#byGatewayId.delete(entry.gatewayLeaseId); + if (this.#byRequester.get(entry.requesterId) === entry.gatewayLeaseId) { + this.#byRequester.delete(entry.requesterId); + } + this.#byWorkerLease.delete(workerKey(entry.workerId, entry.workerLeaseId)); + this.#missingSince.delete(entry.gatewayLeaseId); + } +} + +function workerKey(workerId: string, workerLeaseId: string): string { + return `${workerId} ${workerLeaseId}`; +} diff --git a/src/gateway/owner-routed-facts.test.ts b/src/gateway/owner-routed-facts.test.ts new file mode 100644 index 000000000..ad10b5534 --- /dev/null +++ b/src/gateway/owner-routed-facts.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, it } from "vitest"; + +import { EventBus, type EventMap } from "../bus/index.js"; +import { FakeClock } from "../ports/index.js"; +import { FleetLeaseIndex } from "./lease-index.js"; +import { GatewayOwnerRoutedFacts, type OwnerRoutedFact } from "./owner-routed-facts.js"; + +const PREFIX = "gw:instance-1:"; + +/** `WorkerLink#onWorkerEvent`'s own relay shape: the worker's real event, with `workerId` added. + * H11 (round 2 review): the payload's own `ownerId` is *not* generally "the gateway's own uplink + * principal, never a fleet client's" -- for a gateway-issued lease the worker stores the real + * fleet owner verbatim (ADR §27a) and echoes it back honestly in the ordinary case. The reason + * this class resolves `ownerId` from `FleetLeaseIndex` instead of the relayed field anyway is + * that the field is a value round-tripped through a machine this gateway does not control, not + * one it minted itself -- untrusted by construction, exactly like `FleetLeaseCoordinator`'s own + * H6 fix distrusts the same echo on the grant path. This test's own scenario below (the payload + * naming the gateway's uplink principal) is one way that echo can go wrong, not the only one. */ +function relay( + event: Event, + payload: EventMap[Event] & { readonly workerId: string }, +): [Event, EventMap[Event]] { + return [event, payload as unknown as EventMap[Event]]; +} + +describe("GatewayOwnerRoutedFacts", () => { + it("routes a relayed lease-lost fact to the true fleet owner, never to the other requester holding a lease on the same worker", () => { + const eventBus = new EventBus(new FakeClock(1_000)); + const leaseIndex = new FleetLeaseIndex(PREFIX); + leaseIndex.add({ + gatewayLeaseId: "wrk_1.lse_alice", + grantedAt: 1, + ownerId: "alice-principal", + requesterId: "alice", + workerId: "wrk_1", + workerLeaseId: "lse_alice", + }); + leaseIndex.add({ + gatewayLeaseId: "wrk_1.lse_bob", + grantedAt: 1, + ownerId: "bob-principal", + requesterId: "bob", + workerId: "wrk_1", + workerLeaseId: "lse_bob", + }); + const facts = new GatewayOwnerRoutedFacts(eventBus, leaseIndex); + const received: OwnerRoutedFact[] = []; + facts.subscribe((fact) => received.push(fact)); + + const [event, payload] = relay("lease.expired", { + deviceId: "dev_1", + leaseId: "lse_alice", + // The relayed payload's own `ownerId` -- one thing a worker could echo back that is + // definitely wrong for this lease (it names the gateway's own uplink principal, not + // Alice). A correct implementation never reads this field at all; it resolves `ownerId` + // from the index instead, regardless of what the payload happens to say. + ownerId: "gw:instance-1", + workerId: "wrk_1", + }); + eventBus.emit(event, payload, "lease-lifecycle"); + + expect(received).toEqual([ + { + deviceId: "dev_1", + leaseId: "wrk_1.lse_alice", + ownerId: "alice-principal", + reason: "expired", + type: "lease-lost", + }, + ]); + // Bob's own lease is untouched by Alice's expiry -- a session comparing its principal against + // this one fact's `ownerId` ("alice-principal") would never match Bob's, and no second fact + // was emitted for him at all. + expect(leaseIndex.resolve("wrk_1.lse_bob")).toBeDefined(); + // Alice's own entry is now gone: the lease actually ended, so a subsequent renew/release/exec + // against it correctly finds nothing. + expect(leaseIndex.resolve("wrk_1.lse_alice")).toBeUndefined(); + }); + + it("emits nothing for a worker's own local lease -- one this gateway never issued and has no fact to relay for", () => { + const eventBus = new EventBus(new FakeClock(1_000)); + const leaseIndex = new FleetLeaseIndex(PREFIX); + // The index knows nothing about "lse_local" -- exactly the case for a lease a local agent on + // the worker holds, which this gateway never forwarded. + const facts = new GatewayOwnerRoutedFacts(eventBus, leaseIndex); + const received: OwnerRoutedFact[] = []; + facts.subscribe((fact) => received.push(fact)); + + const [event, payload] = relay("lease.released", { + deviceId: "dev_2", + leaseId: "lse_local", + ownerId: "local-agent", + reason: "explicit", + workerId: "wrk_1", + }); + eventBus.emit(event, payload, "lease-lifecycle"); + + expect(received).toEqual([]); + }); + + it("resolves device-unhealthy the same way, without removing the lease (it is still active)", () => { + const eventBus = new EventBus(new FakeClock(1_000)); + const leaseIndex = new FleetLeaseIndex(PREFIX); + leaseIndex.add({ + gatewayLeaseId: "wrk_1.lse_alice", + grantedAt: 1, + ownerId: "alice-principal", + requesterId: "alice", + workerId: "wrk_1", + workerLeaseId: "lse_alice", + }); + const facts = new GatewayOwnerRoutedFacts(eventBus, leaseIndex); + const received: OwnerRoutedFact[] = []; + facts.subscribe((fact) => received.push(fact)); + + eventBus.emit( + "device.crash-detected", + { + deviceId: "dev_1", + leaseId: "lse_alice", + observed: "stopped", + platform: "ios", + workerId: "wrk_1", + } as unknown as EventMap["device.crash-detected"], + "lease-health-monitor", + ); + + expect(received).toEqual([ + { + deviceId: "dev_1", + leaseId: "wrk_1.lse_alice", + ownerId: "alice-principal", + type: "device-unhealthy", + }, + ]); + expect(leaseIndex.resolve("wrk_1.lse_alice")).toBeDefined(); + }); + + // H10 (round 2 review): the suite's own title used to claim this branch too ("device-unhealthy/ + // device-recovered the same way"), but only ever emitted device.crash-detected -- the + // device-recovered branch (own-routed-facts.ts's "device.recovered" subscription) was correct + // by inspection but never actually exercised. + it("resolves device-recovered the same way, without removing the lease (it is still active)", () => { + const eventBus = new EventBus(new FakeClock(1_000)); + const leaseIndex = new FleetLeaseIndex(PREFIX); + leaseIndex.add({ + gatewayLeaseId: "wrk_1.lse_alice", + grantedAt: 1, + ownerId: "alice-principal", + requesterId: "alice", + workerId: "wrk_1", + workerLeaseId: "lse_alice", + }); + const facts = new GatewayOwnerRoutedFacts(eventBus, leaseIndex); + const received: OwnerRoutedFact[] = []; + facts.subscribe((fact) => received.push(fact)); + + eventBus.emit( + "device.recovered", + { + attempts: 2, + deviceId: "dev_1", + duration: 1_500, + leaseId: "lse_alice", + workerId: "wrk_1", + } as unknown as EventMap["device.recovered"], + "lease-health-monitor", + ); + + expect(received).toEqual([ + { + attempts: 2, + deviceId: "dev_1", + leaseId: "wrk_1.lse_alice", + ownerId: "alice-principal", + type: "device-recovered", + }, + ]); + expect(leaseIndex.resolve("wrk_1.lse_alice")).toBeDefined(); + }); +}); diff --git a/src/gateway/owner-routed-facts.ts b/src/gateway/owner-routed-facts.ts new file mode 100644 index 000000000..a04cee5ce --- /dev/null +++ b/src/gateway/owner-routed-facts.ts @@ -0,0 +1,148 @@ +/** + * `GatewayOwnerRoutedFacts`: the gateway's own `OwnerRoutedFacts` (`src/daemon/owner-routed-facts.ts`), + * replacing `inertOwnerRoutedFacts()` once #118 gives the gateway leases of its own to report + * facts about. + * + * `WorkerLink#onWorkerEvent` republishes a worker's business events on the gateway's bus with + * `workerId` added, under their original names -- including `lease.expired`/`lease.released`, + * whose payload carries the *worker's* `ownerId` (the lease's real owner, since ADR §27a) and + * the *worker's own* `leaseId`, not the gateway's synthesized one. **Do not trust either + * verbatim**: a relayed event's `ownerId` is correct for a worker-local lease, but for a + * gateway-issued one it is only ever recoverable through `FleetLeaseIndex` -- which is exactly + * what round-tripped it home in the first place. Routing straight off the relayed payload would + * still "work" in the sense of pushing *a* fact to *someone*, which is what makes the bug worth + * naming: it would push one client's `lease-lost` at another, or at nobody, depending on which + * `ownerId` string a worker's own local principal happened to collide with. + * + * `device.crash-detected`/`device.recovered` are looked up the same way, but never removed -- + * the lease those describe is still active; only `lease.expired`/`lease.released` end one, and + * `FleetLeaseIndex#removeByWorkerLease` is the one place that happens for either (see its own + * doc comment on why the lookup and the forget are one atomic step here rather than two + * independently-ordered bus subscriptions). + * + * A lease not found in the index at all is a worker's own local lease (or, briefly, a race the + * gateway lost against its own index rebuild) -- either way, not this gateway's fact to relay, + * so nothing is emitted for it. + */ +import type { EventBus } from "../bus/index.js"; +import type { FleetLeaseIndex } from "./lease-index.js"; + +/** + * Structurally identical to `src/daemon/owner-routed-facts.ts`'s own `OwnerRoutedFact`/ + * `OwnerRoutedFacts` -- declared again here, rather than imported, because ADR 0005 §33 allows + * `src/gateway` exactly one `src/daemon` import (`daemon/dispatch.js`, enforced by + * `boundary.test.ts`) and this shape does not need to be the second one: `DaemonServer` accepts + * anything satisfying it, and main.ts is what hands this class to a `DaemonServer` built outside + * `src/gateway`, where the two names line up with no cast required. + */ +export type OwnerRoutedFact = + | { + readonly type: "lease-lost"; + readonly leaseId: string; + readonly deviceId: string; + readonly reason: string; + readonly ownerId: string; + } + | { + readonly type: "device-unhealthy"; + readonly leaseId: string; + readonly deviceId: string; + readonly ownerId: string; + } + | { + readonly type: "device-recovered"; + readonly leaseId: string; + readonly deviceId: string; + readonly attempts: number; + readonly ownerId: string; + }; + +export interface OwnerRoutedFacts { + subscribe(listener: (fact: OwnerRoutedFact) => void): () => void; +} + +/** The fields this class reads off a relayed event's payload -- deliberately not `EventMap`'s + * own declared shape, which knows nothing about `workerId` (added only by the relay, at the + * bus-agnostic edge `WorkerLink#onWorkerEvent` owns). */ +interface RelayedLeaseEvent { + readonly leaseId: string; + readonly deviceId: string; + readonly workerId: string; +} + +export class GatewayOwnerRoutedFacts implements OwnerRoutedFacts { + readonly #listeners = new Set<(fact: OwnerRoutedFact) => void>(); + readonly #unsubscribers: Array<() => void>; + + constructor( + eventBus: EventBus, + private readonly leaseIndex: Pick, + ) { + this.#unsubscribers = [ + eventBus.subscribe("lease.expired", (envelope) => { + const relayed = envelope.payload as unknown as RelayedLeaseEvent; + const entry = this.leaseIndex.removeByWorkerLease(relayed.workerId, relayed.leaseId); + if (entry === undefined) return; + this.#emit({ + deviceId: relayed.deviceId, + leaseId: entry.gatewayLeaseId, + ownerId: entry.ownerId, + reason: "expired", + type: "lease-lost", + }); + }), + eventBus.subscribe("lease.released", (envelope) => { + const relayed = envelope.payload as unknown as RelayedLeaseEvent & { + readonly reason: string; + }; + const entry = this.leaseIndex.removeByWorkerLease(relayed.workerId, relayed.leaseId); + if (entry === undefined) return; + this.#emit({ + deviceId: relayed.deviceId, + leaseId: entry.gatewayLeaseId, + ownerId: entry.ownerId, + reason: relayed.reason, + type: "lease-lost", + }); + }), + eventBus.subscribe("device.crash-detected", (envelope) => { + const relayed = envelope.payload as unknown as RelayedLeaseEvent; + const entry = this.leaseIndex.findByWorkerLease(relayed.workerId, relayed.leaseId); + if (entry === undefined) return; + this.#emit({ + deviceId: relayed.deviceId, + leaseId: entry.gatewayLeaseId, + ownerId: entry.ownerId, + type: "device-unhealthy", + }); + }), + eventBus.subscribe("device.recovered", (envelope) => { + const relayed = envelope.payload as unknown as RelayedLeaseEvent & { + readonly attempts: number; + }; + const entry = this.leaseIndex.findByWorkerLease(relayed.workerId, relayed.leaseId); + if (entry === undefined) return; + this.#emit({ + attempts: relayed.attempts, + deviceId: relayed.deviceId, + leaseId: entry.gatewayLeaseId, + ownerId: entry.ownerId, + type: "device-recovered", + }); + }), + ]; + } + + subscribe(listener: (fact: OwnerRoutedFact) => void): () => void { + this.#listeners.add(listener); + return () => this.#listeners.delete(listener); + } + + dispose(): void { + for (const unsubscribe of this.#unsubscribers) unsubscribe(); + } + + #emit(fact: OwnerRoutedFact): void { + for (const listener of this.#listeners) listener(fact); + } +} diff --git a/src/gateway/queue.ts b/src/gateway/queue.ts new file mode 100644 index 000000000..3a1f6b0e7 --- /dev/null +++ b/src/gateway/queue.ts @@ -0,0 +1,152 @@ +/** + * The fleet's one FIFO (ADR 0005 §10/§11): a thin composition over `src/core/wait-queue.ts`'s + * `WaitQueue`, not a fork of it. `WaitQueue` already owns exactly the state a fleet queue needs + * -- FIFO membership, per-request timeout/cancellation, and settlement promises -- and its + * `LeaseRequestOptions` (`requesterId`, `ownerId`, `timeoutMs`, `noWait`, `allowDownload`, + * `onProgress`, `ttlMs`) are already the fields a fleet request carries. This module only + * narrows `WaitQueue`'s generic `Waiter`/`LeaseGrant` shapes to what the fleet actually produces + * (a `DeviceRequest` for the request, and a lease record that may additionally carry `worker` + * once it names a machine) and forwards every method through. + * + * `DeviceRequest`/`DeviceRecord`/`LeaseRecord`/`WaiterState` are `wait-queue.js`'s own transitive + * type imports (`core/domain.js`, `core/driver.js`) -- see `boundary.test.ts`'s + * `ALLOWED_CORE_IMPORTS` -- not a reach into the registry, capacity, or lifecycle engine ADR 0005 + * §33 keeps off limits. + */ +import type { Clock, IdGenerator } from "../ports/index.js"; +import type { LeaseRecord } from "../core/domain.js"; +import type { DeviceRequest } from "../core/driver.js"; +import { + WaitQueue, + type LeaseProgress, + type LeaseRequestOptions, + type WaiterState, +} from "../core/wait-queue.js"; + +export type { LeaseProgress, LeaseRequestOptions } from "../core/wait-queue.js"; +export { RequestCancelledError, RequesterAlreadyLeasedError } from "../core/wait-queue.js"; + +/** + * The lease record a fleet grant carries. Identical to a worker's own `LeaseRecord` plus the + * additive `worker` (ADR 0005 §18) `FleetLeaseCoordinator` stamps once it knows which machine + * granted it -- absent on nothing this queue itself ever produces (it never grants; the + * coordinator does), so the type says `?` rather than the coordinator having to fabricate one. + */ +export type FleetLeaseRecord = LeaseRecord & { + readonly worker?: { readonly id: string; readonly label?: string }; +}; + +/** + * A fleet grant: the worker's own device/environment/timing, forwarded verbatim (the gateway + * never interprets either -- it is not the driver that produced them), plus the lease record + * above. Untyped (`unknown`) on `device`/`timing` for the same reason: this module has no + * business knowing their shape, only relaying it. + */ +export interface FleetLeaseGrant { + readonly device: unknown; + readonly environment: Readonly>; + readonly lease: FleetLeaseRecord; + readonly timing: unknown; +} + +export interface FleetWaiter { + readonly id: string; + readonly request: DeviceRequest; + readonly options: LeaseRequestOptions; + readonly promise: Promise; + readonly state: WaiterState; +} + +export interface FleetQueueOptions { + readonly clock: Clock; + readonly idGenerator: IdGenerator; + /** Called after a timed-out waiter has been removed and rejected -- the rejection itself + * already happened inside `WaitQueue#armTimeout` by the time this fires; `FleetLeaseCoordinator` + * uses it only to report the gateway's own `lease.rejected` fact for that already-committed + * timeout (H10, round 2 review: this comment used to say it wakes the dispatch loop the same + * way a release or worker-view change does -- it does not; the timed-out waiter is already + * terminal and gone from the queue, and nothing here re-runs `#dispatch` for the *other* + * waiters still behind it). */ + readonly onTimeout?: (waiter: FleetWaiter) => void; +} + +/** + * Casts a `WaitQueue`-native value to its fleet-shaped counterpart. `WaitQueue` itself has no + * fleet awareness (by design -- it stays platform-agnostic and worker-agnostic alike), so the + * cast is this module's whole job: every fleet-facing method below either takes a `FleetWaiter` + * and hands `WaitQueue` back exactly what it minted (never a waiter from a different `FleetQueue` + * or from the worker's own acquisition path, so the shapes always agree at runtime even though + * `WaitQueue`'s own types do not know that). + */ +function asFleet(value: Value): Value extends undefined ? undefined : FleetWaiter { + return value as never; +} + +export class FleetQueue { + readonly #queue: WaitQueue; + + constructor(options: FleetQueueOptions) { + this.#queue = new WaitQueue({ + clock: options.clock, + idGenerator: options.idGenerator, + ...(options.onTimeout === undefined + ? {} + : { onTimeout: (waiter) => options.onTimeout?.(asFleet(waiter)) }), + }); + } + + get depth(): number { + return this.#queue.depth; + } + + /** Every waiter still holding a slot, oldest first (ADR 0005 §11's dispatch order). See + * `WaitQueue#list`. */ + list(): readonly FleetWaiter[] { + return this.#queue.list().map((waiter) => asFleet(waiter)); + } + + hasPendingRequester(requesterId: string): boolean { + return this.#queue.hasPendingRequester(requesterId); + } + + findPendingWaiter(requesterId: string): FleetWaiter | undefined { + return asFleet(this.#queue.findPendingWaiter(requesterId)); + } + + create(request: DeviceRequest, options: LeaseRequestOptions): FleetWaiter { + return asFleet(this.#queue.create(request, options)); + } + + enqueue(waiter: FleetWaiter): boolean { + return this.#queue.enqueue(waiter as never); + } + + markProcessing(waiter: FleetWaiter): boolean { + return this.#queue.markProcessing(waiter as never); + } + + isQueued(waiter: FleetWaiter): boolean { + return this.#queue.isQueued(waiter as never); + } + + notifyProgress(waiter: FleetWaiter, progress: LeaseProgress): void { + this.#queue.notifyProgress(waiter as never, progress); + } + + resolve(waiter: FleetWaiter, grant: FleetLeaseGrant): boolean { + return this.#queue.resolve(waiter as never, grant as never); + } + + reject(waiter: FleetWaiter, error: Error): boolean { + return this.#queue.reject(waiter as never, error); + } + + cancelAll(error: Error | ((waiter: FleetWaiter) => Error)): readonly FleetWaiter[] { + if (typeof error === "function") { + return this.#queue + .cancelAll((waiter) => error(asFleet(waiter))) + .map((waiter) => asFleet(waiter)); + } + return this.#queue.cancelAll(error).map((waiter) => asFleet(waiter)); + } +} diff --git a/src/gateway/routing.test.ts b/src/gateway/routing.test.ts new file mode 100644 index 000000000..35ffac030 --- /dev/null +++ b/src/gateway/routing.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, it } from "vitest"; + +import { + createRoutingPolicy, + DEFAULT_ROUTING_POLICY, + isRoutingPolicyName, + routingPolicyNames, +} from "./routing.js"; +import { catalogFixture, deviceFixture, statusFixture } from "./test-support.js"; +import type { WorkerView } from "./worker-registry.js"; + +const REQUEST = { + allowDownload: false, + model: "iPhone 17", + osVersion: "26.0", + platform: "ios" as const, +}; + +function view(id: string, overrides: Partial = {}): WorkerView { + return { + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + connection: "connected", + devices: [], + drained: false, + id, + lastSeenAt: 1, + leases: [], + capacity: statusFixture().capacity, + ...overrides, + }; +} + +describe("routing registry", () => { + it("names exactly the policies it registers, warm-then-free among them", () => { + expect(routingPolicyNames).toContain("warm-then-free"); + expect(DEFAULT_ROUTING_POLICY).toBe("warm-then-free"); + }); + + it("recognizes only registered names", () => { + expect(isRoutingPolicyName("warm-then-free")).toBe(true); + expect(isRoutingPolicyName("round-robin")).toBe(false); + expect(isRoutingPolicyName(42)).toBe(false); + }); +}); + +describe("warm-then-free policy", () => { + const policy = createRoutingPolicy("warm-then-free"); + + it("prefers a worker with a matching device already in the ready state (a warm hit)", () => { + const cold = view("wrk_cold"); + const warm = view("wrk_warm", { devices: [deviceFixture("dev_1", "ready")] }); + + expect(policy.select(REQUEST, [cold, warm])).toEqual({ + reason: "warm-hit", + workerId: "wrk_warm", + }); + }); + + // H10 (round 2 review): `deviceStateSchema` makes `ready`/`leased` mutually exclusive, so this + // (and the title above) prove the state filter -- "warm-hit" requires `ready` specifically -- + // not some separate "is this device free to hand out" check a device already in `leased` + // state could otherwise still pass. + it("does not treat a device already in the leased state as a warm hit", () => { + const leased = view("wrk_1", { devices: [deviceFixture("dev_1", "leased")] }); + + expect(policy.select(REQUEST, [leased])?.reason).toBe("free-capacity"); + }); + + it("falls back to the worker with the most free running capacity", () => { + const tight = view("wrk_tight", { + capacity: { + ...statusFixture().capacity, + ios: { ...statusFixture().capacity.ios, running: 1 }, + }, + }); + const roomy = view("wrk_roomy", { + capacity: { + ...statusFixture().capacity, + ios: { ...statusFixture().capacity.ios, maxRunning: 10 }, + }, + }); + + expect(policy.select(REQUEST, [tight, roomy])).toEqual({ + reason: "free-capacity", + workerId: "wrk_roomy", + }); + }); + + it("drops a disconnected, incompatible, or drained worker", () => { + expect(policy.select(REQUEST, [view("wrk_1", { connection: "disconnected" })])).toBeUndefined(); + expect(policy.select(REQUEST, [view("wrk_1", { connection: "incompatible" })])).toBeUndefined(); + expect(policy.select(REQUEST, [view("wrk_1", { drained: true })])).toBeUndefined(); + }); + + it("drops a worker whose capacity was never read, rather than guessing it has some", () => { + const { capacity: _capacity, ...withoutCapacity } = view("wrk_1"); + expect(policy.select(REQUEST, [withoutCapacity])).toBeUndefined(); + }); + + it("drops a worker lacking the requested model, and one lacking the requested osVersion", () => { + const noModel = view("wrk_1", { + catalog: catalogFixture([{ models: ["iPhone 15"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + }); + const noRuntime = view("wrk_2", { + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["18.0"] }]) + .platforms, + }); + + expect(policy.select(REQUEST, [noModel])).toBeUndefined(); + expect(policy.select(REQUEST, [noRuntime])).toBeUndefined(); + }); + + it("drops a worker lacking the platform in its catalog at all", () => { + const androidOnly = view("wrk_1", { + catalog: catalogFixture([{ models: ["Pixel 9"], platform: "android", runtimes: ["15"] }]) + .platforms, + }); + expect(policy.select(REQUEST, [androidOnly])).toBeUndefined(); + }); + + it("only counts a missing model/runtime as fillable by a download when the request allows one and the worker's own policy permits it", () => { + const noModel = view("wrk_1", { + catalog: catalogFixture([{ models: ["iPhone 15"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "on-request" }, + }); + + expect(policy.select(REQUEST, [noModel])).toBeUndefined(); + expect(policy.select({ ...REQUEST, allowDownload: true }, [noModel])).toEqual({ + reason: "free-capacity", + workerId: "wrk_1", + }); + + const refusesDownloads = view("wrk_2", { + catalog: catalogFixture([{ models: ["iPhone 15"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "never" }, + }); + expect(policy.select({ ...REQUEST, allowDownload: true }, [refusesDownloads])).toBeUndefined(); + }); + + it("names no worker when none is eligible", () => { + expect(policy.select(REQUEST, [])).toBeUndefined(); + }); +}); diff --git a/src/gateway/routing.ts b/src/gateway/routing.ts new file mode 100644 index 000000000..e5968a4e0 --- /dev/null +++ b/src/gateway/routing.ts @@ -0,0 +1,150 @@ +/** + * Fleet routing (ADR 0005 §13, Decision 7): "a pure function over worker views, a module with + * one entry point selected by `gateway.routing`, the same shape as `CapacityStrategy`" (see + * `src/core/capacity/strategy.ts`/`strategies/index.ts`, whose registry shape this mirrors -- a + * `RoutingPolicyDefinition` per policy, a name-keyed registry, `createRoutingPolicy`). Unlike a + * capacity strategy, a routing policy takes no per-policy config in v1: there is exactly one, + * and picking it is the whole knob `gateway.routing` turns. Nothing outside this module decides + * how a worker is chosen. + */ +import type { Platform } from "../contract/index.js"; +import type { WorkerView } from "./worker-registry.js"; + +export interface RoutableRequest { + readonly platform: Platform; + readonly model: string; + readonly osVersion?: string; + /** + * The request's own flag, forwarded as-is: a gateway has no `downloads.policy` of its own to + * fold it against (that config key is worker-only, ADR §2), so the clamp this module applies + * is only ever the *worker's* declared policy (below), never a gateway-side one -- the worker + * still applies its own `effectiveAllowDownload` when the forwarded `lease.request` lands. + */ + readonly allowDownload: boolean; +} + +export type RoutingReason = "warm-hit" | "free-capacity"; + +export interface RoutingDecision { + readonly workerId: string; + readonly reason: RoutingReason; +} + +/** + * Chooses a worker for one request, or names none. A pure function: everything it needs is in + * `workers`, and it neither mutates a view nor remembers anything between calls -- two calls + * given the same arguments always agree, which is what lets `FleetLeaseCoordinator` re-run it on + * every dispatch pass with no extra bookkeeping. + */ +export interface RoutingPolicy { + select(request: RoutableRequest, workers: readonly WorkerView[]): RoutingDecision | undefined; +} + +/** The registry entry shape a routing policy is declared with -- mirrors + * `CapacityStrategyDefinition`'s `{ name, create }` (capacity strategies also carry + * `defaults`/`validator` for their own per-strategy config, which no routing policy needs in + * v1). Exported for a future policy to implement against, even though `warm-then-free` below is + * declared as a plain object literal of this shape rather than through a builder function -- + * with only one policy in one file, `defineCapacityStrategy`'s real job (letting each strategy's + * own directory import a shared constructor) has nothing to do yet. */ +// fallow-ignore-next-line unused-type -- public shape for a future policy to implement against (see the doc comment above); no second policy exists yet to import it. +export interface RoutingPolicyDefinition { + readonly name: Name; + create(): RoutingPolicy; +} + +/** + * ADR §13's v1 policy, the only one that ships: + * + * 1. **Eligibility.** Drop a worker that is disconnected, incompatible, or drained; that lacks + * the requested platform in its catalog at all; that lacks the requested `model`; that lacks + * the requested `osVersion` (when the request named one) among its reported runtimes; or + * whose own `downloads.policy` would refuse the download filling either gap would need, + * unless the request did not ask to allow one anyway. A worker whose capacity has never been + * read (`capacity` absent -- never actually observed in practice once a view exists, but + * `WorkerView`'s own schema allows it) is dropped too: a policy that cannot see free capacity + * must not guess it has some (`safety.md`'s fail-closed instinct, applied to routing rather + * than destruction). + * 2. **Warm hit.** Among the eligible, the first (by `views()`'s own ascending-id order, so two + * calls over an unchanged fleet agree) with an unleased `ready` device matching the request. + * 3. **Free capacity.** Otherwise the eligible worker with the most free running capacity for + * the platform (`maxRunning - running - reserved`), ties broken the same way. + * + * No requester affinity, no label selectors, no per-worker exclusions -- v1 has none, and adding + * one is a new policy option, not a change to this shape (ADR §13). + */ +const warmThenFree: RoutingPolicyDefinition<"warm-then-free"> = { + name: "warm-then-free", + create: () => ({ + select(request, workers) { + const eligible = workers.filter((worker) => isEligible(worker, request)); + const warm = eligible.find((worker) => hasWarmDevice(worker, request)); + if (warm !== undefined) return { workerId: warm.id, reason: "warm-hit" }; + + let best: { readonly workerId: string; readonly free: number } | undefined; + for (const worker of eligible) { + const free = freeCapacity(worker, request.platform); + if (free <= 0) continue; + if (best === undefined || free > best.free) best = { workerId: worker.id, free }; + } + return best === undefined ? undefined : { workerId: best.workerId, reason: "free-capacity" }; + }, + }), +}; + +function isEligible(worker: WorkerView, request: RoutableRequest): boolean { + if (worker.connection !== "connected") return false; + if (worker.drained) return false; + if (worker.capacity === undefined) return false; + const catalog = worker.catalog.find((entry) => entry.platform === request.platform); + if (catalog === undefined) return false; + const hasModel = catalog.models.includes(request.model); + const hasRuntime = + request.osVersion === undefined || catalog.runtimes.includes(request.osVersion); + if (hasModel && hasRuntime) return true; + // Missing the model or the runtime: only still eligible if this request may fill the gap with + // a download, and this worker's own policy would permit one (ADR §13: "a download is + // considered only on a worker whose download policy allows it"). An unread policy is treated + // as `"never"` -- the same fail-closed default `downloads.policy` itself defaults away from, + // but the right one for a view this gateway could not actually confirm. + return request.allowDownload && (worker.downloads?.policy ?? "never") !== "never"; +} + +function hasWarmDevice(worker: WorkerView, request: RoutableRequest): boolean { + return worker.devices.some( + (device) => + device.state === "ready" && + device.spec.platform === request.platform && + device.spec.model === request.model && + (request.osVersion === undefined || device.spec.osVersion === request.osVersion), + ); +} + +function freeCapacity(worker: WorkerView, platform: Platform): number { + const entry = worker.capacity?.[platform]; + if (entry === undefined) return 0; + return Math.max(0, entry.maxRunning - entry.running - entry.reserved); +} + +/** The registry: adding a policy means adding one here, nothing else. Not exported itself -- + * `createRoutingPolicy`/`isRoutingPolicyName`/`routingPolicyNames` below are its public surface, + * which is all a caller outside this module needs (unlike `capacity/strategies/index.ts`'s own + * registry object, which is exported because each strategy's own directory needs to see it; + * with one policy in one file, nothing here does). */ +const routingPolicies = { + "warm-then-free": warmThenFree, +} as const; + +export type RoutingPolicyName = keyof typeof routingPolicies; + +export const routingPolicyNames = Object.keys(routingPolicies) as readonly RoutingPolicyName[]; + +export const DEFAULT_ROUTING_POLICY: RoutingPolicyName = "warm-then-free"; + +export function isRoutingPolicyName(value: unknown): value is RoutingPolicyName { + return typeof value === "string" && value in routingPolicies; +} + +export function createRoutingPolicy(name: RoutingPolicyName): RoutingPolicy { + return routingPolicies[name].create(); +} diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index d5e01a460..01d8e25d3 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -8,7 +8,22 @@ */ import type { z } from "zod"; -import type { SimlockAdminClient, StatusGetOutput } from "../admin/index.js"; +import type { + ExecInput, + ExecOptions, + ExecOutput, + LeaseCancelInput, + LeaseCancelOutput, + LeaseGrant, + LeaseRecord, + LeaseReleaseInput, + LeaseReleaseOutput, + LeaseRenewInput, + LeaseRequestInput, + RequestLeaseOptions, + SimlockAdminClient, + StatusGetOutput, +} from "../admin/index.js"; import { SimlockError } from "../admin/index.js"; import { PROTOCOL_VERSION_RANGE } from "../contract/index.js"; import type { OPERATIONS, platformCatalogSchema } from "../contract/index.js"; @@ -67,12 +82,91 @@ export function catalogFixture(entries: readonly PlatformCatalog[]): CatalogOutp return { platforms: [...entries] }; } +export function grantFixture(overrides: Partial = {}): LeaseGrant { + return { + device: { + id: "dev_1", + driverDeviceId: "udid-1", + spec: { model: "iPhone 17", osVersion: "26.0", platform: "ios" }, + }, + environment: {}, + lease: leaseFixture("lse_1", "dev_1") as LeaseRecord, + timing: { + estimatedBootMs: 0, + estimatedProvisionMs: 0, + estimatedReclaimMs: 0, + estimatedReadyMs: 0, + }, + ...overrides, + }; +} + +/** A `NO_CAPACITY` a scripted worker refuses a forwarded `lease.request` with -- the shape + * `FleetLeaseCoordinator` recognizes as a stale view (ADR §11), not a terminal failure. */ +export function noCapacityError(): SimlockError<"NO_CAPACITY"> { + return new SimlockError("NO_CAPACITY", "domain", "No device capacity is currently available", {}); +} + type DownloadPolicy = "never" | "on-request" | "always"; +/** One scripted answer to a forwarded `lease.request` -- consumed FIFO from + * `ScriptedWorkerClient#requestLeaseQueue`, oldest first, one per call. */ +export type RequestLeaseOutcome = + | { + readonly kind: "grant"; + readonly grant: LeaseGrant; + readonly progress?: readonly LeaseProgressLike[]; + } + | { + readonly kind: "error"; + readonly error: unknown; + /** P1 (round 2 review): a `NO_CAPACITY` reached *after* progress fired -- the worker's own + * `#evictManaged` failure path can answer this to a `noWait` waiter after already pushing + * `provisioning`/`reclaiming`, which is a terminal failure (device work had begun), never + * a re-queue, unlike an *immediate* `NO_CAPACITY` (no progress) that means a stale view. */ + readonly progress?: readonly LeaseProgressLike[]; + } + /** Never settles -- for exercising a dispatch attempt still in flight (finding 1's test: "a + * dispatch tick firing while a previous attempt for the same waiter is in flight"), and (C4, + * round 2 review) a request that is genuinely dispatched (a `progress` push fired) but then + * never resolves at all -- the only way to prove `request.dispatched` fired *before* + * settlement rather than merely alongside a grant that would have emitted it anyway. */ + | { readonly kind: "hang"; readonly progress?: readonly LeaseProgressLike[] }; + +type LeaseProgressLike = + | { readonly stage: "queued"; readonly queuePosition: number } + | { readonly stage: "provisioning"; readonly etaMs: number } + | { readonly stage: "booting"; readonly etaMs: number } + | { readonly stage: "reclaiming"; readonly etaMs: number }; + +type RenewLeaseOutcome = + | { readonly kind: "ok"; readonly record: LeaseRecord } + | { readonly kind: "error"; readonly error: unknown }; +type ReleaseLeaseOutcome = + | { readonly kind: "ok" } + | { readonly kind: "error"; readonly error: unknown }; +type ExecOutcome = + | { + readonly kind: "ok"; + readonly exitCode: number; + readonly output?: readonly { readonly stream: "stdout" | "stderr"; readonly chunk: string }[]; + /** ADR 0005 §19a: the worker's own "the process now exists" push, sent before any output. + * Every protocol-5 worker sends it; this flag exists so a scripted outcome can model a + * worker that refuses *before* a process exists, which is the case that must not announce + * it. */ + readonly started?: boolean; + } + | { readonly kind: "error"; readonly error: unknown } + /** Never settles -- for exercising `gateway.execTimeoutMs` (P5, round 2 review): the worker + * never answers `device.exec` at all. With `started: true` this is the silent, long-running + * command of §19b/§19e -- a process that exists and has written nothing yet. */ + | { readonly kind: "hang"; readonly started?: boolean }; + /** - * A `SimlockAdminClient` with only the methods a `WorkerLink` actually calls. Everything else - * rejects loudly rather than returning a plausible-looking empty value: if the link starts - * calling something new, the test that notices should be the one that says so. + * A `SimlockAdminClient` with only the methods a `WorkerLink` or a `FleetLeaseCoordinator` + * actually call. Everything else rejects loudly rather than returning a plausible-looking empty + * value: if either starts calling something new, the test that notices should be the one that + * says so. */ export class ScriptedWorkerClient { status: StatusGetOutput = statusFixture(); @@ -107,6 +201,33 @@ export class ScriptedWorkerClient { hangUnsubscribe = false; #eventListener: ((push: { event: EventEnvelope }) => void) | undefined; + /** #118: one scripted `lease.request` answer per call, oldest first. Empty when unset -- + * `requestLeaseDefault` answers every call once this queue runs dry. */ + readonly requestLeaseQueue: RequestLeaseOutcome[] = []; + /** What a `lease.request` this worker was not explicitly scripted for answers with. Defaults + * to `NO_CAPACITY`, deliberately: an un-scripted worker in a multi-worker test should refuse + * rather than silently grant, so a routing bug that dispatches to the *wrong* worker shows up + * as a rejection there instead of a second, unnoticed grant. */ + requestLeaseDefault: RequestLeaseOutcome = { kind: "error", error: noCapacityError() }; + readonly renewLeaseQueue: RenewLeaseOutcome[] = []; + readonly releaseLeaseQueue: ReleaseLeaseOutcome[] = []; + readonly execQueue: ExecOutcome[] = []; + /** + * H4 (round 3 review): the `options` most recently passed to `exec` -- captured before + * `execQueue`'s own outcome is even read, so a `"hang"` outcome (whose returned promise never + * settles) still leaves a test a way to invoke `onOutput` later by hand, simulating a worker + * that keeps streaming output on a call the gateway has already given up awaiting. + */ + lastExecOptions: ExecOptions | undefined; + /** + * P4 (round 3 review): the mirror of `lastExecOptions` above, for `requestLease` -- captured + * before `requestLeaseQueue`'s own outcome is even read, so a `"hang"` outcome leaves a test a + * way to invoke `onProgress` later by hand, simulating a worker whose still-pending + * `lease.request` RPC pushes progress after the gateway's own `leaseRequestTimeoutMs` already + * gave up on it. + */ + lastRequestLeaseOptions: RequestLeaseOptions | undefined; + constructor( readonly role: "admin" | "agent" = "admin", readonly daemonVersion = "0.3.0", @@ -135,7 +256,6 @@ export class ScriptedWorkerClient { return this as unknown as SimlockAdminClient; } - // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. async getStatus(): Promise { this.calls.push("status.get"); if (this.hangingCalls.has("status.get")) return new Promise(() => {}); @@ -152,6 +272,64 @@ export class ScriptedWorkerClient { return this.devices; } + /** #118: `FleetLeaseCoordinator#attempt` forwards every dispatch through this, always with + * `noWait: true` (ADR §12) -- scripted per `requestLeaseQueue`/`requestLeaseDefault` above. */ + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async requestLease( + input: LeaseRequestInput, + options: RequestLeaseOptions = {}, + ): Promise { + this.calls.push(`lease.request:${input.requesterId ?? ""}`); + this.#throwIfFailing(); + this.lastRequestLeaseOptions = options; + const outcome = this.requestLeaseQueue.shift() ?? this.requestLeaseDefault; + for (const progress of outcome.progress ?? []) options.onProgress?.(progress); + if (outcome.kind === "hang") return new Promise(() => {}); + if (outcome.kind === "error") throw outcome.error; + return outcome.grant; + } + + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async renewLease(input: LeaseRenewInput): Promise { + this.calls.push(`lease.renew:${input.leaseId}`); + this.#throwIfFailing(); + const outcome = this.renewLeaseQueue.shift(); + if (outcome?.kind === "error") throw outcome.error; + return outcome?.record ?? (leaseFixture(input.leaseId, "dev_1") as LeaseRecord); + } + + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async releaseLease(input: LeaseReleaseInput): Promise { + this.calls.push(`lease.release:${input.leaseId}`); + this.#throwIfFailing(); + const outcome = this.releaseLeaseQueue.shift(); + if (outcome?.kind === "error") throw outcome.error; + return { leaseId: input.leaseId }; + } + + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async cancelLease(_input: LeaseCancelInput = {}): Promise { + this.calls.push("lease.cancel"); + this.#throwIfFailing(); + return { result: "cancelled" }; + } + + /** #118: `FleetLeaseCoordinator#exec` forwards here with the namespaced requester -- assert + * on `calls` (test: "device.exec forwarding sends the namespaced requesterId"). */ + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. + async exec(input: ExecInput, options: ExecOptions = {}): Promise { + this.calls.push(`device.exec:${input.requesterId ?? ""}`); + this.#throwIfFailing(); + this.lastExecOptions = options; + const outcome = this.execQueue.shift(); + if (outcome?.kind === "error") throw outcome.error; + const { onOutput, onStarted } = options; + if (outcome?.started === true) onStarted?.(); + if (outcome?.kind === "hang") return new Promise(() => {}); + for (const chunk of outcome?.output ?? []) onOutput?.(chunk); + return { exitCode: outcome?.exitCode ?? 0 }; + } + // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. async getCatalog(): Promise { this.calls.push("catalog.get"); @@ -171,7 +349,6 @@ export class ScriptedWorkerClient { return { downloads: { policy: this.downloadPolicy }, lease: { maxTtlMs: this.leaseMaxTtlMs } }; } - // fallow-ignore-next-line unused-class-member -- reached structurally through the `SimlockAdminClient` the cast in `asClient()` produces; the audit cannot follow a member access through that. async subscribeEvents( listener: (push: { event: EventEnvelope }) => void, ): Promise<() => Promise> { diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index b214ab57a..efc53e98e 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -128,8 +128,10 @@ export class WorkerLink { } /** `./fleet-ports.ts`'s `WorkerDispatchTarget#reachable` -- false once this link is closing or - * closed (`close()`/`#handleClosed` both set `#closed` before anything else). */ - // fallow-ignore-next-line unused-class-member -- #118's seam (WorkerDispatchTarget); nothing in this PR calls it yet. + * closed (`close()`/`#handleClosed` both set `#closed` before anything else). Read by #118's + * `FleetLeaseCoordinator` through that interface, which is a structural access `fallow`'s + * audit cannot follow -- hence the ignore below. */ + // fallow-ignore-next-line unused-class-member -- reached only through the `WorkerDispatchTarget` interface (FleetLeaseCoordinator); the audit cannot follow a member access through that. get reachable(): boolean { return !this.#closed; } @@ -142,10 +144,11 @@ export class WorkerLink { } /** `./fleet-ports.ts`'s `WorkerDispatchTarget#client` -- the gateway's own admin session on - * this worker, the same one `#rebuildView`'s refresh round trips use. `undefined` before + * this worker, the same one `#rebuildView`'s refresh round trips use and the one #118's + * `FleetLeaseCoordinator` forwards every lease/exec operation through. `undefined` before * `start()` has assigned it or after `close()`/`#handleClosed` has run -- neither clears * `#client` itself, so this mirrors `reachable` rather than checking it separately. */ - // fallow-ignore-next-line unused-class-member -- #118's seam (WorkerDispatchTarget); nothing in this PR calls it yet. + // fallow-ignore-next-line unused-class-member -- reached only through the `WorkerDispatchTarget` interface (FleetLeaseCoordinator); the audit cannot follow a member access through that. client(): SimlockAdminClient | undefined { return this.#closed ? undefined : this.#client; } diff --git a/src/http/app.test.ts b/src/http/app.test.ts index a750ccb37..3115b7f2a 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -277,6 +277,40 @@ describe("POST /v1/lease-requests", () => { expect(dispatcher.calls).toHaveLength(0); }); + it("forwards a body's owner field to the dispatched lease.request rather than silently dropping it (ADR §27a, H7)", async () => { + // Before this, `leaseRequestBodySchema` had no `owner` field at all, so a caller naming one + // was answered as though it had named none -- the same anti-pattern this codebase's own + // `device.exec`'s `requesterId` precedent already rejected: an identity named and answered + // as if it had not is the kind of silence that reads like authorization. The gate itself + // (FORBIDDEN for a non-admin token) lives in the shared dispatcher, exercised once for every + // transport in `daemon/dispatcher.test.ts`/`gateway/dispatcher.test.ts` -- this only proves + // the field actually reaches that dispatcher from HTTP instead of being dropped in transit. + const { app, dispatcher } = buildHarness(); + void postLeaseRequest(app, { ...defaultBody, owner: "someone-else" }); + const call = await waitForDispatch(dispatcher, "lease.request"); + + expect((call.input as { owner?: string }).owner).toBe("someone-else"); + }); + + it("builds an operator token's session as admin but never as the gateway's uplink, so §27a's owner gate still refuses it at the shared dispatcher (ADR §27a, H3)", async () => { + // §27a's `owner` field is narrowed to `session.isGatewayUplink` (round 3 review, H3): an + // HTTP `operator` bearer token maps onto `role: "admin"` (`dispatcher-session.ts`'s + // `toRole`), same as before, but `buildHttpSession` never sets `isGatewayUplink` -- no HTTP + // request is ever the worker's own uplink connection to its configured gateway, which is the + // only session that connection-acceptance signal is stamped on (`DaemonServer#acceptUplink`, + // via `connection.forcedRole`). This is what makes the real gate in + // `daemon/dispatcher.test.ts`/`gateway/dispatcher.test.ts` (FORBIDDEN for `isGatewayUplink !== + // true`, exercised there against the real dispatcher) actually bite an operator token too, + // not just an agent one -- this test only proves the session HTTP hands that dispatcher never + // carries the one flag that would let it through. + const { app, dispatcher } = buildHarness(); + void postLeaseRequest(app, { ...defaultBody, owner: "someone-else" }, operatorAuth); + const call = await waitForDispatch(dispatcher, "lease.request"); + + expect(call.session.role).toBe("admin"); + expect(call.session.isGatewayUplink).not.toBe(true); + }); + it("maps a fast RequesterAlreadyLeasedError to 409, naming the existing lease", async () => { const { app, dispatcher } = buildHarness(); const responsePromise = postLeaseRequest(app, defaultBody); @@ -878,6 +912,15 @@ describe("lease routes", () => { // ADR 0005 §19e: a command that prints nothing for nine minutes still gets its `200` and // its keepalives, and an `EXEC_TIMEOUT` therefore always arrives as the stream's terminal // event rather than as a status the client can no longer be given. + // + // C3 (round 3 review): this only proves that half of the route's *own* logic given a + // dispatcher that calls `onStarted` when told to (`call.session.onStarted?.()` below is + // this test driving that by hand) -- it says nothing about when a real dispatcher actually + // calls it, and cannot notice a dispatcher that stops calling it for a genuinely silent, + // long-running command. That is `FleetLeaseCoordinator`'s own job for a gateway + // (`src/gateway/fleet-coordinator.ts#exec`); the invariant this comment describes is + // guarded end to end there, not here -- see `fleet-coordinator.test.ts`'s "relays the + // worker's own started push for a silent, long-running command". const { app, clock, dispatcher } = buildHarness(); const responsePromise = postExec(app); diff --git a/src/http/app.ts b/src/http/app.ts index e98239901..85706ba37 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -66,6 +66,10 @@ const leaseRequestBodySchema = z.object({ device: z.string().min(1), full: z.boolean().optional(), noWait: z.boolean().optional(), + // ADR §27a (H7, round 2 review): declared and forwarded, not silently dropped -- the shared + // dispatcher's own `lease.request` handler is the one place that decides whether this token + // may set it (`FORBIDDEN` for non-admin), the same gate every other transport is held to. + owner: z.string().min(1).optional(), os: z.string().min(1).optional(), platform: z.enum(["ios", "android"]), timeoutMs: z.number().int().positive().optional(), @@ -111,6 +115,7 @@ function toLeaseRequestInput(body: z.infer): Leas ...(body.noWait === undefined ? {} : { noWait: body.noWait }), ...(body.allowDownload === undefined ? {} : { allowDownload: body.allowDownload }), ...(body.full === undefined ? {} : { full: body.full }), + ...(body.owner === undefined ? {} : { owner: body.owner }), }; } diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index 68fadb5c7..66de0b38e 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -14,7 +14,12 @@ export function testConfig( ): Config { return { mode, - gateway: { disconnectedRetentionMs: 24 * 60 * 60_000, execTimeoutMs: 11 * 60_000 }, + gateway: { + disconnectedRetentionMs: 24 * 60 * 60_000, + execTimeoutMs: 11 * 60_000, + leaseRequestTimeoutMs: 5 * 60_000, + routing: "warm-then-free" as const, + }, drivers: {}, capacity: { strategy: "resource", diff --git a/src/http/tracker.ts b/src/http/tracker.ts index 34fb38844..472c0b628 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -14,6 +14,14 @@ export interface LeaseRequestInput { readonly noWait?: boolean; readonly allowDownload?: boolean; readonly full?: boolean; + /** ADR §27a. Threaded straight through to the shared dispatcher's own `lease.request` input -- + * the same gate every other transport is held to (`FORBIDDEN` for a non-admin token) decides + * this, not this route (H7, round 2 review: before this, `leaseRequestBodySchema` had no + * `owner` field at all and quietly discarded one a caller sent, the anti-pattern this + * codebase's own `device.exec`'s `requesterId` precedent already rejected for the same reason + * -- an identity named and answered as though it had not been is the kind of silence that + * reads like authorization). */ + readonly owner?: string; } /** Matches the issue's lease object exactly; `dataPlane` is reserved and always `null` in v1. */ @@ -215,6 +223,9 @@ export class LeaseRequestTracker { // old grant-then-immediately-renew hack. Under ADR 0004 the daemon then stores // that width on the lease, so nothing here has to remember it either. ...(body.ttlMs === undefined ? {} : { ttlMs: body.ttlMs }), + // ADR §27a (H7, round 2 review): forwarded as-is -- the shared dispatcher's own + // `lease.request` handler is what rejects a non-admin token naming this. + ...(body.owner === undefined ? {} : { owner: body.owner }), }, session, ) diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index 35ac48617..aba460bd8 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -308,6 +308,49 @@ describe("pushes", () => { expect(onOutput).toHaveBeenCalledTimes(2); }); + it("routes a device.exec started push to that call's onStarted, once, before output, and not to another call in flight", async () => { + // ADR 0005 §19a: `started` is request-scoped like `output` -- the fact a transport chooses + // its response shape on. Round 5 review: the send site and this route could both be deleted + // with the whole suite green, because every test of this frame stopped at the coordinator's + // own callback. This one exercises the wire. + const connection = new ScriptedConnection(); + const connectPromise = connectSimlock({ connection }); + await flushMicrotasks(); + completeHello(connection); + const client = await connectPromise; + + const first = { onOutput: vi.fn(), onStarted: vi.fn() }; + const second = { onOutput: vi.fn(), onStarted: vi.fn() }; + const firstPromise = client.exec({ args: ["list"], leaseId: "lease_1", tool: "simctl" }, first); + const secondPromise = client.exec( + { args: ["devices"], leaseId: "lease_2", tool: "adb" }, + second, + ); + await flushMicrotasks(); + const calls = connection.sent.filter((frame) => frame.type === "device.exec"); + expect(calls).toHaveLength(2); + const [firstCall, secondCall] = calls as [(typeof calls)[0], (typeof calls)[0]]; + + connection.push("started", { requestId: firstCall.id }); + connection.push("output", { chunk: "one", requestId: firstCall.id, stream: "stdout" }); + + // Only the call it names, and before that call's own output. + expect(first.onStarted).toHaveBeenCalledTimes(1); + expect(second.onStarted).not.toHaveBeenCalled(); + expect(first.onStarted.mock.invocationCallOrder[0]).toBeLessThan( + first.onOutput.mock.invocationCallOrder[0] as number, + ); + + connection.reply(firstCall.id, { exitCode: 0 }); + connection.reply(secondCall.id, { exitCode: 0 }); + await expect(firstPromise).resolves.toEqual({ exitCode: 0 }); + await expect(secondPromise).resolves.toEqual({ exitCode: 0 }); + + // Settled calls are no longer tracked, so a late frame is dropped rather than delivered. + connection.push("started", { requestId: firstCall.id }); + expect(first.onStarted).toHaveBeenCalledTimes(1); + }); + it("de-duplicates a repeated device-unhealthy push for the same lease (same state twice in a row)", async () => { const connection = new ScriptedConnection(); const connectPromise = connectSimlock({ connection }); diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index e55df483f..163ccccd0 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -456,6 +456,7 @@ class SimlockClientImpl { this.#parseInput("device.exec", input), undefined, options.onOutput, + options.onStarted, ); return this.#parseOutput("device.exec", payload); } @@ -729,11 +730,14 @@ class SimlockClientImpl { input: unknown, onProgress?: (progress: LeaseProgress) => void, onOutput?: (chunk: DeviceOutputChunk) => void, + onStarted?: () => void, ): Promise { const parsed = this.#parseInput(name, input); - return this.#wire.call(name, parsed, onProgress, onOutput).catch((error: unknown) => { - throw toSimlockError(error); - }); + return this.#wire + .call(name, parsed, onProgress, onOutput, onStarted) + .catch((error: unknown) => { + throw toSimlockError(error); + }); } } diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index 969380678..becc9c78d 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -124,6 +124,11 @@ export interface DeviceRecoveredPush { * the exit code; the output is simply not observed. */ export interface ExecOptions { readonly onOutput?: (chunk: DeviceOutputChunk) => void; + /** ADR 0005 §19a: the command's process now exists on the machine that owns the device -- + * fired once, after every failure that can happen before a process exists and before any + * output. A transport chooses its response shape on this, which is why a gateway forwarding + * the command relays it rather than inferring one. */ + readonly onStarted?: () => void; } export interface RequestLeaseOptions { diff --git a/src/simlock-client/wire.ts b/src/simlock-client/wire.ts index 298baf093..ff5485f30 100644 --- a/src/simlock-client/wire.ts +++ b/src/simlock-client/wire.ts @@ -48,6 +48,9 @@ interface PendingCall { /** ADR 0005 §19a's `output` push, routed exactly like `progress`: by frame id, to the call * that is still waiting on it. */ readonly onOutput?: ((chunk: DeviceOutputChunk) => void) | undefined; + /** ADR 0005 §19a's `started` push, routed by frame id like `output`. Fires once, between the + * spawn and the first chunk; a call that never sees it simply never had a process. */ + readonly onStarted?: (() => void) | undefined; } export type LeaseScopedPush = @@ -186,9 +189,10 @@ export class SimlockWire { payload: unknown, onProgress?: (progress: LeaseProgress) => void, onOutput?: (chunk: DeviceOutputChunk) => void, + onStarted?: () => void, ): Promise { if (this.#dead !== undefined) return Promise.reject(this.#dead); - return this.#send(type, payload, onProgress, onOutput); + return this.#send(type, payload, onProgress, onOutput, onStarted); } onLeaseScopedPush(listener: (push: LeaseScopedPush) => void): () => void { @@ -219,10 +223,11 @@ export class SimlockWire { payload: unknown, onProgress?: (progress: LeaseProgress) => void, onOutput?: (chunk: DeviceOutputChunk) => void, + onStarted?: () => void, ): Promise { const id = this.#nextId++; return new Promise((resolve, reject) => { - this.#pending.set(id, { onOutput, onProgress, reject, resolve }); + this.#pending.set(id, { onOutput, onProgress, onStarted, reject, resolve }); void this.#connection.write(serializeFrame({ id, payload, type })).catch((error: unknown) => { this.#pending.delete(id); reject(error instanceof Error ? error : new Error(String(error))); @@ -297,6 +302,16 @@ export class SimlockWire { pending?.onOutput?.({ chunk: parsed.data.chunk, stream: parsed.data.stream }); return; } + case "started": { + const parsed = PUSH_SCHEMAS.started.safeParse(payload); + if (!parsed.success) return; + // Same routing as `output` above: request-scoped, by frame id, dropped for a call that + // already settled or was never this connection's (ADR 0003 §8). + const requestId = parsed.data.requestId; + const id = typeof requestId === "number" ? requestId : Number(requestId); + this.#pending.get(id)?.onStarted?.(); + return; + } case "lease-lost": { const parsed = PUSH_SCHEMAS["lease-lost"].safeParse(payload); if (!parsed.success) return;