run.ts
This file
Path
apps/sandbox/src/checker/run.ts
688 lines · 19.3 KiB · TypeScript
Last changed by
Merge observability into mainoscabrielbefore adoption1985111
History of this fileTake it
1// A sealed suite is written only after the snapshot and with egress off. From2// its first write on, nothing a command prints leaves the Checker, the public3// lanes' output included (a `bun test` with no path finds the sealed files).4import { CheckAt, evidenceFrom } from "@repo/checks/check-runner";5import type {6 CheckRun,7 EnvPlaceholder,8 HeldBackCheck,9 HeldBackPart,10 LaneEvidence,11 LaneOutput,12} from "@repo/checks/check-runner";13import type { CheckWire } from "@repo/checks/check-runner/wire";14import { classifyRun } from "@repo/checks/classify";15import type { RunExit } from "@repo/checks/classify";16import { areaBits } from "@repo/checks/held-back-filter";17import type { HeldBackExit } from "@repo/checks/held-back-filter";18import { Phase, phasePlan } from "@repo/checks/phases";19import type { PlannedLane } from "@repo/checks/phases";20import type { LaneResult } from "@repo/protocol/domain/answer";21import type { RunBlock } from "@repo/protocol/domain/run";22import { keyOf, RepoName } from "@repo/protocol/ids";23import { VerifierBlocked } from "@repo/protocol/refusal";24import { Duration, Effect, Option, Ref } from "effect";2526import { Box } from "../box.ts";27import type { ExecOptions, Executed } from "../box.ts";28import { envPlanOf } from "./env.ts";29import { CheckLogs } from "./logs.ts";30import type { PhaseLog } from "./logs.ts";31import {32 allows,33 CLONE_HOST,34 cloneUrlOf,35 Network,36 REGISTRIES,37} from "./network.ts";38import { Snapshots } from "./snapshots.ts";3940export const REPO = "/workspace/repo";4142/** Every HTTPS request leaves through an intercept, so TLS clients trust its CA alone. */43const CA = "/etc/cloudflare/certs/cloudflare-containers-ca.crt";4445const TRUST = {46 CARGO_HTTP_CAINFO: CA,47 CURL_CA_BUNDLE: CA,48 GIT_SSL_CAINFO: CA,49 NODE_EXTRA_CA_CERTS: CA,50 PIP_CERT: CA,51 REQUESTS_CA_BUNDLE: CA,52 SSL_CERT_FILE: CA,53};5455/** The project's own bins first, as `npm run` puts them. */56const PATH = [57 `${REPO}/node_modules/.bin`,58 "/usr/local/sbin",59 "/usr/local/bin",60 "/usr/sbin",61 "/usr/bin",62 "/sbin",63 "/bin",64].join(":");6566/** Fixed, so two runs of one tree see the same env. */67const ENV = {68 ...TRUST,69 CI: "1",70 // corepack fetches pnpm or Yarn during setup without asking first.71 COREPACK_ENABLE_DOWNLOAD_PROMPT: "0",72 FORCE_COLOR: "0",73 GIT_CONFIG_NOSYSTEM: "1",74 GIT_TERMINAL_PROMPT: "0",75 HOME: "/root",76 LC_ALL: "C",77 NO_COLOR: "1",78 PATH,79};8081/** Placeholders, never values; no item's key displaces the Checker's own env. */82const commandEnv = (placeholders: readonly EnvPlaceholder[]) => ({83 ...Object.fromEntries(84 placeholders.map(({ key, placeholder }) => [key, placeholder])85 ),86 ...ENV,87});8889const GIT_ENV = {90 ...ENV,91 GIT_AUTHOR_DATE: "2026-10-06T12:00:00Z",92 GIT_AUTHOR_EMAIL: "checker@example.com",93 GIT_AUTHOR_NAME: "Checker",94 GIT_COMMITTER_DATE: "2026-10-06T12:00:00Z",95 GIT_COMMITTER_EMAIL: "checker@example.com",96 GIT_COMMITTER_NAME: "Checker",97};9899const LOCKFILES = [100 "bun.lock",101 "bun.lockb",102 "package-lock.json",103 "npm-shrinkwrap.json",104 "pnpm-lock.yaml",105 "yarn.lock",106 "Cargo.lock",107 "go.sum",108 "poetry.lock",109 "uv.lock",110 "Pipfile.lock",111 "requirements.txt",112];113114const CLONE_LIMIT = Duration.minutes(5);115116const ROOM_LIMIT = Duration.minutes(1);117118const SETUP_LIMIT = Duration.minutes(15);119120const LANE_LIMIT = Duration.minutes(10);121122const timedOut: RunExit = { code: -1, stderr: "", stdout: "", timedOut: true };123124const HOSTS_IN_OUTPUT = [125 /\bhttps?:\/\/(?<host>[a-z0-9.-]+)/giu,126 /\bgetaddrinfo \w+ (?<host>[a-z0-9.-]+)/giu,127 /\bresolve host:? (?<host>[a-z0-9.-]+)/giu,128];129130const refusedIn = (text: string, allowed: readonly string[]) => [131 ...new Set(132 HOSTS_IN_OUTPUT.flatMap((pattern) =>133 [...text.matchAll(pattern)].flatMap(134 ({ groups }) => groups?.host?.toLowerCase() ?? []135 )136 ).filter((host) => !allows(allowed, host))137 ),138];139140const hex = (bytes: ArrayBuffer) =>141 [...new Uint8Array(bytes)]142 .map((byte) => byte.toString(16).padStart(2, "0"))143 .join("");144145const sha256 = (text: string) =>146 Effect.map(147 Effect.promise(() =>148 crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))149 ),150 hex151 );152153export const blocked = (154 reason: string,155 annotations: Record<string, string> = {}156): Effect.Effect<never, VerifierBlocked> =>157 Effect.logWarning(`check blocked: ${reason}`).pipe(158 Effect.annotateLogs(annotations),159 Effect.andThen(Effect.fail(new VerifierBlocked({})))160 );161162interface LaneRan {163 readonly result: LaneResult;164 readonly evidence: Option.Option<LaneEvidence>;165 readonly output: Option.Option<LaneOutput>;166}167168type Kept = Ref.Ref<readonly PhaseLog[]>;169170const keep = (kept: Kept, log: PhaseLog) =>171 Ref.update(kept, (logs) =>172 logs.some(({ name, phase }) => phase === log.phase && name === log.name)173 ? logs.map((each) =>174 each.phase === log.phase && each.name === log.name175 ? { ...each, text: `${each.text}${log.text}` }176 : each177 )178 : [...logs, log]179 );180181type Recorder = (text: string) => Effect.Effect<void>;182183const keeping =184 (kept: Kept, log: Omit<PhaseLog, "text">): Recorder =>185 (text) =>186 keep(kept, { ...log, text });187188const dropping: Recorder = () => Effect.void;189190/** None when it ran out of time. */191const exec = (192 record: Recorder,193 argv: readonly [string, ...string[]],194 options: ExecOptions,195 limit: Duration.Duration196) =>197 Effect.flatMap(Box, (box) =>198 box.exec(argv, { ...options, timeoutMs: Duration.toMillis(limit) })199 ).pipe(200 Effect.timeoutOption(limit),201 Effect.tap((done) =>202 record(203 Option.match(done, {204 onNone: () => `$ ${argv.join(" ")}\ntimed out\n`,205 onSome: ({ stderr, stdout }) =>206 `$ ${argv.join(" ")}\n${stdout}${stderr}`,207 })208 )209 )210 );211212const git = (kept: Kept, ...args: readonly string[]) =>213 exec(214 keeping(kept, { name: "clone", phase: "clone" }),215 ["git", ...args],216 { cwd: "/", env: GIT_ENV },217 CLONE_LIMIT218 ).pipe(219 Effect.catchTag("BoxFailed", ({ reason }) =>220 blocked("the checkout's container failed", { phase: "clone", reason })221 ),222 Effect.flatMap(223 Option.match({224 onNone: () => blocked("the checkout timed out", { phase: "clone" }),225 onSome: (done: Executed) =>226 done.exitCode === 0227 ? Effect.succeed(done.stdout)228 : blocked("a checkout command failed", {229 command:230 args.find((arg) => !arg.startsWith("-") && arg !== REPO) ??231 "git",232 exitCode: String(done.exitCode),233 phase: "clone",234 }),235 })236 )237 );238239/** `clean` keeps ignored files, which setup installed. */240const checkout = (kept: Kept, url: string, at: CheckAt) =>241 Effect.gen(function* () {242 const fetch = (refspec: string) =>243 git(244 kept,245 "-C",246 REPO,247 "fetch",248 "-q",249 "--depth=1",250 "--no-tags",251 url,252 refspec253 );254255 yield* git(kept, "init", "-q", REPO);256257 const head = yield* CheckAt.match(at, {258 Commit: ({ commit }) => Effect.as(fetch(commit), "FETCH_HEAD"),259 // A tree has no ref of its own: it is fetched with every ref's tip,260 // then committed locally so the work tree has a HEAD.261 Tree: ({ tree }) =>262 Effect.andThen(fetch("+refs/*:refs/checked/*"), () =>263 Effect.map(264 git(kept, "-C", REPO, "commit-tree", tree, "-m", "Checked tree"),265 (commit) => commit.trim()266 )267 ),268 });269270 yield* git(kept, "-C", REPO, "checkout", "-q", "--force", "--detach", head);271 yield* git(kept, "-C", REPO, "clean", "-q", "-ffd");272 });273274interface Job {275 readonly wire: CheckWire;276 readonly kept: Kept;277 readonly env: Readonly<Record<string, string>>;278 readonly url: string;279 readonly restored: Ref.Ref<boolean>;280 readonly sealed: Ref.Ref<boolean>;281 readonly exits: Ref.Ref<readonly HeldBackExit[]>;282}283284/** A snapshot is its project's own: two projects with one lockfile never share one. */285const snapshotKeyOf = ({ wire }: Job, key: string) =>286 `${wire.job.project}:${key}`;287288const setup = (289 job: Job,290 command: string,291 egress: readonly string[],292 key: string293) =>294 Effect.gen(function* () {295 const network = yield* Network;296 const snapshots = yield* Snapshots;297298 const hit = yield* snapshots299 .restore(snapshotKeyOf(job, key))300 .pipe(301 Effect.catchTag("BoxFailed", ({ reason }) =>302 blocked("the snapshot did not restore", { phase: "setup", reason })303 )304 );305306 if (hit) {307 yield* Ref.set(job.restored, true);308309 return yield* checkout(job.kept, job.url, job.wire.job.at);310 }311312 const allowed = [...new Set([...REGISTRIES, ...egress])];313314 yield* network.allow(allowed);315316 const done = yield* exec(317 keeping(job.kept, { name: "setup", phase: "setup" }),318 ["sh", "-c", command],319 { cwd: REPO, env: job.env },320 SETUP_LIMIT321 ).pipe(322 Effect.catchTag("BoxFailed", ({ reason }) =>323 blocked("setup's container failed", { phase: "setup", reason })324 )325 );326327 if (Option.isNone(done)) {328 return yield* blocked("setup timed out", { phase: "setup" });329 }330331 if (done.value.exitCode === 0) {332 return yield* Effect.void;333 }334335 const refused = refusedIn(336 `${done.value.stdout}\n${done.value.stderr}`,337 allowed338 );339340 if (refused.length > 0) {341 yield* keep(job.kept, {342 name: "setup",343 phase: "setup",344 text: `refused: ${refused.join(", ")} (not on setup's allow-list)\n`,345 });346 }347348 return yield* blocked("setup failed", {349 blockedHosts: refused.join(" "),350 exitCode: String(done.value.exitCode),351 phase: "setup",352 });353 });354355/** Only the project's own commits save one: an answer's tree may change what setup does. */356const snapshot = (job: Job, key: string) =>357 Effect.gen(function* () {358 const snapshots = yield* Snapshots;359 const { at, project, repo } = job.wire.job;360361 if (yield* Ref.get(job.restored)) {362 return;363 }364365 // A project's canonical repo carries the project's name.366 if (!CheckAt.guards.Commit(at) || repo !== RepoName.make(keyOf(project))) {367 yield* Effect.logInfo("an answer's setup is not kept").pipe(368 Effect.annotateLogs({ phase: "snapshot" })369 );370371 return;372 }373374 yield* snapshots375 .save(snapshotKeyOf(job, key))376 .pipe(377 Effect.catchTag("BoxFailed", ({ reason }) =>378 Effect.logWarning("the setup snapshot was not saved").pipe(379 Effect.annotateLogs({ phase: "snapshot", reason })380 )381 )382 );383 });384385/** A lane beside the sealed files keeps no output or failure signature: it may quote them. */386const runLane = (job: Job, { command, lane }: PlannedLane) =>387 Effect.gen(function* () {388 const own = job.wire.job.lanes.find((each) => each.lane === lane);389 const beside = yield* Ref.get(job.sealed);390391 const limit =392 own?.timeoutMs === undefined393 ? LANE_LIMIT394 : Duration.millis(own.timeoutMs);395396 const printed = (exit: RunExit): Option.Option<LaneOutput> =>397 !beside &&398 own?.output === "stdout" &&399 exit.timedOut !== true &&400 exit.code !== -1401 ? Option.some({ lane, stdout: exit.stdout })402 : Option.none();403404 return yield* exec(405 beside ? dropping : keeping(job.kept, { name: lane, phase: "lane" }),406 ["sh", "-c", command],407 { cwd: REPO, env: job.env },408 limit409 ).pipe(410 Effect.map(411 Option.match({412 onNone: () => timedOut,413 onSome: ({ exitCode, stderr, stdout }): RunExit => ({414 code: exitCode,415 stderr,416 stdout,417 }),418 })419 ),420 Effect.catchTag("BoxFailed", ({ reason }) =>421 Effect.succeed<RunExit>({ code: -1, stderr: reason, stdout: "" })422 ),423 Effect.timed,424 Effect.map(([elapsed, exit]): LaneRan => {425 const result = classifyRun(lane, exit);426427 return {428 evidence:429 result === "passed"430 ? Option.none()431 : Option.some(beside ? { lane } : evidenceFrom(lane, exit)),432 output: printed(exit),433 result: {434 command,435 durationMs: Math.round(Duration.toMillis(elapsed)),436 lane,437 result,438 },439 };440 })441 );442 });443444const inTree = (path: string) =>445 !path.startsWith("/") &&446 path447 .split("/")448 .every((segment) => segment !== "" && segment !== "." && segment !== "..");449450/** Arguments: folders, shallowest first, then `--`, then files; all absolute, so none reads as `--`. */451const ROOM = [452 'while [ "$1" != -- ]; do',453 ' if [ -L "$1" ] || { [ -e "$1" ] && [ ! -d "$1" ]; }; then',454 ' rm -f -- "$1" || exit 1',455 " fi",456 ' [ -d "$1" ] || mkdir -- "$1" || exit 1',457 " shift",458 "done",459 "shift",460 'rm -rf -- "$@"',461].join("\n");462463const foldersAbove = (root: string, path: string) => {464 const folders = path.split("/").slice(0, -1);465466 return folders.map(467 (_, depth) => `${root}/${folders.slice(0, depth + 1).join("/")}`468 );469};470471/** A failed write would tell the answer, for free, that a sealed path is there. */472export const roomFor = (473 root: string,474 paths: readonly string[]475): readonly [string, ...string[]] => [476 "sh",477 "-c",478 ROOM,479 "room",480 ...new Set(paths.flatMap((path) => foldersAbove(root, path))),481 "--",482 ...paths.map((path) => `${root}/${path}`),483];484485/** The sealed files are not all in the work tree: nothing logged says which. */486const unwritten = () =>487 blocked("the sealed files were not written", { phase: "WriteHeldBack" });488489/** No reason the container gave is logged, since it may name a sealed path. */490const writeHeldBack = (job: Job, { files }: HeldBackPart) =>491 Effect.gen(function* () {492 if (!files.every(({ path }) => inTree(path))) {493 return yield* blocked("a sealed file's path leaves the checked tree", {494 phase: "WriteHeldBack",495 });496 }497498 const box = yield* Box;499500 yield* Ref.set(job.sealed, true);501502 const made = yield* exec(503 dropping,504 roomFor(505 REPO,506 files.map(({ path }) => path)507 ),508 { cwd: REPO, env: ENV },509 ROOM_LIMIT510 ).pipe(Effect.catchTag("BoxFailed", unwritten));511512 if (Option.isNone(made) || made.value.exitCode !== 0) {513 return yield* unwritten();514 }515516 return yield* Effect.forEach(517 files,518 ({ content, path }) =>519 box520 .writeFile(`${REPO}/${path}`, content)521 .pipe(Effect.catchTag("BoxFailed", unwritten)),522 { discard: true }523 );524 });525526/** A timeout reads as a plain failure: anything else is one more bit about the suite. */527const runSealed = (job: Job, { area, command }: HeldBackCheck) =>528 exec(529 dropping,530 ["sh", "-c", command],531 { cwd: REPO, env: job.env },532 LANE_LIMIT533 ).pipe(534 Effect.map(535 Option.match({536 onNone: (): HeldBackExit => ({ area, code: -1, timedOut: true }),537 onSome: ({ exitCode }): HeldBackExit => ({538 area,539 code: exitCode,540 timedOut: false,541 }),542 })543 ),544 Effect.catchTag("BoxFailed", () =>545 Effect.succeed<HeldBackExit>({ area, code: -1, timedOut: false })546 )547 );548549const openEnvRoute = (wire: CheckWire) =>550 Effect.gen(function* () {551 const network = yield* Network;552 const { route, skipped } = envPlanOf(wire.job);553554 yield* Effect.forEach(555 skipped,556 ({ host, reason }) =>557 Effect.logWarning("a proxy host is not intercepted").pipe(558 Effect.annotateLogs({ host, phase: "EgressOff", reason })559 ),560 { discard: true }561 );562563 if (Option.isSome(route)) {564 yield* network.routeEnv(route.value);565 }566 });567568const phases = (wire: CheckWire, run: RunBlock, kept: Kept) =>569 Effect.gen(function* () {570 const network = yield* Network;571 const { clone } = wire;572573 const heldBack = Option.fromNullishOr(wire.job.heldBack);574575 const job: Job = {576 env: commandEnv(wire.job.placeholders),577 exits: yield* Ref.make<readonly HeldBackExit[]>([]),578 kept,579 restored: yield* Ref.make(false),580 sealed: yield* Ref.make(false),581 url: cloneUrlOf(clone.url),582 wire,583 };584585 yield* network.routeClone({586 host: CLONE_HOST,587 remote: clone.url,588 token: clone.token,589 });590 yield* checkout(kept, job.url, wire.job.at);591592 const lockfileHash = yield* Effect.flatMap(593 git(kept, "-C", REPO, "ls-tree", "HEAD", "--", ...LOCKFILES),594 sha256595 );596597 const plan = phasePlan({598 heldBack: Option.map(heldBack, ({ areas }) => ({ areas })),599 lanes: wire.job.lanes.map(({ command, lane }) => ({ command, lane })),600 lockfileHash,601 placeholders: wire.job.placeholders.map(({ key }) => key),602 run,603 });604605 const key = plan.find(Phase.$is("Snapshot"))?.key ?? lockfileHash;606607 // Each phase its own span, named by its tag alone: a lane's command or a608 // sealed check's area never names one.609 const ran = yield* Effect.forEach(plan, (phase) =>610 Effect.logInfo("checker phase").pipe(611 Effect.annotateLogs({ phase: phase._tag }),612 Effect.andThen(613 Phase.$match(phase, {614 // Off for every host but the env gateway's, which open here.615 EgressOff: () =>616 Effect.as(617 Effect.andThen(network.allow([]), openEnvRoute(wire)),618 []619 ),620 Report: () => Effect.succeed([]),621 Run: ({ lanes }) =>622 Effect.tap(623 Effect.forEach(lanes, (lane) => runLane(job, lane)),624 () =>625 Option.match(heldBack, {626 onNone: () => Effect.void,627 onSome: ({ runs }) =>628 Effect.flatMap(629 Effect.forEach(runs, (each) => runSealed(job, each)),630 (exits) => Ref.set(job.exits, exits)631 ),632 })633 ),634 Setup: ({ command, egress }) =>635 Effect.as(setup(job, command, egress, key), []),636 Snapshot: (saved) => Effect.as(snapshot(job, saved.key), []),637 WriteHeldBack: () =>638 Option.match(heldBack, {639 onNone: () => Effect.succeed([]),640 onSome: (part) => Effect.as(writeHeldBack(job, part), []),641 }),642 })643 ),644 Effect.withSpan(`Checker.${phase._tag}`)645 )646 );647648 const exits = yield* Ref.get(job.exits);649650 return {651 heldBack: Option.match(heldBack, {652 onNone: () => [],653 onSome: ({ areas, suite }) => areaBits({ areas, exits, suite }),654 }),655 ran: ran.flat(),656 };657 });658659export const check = (660 wire: CheckWire661): Effect.Effect<662 CheckRun,663 VerifierBlocked,664 Box | CheckLogs | Network | Snapshots665> =>666 Effect.gen(function* () {667 const box = yield* Box;668 const logs = yield* CheckLogs;669 const kept = yield* Ref.make<readonly PhaseLog[]>([]);670671 const [elapsed, { heldBack, ran }] = yield* Effect.timed(672 phases(wire, wire.job.run, kept)673 ).pipe(674 Effect.onExit(() => Effect.flatMap(Ref.get(kept), logs.report)),675 Effect.ensuring(box.destroy())676 );677678 const outputs = ran.flatMap(({ output }) => Option.toArray(output));679680 const done = {681 durationMs: Math.round(Duration.toMillis(elapsed)),682 evidence: ran.flatMap(({ evidence }) => Option.toArray(evidence)),683 heldBack,684 lanes: ran.map(({ result }) => result),685 };686687 return outputs.length === 0 ? done : { ...done, outputs };688 });