Files
PaperClipAI/server/src/__tests__/server-package-build-script.test.ts
Dotta 1c36d24d0c perf(ci): parallelize Runner Rust checks, Runner build, and typecheck lane (#22957)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Live 8-core PR runs (`45667106472`, `45665466678`, `45668834558`)
showed two critical-path stragglers on Rust- and TypeScript-heavy PRs:
> 1. `Verify Paperclip Runner (rust)` (`206s` step): ran a redundant
`cargo check --workspace` (`8.1s`) before `cargo test --release`,
executed all 44 compiled Rust test binaries **sequentially** (`119.2s`
vs `~50s` parallel!), and then re-invoked `cargo test --release` twice
more for `check:conformance-parity` and `check:replay-parity` (`~8s`).
> 2. `Typecheck + Release Registry` (`100s–147s` step): ran `CLI
guidance safety` (`2.9s`) and `typecheck @paperclipai/paperclip-runner`
(`5.6s`) serially before `prepare:runner-vendor`, ran
`packages/paperclip-runner` `build` (`17.1s` hit / `51.0s` miss)
serially across 12 steps, and scheduled lighter `7–10s` test projects
ahead of the 4 `17–25s` server test layers.
> - This pull request parallelizes `check:runner`
(`run-check-runner.mjs`), `packages/paperclip-runner` `build`
(`run-build.mjs`), and `scripts/ci-typecheck-lane.mjs` cleanly across 8
cores with full process-group signal cleanup (`stopActiveChildren`),
exact `CARGO_BIN_EXE_*` / `CARGO_MANIFEST_DIR` fidelity, fail-closed
parity assertions, exact `record-build-inputs --begin/--finish`
bracketing, and 100% check parity.

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
Execution wall-clock of `Verify Paperclip Runner (rust)`, `Typecheck +
Release Registry`, and `Build` on 8-core runners.

**Subsystem affected**
packages/paperclip-runner/ and scripts/ — Rust test orchestration,
Runner package build, and monorepo typecheck DAG

**Current behavior**
`check:runner` runs `cargo check`, 44 Rust test binaries sequentially,
and 2 redundant parity re-runs; `packages/paperclip-runner` `build`
executes 12 build/check steps serially; `ci-typecheck-lane.mjs` blocks
`prepare:runner-vendor` behind serial `prepare` steps and under-utilizes
8-core / 32 GiB runners.

**Proposed behavior**
Execute `check:runner` with overlapped `acpx-profiles` / `cargo fmt
--check` / `cargo test --release --no-run` followed by LPT-ordered
concurrent execution of all 44 test binaries + `--doc` + fail-closed
parity verification; parallelize `packages/paperclip-runner` `build`
into race-free pre-dist / build / staging / post-dist phases;
parallelize `CLI guidance safety` and `typecheck
@paperclipai/paperclip-runner` in `ci-typecheck-lane.mjs`, LPT-order
post-declaration tasks, and tune 8-core / >=24 GiB concurrency
(`laneConcurrency: 8`, `serverDeclCheckers: 6`).

## What Changed

- **`packages/paperclip-runner/scripts/run-check-runner.mjs` &
`run-check-runner.test.mjs`:**
- Overlaps `check:acpx-profiles` and `cargo fmt --all -- --check` with
`cargo test --release --locked --workspace --no-run
--message-format=json-render-diagnostics`.
- Parses all 44 compiled test binaries with exact `CARGO_BIN_EXE_*` and
per-crate `CARGO_MANIFEST_DIR`, executes them concurrently in LPT order
(`codex_provider` first, `acpx_sidecar_stopped_time` isolated in its own
detached process group with `--test-threads=1`, plus `cargo test
--release --workspace --doc`).
- Verifies both `runs_the_mock_core_path_with_stable_output` and
`replay_fixture_parity` passed in the workspace run (failing closed if
missing or ignored), eliminating 2 redundant `cargo test`
re-invocations.
- **`packages/paperclip-runner/scripts/run-build.mjs` &
`run-build.test.mjs`:**
- Preserves exact `record-build-inputs.mjs --begin` / `--finish`
bracketing from the same parent PID, overlaps `eval-kernel + tsc`,
`cargo build --release` (honoring
`PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR`), and all 9 pure source-only
pre-dist checks, stages disjoint `dist/` outputs in parallel, and runs
all 5 `dist/`-importing checks (`check:runner-workflow-traceability`,
`check:protocol-coverage`, `check:semantic-contracts`,
`check:replay-goldens`, `check:semantic-action-catalog`) in parallel
post-dist.
- **`scripts/ci-typecheck-lane.mjs`,
`scripts/__tests__/ci-typecheck-lane.test.mjs`, &
`.github/scripts/tests/ci-plan.test.mjs`:**
- Moved `CLI guidance safety` and `typecheck
@paperclipai/paperclip-runner` (`needs: [PREPARE_RUNNER_VENDOR]` when
`runServer`) out of serial `prepare` into `tasks`.
- Ordered post-declaration tasks LPT (`tests/runner-e2e` -> 4 `server
layer test-*` -> smaller projects) and tuned 8+ core / >=24 GiB runners
to `laneConcurrency: 8`, `serverDeclCheckers: 6`.
- **`packages/paperclip-runner/scripts/run-check-static.mjs`,
`run-prep-tests.mjs`, & `package.json`:**
- Shared `stopActiveChildren` / process-group runner helpers across
`run-check-static.mjs`, `run-check-runner.mjs`, and `run-build.mjs`;
wired `run-build.test.mjs` and `run-check-runner.test.mjs` into
`PREP_TEST_FILES`.

## Verification

- `node --test .github/scripts/tests/*.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/check-test-budget.test.mjs
scripts/__tests__/runner-release-crate-cache.test.mjs` — **855/855
PASS**
- `node --test scripts/run-check-runner.test.mjs
scripts/run-build.test.mjs scripts/run-check-static.test.mjs
scripts/build-inputs.test.mjs scripts/stage-runner-binary.test.mjs` (in
`packages/paperclip-runner`) — **32/32 PASS**
- `node scripts/check-test-budget.mjs --base origin/master` and `node
scripts/check-maps.mjs` — **PASS**
- Live Linux Cargo/Runner and monorepo Typecheck/Build execution
verified end-to-end by PR CI.

## Risks

- Low risk: all 9 pre-dist checks were verified pure source read-only
while all 5 `dist/`-importing checks run strictly after `tsc` and asset
staging; Rust parity checks fail closed if either test is absent or
ignored; process-group cancellation ensures zero orphaned test
processes.

## Model Used

- Gemini 4 Neon (High) via Antigravity agent swarm (`server-prune`,
`verifier`, `ci-pipeline`).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-11-25 13:40:47 -06:00

241 lines
11 KiB
TypeScript

import { execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { RUNNER_VENDOR_BUILD_COMMAND } from "../../scripts/prepare-runner-vendor.mjs";
import { buildRunnerBuildPlan } from "../../../packages/paperclip-runner/scripts/run-build.mjs";
type RunnerBuildStep = {
label: string;
command: string;
args: string[];
};
type RunnerBuildPhase = {
name: string;
mode: string;
steps?: RunnerBuildStep[];
chains?: Array<{ name: string; steps: RunnerBuildStep[] }>;
};
function phaseSteps(phase: RunnerBuildPhase): RunnerBuildStep[] {
if (phase.steps) return phase.steps;
return (phase.chains ?? []).flatMap((chain) => chain.steps);
}
const packageJsonPath = fileURLToPath(
new URL("../../package.json", import.meta.url),
);
const runnerShimPath = fileURLToPath(
new URL("../vendor/paperclip-runner/index.ts", import.meta.url),
);
const evidenceClassifierPath = fileURLToPath(
new URL("../services/native-runtime/evidence-classifier.ts", import.meta.url),
);
const workspaceDiffReprojectionPath = fileURLToPath(
new URL("../services/provider-trace-workspace-diff-reprojection.ts", import.meta.url),
);
describe("server package build script", () => {
it("builds the compiled package entry during prepack", () => {
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8")) as {
scripts?: Record<string, string>;
};
expect(packageJson.scripts?.prepack).toBe(
"pnpm run prepare:ui-dist && pnpm run build",
);
});
it("copies static runtime asset directories into dist", () => {
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8")) as {
scripts?: Record<string, string>;
};
const buildScript = packageJson.scripts?.build ?? "";
expect(buildScript).toContain(
"mkdir -p dist/onboarding-assets dist/built-ins",
);
expect(buildScript).toContain(
"cp -R src/onboarding-assets/. dist/onboarding-assets/",
);
expect(buildScript).toContain("cp -R src/built-ins/. dist/built-ins/");
});
it("vendors the private runner runtime without a production workspace dependency", () => {
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8")) as {
scripts?: Record<string, string>;
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
};
expect(
packageJson.dependencies?.["@paperclipai/paperclip-runner"],
).toBeUndefined();
expect(packageJson.devDependencies?.["@paperclipai/paperclip-runner"]).toBe(
"workspace:*",
);
// prepare-runner-vendor.mjs reuses a Runner build whose recorded inputs
// are unchanged (the `pnpm -r build` case) and otherwise runs the Runner's
// full build, which is what a standalone server build (the Dockerfile's
// path) relies on. Pin both the indirection and the command behind it.
expect(packageJson.scripts?.["prepare:runner-vendor"]).toBe(
"node scripts/prepare-runner-vendor.mjs",
);
expect(RUNNER_VENDOR_BUILD_COMMAND).toBe(
"pnpm --filter @paperclipai/paperclip-runner build",
);
expect(packageJson.scripts?.build.startsWith("pnpm run prepare:runner-vendor && ")).toBe(true);
expect(packageJson.scripts?.build).toContain(
"cp -Rf ../packages/paperclip-runner/dist/. dist/vendor/paperclip-runner/",
);
});
it("brackets the Runner's build with its input recording", () => {
// The stamp prepare-runner-vendor.mjs trusts must only exist for a build
// that completed every step and check, so it has to be written last; and
// it must vouch for the inputs the build read, not for whatever the
// sources are when it ends, so the digest has to be captured before the
// first step reads anything (--begin) and compared again at the end
// (--finish). Nothing else in the chain may touch the stamp.
const runner = JSON.parse(readFileSync(new URL(
"../../../packages/paperclip-runner/package.json", import.meta.url,
), "utf8")) as { scripts: Record<string, string> };
expect(runner.scripts.build).toBe("node scripts/run-build.mjs");
const phases = buildRunnerBuildPlan({ env: {} }) as RunnerBuildPhase[];
expect(phases.length).toBeGreaterThan(2);
expect(phases.at(0)?.mode).toBe("serial");
expect(phaseSteps(phases.at(0)!).map((step) => step.args)).toEqual([
["scripts/record-build-inputs.mjs", "--begin"],
]);
expect(phases.at(-1)?.mode).toBe("serial");
expect(phaseSteps(phases.at(-1)!).map((step) => step.args)).toEqual([
["scripts/record-build-inputs.mjs", "--finish"],
]);
const allSteps = phases.flatMap(phaseSteps);
expect(
allSteps.filter((step) => step.args.some((arg) => arg.includes("record-build-inputs"))),
).toHaveLength(2);
});
it("replaces an existing read-only image manifest with the build's copy step", () => {
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
const step = packageJson.scripts.build.split(" && ").find((command: string) =>
command.includes("../packages/paperclip-runner/dist/."));
expect(step).toBeDefined();
const [command, ...args] = step.split(" ");
const root = mkdtempSync(path.join(tmpdir(), "runner-vendor-copy-"));
try {
const relative = "remote-provider-packs/linux-x64/provider-pack.json";
const source = path.join(root, "packages/paperclip-runner/dist", relative);
const destination = path.join(root, "server/dist/vendor/paperclip-runner", relative);
mkdirSync(path.dirname(source), { recursive: true });
mkdirSync(path.dirname(destination), { recursive: true });
writeFileSync(source, "qualified image identity", { mode: 0o444 });
writeFileSync(destination, "previous image identity", { mode: 0o444 });
execFileSync(command, args, { cwd: path.join(root, "server") });
expect(readFileSync(destination, "utf8")).toBe("qualified image identity");
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("verifies vendored runner dependencies are mirrored before building", () => {
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8")) as {
scripts?: Record<string, string>;
};
// See scripts/verify-runner-vendor-dependencies.mjs: packages/paperclip-runner
// is vendored with a raw copy of its compiled dist/, so every runtime
// dependency it imports must also be a direct dependency of server. This
// check derives that requirement from an esbuild scan of the vendored
// entry points instead of relying on a human to have kept a hand-copied
// list in sync (the smol-toml incident in #13110/#13116).
expect(packageJson.scripts?.build).toContain(
"node scripts/verify-runner-vendor-dependencies.mjs",
);
});
it("compiles the vendored Runner's TypeScript surface once per build", () => {
// prepare:runner-vendor runs the Runner's full build whenever its recorded
// inputs are stale or missing (every standalone server build). Each extra
// build:typescript inside that chain (two tsc projects plus the eval-kernel
// rebuild) costs about 7s on the CI Build job's critical path.
// Checks that read dist/ must call their script directly, the way
// generate-replay-goldens.mjs already does, not through a `check:*`
// wrapper that rebuilds first for standalone use.
const runner = JSON.parse(readFileSync(new URL(
"../../../packages/paperclip-runner/package.json", import.meta.url,
), "utf8")) as { scripts: Record<string, string> };
expect(runner.scripts.build).toBe("node scripts/run-build.mjs");
const phases = buildRunnerBuildPlan({ env: {} }) as RunnerBuildPhase[];
const indexedSteps = phases.flatMap((phase, phaseIndex) =>
phaseSteps(phase).map((step) => ({ phaseIndex, step })),
);
const tscPrimary = indexedSteps.filter(({ step }) =>
step.args.includes("tsconfig.json") && step.args.some((arg) => arg.endsWith("/tsc")),
);
const tscSurfaces = indexedSteps.filter(({ step }) =>
step.args.includes("tsconfig.surfaces.json") && step.args.some((arg) => arg.endsWith("/tsc")),
);
const evalKernelBuilds = indexedSteps.filter(({ step }) =>
step.args.includes("@paperclipai/paperclip-eval-kernel") && step.args.includes("build"),
);
const nestedBuildTs = indexedSteps.filter(({ step }) =>
step.args.some((arg) => arg === "build:typescript" || (runner.scripts[arg] ?? "").includes("build:typescript")),
);
expect(tscPrimary).toHaveLength(1);
expect(tscSurfaces).toHaveLength(1);
expect(evalKernelBuilds).toHaveLength(1);
expect(nestedBuildTs).toHaveLength(0);
const tsPhaseIndex = Math.max(tscPrimary[0].phaseIndex, tscSurfaces[0].phaseIndex);
const semanticContracts = indexedSteps.find(({ step }) =>
step.args[0] === "scripts/generate-semantic-contracts.mjs" && step.args[1] === "--check",
);
const traceability = indexedSteps.find(({ step }) =>
step.args[0] === "scripts/check-runner-workflow-traceability.mjs",
);
expect(semanticContracts).toBeDefined();
expect(traceability).toBeDefined();
expect(semanticContracts!.phaseIndex).toBeGreaterThan(tsPhaseIndex);
expect(traceability!.phaseIndex).toBeGreaterThan(tsPhaseIndex);
});
it("ships the pinned OpenCode dependency resolved by the vendored Runner", () => {
const server = JSON.parse(readFileSync(packageJsonPath, "utf8"));
const runner = JSON.parse(readFileSync(new URL(
"../../../packages/paperclip-runner/package.json", import.meta.url,
), "utf8"));
// createRequire resolution is dynamic and is not covered by the import scan.
expect(server.dependencies["opencode-ai"]).toBe("1.18.34");
expect(server.dependencies["opencode-ai"]).toBe(runner.dependencies["opencode-ai"]);
});
it("loads runner source when the source server starts before workspace builds", () => {
const shim = readFileSync(runnerShimPath, "utf8");
expect(shim).toContain(
'"../../../../packages/paperclip-runner/src/index.ts"',
);
expect(shim).not.toContain(
'export * from "@paperclipai/paperclip-runner"',
);
});
it("routes source-mode runtime imports through the runner shim", () => {
for (const consumerPath of [
evidenceClassifierPath,
workspaceDiffReprojectionPath,
]) {
const consumer = readFileSync(consumerPath, "utf8");
expect(consumer).toContain('vendor/paperclip-runner/index.js"');
expect(consumer).not.toContain('from "@paperclipai/paperclip-runner"');
}
});
});