Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(ci): size the jest PR matrix from the selected tests (#116328)

Raúl Negrón-Oterodfc24eea433c
diff --git a/.github/scripts/jest-select.js b/.github/scripts/jest-select.js
new file mode 100644
index 000000000000..9baa294a98cc
--- /dev/null
+++ b/.github/scripts/jest-select.js
@@ -0,0 +1,76 @@
+#!/usr/bin/env node
+// Sizes the PR jest matrix from the count of tests related to the changed files: lists them the
+// way the jest job will, then writes the matrix and the counts to GITHUB_OUTPUT.
+//
+// Run with: CHANGED_FILES="src/a.ts ../products/b.ts" node .github/scripts/jest-select.js
+
+const { execFileSync } = require('node:child_process')
+const fs = require('node:fs')
+const path = require('node:path')
+
+const FRONTEND_DIR = path.resolve(__dirname, '../../frontend')
+
+// Initial limit from the probes documented in docs/internal/ci-things-already-tried.md.
+// File counts approximate runtime; tune this from observed shard durations.
+const TEST_FILES_PER_SHARD = 342
+const MAX_SHARDS = 8
+const SEGMENT = 'app'
+
+function listRelatedTests(changedFiles) {
+ if (changedFiles.length === 0) {
+ return []
+ }
+ // The package's `jest` script runs build:products first, like the jest job does.
+ const args = ['jest', '--listTests', '--findRelatedTests', ...changedFiles]
+ const output = execFileSync('pnpm', args, {
+ cwd: FRONTEND_DIR,
+ encoding: 'utf8',
+ timeout: 2 * 60 * 1000,
+ maxBuffer: 256 * 1024 * 1024,
+ stdio: ['ignore', 'pipe', 'inherit'],
+ })
+ return output.split('\n').filter((line) => line.startsWith('/'))
+}
+
+function planShards(testCount) {
+ return Math.min(MAX_SHARDS, Math.ceil(testCount / TEST_FILES_PER_SHARD))
+}
+
+function planOutputs({ changedFiles, changedFileCount, testCount }) {
+ const shardCount = planShards(testCount)
+ return {
+ mode: 'selective',
+ matrix: JSON.stringify({
+ include: Array.from({ length: shardCount }, (_, i) => ({
+ segment: SEGMENT,
+ chunk: i + 1,
+ shard_count: shardCount,
+ })),
+ }),
+ should_run: String(shardCount > 0),
+ changed_files: changedFiles.join(' '),
+ changed_file_count: String(changedFileCount),
+ selected_file_count: String(changedFiles.length),
+ related_test_count: String(testCount),
+ shard_count: String(shardCount),
+ full_run_reason_category: '',
+ full_run_reason_detail: '',
+ }
+}
+
+function main() {
+ const changedFiles = (process.env.CHANGED_FILES ?? '').split(' ').filter(Boolean)
+ const testCount = listRelatedTests(changedFiles).length
+ const outputs = planOutputs({ changedFiles, changedFileCount: process.env.CHANGED_FILE_COUNT ?? '', testCount })
+ const lines = Object.entries(outputs).map(([key, value]) => `${key}=${value}\n`)
+ fs.appendFileSync(process.env.GITHUB_OUTPUT ?? '/dev/stdout', lines.join(''))
+ console.log(
+ `Selective mode: ${changedFiles.length} changed files, ${testCount} related tests, ${outputs.shard_count} shards`
+ )
+}
+
+if (require.main === module) {
+ main()
+}
+
+module.exports = { planShards, planOutputs, TEST_FILES_PER_SHARD, MAX_SHARDS }
diff --git a/.github/scripts/jest-select.test.js b/.github/scripts/jest-select.test.js
new file mode 100644
index 000000000000..3cb9abb8c01f
--- /dev/null
+++ b/.github/scripts/jest-select.test.js
@@ -0,0 +1,40 @@
+// Run with: node --test .github/scripts/jest-select.test.js
+
+const test = require('node:test')
+const assert = require('node:assert/strict')
+
+const { planShards, planOutputs, TEST_FILES_PER_SHARD, MAX_SHARDS } = require('./jest-select.js')
+
+test('planShards adds a shard when the file limit is exceeded', () => {
+ assert.equal(planShards(TEST_FILES_PER_SHARD), 1)
+ assert.equal(planShards(TEST_FILES_PER_SHARD + 1), 2)
+ assert.equal(planShards(2000), 6)
+})
+
+test('planShards caps the count at MAX_SHARDS', () => {
+ assert.equal(planShards(100000), MAX_SHARDS)
+})
+
+test('planOutputs skips the jest job when no test is related', () => {
+ const outputs = planOutputs({ changedFiles: ['src/types-only.ts'], changedFileCount: 1, testCount: 0 })
+
+ assert.equal(outputs.should_run, 'false')
+ assert.equal(outputs.shard_count, '0')
+ assert.deepEqual(JSON.parse(outputs.matrix), { include: [] })
+})
+
+test('planOutputs emits one matrix cell per shard with the shared shard_count', () => {
+ const outputs = planOutputs({ changedFiles: ['src/a.ts', 'src/b.ts'], changedFileCount: 7, testCount: 1200 })
+ const matrix = JSON.parse(outputs.matrix)
+
+ assert.equal(outputs.should_run, 'true')
+ assert.equal(outputs.selected_file_count, '2')
+ assert.equal(outputs.changed_file_count, '7')
+ assert.equal(outputs.related_test_count, '1200')
+ assert.equal(String(matrix.include.length), outputs.shard_count)
+ assert.deepEqual(matrix.include[0], { segment: 'app', chunk: 1, shard_count: matrix.include.length })
+ assert.deepEqual(
+ matrix.include.map((cell) => cell.chunk),
+ matrix.include.map((_, i) => i + 1)
+ )
+})
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.yml
index 6004f36cbc84..01c537d147c0 100644
--- a/.github/workflows/ci-frontend.yml
+++ b/.github/workflows/ci-frontend.yml
@@ -1,8 +1,9 @@
name: Frontend CI
on:
pull_request:
- # PRs run a narrowed jest selection, draft or ready, over three shards. The
- # merge queue's trunk-merge/** run is the full matrix that gates master.
+ # PRs run a narrowed jest selection, draft or ready, on as many shards as
+ # the selection needs. The merge queue's trunk-merge/** run is the full
+ # matrix that gates master.
# When selection can't be trusted, a ready PR falls back to the full matrix
# and a draft skips jest instead, deferring to its ready run. To force the
# full matrix on a PR, add the `run-ci-frontend` label. The `no-ci` label
@@ -142,6 +143,7 @@ jobs:
- 'products/**/*.tsx'
frontend:
- '.github/scripts/jest-retries.cjs'
+ - '.github/scripts/jest-select.js'
- 'patches/[email protected]'
# Avoid running frontend tests for irrelevant changes
# NOTE: we are at risk of missing a dependency here.
@@ -191,6 +193,7 @@ jobs:
# when only markdown or YAML files change.
frontend_code:
- '.github/scripts/jest-retries.cjs'
+ - '.github/scripts/jest-select.js'
- 'patches/[email protected]'
- 'bin/**'
- 'frontend/**'
@@ -274,7 +277,8 @@ jobs:
select-jest-tests:
name: Select jest tests
runs-on: ubuntu-24.04
- timeout-minutes: 5
+ # Installs the frontend workspace to list the related tests.
+ timeout-minutes: 10
needs: changes
# Trunk's merge-queue branches open as draft PRs, but their run IS the
# merge gate, so they must never get the narrowed selection.
@@ -292,6 +296,7 @@ jobs:
# fallback rate can be read per reason rather than inferred from mode alone.
changed_file_count: ${{ steps.classify.outputs.changed_file_count }}
selected_file_count: ${{ steps.classify.outputs.selected_file_count }}
+ related_test_count: ${{ steps.classify.outputs.related_test_count }}
shard_count: ${{ steps.classify.outputs.shard_count }}
full_run_reason_category: ${{ steps.classify.outputs.full_run_reason_category }}
full_run_reason_detail: ${{ steps.classify.outputs.full_run_reason_detail }}
@@ -314,8 +319,8 @@ jobs:
git diff --name-only "origin/$BASE_REF...HEAD" > /tmp/changed.txt
wc -l < /tmp/changed.txt
- - name: Build narrowed matrix
- id: classify
+ - name: Classify changed files
+ id: prepare
env:
DIFF_OUTCOME: ${{ steps.diff.outcome }}
PR_DRAFT: ${{ github.event.pull_request.draft }}
@@ -353,7 +358,7 @@ jobs:
echo "shard_count=$shards"
echo "full_run_reason_category=$1"
echo "full_run_reason_detail=$2"
- } >> "$GITHUB_OUTPUT"
+ } > /tmp/jest-selection-fallback
}
if [[ "$DIFF_OUTCOME" != "success" ]] || [[ ! -s /tmp/changed.txt ]]; then
@@ -378,7 +383,7 @@ jobs:
case "$f" in
frontend/jest.*|babel.config.js|tsconfig.json|tsconfig.*.json|\
package.json|pnpm-lock.yaml|webpack.config.js|\
- .github/workflows/ci-frontend.yml|.github/scripts/jest-retries.cjs|patches/[email protected]|.nvmrc)
+ .github/workflows/ci-frontend.yml|.github/scripts/jest-retries.cjs|.github/scripts/jest-select.js|patches/[email protected]|.nvmrc)
fall_back config_change "$f"
exit 0
;;
@@ -409,41 +414,48 @@ jobs:
' /tmp/changed.txt | tr '\n' ' ' | sed 's/ $//'
)
- if [[ -z "$CHANGED_FILES" ]]; then
- # No frontend source changes (e.g. PR only edits backend or docs)
- # but `frontend_code` paths-filter still flagged the PR. Skip jest.
- {
- echo "mode=selective"
- echo 'matrix={"include":[]}'
- echo "should_run=false"
- echo "changed_files="
- echo "changed_file_count=$changed_count"
- echo "selected_file_count=0"
- echo "shard_count=0"
- echo "full_run_reason_category="
- echo "full_run_reason_detail="
- } >> "$GITHUB_OUTPUT"
- echo "Selective mode: no frontend source files changed, skipping jest"
- exit 0
- fi
-
- # Selective mode uses three shards because a widely imported source file
- # can make --findRelatedTests approach a full suite. --findRelatedTests
- # walks jest's import graph from these files and runs the matching
- # *.test.* files.
- SELECTED_COUNT=$(echo "$CHANGED_FILES" | wc -w | tr -d ' ')
+ # Preserve the same fallback if dependency installation or test listing fails.
+ fall_back selector_crash "Jest selection unavailable" > /dev/null
{
- echo "mode=selective"
- echo 'matrix={"include":[{"segment":"app","chunk":1,"shard_count":3},{"segment":"app","chunk":2,"shard_count":3},{"segment":"app","chunk":3,"shard_count":3}]}'
- echo "should_run=true"
+ echo "selective=true"
echo "changed_files=$CHANGED_FILES"
echo "changed_file_count=$changed_count"
- echo "selected_file_count=$SELECTED_COUNT"
- echo "shard_count=3"
- echo "full_run_reason_category="
- echo "full_run_reason_detail="
} >> "$GITHUB_OUTPUT"
- echo "Selective mode: $SELECTED_COUNT frontend source files"
+
+ - name: Mint setup-action GitHub token
+ id: setup-gh-token
+ if: steps.prepare.outputs.selective == 'true' && steps.prepare.outputs.changed_files != '' && github.event.pull_request.head.repo.full_name == github.repository
+ continue-on-error: true
+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
+ with:
+ client-id: ${{ vars.GH_APP_POSTHOG_SETUP_ACTIONS_APP_ID }}
+ private-key: ${{ secrets.GH_APP_POSTHOG_SETUP_ACTIONS_PRIVATE_KEY }}
+ skip-token-revoke: true
+
+ - name: Install pnpm dependencies
+ id: selector-install
+ if: steps.prepare.outputs.selective == 'true' && steps.prepare.outputs.changed_files != ''
+ timeout-minutes: 5
+ # Allow the final step to publish the prepared fallback if setup fails.
+ continue-on-error: true
+ uses: ./.github/actions/pnpm-install
+ with:
+ install-command: pnpm --filter=@posthog/frontend... install --frozen-lockfile
+ token: ${{ steps.setup-gh-token.outputs.token || github.token }}
+
+ - name: Build narrowed matrix
+ id: classify
+ env:
+ SELECTIVE: ${{ steps.prepare.outputs.selective }}
+ INSTALL_OUTCOME: ${{ steps.selector-install.outcome }}
+ CHANGED_FILES: ${{ steps.prepare.outputs.changed_files }}
+ CHANGED_FILE_COUNT: ${{ steps.prepare.outputs.changed_file_count }}
+ run: |
+ if [[ "$SELECTIVE" == "true" ]] && [[ -z "$CHANGED_FILES" || "$INSTALL_OUTCOME" == "success" ]]; then
+ node .github/scripts/jest-select.js && exit 0
+ echo "::notice::Test selection failed; using the prepared fallback"
+ fi
+ cat /tmp/jest-selection-fallback >> "$GITHUB_OUTPUT"
frontend-format:
name: Frontend formatting
@@ -867,8 +879,9 @@ jobs:
jest:
runs-on: ubuntu-24.04
- # PRs run three selective shards over the tests reachable from the changed
- # files. The merge queue runs the full four-shard fanout.
+ # PRs run as many selective shards as the tests reachable from the changed
+ # files need under the file limit in .github/scripts/jest-select.js. The
+ # merge queue runs the full four-shard fanout.
timeout-minutes: 20
needs: [changes, select-jest-tests]
# A status function is required because select-jest-tests is skipped on the
@@ -902,6 +915,11 @@ jobs:
matrix: ${{ fromJson(needs.select-jest-tests.outputs.matrix || '{"segment":["app"],"chunk":[1,2,3,4]}') }}
steps:
+ # ubuntu-24.04 hands out several CPU models, and the same shard runs up to
+ # 1.4x slower on one than another, so timings are only comparable per model.
+ - name: Print runner CPU
+ run: lscpu | grep 'Model name' || true
+
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Mint setup-action GitHub token
@@ -1234,6 +1252,7 @@ jobs:
"selection_eligible": ${{ needs.select-jest-tests.result == 'success' }},
"changed_file_count": ${{ needs.select-jest-tests.outputs.changed_file_count || 'null' }},
"selected_file_count": ${{ needs.select-jest-tests.outputs.selected_file_count || 'null' }},
+ "related_test_count": ${{ needs.select-jest-tests.outputs.related_test_count || 'null' }},
"shard_count": ${{ needs.select-jest-tests.outputs.shard_count || 'null' }},
"full_run_reason_category": ${{ toJSON(needs.select-jest-tests.outputs.full_run_reason_category || '') }},
"full_run_reason_detail": ${{ toJSON(needs.select-jest-tests.outputs.full_run_reason_detail || '') }},
diff --git a/docs/internal/ci-things-already-tried.md b/docs/internal/ci-things-already-tried.md
index 020bce2ec413..a4fbd44ec961 100644
--- a/docs/internal/ci-things-already-tried.md
+++ b/docs/internal/ci-things-already-tried.md
@@ -222,6 +222,18 @@ What still differs by draft state is the fallback when a selection cannot be tru
_Also asked as:_ snob, is test selection on, why does CI run all the tests, do we select tests on PRs
+### Give the jest PR matrix a fixed shard count
+
+**Verdict: superseded** · Oct 2026 · 262 sampled PR runs and a [probe run](https://github.com/PostHog/posthog/actions/runs/38407529831)
+
+Jest selection on PRs ran three shards whatever it selected, and the selection was all or nothing: 60% of PR runs executed 2,171 of 2,720 test files and 39% executed under 50.
+The import graph that `--findRelatedTests` walks held one cycle of 2,851 files, and 92% of its edges were imports the transformer removes. Reading imports from the transformer output shrinks it to 218 files and 997 tests.
+The 997 tests that load the cycle cost 3.65 seconds each against 1.07 for the rest, so a changed-file count sizes nothing. `.github/scripts/jest-select.js` counts the related tests and assigns one shard per 342 files, capped at eight. This initial threshold comes from the probe runs and needs tuning against observed shard durations; file counts do not guarantee a ten-minute wall. The selector classifies known fallback cases before installing dependencies. Pricing each shard from the hourly run's JUnit was built and removed: two probe runs sized by count landed within 1.4x of the estimate, and the per-file map cost a recorder job and a cache.
+
+Measured on the way and not worth repeating: `--maxWorkers=100%` on the selective path gained nothing on the 4 vCPU runners; persisting jest's cache made a second run on the same runner 5% (12 seconds) faster; the V8 leak fix (`--retain-maps-for-n-gc=0`, [#114618](https://github.com/PostHog/posthog/pull/114618)) was worth 15 to 20% of a shard and about 5% on the merge queue; a different fixed shard count gained nothing.
+
+_Also asked as:_ jest shard timeout, jest selects everything, more jest shards, jest --maxWorkers, cache jest between runs
+
### Narrow the product test matrix when the backend selector returns `full`
**Verdict: rejected** · Aug 2026 · read off the Turbo task graph, not measured
diff --git a/tools/workflow-plan/tests/workflows.test.ts b/tools/workflow-plan/tests/workflows.test.ts
index 5d98485e2236..1a5b68536232 100644
--- a/tools/workflow-plan/tests/workflows.test.ts
+++ b/tools/workflow-plan/tests/workflows.test.ts
@@ -1,7 +1,7 @@
// These tests check the workflows under .github/workflows, not the planner. A failure here means a
// job condition in a workflow file changed what runs; the planner itself is covered by plan.test.ts.
import { spawnSync } from 'node:child_process'
-import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'
+import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
@@ -498,6 +498,27 @@ const E2E_DISPATCH: Scenario = {
}
const STEP_EXPECTATIONS: StepExpectation[] = [
+ ...[
+ { name: 'known fallback', selective: '', changedFiles: '', fork: false },
+ { name: 'empty source selection', selective: 'true', changedFiles: '', fork: false },
+ { name: 'selective PR', selective: 'true', changedFiles: 'src/example.ts', fork: false },
+ { name: 'selective fork PR', selective: 'true', changedFiles: 'src/example.ts', fork: true },
+ ].flatMap(({ name, selective, changedFiles, fork }) =>
+ ['setup-gh-token', 'selector-install'].map((step) => ({
+ file: 'ci-frontend.yml',
+ job: 'select-jest-tests',
+ step,
+ scenario: {
+ name,
+ github: pullRequest({ fork }),
+ steps: {
+ ...allFiltersChanged(workflow('ci-frontend.yml')),
+ 'select-jest-tests': { prepare: { outputs: { selective, changed_files: changedFiles } } },
+ },
+ },
+ runs: selective === 'true' && changedFiles !== '' && (step === 'selector-install' || !fork),
+ }))
+ ),
{
file: 'ci-frontend.yml',
job: 'changes',
@@ -531,6 +552,47 @@ const namedJobs = (file: string): Set<string> =>
)
describe('.github/workflows run plans', () => {
+ it.each([
+ ['failed install', 'failure', 'src/example.ts', 'full'],
+ ['empty source selection', 'skipped', '', 'selective'],
+ ['successful install', 'success', 'src/example.ts', 'selective'],
+ ])('Jest selection after %s', (_name, installOutcome, changedFiles, mode) => {
+ const script = workflow('ci-frontend.yml').jobs['select-jest-tests']?.steps?.find(
+ (step) => step.id === 'classify'
+ )?.run
+ if (!script) {
+ throw new Error('Missing Jest matrix classification script')
+ }
+ const directory = mkdtempSync(path.join(os.tmpdir(), 'jest-selection-'))
+ const output = path.join(directory, 'output')
+ const fallback = path.join(directory, 'fallback')
+ try {
+ writeFileSync(fallback, 'mode=full\nshould_run=true\n')
+ const result = spawnSync(
+ 'bash',
+ [
+ '-e',
+ '-c',
+ `node() { printf 'mode=selective\\nshould_run=false\\n' >> "$GITHUB_OUTPUT"; }\n${script.replaceAll('/tmp/jest-selection-fallback', fallback)}`,
+ ],
+ {
+ encoding: 'utf8',
+ env: {
+ PATH: process.env.PATH,
+ SELECTIVE: 'true',
+ INSTALL_OUTCOME: installOutcome,
+ CHANGED_FILES: changedFiles,
+ GITHUB_OUTPUT: output,
+ },
+ }
+ )
+ expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' })
+ expect(readFileSync(output, 'utf8')).toBe(`mode=${mode}\nshould_run=${mode === 'full'}\n`)
+ } finally {
+ rmSync(directory, { recursive: true, force: true })
+ }
+ })
+
it.each([
['new bump', workflowDispatch(), 'bump', 'success', 'pass', true, false],
['missing image', workflowDispatch(), 'bump', 'failure', 'pass', false, false],