Files
PaperClipAI/tests/e2e/playwright.config.ts
T
Dotta 0731cd3afc perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Pull-request CI checks run on every commit before maintainers can
merge code
> - PR #22679 cut PR CI from 15–30+ minutes down toward 4.5–5.5 minutes
on 4-core runners
> - Remaining wall-clock bottlenecks sit in unsharded `workspaces-b`,
serial typecheck preparation, E2E server/UI startup, fixed Vitest worker
caps, and remaining soak and duplicated UI tests
> - This pull request adds Phase 2 optimizations across server soak
triage, typecheck DAG overlap, E2E fast boot and shard balance, dynamic
CPU-aware workers, pure-Node workspace link preflight, UI pruning, and
permanent test-budget enforcement
> - The benefit is ordinary feature PRs finish in ~3.1–3.8 minutes on
4-core runners and scale automatically to ~2.0–3.0 minutes on 8-core
runners while keeping core invariants and nightly coverage intact

## Linked Issues or Issue Description

Refs #22679

**Problem Statement**
After #22679 landed, several PR lanes still took 4.5–6 minutes on 4-core
runners (`general-workspaces-b` ran unsharded, `Typecheck + Release
Registry` waited on a serial server build before starting UI and
test-program checks, E2E shards paid full `cli onboard` + minified UI
build overhead, and Vitest worker counts did not scale with runner CPU
count).

**Proposed Solution**
Split `general-workspaces-b` across two duration-balanced shards,
overlap typecheck preparation tasks behind a shared runner-vendor node,
replace E2E `onboard` with a direct template-PG boot + unminified inline
UI build, scale Vitest/Playwright/Typecheck workers dynamically by CPU
and RAM, replace `tsx` in workspace-link preflight with pure Node, prune
redundant mocked UI tests and additional real-clock server soak suites
(still run on `master`, `release-verify`, `cloud-readiness`, and
`PAPERCLIP_CI_FULL=1`), and add a permanent test-budget policy check.

**Expected Benefit**
Brings ordinary PR CI wall-clock down to ~3.1–3.8 minutes on 4-core
runners (and ~2.0–3.0 minutes on 8-core runners) with automated
guardrails against future test-time regressions.

## What Changed

- **Server soak triage & permanent test-budget guardrail
(`scripts/ci/nightly-only-suites.json`, `rules/test-budget.mdc`,
`.greptile/files.json`, `scripts/check-test-budget.mjs`,
`scripts/check-test-budget.test.mjs`,
`.github/workflows/pr-trusted.yml`):** Expanded the PR-excluded
soak/heavy-integration manifest to 568 genuine heavy suites (preserving
100% of company isolation, authz, checkout, approval, budget,
activity-log, security, telemetry, and serialized suites on every PR)
and wired `node scripts/check-test-budget.mjs` into the `policy` job.
- **Typecheck DAG overlap & CPU/RAM scaling
(`scripts/ci-typecheck-lane.mjs`, `scripts/typecheck-test-programs.mjs`,
`scripts/__tests__/ci-typecheck-lane.test.mjs`,
`scripts/typecheck-test-programs.test.mjs`):** Moved `build server
without type checks` and `check server runtime assets` out of serial
`prepare` into parallel DAG nodes behind `prepare runner vendor`, added
`computeResourceProfile` scaling across 2/4/8-core runners, and added
missing UI/Runner consumer routing inputs (`packages/paperclip-runner/`
for `@paperclipai/ui`, `packages/adapter-utils/` for Runner test
programs).
- **E2E fast boot, dynamic workers & 8-shard rebalance
(`tests/e2e/start-e2e-server.ts`, `tests/e2e/playwright.config.ts`,
`scripts/e2e-shard.mjs`, `scripts/e2e-shard-durations.json`,
`.github/workflows/pr-trusted.yml`,
`.github/workflows/release-verify.yml`):** Added direct throwaway
template-PG boot (`fsync=off`), unminified inline Vite fallback build,
dynamic parallel workers (`min(4, floor(cpus/2))`), empirical `1.5x`
parallel speedup weighting across 8 shards, targeted trims to slowest
E2E specs, and hashed workspace `package.json` manifests into the
`e2e-ui-dist-v2` cache key.
- **Dynamic Vitest workers, 2-shard `workspaces-b`, and pure-Node
preflight (`scripts/ci/vitest-workers.mjs`,
`scripts/ci/workspaces-b-shard.mjs`,
`scripts/ensure-workspace-package-links.mjs`,
`scripts/ci-dependency-cache.mjs`,
`packages/db/src/test-embedded-postgres.ts`,
`.github/ci-task-matrix.json`,
`.github/actions/setup-ci-dependencies/action.yml`, `package.json`):**
Scaled Vitest workers dynamically (`4→7` general, `3→5` serialized) with
`max_connections=300` before PostgreSQL start, split
`general-workspaces-b` into 2 duration-weighted shards
(backward-compatible unsharded for release workflows), replaced `tsx`
workspace-link preflight with pure Node (~29× faster), and parallelized
`ci-dependency-cache.mjs` child queries.
- **UI Vitest worker scaling, fake timers & E2E-duplicated suite pruning
(`ui/vitest.config.ts`, 4 `maps/` files, and UI test suites):** Scaled
UI `maxWorkers` dynamically, converted real-clock sleeps in kept suites
to fake timers, removed 34 E2E-duplicated mocked jsdom suites, and
updated corresponding `maps/` prose references.

