diff --git a/.agents/scripts/tool-guard.mjs b/.agents/scripts/tool-guard.mjs index 2c5a5d146..7fde2f723 100644 --- a/.agents/scripts/tool-guard.mjs +++ b/.agents/scripts/tool-guard.mjs @@ -17,6 +17,7 @@ import path from "node:path"; const SCRIPTS = new Set([ "check", "test", + "test:timing", "typecheck", "typecheck:e2e", "lint", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9daaa17b1..43e07592b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -68,6 +68,28 @@ jobs: - name: Unit tests run: pnpm run test:unit + timing: + name: Timing tests + runs-on: ubuntu-24.04 + permissions: + contents: read + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 22 + - name: Enable Corepack + run: | + corepack enable + corepack prepare pnpm@11.22.0+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621 --activate + - name: Install dependencies + run: pnpm install --frozen-lockfile --ignore-scripts + - name: Timing tests + run: pnpm run test:timing + e2e: name: E2E (${{ matrix.shard }}/3) runs-on: ubuntu-24.04 @@ -104,7 +126,7 @@ jobs: # by a failed need would count as passed. quality: name: Quality - needs: [static, unit, e2e] + needs: [static, unit, timing, e2e] if: always() runs-on: ubuntu-24.04 permissions: {} diff --git a/docs/internal/agent-rules/toolchain.md b/docs/internal/agent-rules/toolchain.md index 345f62de4..2634db0de 100644 --- a/docs/internal/agent-rules/toolchain.md +++ b/docs/internal/agent-rules/toolchain.md @@ -9,6 +9,7 @@ command of their own: they take every command from here. | ---------------------------------------------- | -------------------------------------------- | | Unit tests that import what the branch changed | `pnpm test:changed` | | One unit test file | `pnpm exec vitest run --project unit ` | +| One timing file (`*.timing.test.ts`) | `pnpm exec vitest run --project timing ` | | Fast e2e files (builds first) | `pnpm test:e2e ` | | Console lane, Chromium only (1) | `pnpm test:console --project=chromium` | @@ -19,7 +20,7 @@ command of their own: they take every command from here. Hooks and CI run these. Never run them by hand, and never the tools behind them (from `node_modules/.bin` or any other path): `pnpm check`, `pnpm test`, -`pnpm typecheck`, `pnpm typecheck:e2e`, `pnpm lint`, `pnpm lint:comments`, +`pnpm test:timing`, `pnpm typecheck`, `pnpm typecheck:e2e`, `pnpm lint`, `pnpm lint:comments`, `pnpm format`, `pnpm format:check`, `pnpm fallow`, `pnpm mutate` (outside the `harden-tests` routine), the whole e2e suite, the console lane in every browser (`pnpm test:console`), `tsc`, @@ -33,8 +34,8 @@ list and this one the same. in its output. - **Push hook:** Fallow, then the e2e typecheck. - **CI:** what `pnpm check` runs, and Fallow, on every push. The `pnpm - check` steps run as parallel jobs (static checks, unit tests, the e2e - lane in three shards); the Quality check passes only when all of them + check` steps run as parallel jobs (static checks, unit tests, the timing + tests, the e2e lane in three shards); the Quality check passes only when all of them do. The console lane runs on every push to `main`, and on a pull request when it changes a source, UI, console spec or build file: in every browser when it changes `ui/` or the diff --git a/e2e/slow-agent-device-gateway.test.ts b/e2e/slow-agent-device-gateway.test.ts index 01a6e8c8f..6d4c73acd 100644 --- a/e2e/slow-agent-device-gateway.test.ts +++ b/e2e/slow-agent-device-gateway.test.ts @@ -1,3 +1,4 @@ +import { createCipheriv, createHash, randomUUID } from "node:crypto"; import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -51,6 +52,33 @@ interface WorkerView { readonly capabilities?: readonly { readonly name: string; readonly state: string }[]; } +const GIB = 1024 ** 3; +const CHUNK = 1024 * 1024; + +// why: AES in counter mode over zeros gives a 1 GiB body that needs no file on disk: each leg regenerates the same bytes chunk by chunk. +function* uploadChunks(): Generator { + const cipher = createCipheriv("aes-128-ctr", Buffer.alloc(16, 7), Buffer.alloc(16)); + const zeros = Buffer.alloc(CHUNK); + for (let offset = 0; offset < GIB; offset += CHUNK) yield cipher.update(zeros); +} + +const uploadStream = (): ReadableStream => { + const chunks = uploadChunks(); + return new ReadableStream({ + pull(controller) { + const next = chunks.next(); + if (next.done) controller.close(); + else controller.enqueue(new Uint8Array(next.value)); + }, + }); +}; + +function uploadDigest(): string { + const hash = createHash("sha256"); + for (const chunk of uploadChunks()) hash.update(chunk); + return hash.digest("hex"); +} + const sharedEnvs = new Set(); afterAll(async () => { await Promise.allSettled([...sharedEnvs].map((env) => env.teardown())); @@ -277,6 +305,89 @@ function defineSuite(target: Target): void { }, ); + // why: the preflight, the direct PUT and the finalize are what agent-device does for an upload; the time runs from the preflight to the finalize answer. + async function timedUpload( + baseUrl: string, + token: string, + leaseId: string, + sha256: string, + ): Promise { + const headers = { + authorization: `Bearer ${token}`, + "x-agent-device-lease-id": leaseId, + "x-agent-device-token": token, + }; + const started = performance.now(); + const preflight = await fetch(`${baseUrl}/upload/preflight`, { + body: JSON.stringify({ + artifactType: "file", + fileName: "payload.bin", + sha256, + sizeBytes: GIB, + uploadAttemptId: randomUUID(), + }), + headers: { ...headers, "content-type": "application/json" }, + method: "POST", + }); + expect(preflight.status, "preflight").toBe(200); + const ticket = (await preflight.json()) as { + uploadId: string; + upload: { url: string; headers: Record }; + }; + const put = await fetch(ticket.upload.url, { + body: uploadStream(), + duplex: "half", + headers: { ...ticket.upload.headers, "x-agent-device-lease-id": leaseId }, + method: "PUT", + } as RequestInit); + expect(put.status, "direct upload").toBe(200); + await put.arrayBuffer(); + const finalize = await fetch(`${baseUrl}/upload/finalize`, { + body: JSON.stringify({ uploadId: ticket.uploadId }), + headers: { ...headers, "content-type": "application/json" }, + method: "POST", + }); + expect(finalize.status, "finalize").toBe(200); + await finalize.arrayBuffer(); + return performance.now() - started; + } + + it.runIf(platform === "ios")( + "a 1 GiB upload takes at most 1.5 times as long through the gateway as straight to the worker", + { timeout: 1_800_000 }, + async () => { + const sha256 = uploadDigest(); + const median = (values: number[]) => + [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)] as number; + const runs = async (who: Agent, env: SharedTestEnv) => { + ok(await open(who)); + const [lease] = await listLeases(env); + expect(lease, "the opened lease").toBeDefined(); + const base = `http://127.0.0.1:${String(env.httpPort)}/v1/agent-device`; + const times: number[] = []; + for (let run = 0; run < 3; run += 1) { + times.push(await timedUpload(base, who.token, (lease as { id: string }).id, sha256)); + } + ok(await who.run(["close"])); + await waitForFree(worker); + await waitFor(async () => (await listLeases(gateway)).length === 0, { + timeout: 240_000, + interval: 1_000, + label: "the lease is gone from the gateway's simlock list", + }); + return median(times); + }; + + const direct = await runs(await makeAgent(worker, "direct"), worker); + const through = await runs(await agent("gateway"), gateway); + + expect( + through / direct, + `gateway ${String(through)} ms, worker ${String(direct)} ms`, + ).toBeLessThanOrEqual(1.5); + }, + ); + describe("with the device limit raised to 2", () => { const waitForCapacity = (limit: number) => waitForWorker( diff --git a/package.json b/package.json index b90a41ed6..c6a7573a2 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,8 @@ "build:ui": "vite build ui", "build:e2e": "tsc -p e2e/fake-driver/tsconfig.json", "dev:ui": "vite ui", - "test": "pnpm run test:unit && pnpm run test:e2e", + "test": "pnpm run test:unit && pnpm run test:timing && pnpm run test:e2e", + "test:timing": "vitest run --project timing", "test:unit": "vitest run --project unit", "test:changed": "vitest run --project unit --changed origin/main", "test:e2e": "pnpm run build && pnpm run build:e2e && vitest run --project e2e --tags-filter='!slow'", diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index 767bb74e4..90be06e29 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -1,20 +1,15 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; -import { FakeDriver } from "../core/testing.js"; import { GatewayRelay, type GatewayWorkerClient, type WorkerDirectory } from "../gateway/index.js"; -import { linkPair, TappedTransport, TYPE } from "../link/testing.js"; -import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; +import { linkPair, TYPE } from "../link/testing.js"; import { connectSimlockClient } from "../simlock-client/client.js"; import type { DispatchSession } from "./dispatch.js"; -import { startDaemon } from "./main.js"; import type { RelayTarget } from "./relay.js"; import type { DaemonServer } from "./server.js"; import { - adminSession, aborted, cleanUp, digestOf, - freeLoopbackPort, gate, MIB, KIB, @@ -24,12 +19,11 @@ import { readParts, settleWithin, sleep, + startFleet as startFleet_, startWorker, + type FleetExec, type WorkerFixture, } from "./test-relay-support.js"; -import { mkdtemp } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; const poll = (read: () => T | Promise, timeout = 5_000) => expect.poll(read, { timeout }); @@ -163,79 +157,8 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { return { fixture, gatewayEnd, makeRelay, opened, pair, relay, spy }; } - async function startFleet(execCommand?: { args: string[]; command: string; env: object }) { - const gatewayDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-relay-gateway-")); - directories.push(gatewayDirectory); - const port = await freeLoopbackPort(); - let relay: GatewayRelay | undefined; - const taps: TappedTransport[] = []; - const gateway = await startDaemon({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, - dataDirectory: gatewayDirectory, - filesystem: new MemoryFilesystem(), - gatewayRelay: (given) => { - relay = given; - }, - gatewayUplinks: (uplinks) => { - const listen = uplinks.listen.bind(uplinks); - uplinks.listen = (handlers) => - listen({ - ...handlers, - accept: (uplink) => { - const tap = new TappedTransport(uplink.connection); - taps.push(tap); - handlers.accept({ ...uplink, connection: tap }); - }, - }); - }, - logger: new NoopLogger(), - statePath: join(gatewayDirectory, "state.json"), - version: "1.0.0-e2e", - }); - daemons.push(gateway); - const { secret } = await gateway.dispatch( - "token.create", - { label: "worker-a", role: "worker" }, - adminSession, - ); - const driverOptions = - execCommand === undefined - ? {} - : { passthrough: () => execCommand, passthroughTools: ["adb"] }; - const worker = await startWorker( - directories, - daemons, - { "agent-device": target, echo: target }, - { - configOverrides: { - gateway: { label: "worker-a", token: secret, url: `ws://127.0.0.1:${String(port)}` }, - }, - drivers: [ - new FakeDriver({ - availableOsVersions: ["18.0"], - clock: new SystemClock(), - knownModels: ["Pixel-A"], - platform: "android", - ...driverOptions, - } as ConstructorParameters[0]), - ], - }, - ); - let workerId = ""; - await vi.waitFor( - async () => { - const { workers } = await gateway.dispatch("worker.list", {}, adminSession); - const ready = workers.find( - (view) => view.connection === "connected" && view.capacity && view.catalog?.length, - ); - expect(ready).toBeDefined(); - workerId = ready?.id ?? ""; - }, - { timeout: 10_000 }, - ); - expect(relay).toBeDefined(); - return { gateway, relay: relay as unknown as GatewayRelay, taps, worker, workerId }; - } + const startFleet = (execCommand?: FleetExec) => + startFleet_({ daemons, directories, target }, execCommand === undefined ? {} : { execCommand }); const agent = (overrides: Partial = {}): DispatchSession => ({ manageEventSubscription: () => undefined, diff --git a/src/daemon/relay-promises.timing.test.ts b/src/daemon/relay-promises.timing.test.ts new file mode 100644 index 000000000..6e6d000ab --- /dev/null +++ b/src/daemon/relay-promises.timing.test.ts @@ -0,0 +1,399 @@ +import { afterEach, describe, expect, it } from "vitest"; + +import type { DispatchSession } from "./dispatch.js"; +import type { RelayTarget } from "./relay.js"; +import type { DaemonServer } from "./server.js"; +import { + cleanUp, + digestOf, + MIB, + KIB, + patternDigest, + patternDigestSwapped, + patternStream, + readParts, + sleep, + startCountingProxy, + startFleet, + type CountingProxy, +} from "./test-relay-support.js"; + +const GIB = 1024 * MIB; +const WORKER_TENANT = "gw.g1.alice"; + +const agent: DispatchSession = { + manageEventSubscription: () => undefined, + principal: "fleet-agent-1", + role: "agent", +}; + +describe("transfers through a gateway keep their promises", () => { + const daemons: DaemonServer[] = []; + const directories: string[] = []; + const proxies: CountingProxy[] = []; + let behavior: RelayTarget = () => Promise.resolve(new Response("ok")); + const target: RelayTarget = (request, tenant, leaseId) => behavior(request, tenant, leaseId); + + afterEach(async () => { + behavior = () => Promise.resolve(new Response("ok")); + await Promise.all(proxies.splice(0).map((proxy) => proxy.stop())); + await cleanUp(daemons, directories); + }); + + async function fleet() { + const started = await startFleet( + { daemons, directories, target }, + { + gatewayUrl: async (port) => { + const proxy = await startCountingProxy(port); + proxies.push(proxy); + return `ws://127.0.0.1:${String(proxy.port)}`; + }, + }, + ); + const proxy = proxies[0] as CountingProxy; + return { ...started, proxy }; + } + + function call( + url: string, + init: { readonly method?: string; readonly body?: ReadableStream } = {}, + ) { + const request = new Request(`http://gateway.test:4321/agent-device/${url}`, { + method: init.method ?? "GET", + ...(init.body === undefined ? {} : { body: init.body, duplex: "half" }), + } as RequestInit); + return { request, target: "echo", tenant: WORKER_TENANT }; + } + + async function drain(stream: ReadableStream | null): Promise { + if (stream === null) return 0; + const reader = stream.getReader(); + let total = 0; + for (;;) { + const step = await reader.read(); + if (step.done) return total; + total += step.value.length; + } + } + + function median(values: readonly number[]): number { + const sorted = [...values].sort((a, b) => a - b); + return sorted[Math.floor(sorted.length / 2)] as number; + } + + function carriedTotal(proxy: CountingProxy): number { + const { down, up } = proxy.carried(); + return up + down; + } + + async function acceptingUploads(): Promise { + behavior = async (request) => { + await drain(request.body); + return new Response("done"); + }; + } + + it("a 100 MiB upload through the gateway puts at most 105 MiB on the uplink", async () => { + await acceptingUploads(); + const { proxy, relay, workerId } = await fleet(); + proxy.reset(); + + const response = await relay.relay( + workerId, + call("upload", { body: patternStream(100 * MIB, 3), method: "PUT" }), + ); + await response.text(); + const carried = carriedTotal(proxy); + + expect(carried).toBeGreaterThanOrEqual(100 * MIB); + expect(carried).toBeLessThanOrEqual(105 * MIB); + }, 120_000); + + it("a 1 GiB upload through the gateway puts at most 1.05 GiB on the uplink, and so does a 1 GiB download, each measured on its own", async () => { + behavior = async (request) => { + if (request.method === "PUT") { + await drain(request.body); + return new Response("done"); + } + return new Response(patternStream(GIB, 4)); + }; + const { proxy, relay, workerId } = await fleet(); + + proxy.reset(); + const put = await relay.relay( + workerId, + call("upload", { body: patternStream(GIB, 3), method: "PUT" }), + ); + await put.text(); + const uploaded = carriedTotal(proxy); + + proxy.reset(); + const get = await relay.relay(workerId, call("download")); + const received = await drain(get.body); + const downloaded = carriedTotal(proxy); + + expect(uploaded).toBeGreaterThanOrEqual(GIB); + expect(uploaded).toBeLessThanOrEqual(1.05 * GIB); + expect(received).toBe(GIB); + expect(downloaded).toBeGreaterThanOrEqual(GIB); + expect(downloaded).toBeLessThanOrEqual(1.05 * GIB); + }, 180_000); + + // fallow-ignore-next-line complexity -- one measurement: its windows and delays are read in order, and splitting them would hide what each number is measured against. + it("while 10 relays each upload 64 MiB and 10 each download 64 MiB to one worker, a forwarded `lease.renew` and a relayed request whose target answers at once each answer at most 1 s later than with nothing running, and each of the 20 relays carried at least 1 MiB in the second before and the second after each answer came back", async () => { + const samples = new Map(); + const progress = (id: string, total: number) => { + const list = samples.get(id) ?? []; + list.push({ at: performance.now(), total }); + samples.set(id, list); + }; + const finishedAt = new Map(); + behavior = async (request) => { + const url = new URL(request.url); + const id = url.searchParams.get("id") ?? ""; + if (url.pathname.endsWith("/upload")) { + const reader = request.body?.getReader(); + let total = 0; + for (;;) { + const step = await reader?.read(); + if (step === undefined || step.done) break; + total += step.value.length; + progress(id, total); + } + finishedAt.set(id, performance.now()); + return new Response("done"); + } + if (url.pathname.endsWith("/download")) { + return new Response(patternStream(64 * MIB, 6)); + } + return new Response("ok"); + }; + const { gateway, relay, workerId } = await fleet(); + const grant = await gateway.dispatch( + "lease.request", + { model: "Pixel-A", noWait: true, platform: "android" }, + agent, + ); + const timeOf = async (work: () => Promise): Promise => { + const started = performance.now(); + await work(); + return performance.now() - started; + }; + const renew = () => gateway.dispatch("lease.renew", { leaseId: grant.lease.id }, agent); + const small = async () => (await relay.relay(workerId, call("small"))).text(); + + const renewDelays: number[] = []; + const smallDelays: number[] = []; + const quietWindows: string[] = []; + for (let run = 0; run < 5; run += 1) { + const idleRenew = await timeOf(renew); + const idleSmall = await timeOf(small); + samples.clear(); + finishedAt.clear(); + const downloads: Promise[] = []; + const uploads: Promise[] = []; + for (let index = 0; index < 10; index += 1) { + uploads.push( + relay + .relay( + workerId, + call(`upload?id=u${String(index)}`, { + body: patternStream(64 * MIB, 5), + method: "PUT", + }), + ) + .then((response) => response.text()), + ); + downloads.push( + relay + .relay(workerId, call(`download?id=d${String(index)}`)) + .then((response) => drain(response.body)), + ); + } + await sleep(500); + const answers: number[] = []; + renewDelays.push((await timeOf(renew)) - idleRenew); + answers.push(performance.now()); + smallDelays.push((await timeOf(small)) - idleSmall); + answers.push(performance.now()); + await sleep(1_000); + for (const answer of answers) { + for (let index = 0; index < 10; index += 1) { + const id = `u${String(index)}`; + const list = samples.get(id) ?? []; + const within = (from: number, to: number) => { + const inside = list.filter((sample) => sample.at >= from && sample.at <= to); + const first = inside[0]?.total ?? 0; + const last = inside.at(-1)?.total ?? 0; + return last - first; + }; + if (within(answer - 1_000, answer) < MIB || within(answer, answer + 1_000) < MIB) { + quietWindows.push(`${id}@${String(Math.round(answer))}`); + } + const done = finishedAt.get(id); + if (done !== undefined && done < answer + 1_000) + quietWindows.push(`${id} finished early`); + } + } + await Promise.all([...uploads, ...downloads]); + } + + expect(quietWindows).toEqual([]); + expect(median(renewDelays)).toBeLessThanOrEqual(1_000); + expect(median(smallDelays)).toBeLessThanOrEqual(1_000); + }, 300_000); + + it("while one relay's caller reads none of its 1 GiB response, another relay's 256 MiB upload to the same worker takes at most 1.5 times as long as with nothing else running", async () => { + behavior = async (request) => { + const url = new URL(request.url); + if (url.pathname.endsWith("/upload")) { + await drain(request.body); + return new Response("done"); + } + return new Response(patternStream(GIB, 8)); + }; + const { relay, workerId } = await fleet(); + const upload = async (): Promise => { + const started = performance.now(); + const response = await relay.relay( + workerId, + call("upload", { body: patternStream(256 * MIB, 7), method: "PUT" }), + ); + await response.text(); + return performance.now() - started; + }; + + const ratios: number[] = []; + for (let run = 0; run < 5; run += 1) { + const alone = await upload(); + const slow = await relay.relay(workerId, call("download")); + await sleep(500); + const beside = await upload(); + await slow.body?.cancel(); + ratios.push(beside / alone); + } + + expect(median(ratios)).toBeLessThanOrEqual(1.5); + }, 300_000); + + it("while the gateway's caller reads none of a 2 GiB response, the target has handed over at most 8 MiB after 5 s; reading it then gets every byte, in order", async () => { + let handedOver = 0; + behavior = () => { + const source = patternStream(2 * GIB, 11); + const reader = source.getReader(); + return Promise.resolve( + new Response( + new ReadableStream({ + async pull(controller) { + const step = await reader.read(); + if (step.done) controller.close(); + else { + handedOver += step.value.length; + controller.enqueue(step.value); + } + }, + }), + ), + ); + }; + const { relay, workerId } = await fleet(); + + const response = await relay.relay(workerId, call("download")); + await sleep(5_000); + const afterFiveSeconds = handedOver; + const body = await readParts(response.body); + const digest = digestOf(body); + + expect(afterFiveSeconds).toBeGreaterThan(0); + expect(afterFiveSeconds).toBeLessThanOrEqual(8 * MIB); + expect(digest).toBe(patternDigest(2 * GIB, 11)); + }, 180_000); + + it("while the target reads none of a 2 GiB upload, the gateway has read at most 8 MiB of the caller's body after 5 s; once the target reads, every byte arrives, in order", async () => { + let readByGateway = 0; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + let received = ""; + behavior = async (request) => { + await released; + received = digestOf(await readParts(request.body)); + return new Response("done"); + }; + const { relay, workerId } = await fleet(); + const source = patternStream(2 * GIB, 12, { onPull: () => (readByGateway += MIB) }); + + const pending = relay.relay(workerId, call("upload", { body: source, method: "PUT" })); + await sleep(5_000); + const afterFiveSeconds = readByGateway; + release(); + const response = await pending; + await response.text(); + + expect(afterFiveSeconds).toBeGreaterThan(0); + expect(afterFiveSeconds).toBeLessThanOrEqual(8 * MIB); + expect(received).toBe(patternDigest(2 * GIB, 12)); + }, 180_000); + + it("a 2 GiB upload through the gateway arrives byte for byte", async () => { + let received = ""; + let size = 0; + behavior = async (request) => { + const parts = await readParts(request.body); + size = parts.reduce((total, part) => total + part.length, 0); + received = digestOf(parts); + return new Response("done"); + }; + const { relay, workerId } = await fleet(); + + const response = await relay.relay( + workerId, + call("upload", { body: patternStream(2 * GIB, 13), method: "PUT" }), + ); + await response.text(); + + expect(size).toBe(2 * GIB); + expect(received).toBe(patternDigest(2 * GIB, 13)); + }, 180_000); + + it("a 2 GiB download through the gateway arrives byte for byte and finishes within 90 s", async () => { + behavior = () => Promise.resolve(new Response(patternStream(2 * GIB, 14))); + const { relay, workerId } = await fleet(); + + const started = performance.now(); + const response = await relay.relay(workerId, call("download")); + const parts = await readParts(response.body); + const elapsedMs = performance.now() - started; + + expect(digestOf(parts)).toBe(patternDigest(2 * GIB, 14)); + expect(elapsedMs).toBeLessThanOrEqual(90_000); + }, 180_000); + + it("swapping two chunks of different random sizes (1 byte to 64 KiB) at random offsets of a 2 GiB pattern changes its digest, in each of 100 trials", () => { + let state = 0x9e3779b9; + const random = (): number => { + state = (state + 0x6d2b79f5) | 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + const between = (low: number, high: number) => low + Math.floor(random() * (high - low + 1)); + const whole = patternDigest(2 * GIB, 21); + const unchanged: string[] = []; + + for (let trial = 0; trial < 100; trial += 1) { + const firstSize = between(1, 64 * KIB); + let secondSize = between(1, 64 * KIB); + if (secondSize === firstSize) secondSize = firstSize === 1 ? 2 : firstSize - 1; + const first = between(0, GIB - firstSize); + const second = between(GIB, 2 * GIB - secondSize); + const swapped = patternDigestSwapped(2 * GIB, 21, { first, firstSize, second, secondSize }); + if (swapped === whole) + unchanged.push(`trial ${String(trial)} at ${String(first)}/${String(second)}`); + } + + expect(unchanged).toEqual([]); + }, 300_000); +}); diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index a5477c071..18070c1a7 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -1,16 +1,19 @@ -import { createHash } from "node:crypto"; +import { createCipheriv, createHash, type Hash } from "node:crypto"; import { mkdtemp, rm } from "node:fs/promises"; -import { createServer } from "node:net"; +import { connect, createServer, type AddressInfo, type Socket } from "node:net"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { expect, vi } from "vitest"; + import { FakeDriver } from "../core/testing.js"; -import { MemoryFilesystem, SystemClock, type Logger } from "../ports/index.js"; +import type { GatewayRelay } from "../gateway/index.js"; +import { MemoryFilesystem, NoopLogger, SystemClock, type Logger } from "../ports/index.js"; import type { LinkChannel, LinkConnection } from "../link/index.js"; -import { linkPair, type LinkPair } from "../link/testing.js"; +import { linkPair, TappedTransport, type LinkPair } from "../link/testing.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; -import type { RelayTargets } from "./relay.js"; +import type { RelayTarget, RelayTargets } from "./relay.js"; import type { DaemonServer } from "./server.js"; import { SimlockWire, type CallHooks, type RelayHead } from "../simlock-client/wire.js"; @@ -23,7 +26,7 @@ export const adminSession: DispatchSession = { role: "admin", }; -export async function freeLoopbackPort(): Promise { +async function freeLoopbackPort(): Promise { const server = createServer(); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const address = server.address(); @@ -81,12 +84,18 @@ export async function settleWithin(promise: Promise, withinMs = 5_000): Pr return Promise.race([outcome, sleep(withinMs).then((): Settled => ({ state: "pending" }))]); } +/** why: AES in counter mode gives bytes that are random-access by offset and generated at GB/s, so a 2 GiB pattern costs seconds, not a byte loop's minutes. */ export function patternBytes(size: number, seed = 1, offset = 0): Uint8Array { - const bytes = new Uint8Array(size); - for (let index = 0; index < size; index += 1) { - bytes[index] = ((offset + index) * 31 + seed * 17 + ((offset + index) >> 8)) & 0xff; - } - return bytes; + const key = Buffer.alloc(16); + key.writeUInt32BE(seed >>> 0, 12); + const block = BigInt(Math.floor(offset / 16)); + const counter = Buffer.alloc(16); + counter.writeBigUInt64BE(block >> 64n, 0); + counter.writeBigUInt64BE(block & 0xffff_ffff_ffff_ffffn, 8); + const cipher = createCipheriv("aes-128-ctr", key, counter); + const skip = offset % 16; + const out = cipher.update(Buffer.alloc(skip + size)); + return new Uint8Array(out.buffer, out.byteOffset + skip, size); } export function digestOf(parts: readonly Uint8Array[]): string { @@ -292,3 +301,193 @@ export function aborted(signal: AbortSignal): Promise { else signal.addEventListener("abort", () => resolve(), { once: true }); }); } + +export interface FleetExec { + args: string[]; + command: string; + env: object; +} + +export interface FleetContext { + readonly daemons: DaemonServer[]; + readonly directories: string[]; + readonly target: RelayTarget; +} + +export interface FleetOptions { + readonly execCommand?: FleetExec; + // why: a test puts a proxy between the worker and the gateway, so the worker dials the proxy. + readonly gatewayUrl?: (gatewayPort: number) => string | Promise; +} + +export async function startFleet(context: FleetContext, options: FleetOptions = {}) { + const { daemons, directories, target } = context; + const execCommand = options.execCommand; + const gatewayDirectory = await mkdtemp(join(tmpdir(), "simlock-e2e-relay-gateway-")); + directories.push(gatewayDirectory); + const port = await freeLoopbackPort(); + const workerDials = (await options.gatewayUrl?.(port)) ?? `ws://127.0.0.1:${String(port)}`; + let relay: GatewayRelay | undefined; + const taps: TappedTransport[] = []; + const gateway = await startDaemon({ + configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, + dataDirectory: gatewayDirectory, + filesystem: new MemoryFilesystem(), + gatewayRelay: (given) => { + relay = given; + }, + gatewayUplinks: (uplinks) => { + const listen = uplinks.listen.bind(uplinks); + uplinks.listen = (handlers) => + listen({ + ...handlers, + accept: (uplink) => { + const tap = new TappedTransport(uplink.connection); + taps.push(tap); + handlers.accept({ ...uplink, connection: tap }); + }, + }); + }, + logger: new NoopLogger(), + statePath: join(gatewayDirectory, "state.json"), + version: "1.0.0-e2e", + }); + daemons.push(gateway); + const { secret } = await gateway.dispatch( + "token.create", + { label: "worker-a", role: "worker" }, + adminSession, + ); + const driverOptions = + execCommand === undefined ? {} : { passthrough: () => execCommand, passthroughTools: ["adb"] }; + const worker = await startWorker( + directories, + daemons, + { "agent-device": target, echo: target }, + { + configOverrides: { + gateway: { label: "worker-a", token: secret, url: workerDials }, + }, + drivers: [ + new FakeDriver({ + availableOsVersions: ["18.0"], + clock: new SystemClock(), + knownModels: ["Pixel-A"], + platform: "android", + ...driverOptions, + } as ConstructorParameters[0]), + ], + }, + ); + let workerId = ""; + await vi.waitFor( + async () => { + const { workers } = await gateway.dispatch("worker.list", {}, adminSession); + const ready = workers.find( + (view) => view.connection === "connected" && view.capacity && view.catalog?.length, + ); + expect(ready).toBeDefined(); + workerId = ready?.id ?? ""; + }, + { timeout: 10_000 }, + ); + expect(relay).toBeDefined(); + return { gateway, port, relay: relay as unknown as GatewayRelay, taps, worker, workerId }; +} + +export interface CountingProxy { + readonly port: number; + readonly carried: () => { readonly up: number; readonly down: number }; + readonly reset: () => void; + readonly stop: () => Promise; +} + +export function startCountingProxy(targetPort: number): Promise { + const counts = { down: 0, up: 0 }; + const sockets = new Set(); + const server = createServer((client) => { + const upstream = connect({ host: "127.0.0.1", port: targetPort }); + sockets.add(client); + sockets.add(upstream); + const close = () => { + client.destroy(); + upstream.destroy(); + }; + client.on("error", close); + upstream.on("error", close); + client.on("close", close); + upstream.on("close", close); + client.on("data", (chunk: Buffer) => { + counts.up += chunk.length; + }); + upstream.on("data", (chunk: Buffer) => { + counts.down += chunk.length; + }); + // why: pipe pauses the reader while the writer is full, so the proxy never buffers a stream. + client.pipe(upstream); + upstream.pipe(client); + }); + return new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address() as AddressInfo; + resolve({ + carried: () => ({ down: counts.down, up: counts.up }), + port: address.port, + reset: () => { + counts.down = 0; + counts.up = 0; + }, + stop: () => + new Promise((done) => { + for (const socket of sockets) socket.destroy(); + server.close(() => done()); + }), + }); + }); + }); +} + +const CHECKPOINT = 64 * MIB; +const checkpoints = new Map(); + +function checkpointsFor(total: number, seed: number): Hash[] { + const key = `${String(total)}:${String(seed)}`; + const known = checkpoints.get(key); + if (known !== undefined) return known; + const states: Hash[] = []; + const hash = createHash("sha256"); + for (let offset = 0; offset < total; offset += CHECKPOINT) { + states.push(hash.copy()); + hash.update(patternBytes(Math.min(CHECKPOINT, total - offset), seed, offset)); + } + checkpoints.set(key, states); + return states; +} + +/** why: the digest of the pattern with the chunk `[first, first + firstSize)` and the chunk `[second, second + secondSize)` exchanged, where `first + firstSize <= second`. */ +export function patternDigestSwapped( + total: number, + seed: number, + swap: { + readonly first: number; + readonly second: number; + readonly firstSize: number; + readonly secondSize: number; + }, +): string { + const states = checkpointsFor(total, seed); + const start = Math.floor(swap.first / CHECKPOINT) * CHECKPOINT; + const hash = (states[start / CHECKPOINT] as Hash).copy(); + const feed = (from: number, to: number) => { + for (let offset = from; offset < to; offset += MIB) { + hash.update(patternBytes(Math.min(MIB, to - offset), seed, offset)); + } + }; + feed(start, swap.first); + hash.update(patternBytes(swap.secondSize, seed, swap.second)); + feed(swap.first + swap.firstSize, swap.second); + hash.update(patternBytes(swap.firstSize, seed, swap.first)); + feed(swap.second + swap.secondSize, total); + return hash.digest("hex"); +} diff --git a/src/test-lanes.test.ts b/src/test-lanes.test.ts index 8822c479c..50826c62b 100644 --- a/src/test-lanes.test.ts +++ b/src/test-lanes.test.ts @@ -132,4 +132,21 @@ describe("test lanes (package.json)", () => { expect(config).toMatch(/name:\s*"physical"/); expect(config).toMatch(/name:\s*"physical-manual"/); }); + + it("the `unit` project and the mutation config leave out `*.timing.test.ts`, the `timing` project takes them and runs files one at a time, `pnpm test` runs `test:timing`, and CI's `quality` job needs the `timing` job", () => { + const config = readFileSync(join(REPO_ROOT, "vitest.config.ts"), "utf8"); + const mutate = readFileSync(join(REPO_ROOT, "vitest.mutate.config.ts"), "utf8"); + const ci = readFileSync(join(REPO_ROOT, ".github/workflows/ci.yml"), "utf8"); + const unitProject = /name:\s*"unit"[\s\S]*?name:\s*"(?:timing|e2e)"/.exec(config)?.[0] ?? ""; + const timingProject = /name:\s*"timing"[\s\S]*?(?:name:\s*"e2e"|$)/.exec(config)?.[0] ?? ""; + const quality = /\n {2}quality:[\s\S]*$/.exec(ci)?.[0] ?? ""; + + expect(unitProject).toContain("*.timing.test.ts"); + expect(mutate).toContain("*.timing.test.ts"); + expect(timingProject).toContain("src/**/*.timing.test.ts"); + expect(timingProject).toMatch(/fileParallelism:\s*false/); + expect(script("test:timing")).toContain("--project timing"); + expect(script("test")).toContain("test:timing"); + expect(quality).toMatch(/needs:\s*\[[^\]]*\btiming\b/); + }); }); diff --git a/vitest.config.ts b/vitest.config.ts index 432eaf52b..6f8e0fa98 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -18,6 +18,18 @@ export default defineConfig({ // `ui/` holds the console's own unit tests: plain functions, no browser. The browser // lane is Playwright's (`pnpm test:console`). include: ["src/**/*.test.ts", "ui/**/*.test.{ts,tsx}"], + // why: the timing files measure throughput and latency of GiB transfers: they run one + // at a time (`pnpm test:timing`) so another file's load cannot move a number. + exclude: ["**/node_modules/**", "src/**/*.timing.test.ts"], + }, + }, + { + test: { + name: "timing", + include: ["src/**/*.timing.test.ts"], + fileParallelism: false, + testTimeout: 300_000, + hookTimeout: 120_000, }, }, { diff --git a/vitest.mutate.config.ts b/vitest.mutate.config.ts index fae12e6f4..fa5e21b7a 100644 --- a/vitest.mutate.config.ts +++ b/vitest.mutate.config.ts @@ -6,6 +6,8 @@ export default defineConfig({ test: { tags: [{ name: "slow" }, { name: "ios" }, { name: "android" }], include: ["src/**/*.test.ts", "ui/**/*.test.{ts,tsx}"], + // why: timing files move GiB through a daemon pair: far too slow to run once per mutant. + exclude: ["**/node_modules/**", "src/**/*.timing.test.ts"], // Stryker runs every test file in a worker thread, and this test sets process.env.TZ, which // a worker thread ignores: it is left out so it cannot abort every mutation run. testNamePattern: /^(?!.*on the browser's clock face).*$/,