Files
PaperClipAI/packages/paperclip-runner/scripts/run-check-static.test.mjs
T
Dotta 007d1c2ef1 perf(runner): parallelize static checks and memoize contract fingerprinting (#22912)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - On 8-core PR runners (`45592683902`, `45578886514`), `Verify
Paperclip Runner (static checks)` was the #3 PR critical-path straggler
at `192s–222s` (`142s–178s` inside `check:static`) because
`check:static` ran every build, contract check, prep test, and
API-authority Vitest suite serially on a single chain—rebuilding
`@paperclipai/paperclip-eval-kernel` 4 times, repeating
`acpx-profiles`/`protocol-types`/`tsc` twice, re-parsing Rust files
uncached in `contract-fingerprints.mjs` (`26s`), running a duplicate
contract test behind a serial `&&` barrier (`52s`), and running
`check-api-authority.mjs` (`75s`) without `--project
@paperclipai/server` or shared-PG `fsync=off`.
> - This pull request eliminates every redundant rebuild/check inside
`packages/paperclip-runner`, memoizes `contract-fingerprints.mjs` by
content hash (`sha1`, bit-for-bit identical digest, `10x` faster),
consolidates `test:typescript:prep` into one parallel `node:test`
runner, wires `check-api-authority.mjs` to `--project
@paperclipai/server` + disposable shared PostgreSQL while preserving
standalone self-contained execution for `release-verify.yml`, and
orchestrates `check:static` via a race-free 5-phase DAG
(`run-check-static.mjs`) that overlaps disjoint builds and tests across
available CPU cores.
> - All changes stay strictly within `packages/paperclip-runner/` and
preserve 100% of original static, protocol, build, prep-test, and
API-authority checks.

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
Execution speed of `pnpm --filter @paperclipai/paperclip-runner run
check:static` (`Verify Paperclip Runner (static checks)` CI job) on
multi-core runners.

**Subsystem affected**
packages/paperclip-runner/ — static checks, contract fingerprinting, and
prep/authority test orchestration

**Current behavior**
`check:static` chains `check:eval-kernel &&
check:protocol-without-vitest && check:api-authority` serially,
rebuilding `paperclip-eval-kernel` 4x, running `tsc` and protocol checks
2x, re-stripping/re-parsing Rust sources uncached in
`contract-fingerprints.mjs`, running
`acpx-message-boundaries-package-contract.test.mjs` twice across a
serial `&&` barrier, and running `check-api-authority.mjs` without
`--project @paperclipai/server` or disposable shared PG.

**Proposed behavior**
Memoize Rust comment-stripping/parsing in `contract-fingerprints.mjs`
with bit-for-bit identical digest parity, merge `test:typescript:prep`
into one deduplicated parallel runner (`run-prep-tests.mjs`), add
`--project @paperclipai/server` + disposable shared PostgreSQL +
`--skip-build` to `check-api-authority.mjs`, and execute `check:static`
via a race-free 5-phase parallel DAG (`run-check-static.mjs`).

## What Changed

- **Memoized contract fingerprinting
(`packages/paperclip-runner/scripts/contracts/contract-fingerprints.mjs`,
`contract-fingerprints.test.mjs`):**
- Added content-addressed (`sha1`) caches for `stripRustComments`,
`withoutTestModules`, `rustSerdeItems`, per-file string constants, and
`#[cfg(test)] mod` declarations, plus compact `probeCache` keys (`16.23s
-> 1.63s` locally = `10.0x` speedup, bit-for-bit identical digest
`sha256:bacaefb049aa9a0841fe782fefb11ede1f99222d15151873e92194e2aab9c608`).
- **Deduplicated parallel prep test runner
(`packages/paperclip-runner/scripts/run-prep-tests.mjs`):**
- Removed duplicate
`test/acpx-message-boundaries-package-contract.test.mjs` and merged the
8 Copilot `node:test` files plus `run-check-static.test.mjs` into one
parallel `node-test.mjs` invocation (`44` unique suites, no serial `&&`
barrier).
- **Optimized API-authority verification
(`packages/paperclip-runner/scripts/check-api-authority.mjs`):**
- Scoped Vitest to `--project @paperclipai/server`, wrapped with
`scripts/ci/vitest-shared-postgres.mjs` when no external test PG URL is
supplied, and added `--skip-build` / `--dry-run` while keeping
standalone `pnpm run check:api-authority` (used by `release-verify.yml`)
100% self-contained.
- **Race-free 5-phase parallel `check:static` orchestrator
(`packages/paperclip-runner/scripts/run-check-static.mjs`,
`run-check-static.test.mjs`,
`packages/paperclip-runner/package.json`):**
  - Phase 1: `check:eval-kernel` (builds & tests `eval-kernel` once).
- Phase 2 (parallel, read-only): `acpx-profiles`, `antigravity-models`,
`protocol-manifest`, 6 `node --check` checks, 4 `protocol-types` checks
(each once).
- Phase 3 (3 disjoint parallel chains): (A) TS builds + entrypoints +
copilot assets + replay goldens, (B) serialized Cargo debug then release
builds (zero `target/.cargo-lock` contention), (C) `plugin-sdk
ensure-build-deps`.
  - Phase 4: `stage-runner-binary.mjs` after A and B complete.
- Phase 5 (parallel): `run-prep-tests.mjs --skip-build` alongside
`check-api-authority.mjs --skip-build` with buffered per-step output and
signal forwarding.

## Verification

- Verified exact digest parity:
`sha256:bacaefb049aa9a0841fe782fefb11ede1f99222d15151873e92194e2aab9c608`
(unchanged)
- `node --test
packages/paperclip-runner/scripts/contracts/contract-fingerprints.test.mjs
packages/paperclip-runner/scripts/run-check-static.test.mjs
packages/paperclip-runner/scripts/build-inputs.test.mjs
packages/paperclip-runner/scripts/stage-runner-binary.test.mjs` —
**35/35 PASS** (`2.46s`)
- `node packages/paperclip-runner/scripts/run-check-static.mjs
--dry-run` and `node
packages/paperclip-runner/scripts/check-api-authority.mjs --dry-run` —
**PASS**
- `node scripts/check-test-budget.mjs --base origin/master`, `node
scripts/check-maps.mjs`, `node --test scripts/check-test-budget.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/runner-release-crate-cache.test.mjs
.github/scripts/tests/ci-plan.test.mjs` — **PASS**
- Live Linux execution of `Verify Paperclip Runner (static checks)`
(including embedded PG `check-api-authority.mjs` and Copilot asset
installation) will be verified end-to-end on PR CI.

## Risks

- Low risk: all changes are scoped strictly to
`packages/paperclip-runner/`, Cargo builds remain serialized in one
chain to avoid target lock contention, `stage-runner-binary.mjs` waits
for both TS and Rust builds before touching `dist/`, and standalone
`pnpm run check:api-authority` preserves full self-contained builds for
`release-verify.yml`.

## 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
- [x] All Paperclip CI gates are green
- [x] 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 05:22:08 -06:00

137 lines
6.1 KiB
JavaScript

import assert from "node:assert/strict";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import { API_AUTHORITY_VITEST_ARGS, planApiAuthority } from "./check-api-authority.mjs";
import { buildStaticCheckPlan, runCommand, stopActiveChildren } from "./run-check-static.mjs";
import { planPrepCommands, PREP_TEST_FILES } from "./run-prep-tests.mjs";
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
test("PREP_TEST_FILES contains unique existing test files including Copilot suites", () => {
assert.equal(new Set(PREP_TEST_FILES).size, PREP_TEST_FILES.length, "PREP_TEST_FILES must not duplicate entries");
for (const file of PREP_TEST_FILES) {
assert.ok(existsSync(resolve(packageRoot, file)), `missing prep test file: ${file}`);
}
assert.ok(PREP_TEST_FILES.includes("test/protocol-contract.test.mjs"));
assert.ok(PREP_TEST_FILES.includes("scripts/qualify-copilot-acp.test.mjs"));
assert.ok(PREP_TEST_FILES.includes("scripts/contracts/contract-fingerprints.test.mjs"));
assert.ok(PREP_TEST_FILES.includes("scripts/run-check-static.test.mjs"));
});
test("planPrepCommands runs one parallel node-test invocation and honors --skip-build", () => {
const full = planPrepCommands({ skipBuild: false });
assert.equal(full.length, 3);
assert.deepEqual(full[0].args, ["run", "ensure:eval-build-deps"]);
assert.deepEqual(full[1].args, ["run", "build:rust"]);
assert.equal(full[2].args[0], "../../scripts/ci-profile/node-test.mjs");
assert.equal(full[2].args.length, 1 + PREP_TEST_FILES.length);
const skipped = planPrepCommands({ skipBuild: true });
assert.equal(skipped.length, 1);
assert.equal(skipped[0].args[0], "../../scripts/ci-profile/node-test.mjs");
});
test("planApiAuthority targets the server Vitest project and enforces integration flag", () => {
const full = planApiAuthority({ skipBuild: false });
assert.equal(full.buildCommands.length, 2);
assert.deepEqual(full.vitestCommand.args, API_AUTHORITY_VITEST_ARGS);
assert.ok(full.vitestCommand.args.includes("--project"));
assert.ok(full.vitestCommand.args.includes("@paperclipai/server"));
assert.ok(full.vitestCommand.args.includes("server/src/services/native-runtime/runner-api.integration.test.ts"));
assert.equal(full.vitestCommand.env.PAPERCLIP_REQUIRE_RUNNER_API_INTEGRATION, "1");
const skipped = planApiAuthority({ skipBuild: true });
assert.equal(skipped.buildCommands.length, 0);
});
test("buildStaticCheckPlan preserves every static check with race-free parallel phases", () => {
const phases = buildStaticCheckPlan();
assert.deepEqual(
phases.map((phase) => phase.name),
["eval-kernel", "read-only-checks", "disjoint-builds", "stage-runner-binary", "heavy-test-suites"],
);
const allSteps = phases.flatMap((phase) =>
phase.steps ?? phase.chains.flatMap((chain) => chain.steps),
);
const evalKernelSteps = allSteps.filter((step) => step.args.includes("@paperclipai/paperclip-eval-kernel"));
assert.equal(evalKernelSteps.length, 1);
const buildPhase = phases.find((phase) => phase.name === "disjoint-builds");
assert.equal(buildPhase.mode, "parallel-chains");
const rustChain = buildPhase.chains.find((chain) => chain.name === "rust-binaries");
assert.equal(rustChain.steps.length, 2);
assert.equal(rustChain.steps[0].label, "cargo:debug-bins");
assert.equal(rustChain.steps[1].label, "cargo:release-runnerd");
const tsChain = buildPhase.chains.find((chain) => chain.name === "typescript-and-replay-goldens");
const tsLabels = tsChain.steps.map((step) => step.label);
assert.ok(tsLabels.includes("tsc:tsconfig"));
assert.ok(tsLabels.includes("tsc:surfaces"));
assert.ok(tsLabels.includes("build:verified-entrypoints"));
assert.ok(tsLabels.includes("install:copilot-assets"));
assert.ok(tsLabels.includes("check:replay-goldens"));
const testPhase = phases.find((phase) => phase.name === "heavy-test-suites");
assert.equal(testPhase.mode, "parallel");
assert.deepEqual(
testPhase.steps.map((step) => step.args),
[
["scripts/run-prep-tests.mjs", "--skip-build"],
["scripts/check-api-authority.mjs", "--skip-build"],
],
);
});
test("stopActiveChildren terminates nested child process trees and settles buffered runCommand within graceMs", async (t) => {
if (process.platform === "win32") return;
const dir = mkdtempSync(join(tmpdir(), "run-check-static-tree-"));
const pidFile = join(dir, "grandchild.pid");
t.after(() => rmSync(dir, { recursive: true, force: true }));
const script = `
const { spawnSync } = require("node:child_process");
const { writeFileSync } = require("node:fs");
const inner = 'require("node:fs").writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); process.on("SIGTERM", () => {}); setInterval(() => {}, 1000);';
spawnSync(process.execPath, ["-e", inner], { stdio: "inherit" });
`;
const commandPromise = runCommand(
{ label: "nested-tree", command: process.execPath, args: ["-e", script], cwd: packageRoot },
{ bufferOutput: true },
);
const deadline = Date.now() + 5_000;
while (!existsSync(pidFile) && Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 25));
}
assert.ok(existsSync(pidFile), "grandchild process should start and write its pid");
const grandchildPid = Number(readFileSync(pidFile, "utf8").trim());
assert.ok(Number.isInteger(grandchildPid) && grandchildPid > 0);
const stopStart = Date.now();
await stopActiveChildren("SIGTERM", { graceMs: 250, forceGraceMs: 500 });
const result = await commandPromise;
const elapsedMs = Date.now() - stopStart;
assert.notEqual(result.code, 0);
assert.ok(elapsedMs < 3_000, `expected bounded shutdown, took ${elapsedMs}ms`);
let alive = true;
for (let i = 0; i < 20; i += 1) {
try {
process.kill(grandchildPid, 0);
await new Promise((r) => setTimeout(r, 25));
} catch (error) {
if (error?.code === "ESRCH") {
alive = false;
break;
}
}
}
assert.equal(alive, false, `grandchild process ${grandchildPid} should be terminated`);
});