Files
PaperClipAI/scripts/e2e-shard.mjs
T
8bf0646796 perf(ci): split e2e serial specs across two hosted shards (#23289)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The PR workflow runs the Playwright e2e suite in shards.
`scripts/e2e-shard.mjs` plans the shards from recorded spec durations.
> - On GitHub-hosted 4-vCPU runners (4 shards), the planner puts all 16
serial specs on one shard.
> - That serial shard is the longest check in each PR run. It takes a
median of 11.2m (up to 14.4m). The three parallel shards finish in about
5m.
> - The duration weights come from 8-vCPU runners. On hosted runners,
serial specs run slower than their weights and parallel specs run
faster. The planner thinks one serial shard is fine (529s planned
against 363s), but the real times are 672s against 318s.
> - This pull request adds a serial slowdown factor that is calibrated
from hosted runs. The planner now puts the serial specs on two shards.
> - The benefit is that the longest e2e shard on hosted runs drops from
a median of ~11.2m to ~7.9m (about 3.3m saved; about 6m saved on slow
runs).

## Linked Issues or Issue Description

No public issue exists. Inline issue, following the [enhancement
template](https://github.com/paperclipai/paperclip/blob/master/.github/ISSUE_TEMPLATE/enhancement.yml):

**What existing behavior does this improve?**
The e2e shard planner (`scripts/e2e-shard.mjs`) for GitHub-hosted 4-vCPU
PR runs.

**Subsystem affected**
CI / e2e test sharding.

**Current behavior**
On 4-vCPU hosted runners the planner puts all 16 serial specs on one
shard. `e2e shard (1/4)` is the longest check in hosted PR runs and
takes about 2x as long as the other shards.

**Proposed behavior**
Add a serial slowdown factor for 2-worker runners only, so the planner
splits serial specs across two shards.

**Reason and benefit**
The longest hosted e2e shard drops from a median of ~11.2m to ~7.9m
(about 3.3m saved per hosted PR run, ~5–6m on slow runs).

**Breaking changes**
None. The 16-shard AWS plan does not change, and the factor can be
overridden with `--serial-slowdown` or `PAPERCLIP_E2E_SERIAL_SLOWDOWN`.

**Additional context**
Playwright wall time per shard in five recent hosted PR runs:

| Run | Serial shard (1 worker) | Parallel shards (2 workers) |
| --- | --- | --- |
| 46423658483 | 14.4m | 4.5m, 4.9m, 7.9m |
| 46422531627 | 11.7m | 4.3m, 5.4m, 5.7m |
| 46420745048 | 10.9m | 5.3m, 5.6m, 5.8m |
| 46419917065 | 7.5m | 3.6m, 4.0m, 5.8m |
| 46409346442 | 11.2m | 4.9m, 5.3m, 5.8m |

Median: the serial shard is 1.27x its plan estimate and the parallel
shards are 0.88x theirs. Relative to parallel work, serial work costs
~1.45x more than the plan assumes.

## What Changed

- `scripts/e2e-shard.mjs`: Added `SERIAL_SLOWDOWN_2W = 1.45` and
`resolveSerialSlowdown(cpus)`. The factor applies only when Playwright
uses 2 workers (4–5 vCPU). `partitionE2eShards` accepts a
`serialSlowdown` option and multiplies the serial-shard estimate by it.
- `scripts/e2e-shard.mjs` CLI: Added `--serial-slowdown` and
`PAPERCLIP_E2E_SERIAL_SLOWDOWN` overrides. These work the same way as
the existing `--parallel-speedup` overrides. The default comes from the
runner CPU count.
- `scripts/__tests__/e2e-shard.test.mjs`: Added tests for
`resolveSerialSlowdown`, a test that checks that the 4-shard hosted plan
uses at least two serial shards, and a CLI test that simulates a 4-vCPU
runner with no overrides and checks that the automatic default splits
serial specs across exactly two shards.

## Verification

- `node --test scripts/__tests__/e2e-shard.test.mjs`: all 21 tests pass.
Red-green: with the 2-worker default set back to 1, the new CLI test
fails (1 serial shard instead of 2).
- Red-green: with `serialSlowdown: 1` the hosted plan has one serial
shard (16 specs), so the new assertion fails. With 1.45 it has two
serial shards (8 specs each).
- Projection: apply the measured hosted ratios (serial 1.27x, parallel
0.88x) to the plan. The old plan projects to 11.2m / 5.3m / 5.3m / 5.3m,
which is the same as the measured medians. The new plan projects to 5.6m
/ 5.6m / 7.9m / 7.9m.
- The 16-shard AWS plan (8 vCPU, 4 workers) does not change. Its maximum
estimate stays at 79s.
- Note: `pr.yml` runs `pr-trusted.yml` and this script from `master`.
The new split takes effect only after merge.

## Risks

- Low risk. The change affects only how specs are put on shards. The
same specs run, and serial specs never share a shard with parallel
specs.
- The two parallel shards each run about 22 specs. Their median projects
to ~7.9m, up from ~5.3m. This is still shorter than the current serial
shard.
- If hosted runner performance changes, the factor can drift. The
`PAPERCLIP_E2E_SERIAL_SLOWDOWN` override lets you tune it without a code
change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with tool use (shell, GitHub CLI)
in Claude Code.

## 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 00:33:00 +00:00

180 lines
7.4 KiB
JavaScript

import { readdirSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadShardDurations, partitionGeneralServerSuites } from "./general-server-shard.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(HERE, "..");
const E2E_DIR = path.join(REPO_ROOT, "tests", "e2e");
const DURATIONS_MANIFEST = path.join(HERE, "e2e-shard-durations.json");
// Specs the default local_trusted Playwright project deliberately skips. Keep
// this in sync with `testIgnore` in tests/e2e/playwright.config.ts — the unit
// test in scripts/__tests__/e2e-shard.test.mjs fails if the two ever drift.
export const IGNORED_SPECS = ["in-feed-native/**", "multi-user.spec.ts", "multi-user-authenticated.spec.ts"];
// Specs that mutate instance-wide state on the shared throwaway server or
// assert strict real-time latency / focus restoration sensitive to concurrent
// Chromium contention, and therefore must run with `workers: 1`. Keep in sync
// with `SERIAL_SPECS` in tests/e2e/playwright.config.ts —
// `scripts/__tests__/e2e-shard.test.mjs` fails if the two ever drift.
export const SERIAL_SPECS = [
"agent-chat-projects-handoff.spec.ts",
"agent-chat-projects.spec.ts",
"agent-chat-sessions-navigation.spec.ts",
"agent-chat-sessions.spec.ts",
"agent-configuration-revisions.spec.ts",
"agent-configuration.spec.ts",
"ai-personal-connection-recovery.spec.ts",
"cases-read-only.spec.ts",
"classic-workspace.spec.ts",
"composer-stop.spec.ts",
"connection-intents.spec.ts",
"document-image-gallery.spec.ts",
"onboarding-resume.spec.ts",
"onboarding.spec.ts",
"smoke-lab-p1-p4.spec.ts",
"smoke-lab-p5-p7.spec.ts",
];
export const DEFAULT_PARALLEL_WORKERS = 2;
export const EFFECTIVE_PARALLEL_SPEEDUP = 1.85;
export const EFFECTIVE_PARALLEL_SPEEDUP_4W = 3.2;
export function resolveEffectiveParallelSpeedup(cpus = os.availableParallelism()) {
const workers = Math.max(1, Math.min(4, Math.floor(cpus / 2)));
if (workers >= 4) return EFFECTIVE_PARALLEL_SPEEDUP_4W;
if (workers === 3) return 2.55;
if (workers === 2) return EFFECTIVE_PARALLEL_SPEEDUP;
return 1;
}
export const SERIAL_SLOWDOWN_2W = 1.45;
export function resolveSerialSlowdown(cpus = os.availableParallelism()) {
const workers = Math.max(1, Math.min(4, Math.floor(cpus / 2)));
return workers === 2 ? SERIAL_SLOWDOWN_2W : 1;
}
export function isSerialE2eSpec(file) {
return SERIAL_SPECS.includes(path.posix.basename(file.split(path.sep).join("/")));
}
// Enumerates the specs the default e2e lane actually runs, as repo-relative
// paths so the output can be handed straight to `playwright test`.
export function listE2eSpecs(e2eDir = E2E_DIR, repoRoot = REPO_ROOT) {
return readdirSync(e2eDir)
.filter((entry) => entry.endsWith(".spec.ts") && !IGNORED_SPECS.includes(entry))
.map((entry) => path.relative(repoRoot, path.join(e2eDir, entry)).split(path.sep).join("/"))
.sort((a, b) => a.localeCompare(b));
}
// Isolate instance-mutating specs onto dedicated serial shards so every other
// shard runs purely parallel-safe specs with `workers > 1` and `fullyParallel`.
// Choose the serial/parallel shard split that minimizes projected max wall-clock
// across all shards (serial shards run at 1x, parallel shards at 1/parallelWorkers).
export function partitionE2eShards(
files,
shardCount,
durations = {},
{ parallelWorkers = EFFECTIVE_PARALLEL_SPEEDUP, serialSlowdown = 1 } = {},
) {
const serialFiles = files.filter(isSerialE2eSpec);
const parallelFiles = files.filter((file) => !isSerialE2eSpec(file));
if (shardCount <= 1 || serialFiles.length === 0 || parallelFiles.length === 0) {
const mode = serialFiles.length > 0 ? "serial" : "parallel";
const effectiveWorkers = mode === "parallel" ? parallelWorkers : 1;
return partitionGeneralServerSuites(files, shardCount, durations).map((shard) => ({
...shard,
mode,
estimatedWallMs: shard.totalWeight / effectiveWorkers,
}));
}
const maxSerialShards = Math.min(serialFiles.length, shardCount - 1);
let bestPlan = null;
for (let serialShardCount = 1; serialShardCount <= maxSerialShards; serialShardCount += 1) {
const parallelShardCount = shardCount - serialShardCount;
if (parallelShardCount > parallelFiles.length) continue;
const serialShards = partitionGeneralServerSuites(serialFiles, serialShardCount, durations).map((shard) => ({
...shard,
mode: "serial",
estimatedWallMs: shard.totalWeight * serialSlowdown,
}));
const parallelShards = partitionGeneralServerSuites(parallelFiles, parallelShardCount, durations).map((shard) => ({
...shard,
mode: "parallel",
estimatedWallMs: shard.totalWeight / parallelWorkers,
}));
const combined = [...serialShards, ...parallelShards];
const maxWallMs = Math.max(...combined.map((shard) => shard.estimatedWallMs));
if (!bestPlan || maxWallMs < bestPlan.maxWallMs) {
bestPlan = { maxWallMs, shards: combined };
}
}
return bestPlan.shards;
}
// Playwright's own --shard balances by test count, which is useless here: spec
// durations vary by 80x and a handful of specs mutate instance-wide settings.
// Partition into dedicated serial and parallel shards weighted by estimated
// wall-clock time so every runner finishes together.
export function selectE2eShard(files, shardIndex, shardCount, durations = {}, options = {}) {
return partitionE2eShards(files, shardCount, durations, options)[shardIndex].files;
}
function parseArgs(argv) {
const args = { shardIndex: 0, shardCount: 1, parallelSpeedup: null, serialSlowdown: null };
for (let index = 0; index < argv.length; index += 1) {
if (argv[index] === "--shard-index") args.shardIndex = Number(argv[index + 1]);
if (argv[index] === "--shard-count") args.shardCount = Number(argv[index + 1]);
if (argv[index] === "--parallel-speedup") args.parallelSpeedup = Number(argv[index + 1]);
if (argv[index] === "--serial-slowdown") args.serialSlowdown = Number(argv[index + 1]);
}
return args;
}
function main(argv) {
const { shardIndex, shardCount, parallelSpeedup, serialSlowdown } = parseArgs(argv);
if (!Number.isInteger(shardCount) || shardCount < 1) {
throw new Error(`--shard-count must be a positive integer, got ${shardCount}`);
}
if (!Number.isInteger(shardIndex) || shardIndex < 0 || shardIndex >= shardCount) {
throw new Error(`--shard-index must be in [0, ${shardCount}), got ${shardIndex}`);
}
const envSpeedup = Number.parseFloat(process.env.PAPERCLIP_E2E_PARALLEL_SPEEDUP ?? "");
const effectiveSpeedup =
Number.isFinite(parallelSpeedup) && parallelSpeedup > 0
? parallelSpeedup
: Number.isFinite(envSpeedup) && envSpeedup > 0
? envSpeedup
: resolveEffectiveParallelSpeedup();
const envSlowdown = Number.parseFloat(process.env.PAPERCLIP_E2E_SERIAL_SLOWDOWN ?? "");
const effectiveSlowdown =
Number.isFinite(serialSlowdown) && serialSlowdown > 0
? serialSlowdown
: Number.isFinite(envSlowdown) && envSlowdown > 0
? envSlowdown
: resolveSerialSlowdown();
const specs = listE2eSpecs();
const durations = loadShardDurations(DURATIONS_MANIFEST);
process.stdout.write(
`${selectE2eShard(specs, shardIndex, shardCount, durations, {
parallelWorkers: effectiveSpeedup,
serialSlowdown: effectiveSlowdown,
}).join(" ")}\n`,
);
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main(process.argv.slice(2));
}