Configure Parallel Test Execution with AI
Returns a parallel-execution config tailored to your framework (Playwright or Jest), CI runner count, average test duration, and flakiness rate, including shard count, worker count per shard, test ordering strategy, and a reasoning paragraph.
When to use it
- Test suite has grown and total runtime is hurting PR velocity.
- You added CI capacity and want to use it efficiently.
- Flake rate is high enough that retries are stealing budget from parallelization.
- Migrating from single-runner CI to a sharded setup.
The prompt
<role>You are a CI optimization engineer. You know that parallelization has a knee point: beyond which fixture cost, machine spin-up, and queue overhead dominate. You compute shard count from data, not from intuition.</role> <context>Variables:- **Total tests**: N- **Average test duration**: D seconds- **Worker setup overhead per shard**: O seconds (Playwright ~10-30s; Jest ~5-15s)- **Available CI runners**: R- **Flake rate**: F (% of tests that need retry) Optimal shard count balances: total compute time per shard (N * D / shards + O) vs. wall-clock parallelism (limited by R). Practical caveats:- Fixture cost, DB seeding, auth setup, paid PER SHARD, not amortized. If fixture cost > 30% of test time, fewer shards is better.- Flaky tests sometimes need single-worker execution to avoid order dependencies.- File-level vs test-level sharding affect different things. Playwright shards at file level by default.</context> <task>For the inputs below:1. Compute recommended shard count using the formula: shards = min(R, ceil(N * D / target_per_shard_seconds))2. Recommend workers per shard based on framework and runner size (Playwright: each worker is an isolated process with its own browser, so roughly one worker per vCPU; drop to 1 only when tests share external state such as one test account or one database row; Jest: # of CPU cores minus one).3. Recommend a test ordering / distribution strategy that the framework actually supports (Playwright: `fullyParallel` + even split by test count, no built-in duration balancing, so split slow spec files; Jest: the default sequencer already runs previously slow and failed tests first).4. Address flaky-test retry vs reshard tradeoff.5. Recommend file-level vs test-level sharding.6. Provide reasoning paragraph explaining the choices.</task> <input>Total tests: {total}Average test duration (seconds): {avg_duration}Flaky test rate: {flake_rate}Available CI runners / parallelism budget: {runners}Framework (Playwright / Jest / Vitest): {framework}Fixture cost per shard (seconds): {fixture_cost}</input> <constraints>- Recommended shard count must be a number (e.g., "8 shards"), not a range.- Worker count per shard depends on framework and runner vCPUs: Playwright workers are isolated processes (about one per vCPU); Jest can run CPU-bound workers in parallel.- Show the arithmetic: parallel lanes = shards × workers, per-shard time = total test time / lanes + per-worker fixture cost + retry overhead.- Test ordering recommendation MUST address flake: alphabetical can mask flakes; by-duration prevents long tails.- Explicitly note when shard count > runners (queueing) or when fixture cost dominates.- Output target shard runtime should be < 5 min to keep CI snappy.</constraints> <output_format>Four sections:1. **Configuration**: table: Setting | Value | Reasoning2. **Sample CI config**: code block (Playwright config or Jest CI YAML)3. **Tradeoffs**: bullets on what this optimizes for vs against4. **Re-evaluation triggers**: when to re-tune (suite grows, flake increases, CI capacity changes)</output_format> <approach>Before writing, do the math: total time = N * D + (shards * O). Make sure shards / runners ratio is sensible.</approach>## RoleCI optimization engineer. Parallelization has a knee point. Compute from data. ## ContextVariables: N (total tests), D (avg test seconds), O (worker setup overhead per shard), R (available runners), F (flake rate).Formula: shards = min(R, ceil(N * D / target_per_shard_seconds)) Caveats:- Fixture cost paid PER SHARD, not amortized. > 30% of test time → fewer shards.- Flaky tests sometimes need single-worker to avoid order dependencies.- File-level vs test-level sharding (Playwright = file-level by default). ## Task1. Compute shards = min(R, ceil(N*D / target_per_shard_seconds))2. Workers per shard (Playwright = 1 typically; Jest = # CPU cores)3. Test ordering / distribution the framework supports (Playwright: fullyParallel + even split, split slow files; Jest: default sequencer orders by past duration)4. Flake retry vs reshard tradeoff5. File-level vs test-level6. Reasoning paragraph ## Input- N: {total}- D: {avg_duration}- F: {flake_rate}- R: {runners}- Framework: {framework}- Fixture cost per shard: {fixture_cost} ## Constraints- Shard count = number, not range.- Workers/shard framework-dependent.- Ordering addresses flake (alphabetical masks; by-duration prevents tails).- Note when shards > runners (queueing) or fixture cost dominates.- Target shard runtime < 5 min. ## Output format4 sections: Configuration table (Setting | Value | Reasoning) | Sample CI config code block | Tradeoffs | Re-evaluation triggers. ## ApproachMath first: total time = N*D + (shards*O). Shards/runners ratio sensible.Example
Input
Total tests: 1200 E2E tests Average test duration: 8 seconds Flaky test rate: 5% Available CI runners / parallelism budget: 10 GitHub Actions runners Framework: Playwright Fixture cost per shard: 30 seconds (Playwright browser launch + auth state setup)
Output
## 1. Configuration
Math: 1200 tests × 8 s = 9,600 s of test time. Each Playwright worker is a separate process with its own browser, so parallel lanes = shards × workers. Fixture cost (30 s) is paid once per worker, not per test.
| Setting | Value | Reasoning |
|---------|-------|-----------|
| Total test runtime (one lane) | ~2.7 hours (9,600 s) | Baseline: far too long for PR feedback |
| Shards | 10 | Use the whole runner budget: shards beyond 10 would only queue |
| Workers per shard | 2 | GitHub-hosted Linux runners for private repos have 2 vCPUs; one browser worker per vCPU. Raise to 4 on 4-vCPU runners |
| Parallel lanes | 20 | 10 shards × 2 workers |
| Per-shard runtime | ~9-10 min | 9,600 s / 20 lanes = 480 s, + 30 s fixture per worker, + ~25 s of retries (5% × 1200 = 60 retried tests × 8 s / 20 lanes) |
| Distribution | `fullyParallel: true` | Shards split by test instead of by file, so one large spec file can't make a shard lag. Requires tests that don't depend on each other |
| Flake retry strategy | `retries: 1` in CI, flaky tests reported | 5% flake rate ≈ 60 tests; one retry keeps PRs green while the "flaky" list in the report feeds the fix backlog |
## 2. Sample CI config (GitHub Actions + Playwright)## 2. Sample CI config (GitHub Actions + Playwright)
```yaml
jobs:
e2e:
runs-on: ubuntu-latest
strategy:
matrix:
shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
fail-fast: false
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
- run: npm ci --prefer-offline
- run: npx playwright install --with-deps chromium
- name: Run E2E shard ${{ matrix.shard }}
run: npx playwright test --shard=${{ matrix.shard }}/10 --reporter=blob
- name: Upload shard report
if: always()
uses: actions/upload-artifact@v4
with:
name: blob-report-${{ matrix.shard }}
path: blob-report
retention-days: 1
merge-reports:
needs: e2e
runs-on: ubuntu-latest
if: always()
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
- run: npm ci --prefer-offline
- name: Download blob reports
uses: actions/download-artifact@v4
with:
path: all-reports
pattern: blob-report-*
merge-multiple: true
- name: Merge reports
run: npx playwright merge-reports --reporter=html ./all-reports
- name: Upload final report
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: playwright-report
retention-days: 7
```
```typescript
// playwright.config.ts
export default defineConfig({
testDir: './tests',
fullyParallel: true, // shard by test, not by file
workers: process.env.CI ? 2 : undefined, // one browser worker per vCPU on 2-vCPU runners
retries: process.env.CI ? 1 : 0, // absorb the 5% flake rate; flaky tests still show in the report
reporter: process.env.CI ? 'blob' : 'html',
use: {
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
},
});
```
## 3. Tradeoffs
**Optimizes for:**
- Wall-clock feedback: ~10 min instead of 2.7 hours.
- CI capacity utilization: all 10 runners, 2 lanes each.
- Reliability: one retry absorbs most flakes, and the report still names them.
**Optimizes against:**
- Going below 5 min: it would need ~40 lanes. With 10 runners that means 4 workers per shard on 4-vCPU (larger, paid) runners; fixture cost then becomes a bigger share of each lane (30 s of a 4-min lane).
- Fewer shards: 5 shards × 2 workers doubles feedback time to ~17 min to save runner minutes.
**What this DOESN'T optimize:**
- Cost per CI minute: 10 runners × ~10 min ≈ 100 runner-minutes per run, slightly more than a single machine would use (fixture and setup overhead per runner). If cost is the constraint, reduce shards.
- Tail latency: one very slow test still sets its shard's floor; profile the 10 slowest tests.
## 4. Re-evaluation triggers
Re-tune when:
- Test count grows beyond 1500 or drops below 1000 (different fixture amortization).
- Flake rate climbs above 8%: retries no longer enough; investigate root cause (use `refactor-flaky-test` prompt).
- Average test duration changes substantially (e.g., new auth flow adds 2s to every test).
- CI runner budget changes (more / fewer runners available).
- Move to a new framework version (Playwright 1.55 → 1.62 may change worker semantics).Common pitfalls
- Model ignores flake rate and recommends max shards: flaky tests then spread thin and retries don't absorb them.
- Workers per shard set far above the runner's vCPUs: browsers starve for CPU and tests time out. Match workers to vCPUs; Playwright workers are isolated processes, so the limit is CPU, not shared fixtures.
- Model recommends duration-based shard balancing for Playwright: it has none built in (shards split by count). Use `fullyParallel: true` and split the slowest spec files instead.
- Fixture cost ignored in math: fewer shards with same total time often better when fixture > 30% of work.
Tips
- Profile per-test duration first; the longest 10% often dominate runtime. Optimize those before parallelizing.
- Use Playwright `--shard=X/Y` for file-level sharding; merge reports after.
- For Jest, use `--shard=X/Y` (Jest 28+) plus `--maxWorkers=<n>` for in-shard parallelism.
- Pair with `test-impact-from-git-diff` for fewer tests run per PR (further reduces shard count needed).
FAQ
When does sharding hurt?
When fixture cost (DB setup, browser launch, auth) > 30% of total runtime. Adding shards then multiplies fixture cost faster than reducing test time. Profile first.
When should I retry vs reshard?
Retry handles transient flake (~5% rate). Resharding handles capacity. Retries cost ~1.5x runtime per flake; resharding multiplies fixture cost. For low flake rates, retries; for high flake rates, FIX the flake (use refactor-flaky-test).
Playwright workers vs shards?
Workers are separate processes on one machine, each with its own browser. Shards split the suite across machines. Workers reduce per-machine compute time; shards add machines. Use workers up to the machine's vCPUs, then add shards.
Should I shard unit tests too?
Usually no: unit tests are fast enough that shard overhead exceeds benefit. Vitest / Jest run thousands of unit tests in seconds with multiple workers. Reserve sharding for E2E.