Files
PaperClipAI/.github/scripts/tests/ci-dependency-cache.test.mjs
T
Dotta cffd17e78a perf(ci): Phase 3 PR CI under 3m — 4x Runner support, 12x E2E, incremental TS 7 cache, pure-Node postinstall, and rebalanced shards (#22804)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Pull request CI verifies every change before merge across build,
typecheck, server tests, Runner tests, and Playwright E2E shards.
> - After Phase 1 (#22679) and Phase 2 (#22729), full-fanout PR CI still
takes 9m45s wall-clock on 4-core AWS runners because of five
bottlenecks: an unsharded 7m22s `Runner support suite`, stale
server/chat/Runner shard duration manifests plus newly landed SSH/soak
whales, 28s of `pnpm -r run postinstall` replay on every job, cold
server/UI typecheck and single-build overhead, and 3 oversized (>180s)
Playwright E2E specs across 8 shards with double-start Postgres template
boot.
> - Docs-only prose edits under `doc/**` and `docs/**` also fanned out
to 66 CI jobs because only three doc paths bypassed global dependencies.
> - This pull request shards `Runner support suite` 4 ways with `pool:
"threads"`, shards E2E 12 ways after splitting the 3 oversized specs and
removing double-start Postgres boot, adds pure-Node workspace
postinstall replay, adds read-only master-warmed incremental TS 7 and
Runner dist caches, rebalances all server/chat/Runner duration
manifests, demotes 48 new non-invariant soak whales to nightly, and
routes audited prose docs without triggering 66-job storms.
> - The benefit is driving ordinary PR CI toward under 3 minutes
wall-clock while preserving every invariant check, cache boundary, and
full master/nightly test coverage.

## Linked Issues or Issue Description

Refs #22679
Refs #22729

**What existing behavior does this improve?**
Pull request CI wall-clock latency across
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`,
`.github/actions/setup-ci-dependencies/action.yml`, typecheck
orchestration, Vitest/Runner lanes, and Playwright E2E shards.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
Full-fanout PR CI takes 9m45s on 4-core runners (run `45440355579`),
dominated by `Runner support suite` (7m22s), `e2e shards` (5m02s–6m24s),
`General tests (server/chat)` (5m37s–6m01s), `Verify Paperclip Runner
(vitest package)` (6m25s on stale manifests), `Typecheck` (4m13s–6m30s),
`Build` (~4m), and 28s of `pnpm -r postinstall` per job. Prose edits
under `doc/**` trigger 66 jobs.

**Proposed behavior**
Shard `Runner support suite` (4x) and `e2e_shards` (12x), split the 3
oversized E2E specs, boot disposable E2E Postgres in a single
non-durable start, replay workspace `postinstall` in pure Node (<1s),
cache prebuilt Runner dist and TS 7 `.tsbuildinfo` from canonical
`master` pushes (read-only in PRs), use emit-only server compile in
ordinary PR `Build`, rebalance all shard duration manifests, demote 48
new non-invariant soak whales to nightly, and route audited prose docs
cleanly.

## What Changed

- **Pure-Node postinstall replay
(`scripts/replay-workspace-postinstall.mjs`,
`.github/actions/setup-ci-dependencies/action.yml`):** Replaces the 28s
`pnpm -r --if-present run postinstall && pnpm run postinstall` call on
every CI job with a pure-Node parallel runner (~0.84s locally) with
fallback for older checkouts.
- **4-way sharded `Runner support suite` + `threads` pool
(`.github/ci-task-matrix.json`, `.github/workflows/pr-trusted.yml`,
`tests/runner-e2e/run-unit.mjs`, `tests/runner-e2e/vitest.config.ts`):**
Shards Vitest and `node:test` suites 4 ways (`--shard-index 0..3
--shard-count 4`) and switches `tests/runner-e2e` to `pool: "threads"`
with CPU-aware `maxWorkers` while preserving `isolate: true`.
- **12-way E2E shards, single-start E2E Postgres boot, and 3 oversized
spec splits (`tests/e2e/start-e2e-server.ts`, `tests/e2e/*.spec.ts`,
`tests/e2e/playwright.config.ts`, `scripts/e2e-shard.mjs`,
`scripts/e2e-shard-durations.json`, `.github/ci-task-matrix.json`):**
Boots cold ephemeral E2E Postgres in one `initdb --no-sync` +
non-durable `postgresql.conf` start overlapped with server module
import; splits `agent-chat-projects`, `chat-adapters-ui-providers`, and
`chat-adapters-ui-messaging` cleanly with zero tests removed; balances
all 54 specs across 12 shards (6.8s spread).
- **Incremental TS 7 typecheck & Runner dist caching
(`server/scripts/typecheck-layers.mjs`, `scripts/ci-typecheck-lane.mjs`,
`scripts/typecheck-test-programs.mjs`,
`scripts/typecheck-test-projects.mjs`,
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`):** Preserves portable
`.tsbuildinfo`/`.d.ts` with `layer-map.json` invalidation and
stale-declaration pruning, wires read-only `runner-dist-v1` and
`typecheck-incremental-v1` restores in `pr-trusted.yml` (zero
`actions/cache/save`) paired with canonical-`master`-only guarded
writers in `release-verify.yml`, skips redundant Runner Rust `cargo
check` on TS-only shared PRs, and uses LPT scheduling with concurrency 3
(4-core) / 4 (8-core).
- **Emit-only PR `Build` & audited prose doc routing
(`.github/workflows/pr-trusted.yml`, `.github/scripts/ci-inputs.mjs`):**
Passes `PAPERCLIP_TSC_EMIT_ONLY=1` on ordinary PR `Build` jobs (full
`pnpm build` on `full-ci` / `master`), and classifies audited prose
Markdown under `doc/**` and `docs/**` as `guidance` / `historical` while
keeping `docs/api/**`, JSON/TS fixtures, `maps/**`, and unknown files
fail-closed.
- **Rebalanced shard manifests & new soak demotions
(`scripts/ci/nightly-only-suites.json`,
`scripts/*-shard-durations.json`,
`packages/paperclip-runner/scripts/vitest-lane-durations.json`,
`packages/paperclip-runner/vitest.config.ts`,
`packages/paperclip-runner/scripts/vitest-sequencer.mjs`):** Demotes 48
newly landed/grown non-invariant soak suites (including 4 real-SSH
integration suites) to nightly, refreshes all 4 timing manifests from
live CI measurements (0.1s–0.6s LPT skew), and scales Runner package
Vitest CI `maxWorkers` to 3 on 4-core / 6 on 8-core.

## Verification

- `node --test .github/scripts/tests/*.test.mjs
scripts/__tests__/runner-release-crate-cache.test.mjs
scripts/__tests__/public-install-closure.test.mjs
scripts/__tests__/merge-queue-checks-workflow.test.mjs
scripts/__tests__/e2e-shard.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/runner-vitest-package-lanes.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/check-test-budget.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs
scripts/ci/test-selection-timings.test.mjs` — **973/973 PASS**
- `node scripts/check-test-budget.mjs --base origin/master` — **PASS**
(`609` nightly suites validated, zero protected invariants demoted)
- `node scripts/check-maps.mjs` — **PASS**
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs
tests/runner-e2e/unit-launcher.test.mjs` — **PASS**
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
scripts/vitest-sequencer.test.mjs` — **PASS**
- `cd server && node ../node_modules/vitest/vitest.mjs run
scripts/typecheck-layers.test.mjs
scripts/typecheck-layers-incremental.test.mjs` — **56/56 PASS** (real TS
7.0.2 incremental soundness tests)
- `node scripts/run-tsc.mjs -p tests/e2e/tsconfig.json --noEmit && node
scripts/run-tsc.mjs -p tests/tsconfig.playwright.json --noEmit && pnpm
run test:e2e:runner:typecheck` — **0 errors**
- Live Playwright smoke passed across all 6 split E2E spec files on the
cold non-durable Postgres boot path
(`PAPERCLIP_TEST_POSTGRES_TEMPLATE=0`).
- Live sharded `tests/runner-e2e` runs passed under `pool: "threads",
maxWorkers: 4` (shard `1/4` 172/172 PASS; shard `2/4` all Vitest + 65/65
`node:test` PASS).

## Risks

- **Cache invalidation on incremental typecheck / Runner dist:**
Mitigated by exact-key hashing (including
`packages/{shared,adapter-utils,plugins/sdk}/src/**` and
`packages/paperclip-runner/spec/**`) with no `restore-keys:` on
`runner-dist-v1`, SHA-256 self-validation inside
`prepare-runner-vendor.mjs`, `layer-map.json` invalidation + stale
`.d.ts` pruning in `typecheck-layers.mjs`, and read-only PR restores
(only canonical `master` pushes save caches).
- **Shard rebalancing & soak demotions:** All demoted suites remain in
`nightly-only-suites.json` and run on `full-ci` / `master` / nightly;
`check-test-budget.mjs` enforces zero protected invariants are demoted.
- **Workflow security boundaries:** `ci-routing.yml`, `pr.yml`,
`CODEOWNERS`, and all `runs-on:` expressions are unchanged;
`pr-trusted.yml` performs zero `actions/cache/save` calls.

## Model Used

- Google Gemini (Antigravity agent swarm) with extended reasoning, tool
use, and local code/test execution across 6 parallel worker roles
(`ci-pipeline`, `vitest-runner`, `server-prune`, `e2e-opt`,
`typecheck-opt`, `verifier`).

## 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-24 13:25:46 -06:00

189 lines
11 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 { 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);
for (const file of ['scripts/ensure-plugin-build-deps.mjs', 'scripts/new-install-helper.mjs', '.pnpmfile.cjs']) {
assert.notEqual(plan({ ...entries, [file]: 'changed' }).dependencyKey, plan().dependencyKey);
}
});
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/);
});