Files
PaperClipAI/.github/scripts/tests/ci-dependency-cache.test.mjs
T
Dotta 3773d0f40f perf(ci): skip prebaked pnpm setup, move rollups to ubuntu-slim, and narrow dep cache inputs (#22958)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Live 8-core runs on `paperclip-public-ci-fleetd:29`
(`ami-09dfb1e62707f576c`, runs `45665466678` & `45668834558`) revealed
three zero-hot-instance sources of wasted PR wall-clock time:
> 1. `pnpm/action-setup@v6` still spent `4.1–5.0s` on all 68 jobs
switching its bundled `v11.19.0` to `v9.15.4` even though the pre-baked
AMI already has `pnpm@9.15.4` installed at
`$HOME/setup-pnpm/node_modules/.bin/pnpm`.
> 2. `ci / verify` and `ci / e2e` rollups booted fresh 8-core AWS EC2
VMs (`18–23s` cold queue after all tests already finished!) just to run
a 1-second inline Node `assert` check with zero repo checkout and zero
secrets.
> 3. `scripts/ci-dependency-cache.mjs` hashed blanket `scripts/**`,
`server/scripts/**`, and `packages/paperclip-runner/scripts/**`, causing
every merge touching any CI script or shard duration manifest to
invalidate the ~944 MB `ci-dependencies-v1` cache for all 70 jobs
(`35–40s` cold restore vs `10s` hit) until `release-verify.yml` rebuilt
it 15–20 minutes later.
> - This pull request eliminates all three bottlenecks with zero
hot/standby instances and zero security-boundary changes
(`ci-routing.yml`, `pr.yml`, `CODEOWNERS`, and read-only PR caches
untouched).

## Linked Issues or Issue Description

Refs #22804

**What existing behavior does this improve?**
PR job startup latency, rollup tail latency, and `ci-dependencies-v1`
cache hit rate across `.github/workflows/pr-trusted.yml`,
`.github/actions/setup-ci-dependencies/action.yml`, and
`scripts/ci-dependency-cache.mjs`.

**Subsystem affected**
CI — PR workflow bootstrap, rollup jobs, and materialized dependency
cache key inputs

**Current behavior**
All 11 `Setup pnpm` steps run `pnpm/action-setup@v6` unconditionally
(`4–5s` each); `ci / verify` and `ci / e2e` boot full AWS EC2 runners
(`18–23s` queue) after tests complete; `ci-dependency-cache.mjs` hashes
blanket `scripts/**` globs so unrelated CI script edits bust
`node_modules` caching across all 70 PR jobs.

**Proposed behavior**
Dynamically compare `$HOME/setup-pnpm/node_modules/.bin/pnpm --version`
against `package.json`'s `packageManager` before all 11 `Setup pnpm`
steps (skipping `pnpm/action-setup` on pre-baked runners while
preserving identical `PNPM_HOME` and failing closed on version bumps);
run `ci / verify` and `ci / e2e` rollups on `ubuntu-slim`; narrow
`ci-dependency-cache.mjs` script inputs to the exact 8-file
`DEPENDENCY_SCRIPT_INPUTS` closure enforced by a static relative-import
test plus `--prefer-offline` on cold-install fallback.

## What Changed

- **Skip redundant `pnpm/action-setup` on pre-baked AMIs
(`.github/workflows/pr-trusted.yml`):**
- Added inline `Check preinstalled pnpm` (`id: pnpm_preinstalled`)
before all 11 `Setup pnpm` steps: parses `package.json`'s
`packageManager` (`^pnpm@([^+\s]+)(?:\+.*)?$`) dynamically, compares
against `$HOME/setup-pnpm/node_modules/.bin/pnpm --version`, exports
identical `PNPM_HOME` + `$GITHUB_PATH` on match, and fails closed to
`pnpm/action-setup@v6` on version bump or `ubuntu-latest`.
- **Move `ci / verify` & `ci / e2e` rollups to `ubuntu-slim`
(`.github/workflows/pr-trusted.yml`):**
- Switched both zero-checkout rollup jobs from
`needs.gate.outputs.runner` to `ubuntu-slim` (~2–4s container start
instead of `18–23s` EC2 VM boot).
- **Narrow dependency cache script inputs
(`scripts/ci-dependency-cache.mjs`,
`.github/actions/setup-ci-dependencies/action.yml`):**
- Replaced blanket `scripts/**`, `server/scripts/**`, and
`packages/paperclip-runner/scripts/**` hashes with exported
`DEPENDENCY_SCRIPT_INPUTS` (the exact 8 scripts invoked during
dependency materialization/postinstall), kept
`scripts/ensure-plugin-build-deps.mjs` on `buildKey` only, and added
`--prefer-offline` on cold-install fallback.
- **Tests (`.github/scripts/tests/ci-dependency-cache.test.mjs`,
`.github/scripts/tests/ci-plan.test.mjs`):**
- Added automated static relative-import closure verification for
`DEPENDENCY_SCRIPT_INPUTS`, `ubuntu-slim` rollup checks, and execution
tests of the extracted `Check preinstalled pnpm` snippet across
matching, `+sha512`, bumped, missing `packageManager`, and missing
binary cases.

## Verification

- `ruby -ryaml -e 'YAML.load_file(".github/workflows/pr-trusted.yml");
YAML.load_file(".github/actions/setup-ci-dependencies/action.yml")'` —
**YAML OK**
- `node --test .github/scripts/tests/*.test.mjs
scripts/ci/test-selection-workflow.test.mjs
scripts/__tests__/{ci-typecheck-lane,e2e-shard,run-vitest-stable-shard,run-vitest-stable-pr-mode,merge-queue-checks-workflow,runner-release-crate-cache,runner-debug-crate-cache,public-install-closure}.test.mjs
scripts/check-test-budget.test.mjs
scripts/docker-image-metadata.test.mjs` — **942/942 PASS**
- Live PR CI proves `ubuntu-slim` rollup execution, pre-baked `Check
preinstalled pnpm` skip (`hit=true`), and `ci-dependencies-v1` restore
parity end-to-end.

## Risks

- Low risk: `Check preinstalled pnpm` dynamically reads `package.json`'s
`packageManager` and fails closed on mismatch or version bump;
`ci-dependency-cache.test.mjs` statically enforces that no relative
import from `DEPENDENCY_SCRIPT_INPUTS` can escape the cache key; `ci /
verify` and `ci / e2e` check out no code and use no secrets.

## Model Used

- Gemini 4 Neon (High) via Antigravity agent swarm (`typecheck-opt`,
`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 12:39:05 -06:00

221 lines
13 KiB
JavaScript

import assert from "node:assert/strict";
import test from "node:test";
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { DEPENDENCY_SCRIPT_INPUTS, cachePlan } from "../../../scripts/ci-dependency-cache.mjs";
import { findWorkspacePostinstallScripts, replayWorkspacePostinstalls } from "../../../scripts/replay-workspace-postinstall.mjs";
const entries = {
"package.json": '{"scripts":{"postinstall":"node scripts/link-plugin-dev-sdk.mjs"}}',
"server/package.json": '{"dependencies":{"external":"1.0.0"}}',
"packages/shared/package.json": '{}',
"packages/plugins/sdk/package.json": '{}',
"pnpm-lock.yaml": 'lockfile',
"pnpm-workspace.yaml": 'workspace',
".npmrc": 'auto-install-peers=false',
"patches/external.patch": 'patch',
"scripts/link-plugin-dev-sdk.mjs": 'postinstall',
"scripts/ci-dependency-cache.mjs": 'cache schema',
"scripts/ensure-plugin-build-deps.mjs": 'build verifier',
"tsconfig.base.json": '{}',
"packages/shared/src/index.ts": 'shared API',
"packages/plugins/sdk/src/index.ts": 'SDK API',
"server/src/server.ts": 'server',
};
const scope = { node: 'v24.19.0', root: '/work/paperclip', arch: 'x64', libc: '2.39', pnpm: '9.15.4', store: '/store' };
const plan = (files = entries, runtime = scope) => cachePlan({
files: Object.keys(files), read: (file) => files[file] === null ? null : Buffer.from(files[file]), scope: runtime,
packageDirs: ['.', 'packages/plugins/sdk', 'packages/shared', 'server'],
});
test('dependency identity includes manifests, resolution, patches, installer and runtime boundaries', () => {
const original = plan();
for (const file of Object.keys(entries).filter((file) =>
/package\.json$/.test(file) || /^(pnpm-|\.npmrc|patches\/|scripts\/(link-plugin-dev-sdk|ci-dependency-cache))/.test(file))) {
for (const value of [file.endsWith('package.json') ? '{"changed":true}' : 'changed', null]) {
const changed = plan({ ...entries, [file]: value });
assert.notEqual(changed.dependencyKey, original.dependencyKey, file);
assert.notEqual(changed.buildKey, original.buildKey, file);
}
}
assert.notEqual(plan({ ...entries, 'packages/new/package.json': '{}' }).dependencyKey, original.dependencyKey);
for (const key of Object.keys(scope)) {
assert.notEqual(plan(entries, { ...scope, [key]: 'different' }).dependencyKey, original.dependencyKey, key);
}
});
test('shared and SDK source changes invalidate dependent builds without reinstalling packages', () => {
const original = plan();
for (const file of ['packages/shared/src/index.ts', 'packages/plugins/sdk/src/index.ts',
'tsconfig.base.json']) {
const changed = plan({ ...entries, [file]: 'changed' });
assert.equal(changed.dependencyKey, original.dependencyKey, file);
assert.notEqual(changed.buildKey, original.buildKey, file);
}
assert.deepEqual(plan({ ...entries, 'server/src/server.ts': 'different' }), original);
assert.deepEqual(plan(Object.fromEntries(Object.entries(entries).reverse())), original);
assert.deepEqual(original.dependencyPaths, ['node_modules', 'packages/plugins/sdk/node_modules',
'packages/shared/node_modules', 'server/node_modules']);
assert.deepEqual(plan({ ...entries, 'tests/fixtures/app/package.json': '{}' }).dependencyPaths, original.dependencyPaths);
for (const directory of ['/outside', '../outside', 'server/../../outside']) {
assert.throws(() => cachePlan({ files: [], read: () => null, scope, packageDirs: [directory] }));
}
});
test('unmodelled workspace lifecycle scripts disable materialized reuse', () => {
assert.equal(plan().cacheable, true);
for (const hook of ['preinstall', 'install', 'postinstall', 'prepare']) {
assert.equal(plan({ ...entries, 'server/package.json': JSON.stringify({ scripts: { [hook]: 'node custom.mjs' } }) }).cacheable, false);
}
assert.equal(plan({ ...entries, 'package.json': '{"scripts":{"postinstall":"node other.mjs"}}' }).cacheable, false);
assert.notEqual(plan({ ...entries, '.pnpmfile.cjs': 'changed' }).dependencyKey, plan().dependencyKey);
const buildOnly = plan({ ...entries, 'scripts/ensure-plugin-build-deps.mjs': 'changed' });
assert.equal(buildOnly.dependencyKey, plan().dependencyKey);
assert.notEqual(buildOnly.buildKey, plan().buildKey);
for (const file of [
'scripts/general-server-shard-durations.json',
'scripts/ci-typecheck-lane.mjs',
'server/scripts/typecheck-layers.mjs',
'packages/paperclip-runner/scripts/run-check-static.mjs',
]) {
assert.deepEqual(plan({ ...entries, [file]: 'changed' }), plan(), file);
}
});
test('DEPENDENCY_SCRIPT_INPUTS covers the full local import closure of install/postinstall scripts', () => {
const repoRoot = path.resolve(new URL('../../..', import.meta.url).pathname);
const visited = new Set();
const queue = [...DEPENDENCY_SCRIPT_INPUTS];
const importPattern = /(?:from\s+|import\s*\(\s*|require\s*\(\s*)["'](\.[^"']+)["']/g;
while (queue.length > 0) {
const rel = queue.shift();
if (visited.has(rel)) continue;
visited.add(rel);
assert.ok(DEPENDENCY_SCRIPT_INPUTS.has(rel), `missing transitive install helper from DEPENDENCY_SCRIPT_INPUTS: ${rel}`);
const abs = path.join(repoRoot, rel);
const source = readFileSync(abs, 'utf8');
for (const match of source.matchAll(importPattern)) {
const target = path.relative(repoRoot, path.resolve(path.dirname(abs), match[1])).split(path.sep).join('/');
if (!visited.has(target)) queue.push(target);
}
}
const action = readFileSync(new URL('../../actions/setup-ci-dependencies/action.yml', import.meta.url), 'utf8');
assert.equal((action.match(/pnpm install --frozen-lockfile --prefer-offline/g) ?? []).length, 2);
});
test('known Copilot hooks permit caching, track their helpers, and still run on restore', () => {
const files = { ...entries,
'server/package.json': JSON.stringify({ scripts: { postinstall: 'node scripts/install-copilot-assets.mjs' } }),
'packages/paperclip-runner/package.json': JSON.stringify({ scripts: { postinstall: 'node scripts/install-copilot-assets.mjs' } }),
'server/scripts/install-copilot-assets.mjs': 'server bootstrap',
'packages/paperclip-runner/scripts/install-copilot-assets.mjs': 'runner bootstrap',
'packages/paperclip-runner/scripts/materialize-copilot-binary.mjs': 'native materializer',
'packages/paperclip-runner/scripts/copilot-inner-distribution.mjs': 'closure pins',
};
const compute = (input) => cachePlan({ files: Object.keys(input),
read: file => input[file] == null ? null : Buffer.from(input[file]), scope,
packageDirs: ['.', 'server', 'packages/paperclip-runner'],
});
const original = compute(files);
assert.equal(original.cacheable, true);
for (const file of Object.keys(files).filter(file => /^(server|packages\/paperclip-runner)\/scripts\//.test(file))) {
for (const replacement of ['changed', null]) {
assert.notEqual(compute({ ...files, [file]: replacement }).dependencyKey, original.dependencyKey, file);
}
}
assert.equal(cachePlan({ files: ['elsewhere/package.json'],
read: () => Buffer.from(files['server/package.json']), scope, packageDirs: ['elsewhere'],
}).cacheable, false, 'the command is allowed only in its reviewed owners');
const action = readFileSync(new URL('../../actions/setup-ci-dependencies/action.yml', import.meta.url), 'utf8');
const replay = action.split(' - name: Replay workspace install hooks after restore')[1].split(' - name:')[0];
assert.match(replay, /if: steps\.installed\.outputs\.cache-hit == 'true'/);
assert.match(replay, /node scripts\/replay-workspace-postinstall\.mjs/);
assert.match(replay, /pnpm -r --if-present run postinstall\s+pnpm run postinstall/);
assert.ok(action.indexOf('Replay workspace install hooks') < action.indexOf('Validate workspace links'));
});
test('replay-workspace-postinstall discovers repo hooks, runs workspace hooks before root, and fails closed', async () => {
const discovered = findWorkspacePostinstallScripts();
assert.deepEqual(
discovered.workspaceHooks.map((hook) => hook.relDir),
['packages/paperclip-runner', 'server'],
);
assert.equal(discovered.rootHook?.relDir, '.');
const tmp = mkdtempSync(path.join(os.tmpdir(), 'replay-postinstall-'));
try {
const orderFile = path.join(tmp, 'order.log');
mkdirSync(path.join(tmp, 'packages/alpha'), { recursive: true });
mkdirSync(path.join(tmp, 'server'), { recursive: true });
writeFileSync(path.join(tmp, 'package.json'), JSON.stringify({
name: 'root',
scripts: { postinstall: "node -e \"require('node:fs').appendFileSync(process.env.ORDER_FILE, 'root\\n')\"" },
}));
writeFileSync(path.join(tmp, 'packages/alpha/package.json'), JSON.stringify({
name: '@test/alpha',
scripts: { postinstall: "node -e \"require('node:fs').appendFileSync(process.env.ORDER_FILE, 'alpha\\n')\"" },
}));
writeFileSync(path.join(tmp, 'server/package.json'), JSON.stringify({
name: '@test/server',
scripts: { postinstall: "node -e \"require('node:fs').appendFileSync(process.env.ORDER_FILE, 'server\\n')\"" },
}));
const result = await replayWorkspacePostinstalls(tmp, { ...process.env, ORDER_FILE: orderFile });
assert.deepEqual(result, { workspaceCount: 2, ranRoot: true });
const lines = readFileSync(orderFile, 'utf8').trim().split('\n');
assert.equal(lines.length, 3);
assert.equal(lines[2], 'root', 'root postinstall must run after workspace postinstall hooks');
assert.deepEqual(lines.slice(0, 2).sort(), ['alpha', 'server']);
writeFileSync(path.join(tmp, 'server/package.json'), JSON.stringify({
name: '@test/server',
scripts: { postinstall: 'node -e "process.exit(3)"' },
}));
await assert.rejects(() => replayWorkspacePostinstalls(tmp, { ...process.env, ORDER_FILE: orderFile }), /postinstall in server exited with 3/);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
test('cache restores are exact and only a frozen canonical master push can publish entries', () => {
const action = readFileSync(new URL('../../actions/setup-ci-dependencies/action.yml', import.meta.url), 'utf8');
const installed = action.slice(action.indexOf(' - name: Restore installed'), action.indexOf(' - name: Locate pnpm'));
const builds = action.slice(action.indexOf(' - name: Restore certified'), action.indexOf(' - name: Validate workspace'));
for (const restore of [installed, builds]) assert.doesNotMatch(restore, /restore-keys:/);
for (const step of action.split(' - name: Save ').slice(1)) {
assert.match(step, /inputs\.save-cache == 'true'/);
assert.match(step, /github\.repository == 'paperclipai\/paperclip'/);
assert.match(step, /github\.event_name == 'push'/);
assert.match(step, /github\.ref == 'refs\/heads\/master'/);
assert.match(step, /steps\.install\.outputs\.frozen == 'true'/);
}
const workflow = readFileSync(new URL('../../workflows/release-verify.yml', import.meta.url), 'utf8');
assert.match(workflow, /save-cache: .*inputs\.ref == github\.sha/);
});
test('paired test timings remain available when lifecycle hooks disable materialized caching', () => {
const workflow = readFileSync(new URL('../../workflows/ci-work-benchmark.yml', import.meta.url), 'utf8');
const step = name => workflow.split(` - name: ${name}\n`)[1].split(' - name:')[0];
for (const name of ['Save PR-scoped qualification dependencies', 'Save PR-scoped qualification builds',
'Remove materialized outputs before restore', 'Qualify a real warm restore',
'Verify exact cache hits and record setup comparison']) {
assert.match(step(name), /if: steps.qualification.outputs.cacheable == 'true'/);
}
assert.match(step('Explain disabled materialized reuse'), /cacheable != 'true'/);
for (const name of ['Prepare unchanged baseline', 'Compare complete commands and executed case inventories']) {
assert.match(step(name), /if: steps\.test_scope\.outputs\.run == 'true'/);
assert.doesNotMatch(step(name), /if:.*cacheable/);
}
const scope = step('Select changed server test work');
assert.match(scope, /git diff --name-only HEAD\^1 HEAD --/);
for (const file of ['scripts/benchmark-ci-work.mjs', 'scripts/run-vitest-stable.mjs',
'server/src/__tests__/setup-supertest.ts', 'server/src/__tests__/workspace-runtime.test.ts',
'server/src/services/workspace-git-snapshot-streaming.test.ts']) assert.ok(scope.includes(file));
assert.doesNotMatch(scope, /scripts\/ci-dependency-cache|\.github\/actions\/setup-ci-dependencies/);
assert.match(step('Exercise restored dependencies for cache-only changes'), /pnpm exec vitest run --project @paperclipai\/shared/);
});