Skip to content
Myr

checker.test.ts

This file

Path

apps/sandbox/test/checker.test.ts

917 lines · 27.3 KiB · TypeScript

Last changed by

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { CheckAt } from "@repo/checks/check-runner";3import { CheckExit, CheckWire } from "@repo/checks/check-runner/wire";4import { phasePlan } from "@repo/checks/phases";5import { Command, Hostname } from "@repo/protocol/domain/common";6import { RunBlock } from "@repo/protocol/domain/run";7import {8  CommitSha,9  LaneName,10  ProjectName,11  RepoName,12  keyOf,13  TreeSha,14} from "@repo/protocol/ids";15import { VerifierBlocked } from "@repo/protocol/refusal";16import { untouchable } from "@repo/testkit/untouchable";17import {18  Duration,19  Effect,20  Exit,21  Fiber,22  Latch,23  Match,24  Option,25  Redacted,26  Schema,27} from "effect";28import { TestClock } from "effect/testing";29import { vi } from "vitest";3031import { Checker, runCheck } from "../src/checker.ts";32import type { Checkers } from "../src/checker.ts";33import { CLONE_HOST, REGISTRIES } from "../src/checker/network.ts";34import { check } from "../src/checker/run.ts";35import { CloneGateway, EgressGateway } from "../src/outbound.ts";36import type { CloneProps, EgressProps } from "../src/outbound.ts";37import { exited, fakeChecker, fakeContainer } from "./fake-box.ts";38import type { Call, ContainerCall } from "./fake-box.ts";39import { fakeEnv } from "./fake-env.ts";4041const TOKEN = "art_v1_read-only-secret?expires=1791400000";4243const SETUP = "bun install --frozen-lockfile --ignore-scripts";4445const run = RunBlock.make({46  checks: {47    [LaneName.make("lint")]: Command.make("bun run lint"),48    [LaneName.make("unit")]: Command.make("bun test"),49  },50  setup: Command.make(SETUP),51  setupEgress: [Hostname.make("npm.pkg.github.com")],52  test: Command.make("bun test {path}"),53});5455const lanes = [56  { command: "bun run lint", lane: LaneName.make("lint") },57  { command: "bun test", lane: LaneName.make("unit") },58];5960const wireFor = (name = "oscabriel/datekit"): CheckWire => {61  const project = ProjectName.make(name);6263  return {64    clone: {65      token: Redacted.make(TOKEN),66      url: `https://0123abcd.artifacts.cloudflare.net/git/public/${keyOf(project)}.git`,67    },68    job: {69      at: CheckAt.cases.Commit.make({ commit: CommitSha.make("a".repeat(40)) }),70      lanes,71      placeholders: [],72      project,73      proxies: [],74      repo: RepoName.make(keyOf(project)),75      run,76    },77  };78};7980const isShell = (call: Call, command: string) =>81  call.kind === "exec" &&82  call.argv[0] === "sh" &&83  call.argv[1] === "-c" &&84  call.argv[2] === command;8586const setups = (calls: readonly Call[]) =>87  calls.filter((call) => isShell(call, SETUP)).length;8889const phaseOf = Match.type<Call>().pipe(90  Match.discriminatorsExhaustive("kind")({91    allow: ({ hosts }): readonly string[] =>92      hosts.length === 0 ? ["egressOff"] : ["setup"],93    destroy: () => ["destroy"],94    exec: (call) => {95      if (call.argv[0] === "git") {96        return ["clone"];97      }9899      return isShell(call, SETUP) ? ["setup"] : ["run"];100    },101    // The env gateway's routes open as egress goes off.102    intercept: () => ["egressOff"],103    // Log lines are no phase of their own.104    log: () => [],105    report: () => ["report"],106    restore: () => ["setup"],107    route: () => ["clone"],108    save: () => ["snapshot"],109    writeFile: () => ["writeHeldBack"],110  })111);112113const phasesOf = (calls: readonly Call[]) =>114  calls115    .flatMap(phaseOf)116    .filter((phase, at, all) => at === 0 || all[at - 1] !== phase);117118const tagsOf = (plan: ReturnType<typeof phasePlan>) =>119  plan.map(({ _tag }) => `${_tag.charAt(0).toLowerCase()}${_tag.slice(1)}`);120121describe("the Checker", () => {122  it.effect(123    "clones, sets up with registry egress, snapshots, cuts egress, runs the lanes, reports and destroys, in the plan's order",124    () =>125      Effect.gen(function* () {126        const fake = fakeChecker();127128        const outcome = yield* Effect.exit(129          check(wireFor()).pipe(Effect.provide(fake.layer))130        );131132        expect(Exit.isSuccess(outcome)).toBeTruthy();133134        const observed = phasesOf(fake.calls);135136        expect(observed).toStrictEqual([137          "clone",138          "setup",139          "snapshot",140          "egressOff",141          "run",142          "report",143          "destroy",144        ]);145146        expect(observed.slice(1, -1)).toStrictEqual(147          tagsOf(148            phasePlan({149              heldBack: Option.none(),150              lanes,151              lockfileHash: "any",152              placeholders: [],153              run,154            })155          )156        );157158        const setupAt = fake.calls.findIndex((call) => isShell(call, SETUP));159160        const egress = fake.calls161          .slice(0, setupAt)162          .findLast((call) => call.kind === "allow");163164        expect(egress).toStrictEqual({165          hosts: [...REGISTRIES, "npm.pkg.github.com"],166          kind: "allow",167        });168169        expect(170          fake.calls.flatMap((call) =>171            call.kind === "exec" && call.argv[0] === "sh" ? [call.argv[2]] : []172          )173        ).toStrictEqual([SETUP, "bun run lint", "bun test"]);174      })175  );176177  it.effect(178    "clones through the intercepted host, and never shows the container the token",179    () =>180      Effect.gen(function* () {181        const fake = fakeChecker();182183        yield* check(wireFor()).pipe(Effect.provide(fake.layer));184185        expect(186          fake.calls.filter((call) => call.kind === "route")187        ).toStrictEqual([188          {189            host: CLONE_HOST,190            kind: "route",191            remote:192              "https://0123abcd.artifacts.cloudflare.net/git/public/datekit.git",193            token: TOKEN,194          },195        ]);196197        const fetched = fake.calls.find(198          (call) => call.kind === "exec" && call.argv.includes("fetch")199        );200201        expect(fetched?.kind === "exec" ? fetched.argv : []).toContain(202          `https://${CLONE_HOST}/git/public/datekit.git`203        );204205        // Everything the container was handed (commands, their env and206        // working directories, files) and everything logged or reported:207        // only the route, on the Worker's side, holds the token.208        const seen = JSON.stringify(209          fake.calls.filter((call) => call.kind !== "route")210        );211212        expect(seen).not.toContain("read-only-secret");213        expect(seen).not.toContain(TOKEN);214      })215  );216217  it.effect(218    "is VerifierBlocked when setup cannot reach a host, and names the host in setup's log and a log annotation",219    () =>220      Effect.gen(function* () {221        const fake = fakeChecker({222          commands: new Map([223            [224              SETUP,225              exited(1, {226                stderr:227                  "error: GET https://evil.example/left-pad/-/left-pad-1.3.0.tgz - 403\n",228              }),229            ],230          ]),231        });232233        const outcome = yield* Effect.exit(234          check(wireFor()).pipe(Effect.provide(fake.layer))235        );236237        expect(Exit.findErrorOption(outcome)).toStrictEqual(238          Option.some(new VerifierBlocked({}))239        );240241        const reported = fake.calls.flatMap((call) =>242          call.kind === "report" ? call.logs : []243        );244245        const setupLog = reported.find(({ phase }) => phase === "setup");246247        expect(setupLog?.text).toContain("refused: evil.example");248        expect(249          fake.calls.flatMap((call) =>250            call.kind === "log" && call.annotations.phase === "setup"251              ? [call.annotations.blockedHosts]252              : []253          )254        ).toStrictEqual(["evil.example"]);255256        expect(phasesOf(fake.calls)).toStrictEqual([257          "clone",258          "setup",259          "report",260          "destroy",261        ]);262      })263  );264265  it.effect(266    "reports a failing lane as that lane's result, from how it failed, never as an error",267    () =>268      Effect.gen(function* () {269        const fake = fakeChecker({270          commands: new Map([271            [272              "bun test",273              exited(1, {274                stdout:275                  "(fail) week > parses ISO weeks\nAssertionError: expected 52 to be 53\n",276              }),277            ],278            [279              "bun run lint",280              exited(1, { stderr: "Cannot find module 'oxlint'\n" }),281            ],282          ]),283        });284285        const ran = yield* check(wireFor()).pipe(Effect.provide(fake.layer));286287        expect(288          ran.lanes.map(({ command, lane, result }) => ({289            command,290            lane,291            result,292          }))293        ).toStrictEqual([294          { command: "bun run lint", lane: "lint", result: "loadError" },295          { command: "bun test", lane: "unit", result: "failed" },296        ]);297        expect(ran.evidence).toStrictEqual([298          { lane: "lint" },299          {300            lane: "unit",301            signature:302              "week > parses ISO weeks: AssertionError: expected 52 to be 53",303          },304        ]);305        expect(JSON.stringify(ran)).not.toContain("Cannot find module");306      })307  );308309  it.effect(310    "hands back what a count lane printed, and nothing for a lane that did not ask or ran out of time",311    () =>312      Effect.gen(function* () {313        const LINT = "oxlint --format json";314        const printed = `{"diagnostics":[{"code":"typescript-eslint(no-explicit-any)","filename":"src/parser/week.ts"}]}`;315        const started = yield* Latch.make();316317        const fake = fakeChecker({318          commands: new Map([319            // A lint with findings exits 1; its count is read from stdout.320            [LINT, exited(1, { stderr: "1 warning\n", stdout: printed })],321            ["bun test", exited(0, { stdout: "4 pass\n" })],322            ["slow-count", started.open.pipe(Effect.andThen(Effect.never))],323          ]),324        });325326        const wire = wireFor();327328        const fiber = yield* check({329          ...wire,330          job: {331            ...wire.job,332            lanes: [333              {334                command: LINT,335                lane: LaneName.make("no-explicit-any"),336                output: "stdout",337              },338              { command: "bun test", lane: LaneName.make("unit") },339              {340                command: "slow-count",341                lane: LaneName.make("slow"),342                output: "stdout",343                timeoutMs: 1000,344              },345            ],346          },347        }).pipe(Effect.provide(fake.layer), Effect.forkChild);348349        yield* started.await;350        yield* TestClock.adjust(Duration.seconds(1));351352        const ran = yield* Fiber.join(fiber);353354        expect(ran.outputs).toStrictEqual([355          { lane: "no-explicit-any", stdout: printed },356        ]);357358        const crossed = yield* Schema.encodeEffect(CheckExit)(359          Exit.succeed(ran)360        ).pipe(Effect.flatMap(Schema.decodeEffect(CheckExit)));361362        expect(crossed).toStrictEqual(Exit.succeed(ran));363      })364  );365366  it.effect("hands back no outputs when no lane asks for one", () =>367    Effect.gen(function* () {368      const fake = fakeChecker({369        commands: new Map([["bun test", exited(0, { stdout: "4 pass\n" })]]),370      });371372      const ran = yield* check(wireFor()).pipe(Effect.provide(fake.layer));373374      expect(ran).not.toHaveProperty("outputs");375      expect(JSON.stringify(ran)).not.toContain("4 pass");376    })377  );378379  it.effect(380    "restores the snapshot for a second job of the same project and lockfile, instead of running setup again",381    () =>382      Effect.gen(function* () {383        const snapshots = new Set<string>();384        const first = fakeChecker({ snapshots });385        const second = fakeChecker({ snapshots });386        const elsewhere = fakeChecker({ snapshots });387388        yield* check(wireFor()).pipe(Effect.provide(first.layer));389        yield* check(wireFor()).pipe(Effect.provide(second.layer));390        yield* check(wireFor("oscabriel/burrow")).pipe(391          Effect.provide(elsewhere.layer)392        );393394        expect(395          [first, second, elsewhere].map(({ calls }) => setups(calls))396        ).toStrictEqual([1, 0, 1]);397        expect(398          second.calls.flatMap((call) =>399            call.kind === "restore" || call.kind === "save" ? [call.kind] : []400          )401        ).toStrictEqual(["restore"]);402        expect(403          second.calls.flatMap((call) =>404            call.kind === "restore" ? [call.hit] : []405          )406        ).toStrictEqual([true]);407408        const restoredAt = second.calls.findIndex(409          (call) => call.kind === "restore"410        );411412        expect(413          second.calls414            .slice(restoredAt)415            .some(416              (call) => call.kind === "exec" && call.argv.includes("checkout")417            )418        ).toBeTruthy();419        expect(phasesOf(second.calls)).toStrictEqual([420          "clone",421          "setup",422          "clone",423          "egressOff",424          "run",425          "report",426          "destroy",427        ]);428      })429  );430431  it.effect(432    "never keeps the setup a check of an answer's tree ran, though such a check restores the project's",433    () =>434      Effect.gen(function* () {435        const snapshots = new Set<string>();436        const wire = wireFor();437438        const answer: CheckWire = {439          ...wire,440          job: {441            ...wire.job,442            at: CheckAt.cases.Tree.make({ tree: TreeSha.make("e".repeat(40)) }),443            repo: RepoName.make("datekit--week--alice"),444          },445        };446447        const first = fakeChecker({ snapshots });448        const main = fakeChecker({ snapshots });449        const again = fakeChecker({ snapshots });450451        yield* check(answer).pipe(Effect.provide(first.layer));452        yield* check(wire).pipe(Effect.provide(main.layer));453        yield* check(answer).pipe(Effect.provide(again.layer));454455        expect(456          [first, main, again].map(({ calls }) =>457            calls.flatMap((call) =>458              call.kind === "save" || call.kind === "restore" ? [call.kind] : []459            )460          )461        ).toStrictEqual([["restore"], ["restore", "save"], ["restore"]]);462        expect(463          [first, main, again].map(({ calls }) => setups(calls))464        ).toStrictEqual([1, 1, 0]);465      })466  );467468  it.effect(469    "destroys the container when a lane runs out of time, and reports that lane as blocked",470    () =>471      Effect.gen(function* () {472        // The lane says when it has started, so the clock moves only once its473        // time limit is running: the checkout hashes with a real promise474        // first, and a busy machine can let an early `adjust` pass it by.475        const started = yield* Latch.make();476477        const fake = fakeChecker({478          commands: new Map([479            ["bun test", started.open.pipe(Effect.andThen(Effect.never))],480          ]),481        });482483        const wire = wireFor();484485        const fiber = yield* check({486          ...wire,487          job: {488            ...wire.job,489            lanes: [490              {491                command: "bun test",492                lane: LaneName.make("unit"),493                timeoutMs: 1000,494              },495              { command: "bun run lint", lane: LaneName.make("lint") },496            ],497          },498        }).pipe(Effect.provide(fake.layer), Effect.forkChild);499500        yield* started.await;501        yield* TestClock.adjust(Duration.seconds(1));502503        const ran = yield* Fiber.join(fiber);504505        expect(506          ran.lanes.map(({ lane, result }) => ({ lane, result }))507        ).toStrictEqual([508          { lane: "unit", result: "blocked" },509          { lane: "lint", result: "passed" },510        ]);511        expect(fake.calls.at(-1)).toStrictEqual({ kind: "destroy" });512        expect(513          fake.calls.filter((call) => call.kind === "destroy")514        ).toHaveLength(1);515      })516  );517});518519const outboundRecorded = Effect.acquireRelease(520  Effect.sync(() => {521    const sent: Request[] = [];522523    vi.stubGlobal("fetch", (request: Request) => {524      sent.push(request);525526      return Promise.resolve(new Response("upstream"));527    });528529    return sent;530  }),531  () => Effect.sync(() => vi.unstubAllGlobals())532);533534const REMOTE =535  "https://0123abcd.artifacts.cloudflare.net/git/public/datekit.git";536537const cloneGateway = () =>538  new CloneGateway(539    untouchable<ExecutionContext<CloneProps>>("ctx", {540      props: { remote: REMOTE, token: TOKEN },541    }),542    fakeEnv()543  );544545const statusOf = (response: Response) =>546  Effect.promise(() => response.text()).pipe(547    Effect.map((text) => ({ status: response.status, text }))548  );549550describe("the clone gateway", () => {551  it.effect(552    "sends the container's upload-pack requests on to the job's remote, adding the token",553    () =>554      Effect.gen(function* () {555        const sent = yield* outboundRecorded;556        const gateway = cloneGateway();557558        yield* Effect.promise(() =>559          gateway.fetch(560            new Request(561              `https://${CLONE_HOST}/git/public/datekit.git/info/refs?service=git-upload-pack`,562              { headers: { "git-protocol": "version=2" } }563            )564          )565        );566        yield* Effect.promise(() =>567          gateway.fetch(568            new Request(569              `https://${CLONE_HOST}/git/public/datekit.git/git-upload-pack`,570              { body: "0000", method: "POST" }571            )572          )573        );574575        expect(576          sent.map((request) => ({577            authorization: request.headers.get("authorization"),578            method: request.method,579            protocol: request.headers.get("git-protocol"),580            url: request.url,581          }))582        ).toStrictEqual([583          {584            authorization: `Bearer ${TOKEN}`,585            method: "GET",586            protocol: "version=2",587            url: `${REMOTE}/info/refs?service=git-upload-pack`,588          },589          {590            authorization: `Bearer ${TOKEN}`,591            method: "POST",592            protocol: null,593            url: `${REMOTE}/git-upload-pack`,594          },595        ]);596      })597  );598599  it.effect(600    "refuses a push, a query git never sends, another repo's path, and another host, sending nothing on",601    () =>602      Effect.gen(function* () {603        const sent = yield* outboundRecorded;604        const gateway = cloneGateway();605606        const refused = yield* Effect.forEach(607          [608            new Request(609              `https://${CLONE_HOST}/git/public/datekit.git/info/refs?service=git-receive-pack`610            ),611            new Request(612              `https://${CLONE_HOST}/git/public/datekit.git/git-receive-pack`,613              { body: "0000", method: "POST" }614            ),615            new Request(616              `https://${CLONE_HOST}/git/public/datekit.git/git-upload-pack?service=git-receive-pack`,617              { body: "0000", method: "POST" }618            ),619            new Request(620              `https://${CLONE_HOST}/git/public/burrow.git/info/refs?service=git-upload-pack`621            ),622            new Request(623              "https://0123abcd.artifacts.cloudflare.net/git/public/datekit.git/info/refs?service=git-upload-pack"624            ),625          ],626          (request) =>627            Effect.map(628              Effect.promise(() => gateway.fetch(request)),629              ({ status }) => status630            )631        );632633        expect(refused).toStrictEqual([403, 403, 403, 403, 403]);634        expect(sent).toStrictEqual([]);635      })636  );637});638639describe("the egress gateway", () => {640  it.effect(641    "lets out requests to the hosts it allows, unchanged, and refuses the rest, naming the host",642    () =>643      Effect.gen(function* () {644        const sent = yield* outboundRecorded;645646        const gateway = new EgressGateway(647          untouchable<ExecutionContext<EgressProps>>("ctx", {648            props: { allow: ["registry.npmjs.org", "*.pkg.example.com"] },649          }),650          fakeEnv()651        );652653        const answers = yield* Effect.forEach(654          [655            "https://registry.npmjs.org/left-pad",656            "https://npm.pkg.example.com/@acme/kit",657            "https://evil.example/left-pad.tgz",658            "https://pkg.example.com/apex",659          ],660          (url) =>661            Effect.flatMap(662              Effect.promise(() => gateway.fetch(new Request(url))),663              statusOf664            )665        );666667        expect(answers).toStrictEqual([668          { status: 200, text: "upstream" },669          { status: 200, text: "upstream" },670          {671            status: 403,672            text: "egress refused: evil.example is not on this check's allow-list\n",673          },674          {675            status: 403,676            text: "egress refused: pkg.example.com is not on this check's allow-list\n",677          },678        ]);679        expect(sent.map(({ url }) => url)).toStrictEqual([680          "https://registry.npmjs.org/left-pad",681          "https://npm.pkg.example.com/@acme/kit",682        ]);683      })684  );685686  it.effect("with nothing allowed, lets nothing out", () =>687    Effect.gen(function* () {688      const sent = yield* outboundRecorded;689690      const gateway = new EgressGateway(691        untouchable<ExecutionContext<EgressProps>>("ctx", {692          props: { allow: [] },693        }),694        fakeEnv()695      );696697      const response = yield* Effect.promise(() =>698        gateway.fetch(new Request("https://registry.npmjs.org/left-pad"))699      );700701      expect(response.status).toBe(403);702      expect(sent).toStrictEqual([]);703    })704  );705});706707const checkerWorld = (options: {708  readonly withGateways: boolean;709  readonly running?: boolean;710}) => {711  const boxes: ReturnType<typeof fakeContainer>[] = [];712  const index = new Map<string, string>();713  const named: string[] = [];714715  const indexStub = untouchable<DurableObjectStub<Checker>>("index", {716    forgetSnapshot: (key) => {717      index.delete(key);718719      return Promise.resolve();720    },721    keepSnapshot: (key, id) => {722      index.set(key, id);723724      return Promise.resolve();725    },726    snapshotOf: (key) => {727      const id = index.get(key);728729      return id === undefined ? Promise.resolve(null) : Promise.resolve(id);730    },731  });732733  const indexNamed = (name: string) => {734    named.push(name);735736    return indexStub;737  };738739  const env: Env = {740    CHECKER: untouchable<Env["CHECKER"]>("CHECKER", { getByName: indexNamed }),741    LANDER: untouchable("LANDER"),742  };743744  const checkers: Checkers = {745    CHECKER: {746      get: () => {747        const box = fakeContainer({ running: options.running ?? true });748749        boxes.push(box);750751        // The Worker's other exports are not the Checker's to touch: only752        // the gateways are real members.753        const exports = options.withGateways754          ? { ...untouchable<Cloudflare.Exports>("exports"), ...box.exports }755          : { ...untouchable<Cloudflare.Exports>("exports") };756757        return new Checker(758          untouchable<DurableObjectState>("ctx", {759            container: box.container,760            exports,761          }),762          env763        );764      },765      getByName: indexNamed,766      newUniqueId: () => untouchable<DurableObjectId>(`id-${boxes.length}`),767    },768  };769770  return { boxes, checkers, index, named };771};772773const encodedWire = () =>774  Schema.encodeEffect(CheckWire)(wireFor()).pipe(Effect.orDie);775776const twoJobsIn = ({ running = true } = {}) =>777  Effect.gen(function* () {778    const world = checkerWorld({ running, withGateways: true });779    const wire = yield* encodedWire();780781    const outcomes = yield* Effect.forEach([wire, wire], (each) =>782      Effect.flatMap(783        Effect.promise(() => runCheck(world.checkers, each)),784        Schema.decodeEffect(CheckExit)785      )786    );787788    return { ...world, outcomes };789  });790791const twoJobs = twoJobsIn();792793const intercepts = (calls: readonly ContainerCall[]) =>794  calls.flatMap((call) =>795    call.kind === "intercept" ? [`${call.target} → ${call.to}`] : []796  );797798describe(runCheck, () => {799  it.effect(800    "decodes the job, runs it in a Checker of its own, and encodes its outcome, destroying each container",801    () =>802      Effect.gen(function* () {803        const { boxes, outcomes } = yield* twoJobs;804805        expect(806          outcomes.map((outcome) =>807            Exit.match(outcome, {808              onFailure: () => [],809              onSuccess: ({ lanes: ran }) => ran.map(({ result }) => result),810            })811          )812        ).toStrictEqual([813          ["passed", "passed"],814          ["passed", "passed"],815        ]);816        expect(boxes.map(({ calls }) => calls.at(-1))).toStrictEqual([817          { kind: "destroy" },818          { kind: "destroy" },819        ]);820      })821  );822823  it.effect(824    "routes the clone host to the clone gateway until setup starts, the rest to the egress gateway, and closes every route once egress is off",825    () =>826      Effect.gen(function* () {827        const { boxes } = yield* twoJobs;828        const setupHosts = [...REGISTRIES, "npm.pkg.github.com"].join(" ");829830        expect(intercepts(boxes[0]?.calls ?? [])).toStrictEqual([831          `${CLONE_HOST} → clone ${REMOTE} ${TOKEN}`,832          "* → egress []",833          "http:* → egress []",834          `${CLONE_HOST} → egress [${setupHosts}]`,835          `* → egress [${setupHosts}]`,836          `http:* → egress [${setupHosts}]`,837          `${CLONE_HOST} → egress []`,838          "* → egress []",839          "http:* → egress []",840        ]);841        // Nothing the containers ran or were given holds the token: it went842        // only to the clone gateway's props, on the Worker's side.843        expect(844          JSON.stringify(845            boxes.flatMap(({ calls }) =>846              calls.filter((call) => call.kind !== "intercept")847            )848          )849        ).not.toContain("read-only-secret");850      })851  );852853  it.effect(854    "starts the second job's container from the snapshot the first one kept, in the project's index",855    () =>856      Effect.gen(function* () {857        const { boxes, index, named } = yield* twoJobs;858        const [first, second] = boxes;859860        expect(861          first?.calls.filter((call) => call.kind === "snapshot")862        ).toHaveLength(1);863        expect([...index.values()]).toStrictEqual(["snapshot-1"]);864        expect([...new Set(named)]).toStrictEqual(["snapshots:datekit"]);865        expect(866          second?.calls.filter((call) => call.kind === "start")867        ).toStrictEqual([868          { from: "snapshot-1", instance: "standard-3", kind: "start" },869        ]);870        expect(871          second?.calls.filter(872            (call) => call.kind === "exec" && call.argv.includes(SETUP)873          )874        ).toStrictEqual([]);875      })876  );877878  it.effect(879    "starts each container on two vCPUs and 8 GiB, from the image and from a snapshot alike",880    () =>881      Effect.gen(function* () {882        const { boxes } = yield* twoJobsIn({ running: false });883884        // oxlint with JS plugins reserves 6 GiB of address space per885        // thread, which Linux refuses on a smaller instance.886        const starts = boxes.flatMap(({ calls }) =>887          calls.flatMap((call) => (call.kind === "start" ? [call] : []))888        );889890        expect(new Set(starts.map(({ from }) => from))).toStrictEqual(891          new Set(["registry.cloudflare.com/sandbox/check:315", "snapshot-1"])892        );893        expect(new Set(starts.map(({ instance }) => instance))).toStrictEqual(894          new Set(["standard-3"])895        );896      })897  );898899  it.effect(900    "is VerifierBlocked, starting no container, while the Worker does not export the gateways",901    () =>902      Effect.gen(function* () {903        const world = checkerWorld({ withGateways: false });904        const wire = yield* encodedWire();905906        const outcome = yield* Effect.flatMap(907          Effect.promise(() => runCheck(world.checkers, wire)),908          Schema.decodeEffect(CheckExit)909        );910911        expect(Exit.findErrorOption(outcome)).toStrictEqual(912          Option.some(new VerifierBlocked({}))913        );914        expect(world.boxes.flatMap(({ calls }) => calls)).toStrictEqual([]);915      })916  );917});