Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .agents/scripts/tool-guard.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import path from "node:path";
const SCRIPTS = new Set([
"check",
"test",
"test:timing",
"typecheck",
"typecheck:e2e",
"lint",
Expand Down
24 changes: 23 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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: {}
Expand Down
7 changes: 4 additions & 3 deletions docs/internal/agent-rules/toolchain.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <file>` |
| One timing file (`*.timing.test.ts`) | `pnpm exec vitest run --project timing <file>` |
| Fast e2e files (builds first) | `pnpm test:e2e <files>` |
| Console lane, Chromium only (1) | `pnpm test:console --project=chromium` |

Expand All @@ -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`,
Expand All @@ -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
Expand Down
111 changes: 111 additions & 0 deletions e2e/slow-agent-device-gateway.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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<Buffer> {
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<Uint8Array> => {
const chunks = uploadChunks();
return new ReadableStream<Uint8Array>({
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<SharedTestEnv>();
afterAll(async () => {
await Promise.allSettled([...sharedEnvs].map((env) => env.teardown()));
Expand Down Expand Up @@ -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<number> {
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<string, string> };
};
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(
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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'",
Expand Down
89 changes: 6 additions & 83 deletions src/daemon/relay-gateway.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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 = <T>(read: () => T | Promise<T>, timeout = 5_000) => expect.poll(read, { timeout });

Expand Down Expand Up @@ -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<typeof FakeDriver>[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> = {}): DispatchSession => ({
manageEventSubscription: () => undefined,
Expand Down
Loading
Loading