From 26a0084cc8ad53307e773c2ee690d142cace34c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 7 Sep 2026 20:27:50 +0000 Subject: [PATCH 1/2] test(gateway): prove drain lifecycle, WORKER_UNREACHABLE paths, and reconnect rebuild end to end (#119) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #118 already built the machinery this issue asks for: routing.ts drops a drained/disconnected worker at admission, #forwardToWorker/#classifyRelayedError map kind:"transport" to WORKER_UNREACHABLE, FleetLeaseIndex#rebuildFromWorker reconciles a worker's leases on every view change, and dispatcher.test.ts already pins §27a's ownership round-trip on a rebuilt lease. No production code needed to change for this PR -- what was missing was the tested proof that those pieces hold together under the specific failure shapes ADR 0005 §9/§28/§29/§30 describe, with call-count assertions rather than where-the-grant-landed assertions. Adds to src/gateway/fleet-coordinator.test.ts: - a drained worker keeps its existing lease and its own client's call count never grows, while a sibling with strictly less free capacity serves the next request (proving drain, not capacity, excluded it) - the same shape for a disconnected worker - device.exec on a directory-unreachable worker answers WORKER_UNREACHABLE without ever reaching the worker's client - a lease.request whose uplink drops mid-call surfaces WORKER_UNREACHABLE to the client, and once the worker's view later reports the lease it actually granted, a retry from the same requester is refused REQUESTER_ALREADY_LEASED rather than double-granted Adds to src/daemon/gateway-fleet.e2e.test.ts: the flagship two-worker, real-WebSocket scenario -- lease through the gateway, drain one worker, kill it, restart the gateway (reusing its own directory and Filesystem so instance.json/tokens.json/workers.json survive, exactly as a real restart would), and prove the surviving worker's lease renews for its original requester and is refused for anyone else post-restart. Every new test was verified by deleting the production code it covers and confirming the test fails first (routing.ts's drained/connected checks, the exec reachability precheck, request()'s one-lease admission check, and -- for the e2e -- swapping in a fresh Filesystem on restart to break identity continuity), then restored. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- src/daemon/gateway-fleet.e2e.test.ts | 184 +++++++++++++++++++++++++- src/gateway/fleet-coordinator.test.ts | 177 +++++++++++++++++++++++++ 2 files changed, 360 insertions(+), 1 deletion(-) diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts index fc820adae..009ef12ad 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,10 @@ 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 suite never races the first test's + * own listener through TIME_WAIT on the same port. */ +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" }; @@ -78,17 +83,53 @@ 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; + readonly gatewayUrl?: 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 }, + gateway: { + url: options.gatewayUrl ?? GATEWAY_URL, + token: options.token, + label: options.label, + }, }, dataDirectory: directory, drivers: [ @@ -183,4 +224,145 @@ 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, + }); + + await vi.waitFor(async () => { + const { workers } = await firstGateway.dispatch("worker.list", {}, adminSession()); + expect(workers.filter((worker) => worker.connection === "connected")).toHaveLength(2); + }); + 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. + const grant = await firstGateway.dispatch( + "lease.request", + { model: "Pixel-A", platform: "android", noWait: true }, + 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 request only worker-b could serve queues + // rather than landing on it -- 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.stop("test"); + daemons.splice(daemons.indexOf(workerB), 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 }, + ); + + // 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" }), + ); + }, 40_000); }); diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 74b330d9c..26321d238 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,179 @@ 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)", () => { + it("keeps a drained worker's existing lease and sends it no new dispatch, while an undrained sibling serves the next request (§9)", async () => { + const { coordinator, directory, leaseIndex, workers } = harness(); + const clientA = new ScriptedWorkerClient(); + const clientB = new ScriptedWorkerClient(); + directory.add("wrk_a", clientA); + directory.add("wrk_b", clientB); + // wrk_a starts saturated so the first request is forced onto wrk_b -- which one ends up + // drained is deliberate, not incidental to routing's own tie-break. + 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); + + // Drained mid-service: its existing lease must stay exactly where it is (§9's "keeps its + // existing leases"). + await workers.setDrained("wrk_b", true); + expect(leaseIndex.resolve(firstGrant.lease.id)).toBeDefined(); + + // wrk_a now has *less* free capacity than wrk_b's own (unchanged) view still reports -- if + // drain did not exclude 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 drain flag -- not the capacity numbers -- is + // what excluded B. + workers.refresh("wrk_a", { + capacity: { + ...statusFixture().capacity, + ios: { ...statusFixture().capacity.ios, maxRunning: 1 }, + }, + }); + clientA.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 drained worker's own call count never grew past the one lease it + // already held before the drain -- 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 disconnected worker's existing lease and sends it no new dispatch, while a connected sibling serves the next request (§6/§28)", async () => { + 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"); + + // The uplink drops: the view flips to disconnected, but the lease it already holds is kept + // (ADR §6) -- nothing here releases it or forgets it. + workers.disconnected("wrk_b"); + expect(leaseIndex.resolve(firstGrant.lease.id)).toBeDefined(); + + // wrk_a gets *less* free capacity than wrk_b's own (unchanged, still-reported) view -- so a + // routing pass that forgot to drop a disconnected worker would still prefer B on capacity + // alone. Landing on A anyway is the proof that "disconnected" is what excluded B, not the + // numbers. + workers.refresh("wrk_a", { + capacity: { + ...statusFixture().capacity, + ios: { ...statusFixture().capacity.ios, maxRunning: 1 }, + }, + }); + clientA.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); + expect(clientB.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + }); + + 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 -- the pre-flight reachability check in `#forwardToWorker` + // is what answered this, not a call that then failed. + 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 () => { + 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); + }); +}); From 8b63ec2c864336269a8f4bb940a35421ca26858a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 8 Sep 2026 16:19:26 +0000 Subject: [PATCH 2/2] test(gateway): pin the drain-persistence claim and turn two timeouts into assertions (#119, round 1 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C1: the e2e's drain test never re-read `workerBId`'s drained flag after the restart it claimed to survive -- add that assertion (worker-b's own machine reconnecting to prove `workers.json` was actually loaded, since a drained-but-absent worker has no view to read it off), plus a direct `FileDrainStore` round-trip test that closes the only-e2e-covers-this gap entirely. C2: script the excluded worker's client with a spare grant in both drain/disconnect unit tests, so a routing regression lands as a wrong-worker assertion instead of a 5s `noWait: false` hang. C3: gate the e2e's "both connected" waits on catalog + capacity, not just the connection flag -- `WorkerLink#start` flips to `connected` before its first refresh lands, a real race reproduced 7/10 under load. The same gate before draining doubles as a positive pre-drain assertion that worker-b's view already carries its model, so the later NO_CAPACITY can only mean the drain. P1: reword a test comment that credited a specific (dead) conjunct in `#forwardToWorker` with an outcome neither the fake nor production code can actually attribute to it. P2: give the original lease.request a `requesterId` distinct from its principal, so §27a's owner-vs-requester assertion actually exercises the distinction the ADR reserves it for. H2/H3/H4: dedupe the two near-clone drain/disconnect tests into one shared helper, fix two inaccurate comments, and flag the §29 test's re-assertive first half. Verified against the mutations round 1 named: both C1 mutations (FileDrainStore.load() -> [], and MemoryDrainStore wired into main.ts) now fail with a named assertion; both C2 mutations (routing.ts's drained/connection checks) now fail in ~20ms instead of timing out at 5s. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01MA98m7ua7qvDFZjxFaww6Z --- src/daemon/gateway-fleet.e2e.test.ts | 123 ++++++++++++++++++++++---- src/gateway/drain-store.test.ts | 105 ++++++++++++++++++++++ src/gateway/fleet-coordinator.test.ts | 101 ++++++++++----------- 3 files changed, 260 insertions(+), 69 deletions(-) create mode 100644 src/gateway/drain-store.test.ts diff --git a/src/daemon/gateway-fleet.e2e.test.ts b/src/daemon/gateway-fleet.e2e.test.ts index 009ef12ad..17737eb59 100644 --- a/src/daemon/gateway-fleet.e2e.test.ts +++ b/src/daemon/gateway-fleet.e2e.test.ts @@ -36,8 +36,9 @@ 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 suite never races the first test's - * own listener through TIME_WAIT on the same 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}`; @@ -54,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[] = []; @@ -120,9 +148,20 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { readonly token: string; readonly stdout: string; readonly gatewayUrl?: string; - }): Promise { - const directory = await mkdtemp(join(tmpdir(), `simlock-e2e-${options.label}-`)); - directories.push(directory); + /** + * 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: { @@ -152,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 () => { @@ -189,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( @@ -263,9 +303,15 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { 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(workers.filter((worker) => worker.connection === "connected")).toHaveLength(2); + 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; @@ -273,9 +319,21 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { // 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 }, + { + model: "Pixel-A", + platform: "android", + noWait: true, + requesterId: "fleet-owner-session-1", + }, agentSession({ principal: "fleet-owner" }), ); expect(grant.lease.worker?.label).toBe("worker-a"); @@ -287,8 +345,10 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { 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 request only worker-b could serve queues - // rather than landing on it -- proven over the real uplink, not a scripted directory. + // 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", @@ -298,8 +358,8 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { ).rejects.toMatchObject({ code: "NO_CAPACITY" }); // Kill worker-b outright: an operator taking a drained machine down for maintenance. - await workerB.stop("test"); - daemons.splice(daemons.indexOf(workerB), 1); + 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 @@ -334,6 +394,37 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { { 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. @@ -364,5 +455,5 @@ describe("gateway fleet smoke (ADR 0005 §35)", () => { { leaseId: grant.lease.id }, agentSession({ principal: "fleet-owner" }), ); - }, 40_000); + }, 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 26321d238..315083805 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -1605,14 +1605,32 @@ describe("FleetLeaseCoordinator dispatch", () => { * a call-count assertion, not just "the grant landed on the other one". */ describe("drain and unreachable lifecycle (ADR §9/§28/§29, #119)", () => { - it("keeps a drained worker's existing lease and sends it no new dispatch, while an undrained sibling serves the next request (§9)", async () => { + /** + * 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); - // wrk_a starts saturated so the first request is forced onto wrk_b -- which one ends up - // drained is deliberate, not incidental to routing's own tie-break. const saturated = { ...statusFixture().capacity.ios, maxRunning: 0, running: 0 }; connectWorker(workers, "wrk_a", { capacity: { ...statusFixture().capacity, ios: saturated } }); connectWorker(workers, "wrk_b"); @@ -1622,16 +1640,11 @@ describe("drain and unreachable lifecycle (ADR §9/§28/§29, #119)", () => { expect(firstGrant.lease.worker?.id).toBe("wrk_b"); expect(clientB.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); - // Drained mid-service: its existing lease must stay exactly where it is (§9's "keeps its - // existing leases"). - await workers.setDrained("wrk_b", true); + // 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(); - // wrk_a now has *less* free capacity than wrk_b's own (unchanged) view still reports -- if - // drain did not exclude 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 drain flag -- not the capacity numbers -- is - // what excluded B. workers.refresh("wrk_a", { capacity: { ...statusFixture().capacity, @@ -1639,6 +1652,7 @@ describe("drain and unreachable lifecycle (ADR §9/§28/§29, #119)", () => { }, }); clientA.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + clientB.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); const secondGrant = await coordinator.request( REQUEST, @@ -1647,50 +1661,19 @@ describe("drain and unreachable lifecycle (ADR §9/§28/§29, #119)", () => { expect(secondGrant.lease.worker?.id).toBe("wrk_a"); expect(clientA.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); - // The real assertion: the drained worker's own call count never grew past the one lease it - // already held before the drain -- not merely "the second grant's worker id is wrk_a". + // 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 disconnected worker's existing lease and sends it no new dispatch, while a connected sibling serves the next request (§6/§28)", async () => { - 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"); - - // The uplink drops: the view flips to disconnected, but the lease it already holds is kept - // (ADR §6) -- nothing here releases it or forgets it. - workers.disconnected("wrk_b"); - expect(leaseIndex.resolve(firstGrant.lease.id)).toBeDefined(); - - // wrk_a gets *less* free capacity than wrk_b's own (unchanged, still-reported) view -- so a - // routing pass that forgot to drop a disconnected worker would still prefer B on capacity - // alone. Landing on A anyway is the proof that "disconnected" is what excluded B, not the - // numbers. - workers.refresh("wrk_a", { - capacity: { - ...statusFixture().capacity, - ios: { ...statusFixture().capacity.ios, maxRunning: 1 }, - }, - }); - clientA.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + } - const secondGrant = await coordinator.request( - REQUEST, - requestOptions({ ownerId: "agent-2", requesterId: "agent-2" }), + 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), ); + }); - expect(secondGrant.lease.worker?.id).toBe("wrk_a"); - expect(clientA.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); - expect(clientB.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + 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 () => { @@ -1717,12 +1700,24 @@ describe("drain and unreachable lifecycle (ADR §9/§28/§29, #119)", () => { expect(rejection).toBeInstanceOf(DispatchError); expect((rejection as DispatchError).code).toBe("WORKER_UNREACHABLE"); - // Never reached the worker at all -- the pre-flight reachability check in `#forwardToWorker` - // is what answered this, not a call that then failed. + // 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);