Files
PaperClipAI/scripts/ci/test-selection-pr-timings.test.mjs
T
Dotta 9a04538391 perf(ci): cut PR CI under 5 minutes (shared PG, E2E parallelism, routing, test pruning) (#22679)
## 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 typecheck,
build, server/DB/UI unit tests, and Playwright E2E shards.
> - Today PR CI takes 15–30+ minutes wall-clock on ordinary feature and
fix PRs (such as #22626) because every PR runs
release/packaging/runner-support bloat, boots 800+ separate embedded
Postgres clusters, runs Vitest serialized shards and E2E shards at 1
worker, builds the UI 8 separate times for E2E, emits 52 MB of React
`act(...)` stderr spam in UI tests, and runs 61 real-clock soak suites
plus hundreds of historical one-time SQL migration and mocked component
wiring tests.
> - Slow PR CI delays developer feedback, wastes runner capacity, and
encourages batching changes instead of shipping small, safe PRs.
> - This pull request cuts PR CI across all 6 bottlenecks (pipeline
routing/Build bloat, PR-scoped parallel typecheck, shared embedded
Postgres + batched/parallel Vitest runner, parallel E2E shards +
prebuilt UI cache, historical/soak DB+server pruning with a checked-in
nightly manifest, and UI stderr cleanup + low-value test pruning) while
preserving all core control-plane invariants and full post-merge/release
coverage.
> - The benefit is projected PR CI wall-clock drops from 15–30+ minutes
to ~3.8–4.4 minutes on ordinary PRs while keeping `master`,
`release-verify`, `cloud-readiness`, local `pnpm test:run`, and
`full-ci` runs at full coverage.

## Linked Issues or Issue Description

Refs #22626.

**What existing behavior does this improve?**

Trusted pull-request CI wall-clock duration and runner efficiency across
`.github/workflows/pr-trusted.yml`, `turbo.json`,
`scripts/ci-typecheck-lane.mjs`, `scripts/run-vitest-stable.mjs`,
`tests/e2e/`, `packages/db`, `server`, and `ui` test suites.

**Subsystem affected**

Cross-cutting (multiple of the above)

**Current behavior**

Ordinary PRs take 15–30+ minutes wall-clock in PR CI:
- `Build` (~7.5–8.0m) runs a 231s clean public npm Grok install verifier
and a 57s embedded-Postgres boot smoke on every PR.
- `Canary Dry Run` (6.2m), `Runner support suite` (7.9m), `Docker
context integrity`, `General tests (chat 1–3/3)`, and `Verify Paperclip
Runner (vitest package 1–3/3)` fan out on ordinary app PRs due to broad
`turbo.json` inputs.
- `Typecheck + Release Registry` (7.1m) runs `test:release-registry`
(193s), all standalone sandbox provider installs/checks, all untouched
`tests/*` projects, and `--singleThreaded` `tsc` on every PR.
- `General tests` and `Verify serialized server suites` boot 800+
separate embedded Postgres clusters instead of using
`packages/db/src/test-postgres-command.ts`, run 17 serial Vitest
invocations in `workspaces-b`, and run `verify_serialized_server` with
`--no-file-parallelism --maxWorkers=1`.
- `e2e_shards` (8.6m slowest shard) rebuilds the UI 8 separate times and
forces `workers: 1` across all 56 specs because 7 specs mutate
instance-level flags.
- `workspaces-a` (8.3m × 2 shards) emits ~52 MB of React `act(...)` /
`IS_REACT_ACT_ENVIRONMENT` stderr spam and executes 992 UI test files
(including hundreds of brittle mocked wiring / `renderToStaticMarkup`
suites).
- `packages/db` and `server` run 43 historical one-time SQL migration
replay tests, 12 static prose-grep tests, and 61 real-clock
soak/crash/lease-expiry suites (~108.5 CPU-min) on every PR.

**Proposed behavior**

Ordinary PRs complete in under 5 minutes wall-clock while preserving
full control-plane invariant coverage and full
`master`/`release-verify`/`cloud-readiness`/`full-ci` verification:
- PR `Build` removes the 231s Grok clean-npm verifier (already covered
in `release-smoke.yml` and `docker-runner-check.yml`) and gates the 53s
boot smoke on `PAPERCLIP_CI_FULL=1` (keeping fast `build:runtime` on
every PR).
- `turbo.json` and `.github/ci-task-matrix.json` path-gate `Canary Dry
Run`, `Runner support suite`, `Docker context integrity`,
`general-chat`, `ci:runner-package`, `ci:workspaces-a`, and `ci:db`, and
narrow `tests/**` out of `globalDependencies`.
- `Typecheck + Release Registry` uses fail-closed PR-mode scoping
(`CI_PLAN`, `PAPERCLIP_CI_BASE_SHA`, `PAPERCLIP_CI_FULL`), parallel
`typecheck-test-programs.mjs`, and `--checkers` / `GOMAXPROCS=2` within
the 15.7 GiB RAM budget.
- `run-vitest-stable.mjs` automatically wraps Postgres-backed lanes with
one shared embedded Postgres template server
(`test-postgres-command.ts`), batches `workspaces-b` and `workspaces-a`
into single multi-project Vitest invocations, parallelizes isolated
`serialized` shards, and filters `scripts/ci/nightly-only-suites.json`
in PR mode (respecting `PAPERCLIP_CI_FULL=1`).
- `e2e_shards` restores a read-only exact-key `server/ui-dist` cache
written on canonical `master` pushes (`PAPERCLIP_E2E_SKIP_UI_BUILD=1`,
inline fallback on UI PRs), isolates the 7 flag-mutating specs onto 2
serial shards while running the other 6 shards at `workers: 3` +
`fullyParallel: true`, prunes 5 legacy/screenshot specs, and replaces
fixed 20s/30s sleeps with deterministic waits.
- `ui/vitest.setup.ts` eliminates >99.9% of stderr spam
(`IS_REACT_ACT_ENVIRONMENT = true`, clean localStorage/DOM stubs,
targeted `act(...)`/`No queryFn` suppression) and prunes 445 low-value
mocked/presentational/screenshot UI tests + slims 2 giant mocked suites
(keeping all `ui/src/lib`, `api`, `hooks`, `context`, `adapters`,
`features`, `plugins`, and privacy/authz tests).
- `packages/db` and `server` prune 43 historical one-time SQL migration
tests, 12 static prose-grep tests, and 28 redundant `it.each` cases in
`chat-channels.integration.test.ts`, and classify 61 real-clock
soak/restart/lease-expiry/workspace-recovery suites (6,510.2s / 108.5
CPU-min) into `scripts/ci/nightly-only-suites.json`.

**Reason and benefit**

Cuts ordinary PR CI wall-clock from 15–30+ minutes to a projected
~3.8–4.4 minutes and removes ~156,353 LOC of redundant/brittle test code
without dropping any core Paperclip invariant (company isolation, authz,
atomic checkout, single-assignee, approval gates, budget hard-stop,
activity logging).

**Breaking changes**

None for product runtime behavior. In PR CI, 61 real-clock soak suites
listed in `scripts/ci/nightly-only-suites.json` run on `master`,
`release-verify`, `cloud-readiness`, local `pnpm test:run`, and PRs with
the `full-ci` label (`PAPERCLIP_CI_FULL=1`) instead of every ordinary
PR.

## What Changed

- **Pipeline & routing (`ci-fast/pipeline`):**
- `.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`, `.github/ci-task-matrix.json`,
`turbo.json`: removed Grok clean-npm verifier from PR `Build`, gated
`server-boot-smoke.sh` on `PAPERCLIP_CI_FULL=1`, path-gated
`canary_dry_run`, `verify_runner_e2e_support`,
`docker_context_integrity`, `general-chat`, `ci:runner-package`,
`ci:workspaces-a`, and `ci:db`, forwarded `CI_PLAN` /
`PAPERCLIP_CI_BASE_SHA` / `PAPERCLIP_CI_FULL` (keeping `profile-ci` in
PR mode), and added exact-key read-only `server/ui-dist` cache restore
in `e2e_shards` with a master-only writer in `release-verify.yml`.
- Updated `.github/scripts/tests/ci-plan.test.mjs`,
`scripts/__tests__/public-install-closure.test.mjs`, and
`scripts/__tests__/runner-release-crate-cache.test.mjs`.
- **Typecheck lane (`ci-fast/typecheck`):**
- `scripts/ci-typecheck-lane.mjs`,
`scripts/typecheck-test-programs.mjs`,
`scripts/typecheck-test-projects.mjs`,
`server/scripts/typecheck-layers.mjs`: added fail-closed PR-mode diff
scoping (skipping `test:release-registry`, standalone sandbox providers,
demo plugins, and untouched test projects/workspaces on unrelated PRs),
concurrent `typecheckTestProgramsAsync`, and `--checkers` /
`GOMAXPROCS=2` parallelism within 15.7 GiB RAM.
- Updated `scripts/__tests__/ci-typecheck-lane.test.mjs`,
`scripts/typecheck-test-programs.test.mjs`, and
`server/scripts/typecheck-layers.test.mjs`.
- **Vitest runner (`ci-fast/vitest-runner`):**
- `scripts/run-vitest-stable.mjs`,
`packages/db/src/test-postgres-command.ts`,
`scripts/__tests__/run-vitest-stable-shard.test.mjs`: wired automatic
shared embedded Postgres template DB (`test-postgres-command.ts` with
`fsync=off`), batched `workspaces-b` and `workspaces-a` into single
multi-project Vitest runs, parallelized isolated `serialized` shards
(`maxWorkers=3`), and added PR-mode filtering for
`scripts/ci/nightly-only-suites.json` (honoring `PAPERCLIP_CI_FULL=1`).
- **Playwright E2E (`ci-fast/e2e`):**
- `tests/e2e/playwright.config.ts`, `scripts/e2e-shard.mjs`,
`scripts/e2e-shard-durations.json`,
`scripts/__tests__/e2e-shard.test.mjs`, `maps/feature-map/recovery.md`:
added `PAPERCLIP_E2E_SKIP_UI_BUILD=1`, isolated the 7 instance-mutating
`SERIAL_SPECS` onto dedicated serial shards while running the remaining
44 specs across 6 shards at `workers: 3` + `fullyParallel: true`, pruned
5 legacy/screenshot specs (`-743 LOC`), and replaced fixed 20s/30s
sleeps in `disconnect-resilience.spec.ts` and `composer-stop.spec.ts`.
- **Server & DB test pruning + nightly soak manifest
(`ci-fast/server-prune`):**
- Deleted 41 historical one-time SQL migration tests + 5 obsolete
fixture SQLs in `packages/db/src`, 2 historical server SQL migration
tests, and 12 brittle static prose-guidance tests; trimmed
`packages/db/src/client.test.ts` (2,328 → 219 LOC),
`packages/db/src/better-auth-account-issuer-migration.test.ts` (167 → 19
LOC), and 2 redundant `it.each` matrices in
`server/src/__tests__/chat-channels.integration.test.ts`.
- Added `scripts/ci/nightly-only-suites.json` classifying 61 real-clock
soak/restart/lease-expiry/workspace-recovery suites (6,510.2s / 108.5
CPU-min).
- **UI test log spam fix & pruning (`ci-fast/ui-prune`):**
- `ui/vitest.setup.ts`, `ui/vitest.config.ts`: eliminated >99.9% stderr
spam (22–52 MB → 3.6 KB) by enabling `IS_REACT_ACT_ENVIRONMENT = true`,
adding clean DOM/localStorage stubs, and filtering React `act(...)` /
TanStack Query `No queryFn` noise.
- Pruned 445 low-value mocked/presentational/screenshot UI test files,
slimmed `AgentConfigForm.render.test.tsx` and `Browse.test.tsx` to their
privacy/access checks, updated 34 `maps/` files to remove dead test
links, and removed the stale `ui/src/pages/NewAgent.test-support.tsx`
allowlist entry in `scripts/check-query-error-rendering.mjs`.

## Verification

- Combined CI contract & shard test suite (`node --test
.github/scripts/tests/ci-plan.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/__tests__/e2e-shard.test.mjs
scripts/__tests__/public-install-closure.test.mjs
scripts/__tests__/runner-release-crate-cache.test.mjs
scripts/__tests__/merge-queue-checks-workflow.test.mjs`): **136/136
PASS** (23.13s).
- Full `.github/scripts/tests/*.test.mjs` suite on `ci-fast/pipeline`:
**850/850 PASS** + Turbo cached-lane check **1/1 PASS**.
- `node scripts/check-query-error-rendering.mjs --enforce --summary` and
`node --test scripts/check-query-error-rendering.test.mjs`: **0
findings, 7/7 PASS**.
- `node scripts/check-maps.mjs`: **PASS** (`35 areas, 192 capability
IDs`).
- `pnpm --filter @paperclipai/db typecheck`: **PASS**
(`check:migrations` + `tsc --noEmit`).
- `pnpm --filter @paperclipai/ui typecheck`: **PASS** (`369 files, 3454
stories` + `run-tsc.mjs -b`).
- Component-level benchmarks verified on individual branches prior to
merge (`ci-typecheck-lane.mjs` 63.4s simulated PR run; real Playwright
3-worker parallel specs passing; UI suite full run reduced to 3.6 KB
stderr).
- Live GitHub PR CI run triggered on this draft PR to verify real runner
execution and measure before/after timings.

## Risks

- **Two-phase CI effect:** Because `.github/workflows/pr.yml` invokes
`pr-trusted.yml@master`, the workflow-level changes (removing Grok
clean-npm install from PR `Build`, path-gating `Canary Dry Run`/`Runner
support suite`/`general-chat`/`ci:runner-package`, passing
`CI_PLAN`/`PAPERCLIP_CI_BASE_SHA`/`PAPERCLIP_CI_FULL`, and restoring
`e2e-ui-dist`) take full effect only after merging to `master` (and
`e2e-ui-dist` warms on the first `master` push; until then `e2e_shards`
cleanly falls back to inline UI build). Furthermore, this PR modifies
global CI inputs (`turbo.json`, `scripts/**`, `.github/**`), so its own
PR CI runs the full matrix.
- **Nightly soak demotion:** The 61 real-clock soak suites in
`scripts/ci/nightly-only-suites.json` still run on every `master` push
(`release-verify.yml`), `cloud-readiness.yml`, local `pnpm test:run`,
and `full-ci`-labeled PRs, so regressions are caught post-merge rather
than blocking ordinary PRs.
- **Duration manifest rebalance:** Post-merge, the weekly
`ci-test-durations.yml` refresh will recalibrate shard weights to
reflect shared-Postgres timings for optimal LPT balance.
- **No product runtime or DB schema changes:** All changes are confined
to CI workflows, build/test orchestration scripts, test setup, test
suites, and feature-map references.

## Model Used

- Google Gemini 4 Neon (`Gemini 4 Neon (High)`), Google DeepMind, with
repository tools, code execution, and multi-agent swarm coordination.

## 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-23 21:11:57 -06:00

399 lines
26 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { ghApi, resetGhApiForTests } from "./gh-api.mjs";
import OversizedSpecReporter from "./oversized-test-files-playwright.mjs";
import OversizedTestFileReporter, { oversizedAnnotation, oversizedThresholdMs } from "./oversized-test-files.mjs";
import { assertManifestSource, attributeSpec, collectMergedPrSamples, completeShardSet, e2eShardJob, parseE2eLog, parseRunnerLog,
runnerInventory, runnerPackageJob, validatePrRun, validatePull } from "./pr-run-durations.mjs";
import { generalServerJob, generalServerShardCount, oversizedFiles, oversizedPlaceholder, parseArgs, parseTimings, renderPrBody, serverLane,
updatedDurations } from "./refresh-test-durations.mjs";
import { timingPrefix } from "./test-timing-reporter.mjs";
const esc = "\u001b";
const sha = character => character.repeat(40);
const stamp = seconds => new Date(Date.UTC(2026, 10, 6, 21, 0, 0) + seconds * 1000).toISOString().replace("Z", "0000Z");
const logLines = lines => lines.map(([seconds, text]) => `${stamp(seconds)} ${text}`).join("\n");
test("gh api opts into escape sequences, falls back for older gh, and strips colour from logs", async () => {
resetGhApiForTests();
const calls = [];
const modern = async (command, args) => {
calls.push(args);
return { stdout: `${esc}[32m ✓${esc}[39m src/a.test.ts (1 test) 5ms` };
};
assert.equal(await ghApi("/repos/x/actions/jobs/1/logs", { json: false, run: modern }), " ✓ src/a.test.ts (1 test) 5ms");
assert.deepEqual(calls[0], ["api", "--allow-escape-sequences", "/repos/x/actions/jobs/1/logs"]);
resetGhApiForTests();
calls.length = 0;
const legacy = async (command, args) => {
calls.push(args);
if (args.includes("--allow-escape-sequences")) {
throw Object.assign(new Error("Command failed"), { stderr: "unknown flag: --allow-escape-sequences\n\nUsage: gh api <endpoint> [flags]" });
}
return { stdout: "{\"ok\":true}" };
};
assert.deepEqual(await ghApi("/a", { run: legacy }), { ok: true });
assert.deepEqual(await ghApi("/b", { run: legacy }), { ok: true });
// The unsupported flag is tried once, then dropped for the process.
assert.deepEqual(calls, [["api", "--allow-escape-sequences", "/a"], ["api", "/a"], ["api", "/b"]]);
resetGhApiForTests();
const failing = async () => { throw Object.assign(new Error("HTTP 404"), { stderr: "gh: Not Found (HTTP 404)" }); };
await assert.rejects(ghApi("/missing", { run: failing }), /HTTP 404/);
resetGhApiForTests();
});
test("gh api allows a large server shard log to finish downloading and never prints a partial log", async () => {
resetGhApiForTests();
const seen = [];
const capture = async (command, args, options) => {
seen.push(options);
return { stdout: "{}" };
};
await ghApi("/repos/x/actions/runs/1/jobs", { run: capture });
await ghApi("/repos/x/actions/jobs/1/logs", { json: false, run: capture });
// A 64 MB shard log took 59 s alone (actions run 43133035381); three at once
// overran the old 120 s limit and failed the weekly refresh.
assert.equal(seen[0].timeout, 120_000);
assert.ok(seen[1].timeout >= 600_000, `log timeout ${seen[1].timeout}`);
assert.ok(seen[1].maxBuffer >= 256 * 1024 * 1024, `log buffer ${seen[1].maxBuffer}`);
resetGhApiForTests();
const partial = "x".repeat(10_000);
const timedOut = async () => {
throw Object.assign(new Error(`Command failed: gh api /logs\n${partial}`),
{ killed: true, signal: "SIGTERM", stdout: partial, stderr: "" });
};
await assert.rejects(ghApi("/repos/x/actions/jobs/2/logs", { json: false, run: timedOut }), error => {
assert.match(error.message, /\/repos\/x\/actions\/jobs\/2\/logs failed \(killed by SIGTERM\)/);
assert.ok(!error.message.includes(partial));
assert.equal(error.stdout, undefined);
return true;
});
resetGhApiForTests();
});
test("server timing parsing tolerates colour codes in fetched logs", () => {
const file = "server/src/slow.test.ts";
const log = `${esc}[2m${stamp(0)}${esc}[22m ${timingPrefix}${JSON.stringify({ version: 1, file, durationMs: 360 })}`;
assert.deepEqual(parseTimings(log, new Set([file])).get(file), { ms: 360, complete: true });
});
const shardLine = "shard 2/4 specs: tests/e2e/alpha.spec.ts tests/e2e/smoke-lab-p1-p4.spec.ts tests/e2e/smoke-lab-p5-p7.spec.ts tests/e2e/gone.spec.ts";
const e2eLog = logLines([
[0, `${esc}[36;1mecho "shard 2/4 specs: $specs"${esc}[0m`],
[1, shardLine],
[2, "[WebServer] > vite build"],
[30, "Running 4 tests using 1 worker"],
[31, "[WebServer] ✓ 4 tests/e2e/alpha.spec.ts noise"],
[40, ` ${esc}[32m✓${esc}[39m 1 [chromium] › tests/e2e/alpha.spec.ts:9:1 › first (7.6s)`],
[45, " - 2 [chromium] › tests/e2e/alpha.spec.ts:20:1 › skipped test"],
[70, " ✓ 3 [chromium] › tests/e2e/smoke-lab.shared.ts:316:3 › Smoke Lab scenario catalog mirror (P5-P7) › records the P5-P7 lifecycle @smoke-lab (24.0s)"],
[75, " ✓ 4 [chromium] › tests/e2e/gone.spec.ts:1:1 › removed later (4.0s)"],
[76, " 1 skipped"],
[76, " 3 passed (46.0s)"],
]);
test("e2e weights are gaps between Playwright results, attributed to the running spec", () => {
const inventory = new Set(["tests/e2e/alpha.spec.ts", "tests/e2e/smoke-lab-p1-p4.spec.ts", "tests/e2e/smoke-lab-p5-p7.spec.ts"]);
const parsed = parseE2eLog(e2eLog, inventory);
assert.deepEqual(Object.fromEntries(parsed), {
"tests/e2e/alpha.spec.ts": { ms: 15_000, complete: true },
"tests/e2e/smoke-lab-p5-p7.spec.ts": { ms: 25_000, complete: true },
});
assert.throws(() => parseE2eLog(e2eLog.replace("Running 4 tests", "Running 5 tests"), inventory), /Parsed 4 of 5/);
assert.throws(() => parseE2eLog(e2eLog.replace("using 1 worker", "using 2 workers"), inventory), /single Playwright worker/);
assert.throws(() => parseE2eLog(logLines([[0, shardLine]]), inventory), /No Playwright run/);
assert.throws(() => parseE2eLog(e2eLog.replace("tests/e2e/gone.spec.ts:1:1", "tests/e2e/elsewhere.spec.ts:1:1"), inventory),
/not in this shard/);
});
test("shared-file tests map to exactly one shard spec", () => {
const specs = ["tests/e2e/smoke-lab-p1-p4.spec.ts", "tests/e2e/smoke-lab-p5-p7.spec.ts", "tests/e2e/agent-chat-projects.spec.ts"];
assert.equal(attributeSpec("tests/e2e/smoke-lab.shared.ts", "Smoke Lab (P1-P4) › records", specs), specs[0]);
assert.equal(attributeSpec("tests/e2e/agent-chat.shared.ts", "anything", specs), specs[2]);
assert.throws(() => attributeSpec("tests/e2e/smoke-lab.shared.ts", "no label", specs), /Cannot attribute/);
assert.throws(() => attributeSpec("tests/e2e/helpers/x.ts", "t", specs), /Cannot attribute/);
assert.throws(() => attributeSpec("tests/e2e/smoke-lab.shared.ts", "(P1-P4)", null), /No shard spec list/);
});
const runnerLog = logLines([
[0, " RUN v5.0.0 /home/runner/_work/paperclip/paperclip/packages/paperclip-runner"],
[10, ` ${esc}[32m✓${esc}[39m src/live/runnerd-codex-transport.test.ts ${esc}[2m(257 tests)${esc}[22m 126679ms`],
[11, " ✓ src/control-plane/acpx-controller-recovery.test.ts (11 tests | 1 skipped) 78087ms"],
[12, " ✓ scripts/vitest-sequencer.test.mjs (3 tests) 12ms"],
[12, " ✓ a slow test inside a file 5000ms"],
[13, " ✓ src/deleted.test.ts (1 test) 9ms"],
[20, " Test Files 4 passed | 1 skipped (5)"],
[20, " Tests 272 passed | 1 skipped (273)"],
]);
test("Runner weights come from Vitest per-file lines and must account for every passed file", () => {
const inventory = new Set(["packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts",
"packages/paperclip-runner/src/control-plane/acpx-controller-recovery.test.ts",
"packages/paperclip-runner/scripts/vitest-sequencer.test.mjs"]);
assert.deepEqual(Object.fromEntries(parseRunnerLog(runnerLog, inventory)), {
"packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts": { ms: 126_679, complete: false },
"packages/paperclip-runner/src/control-plane/acpx-controller-recovery.test.ts": { ms: 78_087, complete: false },
"packages/paperclip-runner/scripts/vitest-sequencer.test.mjs": { ms: 12, complete: false },
});
assert.throws(() => parseRunnerLog(runnerLog.replace("4 passed", "5 passed"), inventory), /Parsed 4 of 5/);
assert.throws(() => parseRunnerLog(runnerLog.replace(/ Test Files.*\n/, ""), inventory), /No Vitest summary/);
assert.throws(() => parseRunnerLog(runnerLog.replace("src/deleted.test.ts", "src/../../x.test.ts"), inventory));
});
test("the Runner inventory follows the package's Vitest include list", () => {
const inventory = runnerInventory();
assert.ok(inventory.size > 100, `unexpectedly small Runner inventory: ${inventory.size}`);
assert.ok(inventory.has("packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts"));
assert.ok(inventory.has("packages/paperclip-runner/scripts/vitest-sequencer.test.mjs"));
// node --test files in the same package are not Vitest weights.
assert.ok(!inventory.has("packages/paperclip-runner/scripts/vitest-sequencer.mjs"));
assert.ok(![...inventory].some(file => file.startsWith("packages/paperclip-runner/test/")));
});
test("job names select complete, successful shard sets only", () => {
assert.deepEqual(e2eShardJob("ci / e2e shard (3/8)"), { index: 3, count: 8 });
assert.equal(e2eShardJob("ci / e2e"), null);
assert.deepEqual(runnerPackageJob("ci / Verify Paperclip Runner (vitest package)"), { index: 1, count: 1 });
assert.deepEqual(runnerPackageJob("ci / Verify Paperclip Runner (package (2/3))"), { index: 2, count: 3 });
// The lane labels that #19646 shipped keep the "vitest" prefix.
assert.deepEqual(runnerPackageJob("ci / Verify Paperclip Runner (vitest package (3/3))"), { index: 3, count: 3 });
assert.equal(runnerPackageJob("ci / Verify Paperclip Runner (vitest native server)"), null);
assert.equal(runnerPackageJob("ci / Verify Paperclip Runner (vitest native server)"), null);
const job = (name, conclusion = "success") => ({ name, conclusion });
const shards = [job("ci / e2e shard (1/2)"), job("ci / e2e shard (2/2)"), job("ci / build")];
assert.equal(completeShardSet(shards, e2eShardJob).length, 2);
assert.equal(completeShardSet(shards.slice(1), e2eShardJob), null);
assert.equal(completeShardSet([shards[0], job("ci / e2e shard (2/2)", "skipped")], e2eShardJob), null);
assert.equal(completeShardSet([shards[0], shards[1], shards[1]], e2eShardJob), null);
assert.equal(completeShardSet([job("ci / build")], e2eShardJob), null);
});
const pull = (number, head, merge, extra = {}) => ({ number, merged_at: `2026-11-0${number % 9 + 1}T00:00:00Z`,
base: { ref: "master", repo: { id: 1170821064 } }, head: { sha: head }, merge_commit_sha: merge, ...extra });
const prRun = (id, head, extra = {}) => ({ id, run_attempt: 1, head_sha: head, event: "pull_request", path: ".github/workflows/pr.yml",
status: "completed", conclusion: "success", html_url: `https://example.test/${id}`,
repository: { id: 1170821064, full_name: "paperclipai/paperclip" }, ...extra });
test("merged-PR runs must be successful pull_request runs of pr.yml at the PR's final head", () => {
const merged = pull(1, sha("a"), sha("b"));
validatePull(merged);
validatePrRun(prRun(5, sha("a")), merged);
for (const override of [{ merged_at: null }, { base: { ref: "release", repo: { id: 1170821064 } } },
{ base: { ref: "master", repo: { id: 7 } } }, { merge_commit_sha: null }]) {
assert.throws(() => validatePull({ ...merged, ...override }));
}
for (const override of [{ head_sha: sha("c") }, { event: "push" }, { path: ".github/workflows/pr-trusted.yml" },
{ conclusion: "failure" }, { status: "in_progress" }, { repository: { id: 7, full_name: "fork/paperclip" } }, { run_attempt: 0 }]) {
assert.throws(() => validatePrRun(prRun(5, sha("a"), override), merged));
}
});
test("collection skips unmerged, absent, stale-head and incomplete runs, and samples each lane per run", async () => {
const api = "/repos/paperclipai/paperclip";
const pulls = [pull(1, sha("1"), sha("a")), pull(2, sha("2"), sha("b")), pull(3, sha("3"), sha("c")),
{ ...pull(4, sha("4"), sha("d")), merged_at: null }, pull(5, sha("5"), sha("e"))];
const e2eJobs = [{ id: 101, name: "ci / e2e shard (1/1)" }, { id: 102, name: "ci / Verify Paperclip Runner (vitest package)" }];
const responses = {
[`${api}/pulls?state=closed&base=master&sort=updated&direction=desc&per_page=40`]: pulls,
// PR 1 has only a run of an earlier push; PR 2 is newest-first; PR 5 lacks a Runner job.
[`${api}/actions/workflows/pr.yml/runs?head_sha=${sha("1")}&event=pull_request&status=success&per_page=20`]: { workflow_runs: [prRun(11, sha("9"))] },
[`${api}/actions/workflows/pr.yml/runs?head_sha=${sha("2")}&event=pull_request&status=success&per_page=20`]: { workflow_runs: [prRun(20, sha("2")), prRun(21, sha("2"))] },
[`${api}/actions/workflows/pr.yml/runs?head_sha=${sha("5")}&event=pull_request&status=success&per_page=20`]: { workflow_runs: [prRun(50, sha("5"))] },
[`${api}/actions/runs/21/jobs?filter=latest&per_page=100&page=1`]: { jobs: e2eJobs.map(job => ({ ...job, run_id: 21, conclusion: "success" })) },
[`${api}/actions/runs/50/jobs?filter=latest&per_page=100&page=1`]: { jobs: [{ id: 501, name: "ci / e2e shard (1/1)", run_id: 50, conclusion: "success" }] },
[`${api}/actions/jobs/101/logs`]: e2eLog,
[`${api}/actions/jobs/102/logs`]: runnerLog,
[`${api}/actions/jobs/501/logs`]: e2eLog.replace("Running 4 tests", "Running 9 tests"),
};
const requested = [];
const gh = async endpoint => {
requested.push(endpoint);
assert.ok(endpoint in responses, `unexpected request ${endpoint}`);
return responses[endpoint];
};
const warnings = [];
const lanes = [
{ name: "e2e", classify: e2eShardJob, parse: parseE2eLog, inventory: new Set(["tests/e2e/alpha.spec.ts"]) },
{ name: "runner", classify: runnerPackageJob, parse: parseRunnerLog,
inventory: new Set(["packages/paperclip-runner/scripts/vitest-sequencer.test.mjs"]) },
];
const result = await collectMergedPrSamples({ gh, lanes, isMerged: merge => merge !== sha("c"), log: line => warnings.push(line) });
assert.deepEqual(result.e2e.sources.map(source => source.run), [21]);
assert.deepEqual(result.runner.sources, [{ pull: 2, run: 21, attempt: 1, sha: sha("2"), url: "https://example.test/21" }]);
// The checked-in manifest test uses this same check, so the format the
// collector writes stays accepted even while no manifest carries it yet.
for (const source of [...result.e2e.sources, ...result.runner.sources]) assertManifestSource(source);
assertManifestSource({ run: 21, attempt: 1, sha: sha("2"), url: "https://example.test/21" });
for (const bad of [{ run: 21, attempt: 1, sha: sha("2") }, { pull: 0, run: 21, attempt: 1, sha: sha("2"), url: "u" },
{ run: 21, pull: 2, attempt: 1, sha: sha("2"), url: "u" }]) assert.throws(() => assertManifestSource(bad));
assert.deepEqual(Object.fromEntries(result.e2e.samples[0]), { "tests/e2e/alpha.spec.ts": { ms: 15_000, complete: true } });
assert.match(warnings.join("\n"), /e2e: skipped run 50 for PR #5: Parsed 4 of 9/);
// PR 3 is not in this checkout and PR 4 never merged: neither is queried.
assert.ok(!requested.some(endpoint => endpoint.includes(sha("3")) || endpoint.includes(sha("4"))));
});
test("general server weights come from complete full-width PR shard sets that cover the lane", async () => {
assert.equal(generalServerShardCount(), 20);
assert.deepEqual(generalServerJob("ci / General tests (server (3/20))", 20), { index: 3, count: 20 });
for (const name of ["ci / General tests (server (1/3))", "ci / General tests (chat (1/5))", "ci / Serialized tests (1/9)"]) {
assert.equal(generalServerJob(name, 20), null);
}
const api = "/repos/paperclipai/paperclip";
const timing = (file, ms) => `2026-11-13T00:00:00.0000000Z ${timingPrefix}${JSON.stringify({ version: 1, file, durationMs: ms })}`;
const files = ["server/src/a.test.ts", "server/src/b.test.ts"];
const jobs = (run, ids) => ({ jobs: ids.map((id, index) => ({ id, run_id: run, conclusion: "success",
name: `ci / General tests (server (${index + 1}/${ids.length}))` })) });
const responses = {
[`${api}/pulls?state=closed&base=master&sort=updated&direction=desc&per_page=40`]: [pull(1, sha("1"), sha("a")),
pull(2, sha("2"), sha("b")), pull(3, sha("3"), sha("c")), pull(4, sha("4"), sha("d"))],
...Object.fromEntries([1, 2, 3, 4].map(n => [
`${api}/actions/workflows/pr.yml/runs?head_sha=${sha(String(n))}&event=pull_request&status=success&per_page=20`,
{ workflow_runs: [prRun(n * 10, sha(String(n)))] }])),
[`${api}/actions/runs/10/jobs?filter=latest&per_page=100&page=1`]: jobs(10, [101, 102]),
[`${api}/actions/runs/20/jobs?filter=latest&per_page=100&page=1`]: jobs(20, [201]),
[`${api}/actions/runs/30/jobs?filter=latest&per_page=100&page=1`]: jobs(30, [301, 302]),
[`${api}/actions/runs/40/jobs?filter=latest&per_page=100&page=1`]: jobs(40, [401, 402]),
[`${api}/actions/jobs/101/logs`]: timing(files[0], 1000),
[`${api}/actions/jobs/102/logs`]: timing(files[1], 3000),
[`${api}/actions/jobs/301/logs`]: timing(files[0], 2000),
[`${api}/actions/jobs/302/logs`]: "",
[`${api}/actions/jobs/401/logs`]: timing(files[0], 4000),
[`${api}/actions/jobs/402/logs`]: timing(files[1], 5000),
};
const requested = [];
const gh = async endpoint => {
requested.push(endpoint);
assert.ok(endpoint in responses, `unexpected request ${endpoint}`);
return responses[endpoint];
};
const lane = { name: "general", classify: name => generalServerJob(name, 2), parse: parseTimings,
inventory: new Set(files), maxRuns: 2, minFiles: 2 };
const result = await collectMergedPrSamples({ gh, lanes: [lane], isMerged: () => true, log: () => {} });
assert.deepEqual(result.general.sources.map(source => source.run), [40, 10]);
assert.deepEqual(result.general.samples.map(sample => Object.fromEntries([...sample].map(([file, value]) => [file, value.ms]))),
[{ [files[0]]: 4000, [files[1]]: 5000 }, { [files[0]]: 1000, [files[1]]: 3000 }]);
assert.ok(!requested.some(endpoint => endpoint.includes("/jobs/201/")), "a narrower selected run is never downloaded");
});
test("merged-PR manifests use the shared schema and only reorder placement", () => {
const inventory = new Set(["tests/e2e/a.spec.ts", "tests/e2e/b.spec.ts"]);
const samples = [new Map([["tests/e2e/a.spec.ts", { ms: 1000, complete: true }], ["tests/e2e/b.spec.ts", { ms: 50, complete: true }]]),
new Map([["tests/e2e/a.spec.ts", { ms: 3000, complete: true }]])];
const result = updatedDurations({ durations: {} }, inventory, samples, [{ pull: 1, run: 2 }], { comment: "c" });
assert.deepEqual(result, { $comment: "c", unit: "ms", sources: [{ pull: 1, run: 2 }],
coverage: { measured: 2, withSetup: 2, inventory: 2 }, durations: { "tests/e2e/a.spec.ts": 2000, "tests/e2e/b.spec.ts": 100 } });
const manifest = JSON.parse(readFileSync("scripts/e2e-shard-durations.json", "utf8"));
assert.match(manifest.$comment, /never change which specs run/);
assert.equal(manifest.unit, "ms");
assert.ok(manifest.sources.length >= 2 && manifest.sources.every(source => Number.isSafeInteger(source.pull)));
});
test("oversized files are listed in the refresh PR body", () => {
const template = readFileSync(".github/ci-duration-pr.md", "utf8");
assert.ok(template.includes(oversizedPlaceholder));
const manifests = [{ data: { durations: { "server/src/a.test.ts": 200_000, "server/src/b.test.ts": 1000 } } },
{ data: { durations: { "tests/e2e/c.spec.ts": 400_000 } } }];
const oversized = oversizedFiles(manifests, 180_000);
assert.deepEqual(oversized, [["tests/e2e/c.spec.ts", 400_000], ["server/src/a.test.ts", 200_000]]);
const body = renderPrBody(template, oversized, 180_000);
assert.ok(!body.includes(oversizedPlaceholder));
assert.match(body, /2 test file\(s\) exceed the 180s per-file budget/);
assert.match(body, / - `tests\/e2e\/c\.spec\.ts`: 400s\n - `server\/src\/a\.test\.ts`: 200s/);
assert.match(renderPrBody(template, [], 180_000), /No measured test file exceeds the 180s/);
assert.throws(() => renderPrBody("no placeholder", [], 180_000), /placeholder/);
});
test("master sampling recognizes only server timing jobs", () => {
assert.equal(serverLane("ci / General tests (server (3/12))"), "general");
assert.equal(serverLane("verify / Serialized tests (2/4)"), "serialized");
// Admission-only master runs have no server jobs and are passed over.
for (const name of ["Cloud candidate admission v1", "verify", "ci / General tests (ui (1/2))"]) assert.equal(serverLane(name), null);
});
test("refresh arguments keep explicit master run IDs and add dry-run, PR body and lane selection", () => {
const options = parseArgs(["123", "--dry-run", "--pr-body=/tmp/body.md", "--lanes=e2e,runner"]);
assert.deepEqual(options.runIds, ["123"]);
assert.equal(options.dryRun, true);
assert.equal(options.prBody, "/tmp/body.md");
assert.deepEqual([...options.lanes], ["e2e", "runner"]);
assert.throws(() => parseArgs(["--lanes=ui"]), /Unknown lane/);
assert.throws(() => parseArgs(["--force"]), /Unexpected argument/);
});
test("the refresh workflow may only commit the four timing manifests and uses the rendered PR body", () => {
const workflow = readFileSync(".github/workflows/ci-test-durations.yml", "utf8");
for (const file of ["scripts/general-server-shard-durations.json", "scripts/serialized-shard-durations.json",
"scripts/e2e-shard-durations.json", "packages/paperclip-runner/scripts/vitest-lane-durations.json"]) {
assert.ok(workflow.split(file).length >= 3, `${file} must be both allowed and staged`);
}
assert.match(workflow, /refresh-test-durations\.mjs "--pr-body=\$RUNNER_TEMP\/ci-duration-pr\.md"/);
assert.match(workflow, /--body-file "\$RUNNER_TEMP\/ci-duration-pr\.md"/);
});
test("oversized-file reporters warn above the configurable budget and never throw", () => {
assert.equal(oversizedThresholdMs({}), 180_000);
assert.equal(oversizedThresholdMs({ PAPERCLIP_CI_OVERSIZED_TEST_FILE_SECONDS: "90" }), 90_000);
for (const invalid of ["", "0", "-5", "soon"]) {
assert.equal(oversizedThresholdMs({ PAPERCLIP_CI_OVERSIZED_TEST_FILE_SECONDS: invalid }), 180_000);
}
assert.match(oversizedAnnotation("a,b:c.test.ts", 200_000, 180_000),
/^::warning file=a%2Cb%3Ac\.test\.ts,title=Oversized test file::a,b:c\.test\.ts took 200s, over the 180s per-file budget/);
const lines = [];
const reporter = new OversizedTestFileReporter({ environment: {}, write: line => lines.push(line), root: "/repo" });
const module = (file, total, state = "passed") => ({ moduleId: `/repo/${file}`, state: () => state,
diagnostic: () => ({ duration: total - 3, collectDuration: 1, setupDuration: 1, prepareDuration: 1, environmentSetupDuration: 0 }) });
reporter.onTestModuleEnd(module("server/src/slow.test.ts", 180_001));
reporter.onTestModuleEnd(module("server/src/failed-slow.test.ts", 200_000, "failed"));
reporter.onTestModuleEnd(module("server/src/fast.test.ts", 180_000));
reporter.onTestModuleEnd(module("server/src/skipped.test.ts", 900_000, "skipped"));
reporter.onTestModuleEnd({ moduleId: "/repo/x", state: () => { throw new Error("broken"); } });
assert.deepEqual(lines.map(line => /file=([^,]+)/.exec(line)[1]), ["server/src/slow.test.ts", "server/src/failed-slow.test.ts"]);
lines.length = 0;
const custom = new OversizedTestFileReporter({ environment: { PAPERCLIP_CI_OVERSIZED_TEST_FILE_SECONDS: "60" },
write: line => lines.push(line), root: "/repo" });
custom.onTestModuleEnd(module("server/src/medium.test.ts", 61_000));
assert.equal(lines.length, 1);
lines.length = 0;
const playwright = new OversizedSpecReporter({ environment: {}, write: line => lines.push(line), root: "/repo" });
assert.equal(playwright.printsToStdio(), false);
const spec = file => ({ location: { file: `/repo/${file}` } });
playwright.onTestEnd(spec("tests/e2e/long.spec.ts"), { status: "passed", duration: 100_000 });
playwright.onTestEnd(spec("tests/e2e/long.spec.ts"), { status: "passed", duration: 90_000 });
playwright.onTestEnd(spec("tests/e2e/long.spec.ts"), { status: "skipped", duration: 500_000 });
playwright.onTestEnd(spec("tests/e2e/short.spec.ts"), { status: "passed", duration: 170_000 });
playwright.onEnd();
assert.equal(lines.length, 1);
assert.match(lines[0], /^::warning file=tests\/e2e\/long\.spec\.ts,.*took 190s/);
// Two specs that declare their tests through one shared helper are timed
// per spec, not added together under the helper.
lines.length = 0;
const shared = new OversizedSpecReporter({ environment: {}, write: line => lines.push(line), root: "/repo" });
const viaHelper = specPath => ({
location: { file: "/repo/tests/e2e/smoke-lab.shared.ts" },
parent: { type: "describe", location: { file: "/repo/tests/e2e/smoke-lab.shared.ts" },
parent: { type: "file", location: { file: `/repo/${specPath}` }, parent: { type: "project" } } },
});
shared.onTestEnd(viaHelper("tests/e2e/smoke-lab-p1-p4.spec.ts"), { status: "passed", duration: 120_000 });
shared.onTestEnd(viaHelper("tests/e2e/smoke-lab-p5-p7.spec.ts"), { status: "passed", duration: 120_000 });
shared.onEnd();
assert.deepEqual(lines, [], "neither spec is over the limit; the helper must not sum them");
shared.onTestEnd(viaHelper("tests/e2e/smoke-lab-p5-p7.spec.ts"), { status: "passed", duration: 70_000 });
shared.onEnd();
assert.equal(lines.length, 1);
assert.match(lines[0], /^::warning file=tests\/e2e\/smoke-lab-p5-p7\.spec\.ts,.*took 190s/);
});
test("CI test configs wire the oversized-file reporters for GitHub Actions", () => {
assert.match(readFileSync("vitest.config.ts", "utf8"), /GITHUB_ACTIONS === "true"[\s\S]{0,120}oversized-test-files\.mjs/);
assert.match(readFileSync("packages/paperclip-runner/vitest.config.ts", "utf8"), /GITHUB_ACTIONS === "true"[^\n]*oversized-test-files\.mjs/);
assert.match(readFileSync("tests/e2e/playwright.config.ts", "utf8"), /GITHUB_ACTIONS === "true"[\s\S]{0,120}oversized-test-files-playwright\.mjs/);
});