Files
PaperClipAI/packages/paperclip-runner/scripts/contracts/contract-fingerprints.test.mjs
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

177 lines
11 KiB
JavaScript

import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import { checkoutSources, fingerprintContracts, packContractDigest } from "./contract-fingerprints.mjs";
const root = resolve(fileURLToPath(new URL("../../../..", import.meta.url)));
const diskSources = checkoutSources(root);
const readCache = new Map();
const listCache = new Map();
const sources = {
read: p => {
if (!readCache.has(p)) readCache.set(p, diskSources.read(p));
return readCache.get(p);
},
list: dir => {
if (!listCache.has(dir)) listCache.set(dir, diskSources.list(dir));
return listCache.get(dir);
},
};
const R = "packages/paperclip-runner";
const RUST = `${R}/runner/crates/runner-core/src`;
const baseline = packContractDigest(root, sources);
/** Digest of the checkout with one file's text rewritten in memory. */
function digestWith(path, edit) {
const original = sources.read(path);
assert.ok(original, `${path} exists`);
const edited = edit(original);
assert.ok(edited !== original, `edit applies to ${path}`);
return packContractDigest(root, { read: p => p === path ? edited : sources.read(p), list: sources.list });
}
test("the digest is a stable sha256 of the checkout", () => {
assert.match(baseline, /^sha256:[a-f0-9]{64}$/);
assert.equal(packContractDigest(root), baseline);
});
const SIDECAR_SCHEMA = `${R}/protocol/provider-schemas/acpx-sidecar.schema.json`;
test("incidental edits leave the digest unchanged", () => {
const unchanged = [
[SIDECAR_SCHEMA, s => s.replace(/"description": "/, "\"description\": \"Edited. ")],
[SIDECAR_SCHEMA, s => s.replace(/\n {6}"/g, "\n \"")],
[`${R}/protocol/schemas/auth-credentials.schema.json`, s => s.replace(/"description": "/, "\"description\": \"Edited. ")],
// TypeScript is generated from or enforced by the schemas; it is not read.
[`${R}/src/cli/acpx-runtime-sidecar.ts`, s => s.replaceAll("parseOpenParams", "parseSessionOpenParams")],
[`${RUST}/configured_environment.rs`, s => `// header\n${s.replace("const RESERVED", "/// doc\nconst RESERVED")}`],
[`${RUST}/acpx_provider_checkpoint.rs`, s => s.replace("pub struct AcpxSuspensionCheckpoint {",
"pub struct AcpxSuspensionCheckpoint {\n #[serde(skip)]\n pub cache: Option<String>,")],
[`${RUST}/acpx_provider_checkpoint.rs`, s => `${s}\n#[cfg(test)]\nmod extra {\n #[derive(Serialize)]\n struct T { a: u8 }\n}\n`],
// Rust type names never reach JSON; renaming a serde type keeps its shape.
[`${RUST}/acpx_provider_checkpoint.rs`, s => s.replaceAll("AcpxSuspensionCheckpoint", "AcpxSavedSuspension")],
// Renaming the Rust constant that carries an env key keeps the key itself.
[`${RUST}/process_supervisor.rs`, s => s.replaceAll("VERIFIED_RUNTIME_EXECUTABLE_ENV", "RUNTIME_EXECUTABLE_HANDOFF_ENV")],
// A file compiled only through `#[cfg(test)] #[path = ..] mod ..;`.
[`${RUST}/tests/provider_api_validation.rs`, s => s.replaceAll("PRIVATE_FIELD", "PRIVATE_FIXTURE_FIELD")],
];
for (const [path, edit] of unchanged) assert.equal(digestWith(path, edit), baseline, `${path} edit is incidental`);
});
test("contract edits change the digest", () => {
const changed = [
// A new session.open field, the change an older pack sidecar rejects.
[SIDECAR_SCHEMA, s => s.replace("\"grokEffort\": true,", "\"grokEffort\": true,\n \"newField\": true,")],
// A property named `description` is a declaration, not an annotation.
[`${R}/protocol/schemas/result.schema.json`, s => s.replace("\"description\": { \"type\": \"string\", \"minLength\": 1 }",
"\"description\": { \"type\": \"string\", \"minLength\": 2 }")],
// A nested runtime context field, which the pack's strict parser rejects.
[`${R}/protocol/provider-schemas/runtime-context.schema.json`, s => s.replace("\"aggregateDigest\": { \"$ref\": \"#/$defs/sha256Hex\" }",
"\"aggregateDigest\": { \"$ref\": \"#/$defs/sha256Hex\" },\n \"newContextField\": true")],
// The swarm route's credential facts: channel selection and the account comparison.
[SIDECAR_SCHEMA, s => s.replace("\"swarmChannel\": { \"enum\": [\"provider_default\", \"stable\"] }",
"\"swarmChannel\": { \"enum\": [\"provider_default\", \"stable\", \"daily\"] }")],
[SIDECAR_SCHEMA, s => s.replace("\"accountSha256\": { \"type\": \"string\", \"pattern\": \"^[a-f0-9]{64}$\" }",
"\"accountSha256\": { \"type\": \"string\", \"pattern\": \"^[a-f0-9]{40}$\" }")],
// The Antigravity swarm turn's request field: an older pack reads the request elsewhere.
[SIDECAR_SCHEMA, s => s.replace("\"swarmRequest\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 16000 }",
"\"swarmRequest\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 8000 }")],
[SIDECAR_SCHEMA, s => s.replace("\"readOnly\": { \"type\": \"boolean\" }", "\"readOnly\": { \"type\": \"boolean\" },\n \"newPolicyField\": { \"type\": \"boolean\" }")],
[`${RUST}/configured_environment.rs`, s => s.replace("const RESERVED: &[&str] = &[", "const RESERVED: &[&str] = &[\"NEW_KEY\",")],
[`${RUST}/acpx_provider_checkpoint.rs`, s => s.replace("pub struct AcpxSuspensionCheckpoint {",
"pub struct AcpxSuspensionCheckpoint {\n pub extra: Option<String>,")],
[`${RUST}/acpx_sidecar_transport.rs`, s => s.replace(/keys\.push\("/, "keys.push(\"PAPERCLIP_NEW_SIDECAR_KEY\");\n keys.push(\"")],
// Field names serialize (here through rename_all = "camelCase").
[`${RUST}/acpx_provider_checkpoint.rs`, s => s.replace("pub struct AcpxSuspensionCheckpoint {\n schema: String,\n run_id: String,",
"pub struct AcpxSuspensionCheckpoint {\n schema: String,\n turn_run_id: String,")],
// An env key passed through a constant: the verified executable handoff.
[`${RUST}/process_supervisor.rs`, s => s.replace("\"PAPERCLIP_VERIFIED_RUNTIME_EXECUTABLE\"", "\"PAPERCLIP_RUNTIME_EXECUTABLE_PATH\"")],
];
for (const [path, edit] of changed) assert.notEqual(digestWith(path, edit), baseline, `${path} edit changes a contract`);
});
test("variant names stay part of the shape even when they match a type name", () => {
const path = `${RUST}/acpx_provider_checkpoint.rs`;
const withEnum = original => `${original}\n#[derive(Serialize)]\nenum ProbeShape {\n AcpxSuspensionCheckpoint(AcpxSuspensionCheckpoint),\n}\n`;
const renamedVariant = original => `${original}\n#[derive(Serialize)]\nenum ProbeShape {\n Checkpoint(AcpxSuspensionCheckpoint),\n}\n`;
assert.notEqual(digestWith(path, withEnum), digestWith(path, renamedVariant));
});
test("a field that names a differently shaped type changes the digest", () => {
const path = `${RUST}/acpx_provider_checkpoint.rs`;
// AcpxProviderSessionIdentity, defined in another file, lets permissionMode be absent.
assert.notEqual(digestWith(path, s => s.replace(" identity: PersistedAcpxProviderSessionIdentity,\n}",
" identity: AcpxProviderSessionIdentity,\n}")), baseline);
// Renaming the referenced type keeps its shape and the digest.
assert.equal(digestWith(path, s => s.replaceAll("PersistedAcpxProviderSessionIdentity", "SavedProviderSessionIdentity")), baseline);
// A change inside the referenced type also reaches the field that names it.
const nested = original => `${original}\n#[derive(Serialize)]\nstruct ProbeInner {\n a: u8,\n}\n#[derive(Serialize)]\nstruct ProbeOuter {\n inner: ProbeInner,\n}\n`;
const fingerprints = edit => {
const edited = edit(sources.read(path));
return fingerprintContracts(p => p === path ? edited : sources.read(p), sources.list);
};
const before = fingerprints(nested), after = fingerprints(s => nested(s).replace("a: u8", "a: u16"));
const outer = contracts => contracts.rust.value[0].find(shape => shape.includes("inner:"));
assert.notEqual(outer(before), outer(after));
});
test("an env key handed to the sidecar in a key list is part of the contract", () => {
const path = `${RUST}/acpx_sidecar_transport.rs`;
assert.notEqual(digestWith(path, s => s.replace("\"PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT\",", "\"PAPERCLIP_ACPX_PACKAGE_ROOT\",")), baseline);
// Lists outside compiled code are not contracts.
assert.equal(digestWith(path, s => s.replace("\"LD_API_KEY\", \"DYLD_API_KEY\"", "\"LD_API_KEY\", \"DYLD_OTHER_KEY\"")), baseline);
});
test("moving Rust code to another file leaves the digest unchanged", () => {
const from = `${RUST}/acpx_provider_checkpoint.rs`, to = `${RUST}/acpx_saved_suspension.rs`;
const moved = packContractDigest(root, {
read: p => p === from ? null : p === to ? sources.read(from) : sources.read(p),
list: dir => sources.list(dir).map(p => p === from ? to : p),
});
assert.equal(moved, baseline);
});
test("a parser that reads another key changes the digest even when other code reads it", () => {
const path = `${RUST}/acpx_provider_session.rs`;
// provider_backend.rs already reads both `status` and `result`.
assert.notEqual(digestWith(path, s => s.replace("|| !value.get(\"status\").is_some_and(Value::is_object)",
"|| !value.get(\"result\").is_some_and(Value::is_object)")), baseline);
// Renaming the function keeps its keys and the digest.
assert.equal(digestWith(path, s => s.replaceAll("verify_open_response", "verify_session_open_response")), baseline);
});
test("the Runner's ACPX patch binds the pack for every ACPX harness; other patches do not", () => {
const version = JSON.parse(sources.read(`${R}/package.json`)).dependencies.acpx;
const runnerPatch = `patches/acpx@${version}.patch`;
assert.notEqual(digestWith(runnerPatch, s => `${s}\n`), baseline);
const others = sources.list("patches").filter(path => path.endsWith(".patch") && path !== runnerPatch);
for (const path of others) assert.equal(digestWith(path, s => `${s}\n`), baseline, path);
// A patch for another ACPX version (another package's pin) never binds the pack.
const otherAcpx = "patches/acpx@0.0.0-other.patch";
assert.equal(packContractDigest(root, {
read: p => p === otherAcpx ? "--- a\n+++ b\n" : sources.read(p),
list: dir => dir === "patches" ? [...sources.list(dir), otherAcpx] : sources.list(dir),
}), baseline);
// A build context without the Runner's patch fails instead of dropping the contract.
assert.throws(() => packContractDigest(root, { read: p => p === runnerPatch ? null : sources.read(p),
list: dir => sources.list(dir).filter(p => p !== runnerPatch) }), /Registered contract source is missing: acpx-patch/);
});
test("recursive serde types resolve", () => {
const path = `${RUST}/acpx_provider_checkpoint.rs`;
const recursive = name => original => `${original}\n#[derive(Serialize)]\nstruct ${name} {\n children: Vec<${name}>,\n}\n`;
assert.equal(digestWith(path, recursive("ProbeTree")), digestWith(path, recursive("ProbeNode")));
});
test("a build context without a registered source fails instead of producing another digest", () => {
const empty = mkdtempSync(join(tmpdir(), "contract-fingerprints-"));
try {
assert.throws(() => packContractDigest(empty), /Registered contract (source|directory) is missing/);
} finally {
rmSync(empty, { recursive: true, force: true });
}
});