## Verification

- `node --test .github/scripts/tests/ci-plan.test.mjs
.github/scripts/tests/ci-dependency-cache.test.mjs
.github/scripts/tests/pr-dependency-cache.test.mjs
scripts/__tests__/run-vitest-stable-shard.test.mjs
scripts/__tests__/run-vitest-stable-pr-mode.test.mjs
scripts/__tests__/ci-typecheck-lane.test.mjs
scripts/typecheck-test-programs.test.mjs
scripts/__tests__/e2e-shard.test.mjs scripts/check-test-budget.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs`: **160/160 PASS**
- `node scripts/check-test-budget.mjs`: **PASS** (`568` nightly suites
validated)
- `node scripts/check-maps.mjs`: **PASS** (`35 areas, 192 capability
IDs`)
- `pnpm --filter @paperclipai/ui typecheck` & `pnpm --filter
@paperclipai/db typecheck`: **PASS**
- Live CI verification runs on the new `pr-trusted.yml@master` (from
#22679) with `profile-ci` enabled to export the full job/step/file
waterfall to Honeycomb `paperclip-ci`.

## Risks

- Medium CI scope: touches workflow matrix partitioning, E2E startup,
and test runners; does not change production app runtime behavior.
- All PR-demoted soak suites continue to execute on `master`,
`release-verify`, `cloud-readiness`, local `pnpm test:run`, and
`PAPERCLIP_CI_FULL=1`.
- All new `policy` and `setup-ci-dependencies` commands keep
file-existence guards so reruns of older PR branches continue to work.

## Model Used

- Google Gemini (Antigravity swarm orchestrating specialized worker
agents with shell, file editing, and test execution tools) and Anthropic
Claude Opus (verification and optimization sub-agents).

## 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-24 10:53:19 -06:00

209 lines
8.9 KiB
TypeScript

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { defineConfig } from "@playwright/test";
// Use a dedicated port so e2e tests always start their own server in local_trusted mode,
// even when the dev server is running on :3100 in authenticated mode.
const PORT = Number(process.env.PAPERCLIP_E2E_PORT ?? 3199);
const BASE_URL = `http://127.0.0.1:${PORT}`;
const PAPERCLIP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-e2e-home-"));
const PAPERCLIP_INSTANCE_ID = "playwright-e2e";
const PAPERCLIP_CONFIG = path.join(PAPERCLIP_HOME, "instances", PAPERCLIP_INSTANCE_ID, "config.json");
const PAPERCLIP_AGENT_JWT_SECRET = process.env.PAPERCLIP_AGENT_JWT_SECRET ?? "playwright-e2e-agent-jwt-secret";
const PAPERCLIP_DECISION_SIGNING_SECRET =
process.env.PAPERCLIP_DECISION_SIGNING_SECRET ?? "playwright-e2e-decision-signing-secret";
const PAPERCLIP_TOOL_ACTION_SIGNING_SECRET =
process.env.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET ?? "playwright-e2e-tool-action-signing-secret";
const PLAYWRIGHT_CHANNEL = process.env.PAPERCLIP_PLAYWRIGHT_CHANNEL;
process.env.PAPERCLIP_HOME = PAPERCLIP_HOME;
process.env.PAPERCLIP_CONFIG = PAPERCLIP_CONFIG;
// Worker processes reload this config; retain the main process's server path
// for specs that seed historical database state in the throwaway instance.
process.env.PAPERCLIP_E2E_SERVER_CONFIG ??= PAPERCLIP_CONFIG;
// Specs that mint agent JWTs in-process (via createLocalAgentJwt) must derive
// the same per-instance signing key as the webServer, or verification fails
// with a 401 instead of authenticating as the agent.
process.env.PAPERCLIP_INSTANCE_ID = PAPERCLIP_INSTANCE_ID;
process.env.PAPERCLIP_AGENT_JWT_SECRET = PAPERCLIP_AGENT_JWT_SECRET;
process.env.PAPERCLIP_DECISION_SIGNING_SECRET = PAPERCLIP_DECISION_SIGNING_SECRET;
process.env.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET = PAPERCLIP_TOOL_ACTION_SIGNING_SECRET;
const REPO_ROOT = path.resolve(import.meta.dirname, "../..");
const UI_DIST_INDEX = path.join(REPO_ROOT, "server", "ui-dist", "index.html");
const SKIP_UI_BUILD = ["1", "true"].includes(
(process.env.PAPERCLIP_E2E_SKIP_UI_BUILD ?? "").trim().toLowerCase(),
);
if (SKIP_UI_BUILD && !fs.existsSync(UI_DIST_INDEX)) {
throw new Error(
`PAPERCLIP_E2E_SKIP_UI_BUILD is enabled, but prebuilt UI assets are missing at ${UI_DIST_INDEX}. ` +
"Build @paperclipai/ui into server/ui-dist first or unset PAPERCLIP_E2E_SKIP_UI_BUILD.",
);
}
// Specs that mutate instance-wide state on the shared throwaway server
// (server-read experimental flags or server-persisted workspace preferences)
// or assert strict real-time latency / focus restoration sensitive to
// multi-worker Chromium CPU contention. Keep in sync with `SERIAL_SPECS` in
// `scripts/e2e-shard.mjs` — `scripts/__tests__/e2e-shard.test.mjs` fails if
// the two ever drift.
export const SERIAL_SPECS = [
"agent-chat-projects.spec.ts",
"agent-chat-sessions.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.spec.ts",
"smoke-lab-p1-p4.spec.ts",
"smoke-lab-p5-p7.spec.ts",
];
function extractCliSpecBasenames(argv: string[]): string[] {
const specs: string[] = [];
for (let index = 2; index < argv.length; index += 1) {
const arg = argv[index]!;
if (arg === "--config" || arg === "-c" || arg === "--project" || arg === "--grep" || arg === "-g") {
index += 1;
continue;
}
if (arg.startsWith("-")) continue;
if (arg.endsWith(".spec.ts")) {
specs.push(path.basename(arg));
}
}
return specs;
}
function resolveExecutionMode(): { workers: number; fullyParallel: boolean } {
// Worker processes reload this config without the parent CLI spec filters.
// Cache the parent process's decision in env so workers agree with the runner.
if (
process.env.PAPERCLIP_E2E_RESOLVED_WORKERS &&
process.env.PAPERCLIP_E2E_RESOLVED_FULLY_PARALLEL
) {
return {
workers: Number(process.env.PAPERCLIP_E2E_RESOLVED_WORKERS),
fullyParallel: process.env.PAPERCLIP_E2E_RESOLVED_FULLY_PARALLEL === "true",
};
}
const cliSpecs = extractCliSpecBasenames(process.argv);
const serialSet = new Set(SERIAL_SPECS);
const includesSerial = cliSpecs.some((spec) => serialSet.has(spec));
const strictlyParallelSafe = cliSpecs.length > 0 && !includesSerial;
const explicitWorkers = Number.parseInt(process.env.PAPERCLIP_E2E_WORKERS ?? "", 10);
let workers: number;
let fullyParallel: boolean;
if (Number.isInteger(explicitWorkers) && explicitWorkers >= 1) {
workers = explicitWorkers;
fullyParallel = workers > 1 && !includesSerial;
} else if (strictlyParallelSafe) {
// Scale parallel Chromium workers dynamically with runner CPU cores while
// reserving headroom for the shared Node server + embedded Postgres:
// 4-vCPU runner -> 2 workers; 8-vCPU runner (c8i.2xlarge) -> 4 workers.
const cpus = os.availableParallelism();
workers = Math.max(1, Math.min(4, Math.floor(cpus / 2)));
fullyParallel = workers > 1;
} else {
workers = 1;
fullyParallel = false;
}
process.env.PAPERCLIP_E2E_RESOLVED_WORKERS = String(workers);
process.env.PAPERCLIP_E2E_RESOLVED_FULLY_PARALLEL = String(fullyParallel);
return { workers, fullyParallel };
}
const EXECUTION_MODE = resolveExecutionMode();
const UI_BUILD_COMMAND =
"node ui/node_modules/vite/bin/vite.js build ui --outDir ../server/ui-dist --emptyOutDir --minify false";
const SERVER_START_COMMAND =
"node cli/node_modules/tsx/dist/cli.mjs tests/e2e/start-e2e-server.ts";
const WEB_SERVER_COMMAND = SKIP_UI_BUILD
? SERVER_START_COMMAND
: `${UI_BUILD_COMMAND} && ${SERVER_START_COMMAND}`;
export default defineConfig({
testDir: ".",
testMatch: "**/*.spec.ts",
// These suites target dedicated multi-user configurations/ports and are
// intentionally not part of the default local_trusted e2e run.
testIgnore: ["in-feed-native/**", "multi-user.spec.ts", "multi-user-authenticated.spec.ts"],
timeout: 60_000,
expect: { timeout: 10_000 },
retries: 0,
// Parallel-safe shards run concurrently across multiple workers; shards or
// runs that include any spec in SERIAL_SPECS (or unfiltered full runs) fall
// back to 1 worker so server-level experimental flags cannot race mid-flight.
workers: EXECUTION_MODE.workers,
fullyParallel: EXECUTION_MODE.fullyParallel,
use: {
baseURL: BASE_URL,
headless: true,
screenshot: "only-on-failure",
trace: "on-first-retry",
},
projects: [
{
name: "chromium",
use: {
browserName: "chromium",
...(PLAYWRIGHT_CHANNEL ? { channel: PLAYWRIGHT_CHANNEL } : {}),
},
},
],
// The webServer directive bootstraps a throwaway instance and then starts it.
// `onboard --yes --run` works in a non-interactive temp PAPERCLIP_HOME.
webServer: {
cwd: REPO_ROOT,
// Exercise the shipped UI. Source-checkout onboarding otherwise enables
// Vite middleware: every reload traverses thousands of modules, including
// service-worker-intercepted requests, before React can even start.
// Build the server's first-choice static directory unless CI/caller already
// prebuilt server/ui-dist and opted in via PAPERCLIP_E2E_SKIP_UI_BUILD=1.
command: WEB_SERVER_COMMAND,
url: `${BASE_URL}/api/health`,
// Always boot a dedicated throwaway instance for e2e so browser tests
// never attach to the developer's active Paperclip home/server.
reuseExistingServer: false,
timeout: 120_000,
stdout: "pipe",
stderr: "pipe",
env: {
...process.env,
NODE_ENV: "test",
PAPERCLIP_UI_DEV_MIDDLEWARE: "false",
HEARTBEAT_SCHEDULER_INTERVAL_MS: process.env.HEARTBEAT_SCHEDULER_INTERVAL_MS ?? "10000",
NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --import=${path.resolve(import.meta.dirname, "fixtures/agent-chat-github.mjs")} --import=${path.resolve(import.meta.dirname, "fixtures/ai-connection-provider.mjs")}`,
PORT: String(PORT),
PAPERCLIP_OPEN_ON_LISTEN: "false",
PAPERCLIP_API_URL: BASE_URL,
PAPERCLIP_HOME,
PAPERCLIP_INSTANCE_ID,
PAPERCLIP_CONFIG,
PAPERCLIP_AGENT_JWT_SECRET,
PAPERCLIP_DECISION_SIGNING_SECRET,
PAPERCLIP_TOOL_ACTION_SIGNING_SECRET,
PAPERCLIP_BIND: "loopback",
PAPERCLIP_DEPLOYMENT_MODE: "local_trusted",
PAPERCLIP_DEPLOYMENT_EXPOSURE: "private",
},
},
outputDir: "./test-results",
reporter: [
["list"], ["html", { open: "never", outputFolder: "./playwright-report" }],
...(process.env.GITHUB_ACTIONS === "true"
? [[path.resolve(import.meta.dirname, "../../scripts/ci/oversized-test-files-playwright.mjs")] as [string]]
: []),
...(process.env.PAPERCLIP_CI_PROFILE === "true"
? [[path.resolve(import.meta.dirname, "../../scripts/ci-profile/playwright-reporter.mjs")] as [string]]
: []),
],
});