diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts index fc820adae..17737eb59 100644 --- a/src/daemon/gateway-fleet.e2e.test.ts +++ b/src/daemon/gateway-fleet.e2e.test.ts @@ -28,6 +28,7 @@ import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { FakeDriver } from "../core/index.js"; +import type { Filesystem } from "../ports/index.js"; import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; @@ -35,6 +36,11 @@ import type { DaemonServer } from "./server.js"; const GATEWAY_PORT = 48173; const GATEWAY_URL = `ws://127.0.0.1:${GATEWAY_PORT}`; +/** Distinct from `GATEWAY_PORT` above so this file's second `it` never races the first one's + * own listener through TIME_WAIT on the same port (H3, round 1 review: both are `it`s in this + * one `describe`, not two separate suites). */ +const RESTART_GATEWAY_PORT = 48174; +const RESTART_GATEWAY_URL = `ws://127.0.0.1:${RESTART_GATEWAY_PORT}`; function adminSession(): DispatchSession { return { manageEventSubscription: () => undefined, principal: "test-operator", role: "admin" }; @@ -49,6 +55,33 @@ function agentSession(overrides: Partial = {}): DispatchSession }; } +/** + * C3 (round 1 review, #119): `connection === "connected"` alone does not mean a worker's view is + * usable. `WorkerLink#start` (`worker-link.ts`) calls `registry.connected(...)` *before* + * `events.subscribe` and before the first `refresh({ includeCatalog: true })` lands, so there is + * a real window in which a worker reports `connected` while its view still carries an empty + * `catalog` and an `undefined` `capacity` -- both of which make `routing.ts#isEligible` drop it. + * Reproduced 7/10 under load (8 `yes` processes on a 4-core box). Gate on the view actually + * being able to serve `model`, not merely on the connection flag, so a `lease.request` right + * after this wait never races that window into a spurious `No worker in the fleet can currently + * serve this request`. + */ +function workerServes( + workers: readonly { + readonly connection: string; + readonly capacity?: unknown; + readonly catalog: readonly { readonly models: readonly string[] }[]; + }[], + model: string, +): boolean { + return workers.some( + (worker) => + worker.connection === "connected" && + worker.capacity !== undefined && + worker.catalog.some((entry) => entry.models.includes(model)), + ); +} + describe("gateway fleet smoke (ADR 0005 §35)", () => { const daemons: DaemonServer[] = []; const directories: string[] = []; @@ -78,17 +111,64 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { return daemon; } + /** + * #119: a gateway that can be stopped and started again *as the same gateway* -- the same + * `SIMLOCK_HOME` directory and the same `Filesystem` instance backing it, which is what + * `instance.json`/`tokens.json`/`workers.json` actually persisting across the restart depends + * on (ADR §30, §8a). `startGateway` above deliberately hands each call a fresh + * `MemoryFilesystem`, which is right for a test that starts one gateway once; this one needs + * the state to survive the restart it is about to perform. + */ + async function startRestartableGateway(): Promise<{ + daemon: DaemonServer; + filesystem: Filesystem; + directory: string; + }> { + const directory = await mkdtemp(join(tmpdir(), "simlock-e2e-gateway-restart-")); + directories.push(directory); + const filesystem = new MemoryFilesystem(); + const daemon = await startDaemon({ + configOverrides: { + mode: "gateway", + http: { enabled: true, host: "127.0.0.1", port: RESTART_GATEWAY_PORT }, + }, + dataDirectory: directory, + filesystem, + logger: new NoopLogger(), + statePath: join(directory, "state.json"), + version: "1.0.0-e2e", + }); + daemons.push(daemon); + return { daemon, filesystem, directory }; + } + 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); + readonly gatewayUrl?: string; + /** + * C1 (round 1 review, #119): reuse an already-`mkdtemp`'d directory and its `Filesystem` + * instead of minting fresh ones -- what restarting *this same worker machine* after an + * outage needs, so its `instance.json` (and therefore the `workerId` the gateway already + * knows) survives the restart, exactly as `startRestartableGateway` reuses the gateway's own + * directory and filesystem below. Omit for a worker that starts once and is never restarted. + */ + readonly existing?: { readonly filesystem: Filesystem; readonly directory: string }; + }): Promise<{ daemon: DaemonServer; filesystem: Filesystem; directory: string }> { + const directory = + options.existing?.directory ?? + (await mkdtemp(join(tmpdir(), `simlock-e2e-${options.label}-`))); + if (options.existing === undefined) directories.push(directory); + const filesystem = options.existing?.filesystem ?? new MemoryFilesystem(); const daemon = await startDaemon({ configOverrides: { - gateway: { url: GATEWAY_URL, token: options.token, label: options.label }, + gateway: { + url: options.gatewayUrl ?? GATEWAY_URL, + token: options.token, + label: options.label, + }, }, dataDirectory: directory, drivers: [ @@ -111,13 +191,13 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { platform: "android", }), ], - filesystem: new MemoryFilesystem(), + filesystem, logger: new NoopLogger(), statePath: join(directory, "state.json"), version: "1.0.0-e2e", }); daemons.push(daemon); - return daemon; + return { daemon, directory, filesystem }; } it("leases a device on the right worker and execs a real command against it through the gateway", async () => { @@ -148,10 +228,11 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { // 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. + // actually see both usably (C3, round 1 review) before leasing, not merely `connected`. await vi.waitFor(async () => { const { workers } = await gateway.dispatch("worker.list", {}, adminSession()); - expect(workers.filter((worker) => worker.connection === "connected")).toHaveLength(2); + expect(workerServes(workers, "Pixel-A")).toBe(true); + expect(workerServes(workers, "Pixel-B")).toBe(true); }); const grant = await gateway.dispatch( @@ -183,4 +264,196 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { await gateway.dispatch("lease.release", { leaseId: grant.lease.id }, agentSession()); }, 30_000); + + /** + * #119's own flagship: drain semantics, `WORKER_UNREACHABLE`-shaped exclusion, and reconnect + * rebuild, proved together over real processes and a real WebSocket restart -- not the + * scripted uplink `fleet-coordinator.test.ts` and `dispatcher.test.ts` already cover each + * piece of in isolation (including §27a's ownership round trip, pinned there too). What only + * this shape of test can catch: the gateway's own persisted state (`instance.json`, + * `tokens.json`, `workers.json`) actually surviving a real `stop()`/`startDaemon()` cycle, and + * a real worker's own `GatewayUplink` actually redialling and reconnecting on its own backoff + * once the new process is listening again. + */ + it("drains one worker, kills it, restarts the gateway, and proves the surviving worker's lease outlives the restart with renewing resumed (ADR §9/§27a/§30, #119)", async () => { + const { daemon: firstGateway, filesystem, directory } = await startRestartableGateway(); + const { secret: tokenA } = await firstGateway.dispatch( + "token.create", + { role: "worker", label: "worker-a" }, + adminSession(), + ); + const { secret: tokenB } = await firstGateway.dispatch( + "token.create", + { role: "worker", label: "worker-b" }, + adminSession(), + ); + + await startWorker({ + label: "worker-a", + model: "Pixel-A", + token: tokenA, + stdout: "hello-from-a", + gatewayUrl: RESTART_GATEWAY_URL, + }); + const workerB = await startWorker({ + label: "worker-b", + model: "Pixel-B", + token: tokenB, + stdout: "hello-from-b", + gatewayUrl: RESTART_GATEWAY_URL, + }); + + // C3 (round 1 review, #119): gate on both views actually being usable, not merely + // `connected` -- see `workerServes`'s own doc comment. This also doubles as the second-order + // fix the review calls for: it is a positive assertion, *before* draining, that worker-b's + // view already carries "Pixel-B" -- so the later `NO_CAPACITY` below can only mean the drain + // excluded it, never that its catalog just had not landed yet. + await vi.waitFor(async () => { + const { workers } = await firstGateway.dispatch("worker.list", {}, adminSession()); + expect(workerServes(workers, "Pixel-A")).toBe(true); + expect(workerServes(workers, "Pixel-B")).toBe(true); + }); + const beforeDrain = (await firstGateway.dispatch("worker.list", {}, adminSession())).workers; + const workerBId = beforeDrain.find((worker) => worker.label === "worker-b")?.id; + if (workerBId === undefined) throw new Error("worker-b never connected"); + + // Lease worker-a's own device -- the fleet client below must still be able to renew this + // exact lease after everything that follows. + // P2 (round 1 review, #119): `requesterId` set explicitly, distinct from the session + // principal -- `agentSession({ principal: "fleet-owner" })` alone makes `ownerId` and + // `requesterId` the same string (`dispatcher.ts` defaults both to `session.principal`), so + // the §27a assertion below (owner authorizes, requester does not) could not tell the two + // fields apart: mutating `lease-index.ts` to re-derive `ownerId` from `requesterId` on + // rebuild would still pass. With a distinct `requesterId`, only a genuinely separate + // `ownerId` on the rebuilt entry can authorize the renew below. + const grant = await firstGateway.dispatch( + "lease.request", + { + model: "Pixel-A", + platform: "android", + noWait: true, + requesterId: "fleet-owner-session-1", + }, + agentSession({ principal: "fleet-owner" }), + ); + expect(grant.lease.worker?.label).toBe("worker-a"); + + // Drain worker-b (ADR §9). It holds no lease of its own here; the point of draining it is + // that the drain has to survive everything below, not just this call. + await firstGateway.dispatch("worker.drain", { workerId: workerBId }, adminSession()); + await vi.waitFor(async () => { + const { workers } = await firstGateway.dispatch("worker.list", {}, adminSession()); + expect(workers.find((worker) => worker.id === workerBId)?.drained).toBe(true); + }); + // No new dispatch reaches a drained worker: a `noWait: true` request only worker-b could + // serve is rejected outright (H3, round 1 review: it does not queue -- with worker-b the + // only worker for "Pixel-B" now excluded, there is no eligible worker at all) rather than + // landing on worker-b -- proven over the real uplink, not a scripted directory. + await expect( + firstGateway.dispatch( + "lease.request", + { model: "Pixel-B", platform: "android", noWait: true }, + agentSession({ principal: "someone-else" }), + ), + ).rejects.toMatchObject({ code: "NO_CAPACITY" }); + + // Kill worker-b outright: an operator taking a drained machine down for maintenance. + await workerB.daemon.stop("test"); + daemons.splice(daemons.indexOf(workerB.daemon), 1); + + // Restart the gateway. Everything it held only in memory -- worker views, the lease index, + // the fleet queue -- is gone (ADR §30); only what it persisted survives, because this reuses + // the *same* directory and the *same* `Filesystem` instance rather than fabricating a fresh + // gateway that merely happens to listen on the same port. + await firstGateway.stop("test"); + daemons.splice(daemons.indexOf(firstGateway), 1); + const restartedGateway = await startDaemon({ + configOverrides: { + mode: "gateway", + http: { enabled: true, host: "127.0.0.1", port: RESTART_GATEWAY_PORT }, + }, + dataDirectory: directory, + filesystem, + logger: new NoopLogger(), + statePath: join(directory, "state.json"), + version: "1.0.0-e2e", + }); + daemons.push(restartedGateway); + + // worker-a's own uplink was never touched -- it keeps redialling on its own backoff and + // finds the restarted gateway listening again on the same port. + await vi.waitFor( + async () => { + const { workers } = await restartedGateway.dispatch("worker.list", {}, adminSession()); + expect( + workers.some( + (worker) => worker.label === "worker-a" && worker.connection === "connected", + ), + ).toBe(true); + }, + { timeout: 15_000 }, + ); + + // C1 (round 1 review, #119): this is the assertion this test's own header comment promises + // and never made -- that `workers.json` actually survived the restart. A drained-but-absent + // worker has no `WorkerView` at all (a view is only ever built by `connected()`/`refresh()`, + // never synthesized from the persisted drain set on its own), so the only way to observe the + // restarted gateway's own on-disk state through the same `worker.list` the rest of this test + // uses is a worker bearing `workerBId` actually reconnecting to it -- "worker-b's machine + // comes back up after maintenance" reusing the *same* directory and `Filesystem` worker-b + // had before (so its `instance.json`, and therefore its `workerId`, survives too), exactly as + // `restartedGateway` reuses the gateway's own. Its view is built from nothing but this fresh + // process's own `connected()` call plus whatever `restartedGateway` loaded from + // `workers.json` at startup -- there is no other way `drained` could come back `true` here. + const restartedWorkerB = await startWorker({ + label: "worker-b", + model: "Pixel-B", + token: tokenB, + stdout: "hello-from-b", + gatewayUrl: RESTART_GATEWAY_URL, + existing: { directory: workerB.directory, filesystem: workerB.filesystem }, + }); + await vi.waitFor( + async () => { + const { workers } = await restartedGateway.dispatch("worker.list", {}, adminSession()); + const view = workers.find((worker) => worker.id === workerBId); + expect(view?.connection).toBe("connected"); + expect(view?.drained).toBe(true); + }, + { timeout: 15_000 }, + ); + await restartedWorkerB.daemon.stop("test"); + daemons.splice(daemons.indexOf(restartedWorkerB.daemon), 1); + + // The lease survives the restart (ADR §30) and renewing resumes for its original requester + // once the reconnect rebuild has run -- retried because the rebuild races the reconnect + // itself becoming visible above. + const renewed = await vi.waitFor( + () => + restartedGateway.dispatch( + "lease.renew", + { leaseId: grant.lease.id }, + agentSession({ principal: "fleet-owner" }), + ), + { timeout: 15_000 }, + ); + expect(renewed.ttlDeadline).toBeGreaterThan(grant.lease.ttlDeadline); + + // ...and refused for anyone else (ADR §27a, pinned end to end across a real restart): the + // owner this gateway forwarded before it died is what the rebuilt lease authorizes against, + // not whichever principal happens to ask first. + await expect( + restartedGateway.dispatch( + "lease.renew", + { leaseId: grant.lease.id }, + agentSession({ principal: "an-impostor" }), + ), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + + await restartedGateway.dispatch( + "lease.release", + { leaseId: grant.lease.id }, + agentSession({ principal: "fleet-owner" }), + ); + }, 55_000); }); diff --git a/src/gateway/drain-store.test.ts b/src/gateway/drain-store.test.ts new file mode 100644 index 000000000..f2d2ffdd3 --- /dev/null +++ b/src/gateway/drain-store.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from "vitest"; + +import type { Logger } from "../ports/index.js"; +import { MemoryFilesystem } from "../ports/index.js"; +import { FileDrainStore } from "./drain-store.js"; + +/** A minimal `Logger` that only records `error` calls -- everything this suite needs to assert + * the corrupt-file fallback logs loudly rather than swallowing silently. */ +function recordingLogger(): { + logger: Logger; + errors: Array<{ message: string; fields?: Record }>; +} { + const errors: Array<{ message: string; fields?: Record }> = []; + const logger: Logger = { + debug: () => undefined, + info: () => undefined, + warn: () => undefined, + error: (message, fields) => { + errors.push(fields === undefined ? { message } : { fields, message }); + }, + child: () => logger, + }; + return { errors, logger }; +} + +/** + * C1 (round 1 review, #119): `FileDrainStore` -- the on-disk half of ADR §8a/§9's "the only + * gateway state that survives a restart" -- had no test of its own anywhere in the repo. Every + * registry-level persistence test injects `MemoryDrainStore`, which exercises the `#drained` set, + * not the file; `gateway-fleet.e2e.test.ts`'s restart test is the only place the real store was + * even constructed, and it never read the file back either. This file closes that gap directly, + * over a `MemoryFilesystem` rather than the real disk, the same way every other persistence test + * in this codebase does. + */ +describe("FileDrainStore", () => { + const PATH = "/home/.simlock/workers.json"; + + it("round-trips an empty store as an empty array without touching the filesystem", async () => { + const filesystem = new MemoryFilesystem(); + const store = new FileDrainStore({ filesystem, path: PATH }); + + expect(await filesystem.exists(PATH)).toBe(false); + await expect(store.load()).resolves.toEqual([]); + }); + + it("saves drained worker ids as `{drained: [...]}` and loads them back, mode 0o600", async () => { + const filesystem = new MemoryFilesystem(); + const store = new FileDrainStore({ filesystem, path: PATH }); + + await store.save(["wrk_a", "wrk_b"]); + + expect(await filesystem.exists(PATH)).toBe(true); + const raw = await filesystem.readFile(PATH); + expect(JSON.parse(raw)).toEqual({ drained: ["wrk_a", "wrk_b"] }); + expect((await filesystem.stat(PATH)).mode).toBe(0o600); + + // A fresh store instance -- the same file, not the same object -- reading it back is the + // shape a real gateway restart depends on: a new process, same directory. + const reloaded = new FileDrainStore({ filesystem, path: PATH }); + await expect(reloaded.load()).resolves.toEqual(["wrk_a", "wrk_b"]); + }); + + it("a later save overwrites the file rather than merging with what was there before", async () => { + const filesystem = new MemoryFilesystem(); + const store = new FileDrainStore({ filesystem, path: PATH }); + + await store.save(["wrk_a", "wrk_b"]); + await store.save(["wrk_b"]); + + await expect(store.load()).resolves.toEqual(["wrk_b"]); + }); + + it("falls back to an empty array, logging loudly, when the file holds invalid JSON", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/.simlock"); + await filesystem.writeFileAtomic(PATH, "not json at all"); + const { errors, logger } = recordingLogger(); + const store = new FileDrainStore({ filesystem, logger, path: PATH }); + + await expect(store.load()).resolves.toEqual([]); + expect(errors).toHaveLength(1); + expect(errors[0]?.fields).toMatchObject({ path: PATH }); + }); + + it("falls back to an empty array when the file is valid JSON but `drained` is not an array", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/.simlock"); + await filesystem.writeFileAtomic(PATH, JSON.stringify({ drained: "wrk_a" })); + const store = new FileDrainStore({ filesystem, path: PATH }); + + await expect(store.load()).resolves.toEqual([]); + }); + + it("drops non-string entries from `drained` rather than throwing", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/.simlock"); + await filesystem.writeFileAtomic( + PATH, + JSON.stringify({ drained: ["wrk_a", 7, null, "wrk_b"] }), + ); + const store = new FileDrainStore({ filesystem, path: PATH }); + + await expect(store.load()).resolves.toEqual(["wrk_a", "wrk_b"]); + }); +}); diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 74b330d9c..315083805 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -13,6 +13,7 @@ import { catalogFixture, deviceFixture, grantFixture, + leaseFixture, noCapacityError, ScriptedWorkerClient, statusFixture, @@ -1595,3 +1596,174 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(leaseIndex.resolve("wrk_b.lse_1")).toBeDefined(); }); }); + +/** + * #119: drain and disconnect lifecycle, and the `WORKER_UNREACHABLE` paths §28/§29 name. + * `routing.test.ts` already proves eligibility is a pure function that drops a drained or + * disconnected worker; what these tests add is the coordinator-level proof that the exclusion + * actually starves that worker's own client of calls while an eligible sibling keeps serving -- + * a call-count assertion, not just "the grant landed on the other one". + */ +describe("drain and unreachable lifecycle (ADR §9/§28/§29, #119)", () => { + /** + * H2 (round 1 review, #119): the drain and disconnect tests below were ~40-line near-clones + * differing in three lines -- the exclusion action, and which ADR section it cites. Shared + * here so the one real difference between them is what each `it` block shows, not buried in + * two copies of the setup and assertions around it. + * + * wrk_a starts saturated so the first request is forced onto wrk_b -- which one ends up + * excluded is deliberate, not incidental to routing's own tie-break. After `exclude` runs, + * wrk_a is given *less* free capacity than wrk_b's own (unchanged) view still reports: if + * exclusion did not drop wrk_b outright, warm-then-free's free-capacity tie-break would still + * prefer B (more free capacity wins). The second request landing on A anyway, despite being + * the worse capacity pick, is what proves the exclusion -- not the capacity numbers -- is what + * kept B out. wrk_b's client is scripted with a spare grant too (C2, round 1 review): without + * it, a routing regression that let the excluded worker back into eligibility would route + * there, its empty queue would answer `NO_CAPACITY`, the coordinator would read that as a + * stale view (§11) and re-enqueue forever, and this test would time out instead of failing the + * wrong-worker assertion below. + */ + async function excludedWorkerKeepsLeaseButGetsNoNewDispatch( + exclude: (workers: WorkerRegistry) => unknown, + ): Promise { + const { coordinator, directory, leaseIndex, workers } = harness(); + const clientA = new ScriptedWorkerClient(); + const clientB = new ScriptedWorkerClient(); + directory.add("wrk_a", clientA); + directory.add("wrk_b", clientB); + const saturated = { ...statusFixture().capacity.ios, maxRunning: 0, running: 0 }; + connectWorker(workers, "wrk_a", { capacity: { ...statusFixture().capacity, ios: saturated } }); + connectWorker(workers, "wrk_b"); + clientB.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + const firstGrant = await coordinator.request(REQUEST, requestOptions()); + expect(firstGrant.lease.worker?.id).toBe("wrk_b"); + expect(clientB.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + + // Excluded mid-service: its existing lease must stay exactly where it is (§9's "keeps its + // existing leases" / §6). + await exclude(workers); + expect(leaseIndex.resolve(firstGrant.lease.id)).toBeDefined(); + + workers.refresh("wrk_a", { + capacity: { + ...statusFixture().capacity, + ios: { ...statusFixture().capacity.ios, maxRunning: 1 }, + }, + }); + clientA.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + clientB.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + const secondGrant = await coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-2", requesterId: "agent-2" }), + ); + + expect(secondGrant.lease.worker?.id).toBe("wrk_a"); + expect(clientA.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + // The real assertion: the excluded worker's own call count never grew past the one lease it + // already held before its exclusion -- not merely "the second grant's worker id is wrk_a". + expect(clientB.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + } + + it("keeps a drained worker's existing lease and sends it no new dispatch, while an undrained sibling serves the next request (§9)", async () => { + await excludedWorkerKeepsLeaseButGetsNoNewDispatch((workers) => + workers.setDrained("wrk_b", true), + ); + }); + + it("keeps a disconnected worker's existing lease and sends it no new dispatch, while a connected sibling serves the next request (§6/§28)", async () => { + await excludedWorkerKeepsLeaseButGetsNoNewDispatch((workers) => workers.disconnected("wrk_b")); + }); + + it("answers WORKER_UNREACHABLE for a forwarded device.exec on a worker the directory reports unreachable, never a success (§28)", 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", + }); + directory.unreachable.add("wrk_a"); + + const rejection = await coordinator + .exec( + { args: ["devices"], leaseId: "wrk_a.lse_1", tool: "adb" }, + { manageEventSubscription: () => undefined, principal: "agent-1", role: "agent" }, + ) + .catch((error: unknown) => error); + + expect(rejection).toBeInstanceOf(DispatchError); + expect((rejection as DispatchError).code).toBe("WORKER_UNREACHABLE"); + // Never reached the worker at all -- a call that then failed would still show up here. + // P1 (round 1 review, #119): this does *not* pin the pre-flight `target?.reachable === true + // ?` conjunct in `#forwardToWorker` specifically -- deleting it leaves this test (and all + // 1776 others) green, because `FakeDirectory.target()` already makes `client()` return + // `undefined` whenever `reachable` is false, so the conjunct is redundant here. It is + // redundant in production too: `WorkerLink#reachable` and `#client()` both mirror the same + // `#closed` flag (`worker-link.ts`), so the conjunct can never change the outcome there + // either. Left in place rather than dropped, since this PR makes no production changes. + expect(client.calls.filter((call) => call.startsWith("device.exec"))).toEqual([]); + }); + + it("a request dispatched to a worker whose uplink then drops: the client sees WORKER_UNREACHABLE, and the lease is not silently double-granted once the worker's view catches up (§29)", async () => { + // H4 (round 1 review, #119): everything through `rebuiltLeaseId`'s own assertion below + // re-asserts what "maps a transport failure on lease.request to WORKER_UNREACHABLE" (P4, + // above) already pins -- not new load-bearing coverage, just the setup this test's own + // genuinely new part (the retry below) needs. That retry -- proving the fleet-wide rule the + // rebuild just populated is what a same-requester retry finds, never a second grant -- is + // what §29 adds here. + const { coordinator, directory, workers, leaseIndex } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + // The worker's own answer to this dispatch never makes it back -- the uplink itself died + // mid-call, exactly the `kind: "transport"` shape a real connection loss arrives as. + client.requestLeaseQueue.push({ + error: new SimlockError("DAEMON_CONNECTION_LOST", "transport", "Connection lost", {}), + 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"); + // The client's own request is over -- nothing is left queued to double-settle later. + expect(coordinator.queueDepth).toBe(0); + + // The worker actually granted it before the uplink dropped: the next real snapshot the + // gateway sees once the uplink returns reports the lease, exactly as §29 describes ("if the + // worker actually granted it, the lease exists on the worker"). This is the ordinary + // reconcile path (`#onViewsChanged`/`rebuildFromWorker`), not a special case. + workers.refresh("wrk_a", { + leases: [ + { + ...leaseFixture("lse_ghost", "dev_ghost"), + ownerId: "agent-1", + requesterId: `${GATEWAY_PREFIX}agent-1`, + }, + ], + }); + + const rebuiltLeaseId = "wrk_a.lse_ghost"; + expect(leaseIndex.resolve(rebuiltLeaseId)).toBeDefined(); + + // The requester's retry -- "the same `409 → GET` recovery loop ... applied across the + // uplink gap" -- must find the lease the fleet-wide rule now knows about, never a second + // grant for the same requester. + const retry = await coordinator + .request(REQUEST, requestOptions()) + .catch((error: unknown) => error); + expect(retry).toBeInstanceOf(RequesterAlreadyLeasedError); + expect((retry as RequesterAlreadyLeasedError).existingLeaseId).toBe(rebuiltLeaseId); + // Only ever the one `lease.request` call this worker actually answered -- the retry above + // was refused at admission, before ever reaching a worker again. + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + }); +});