: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(ci): run only affected Playwright specs on ready-PR pushes (#71096)
Georges-Antoine Assi33539c622176
diff --git a/.github/workflows/ci-e2e-playwright.yml b/.github/workflows/ci-e2e-playwright.ymlindex 9b38aa37a6f4..d8c74c24ab63 100644--- a/.github/workflows/ci-e2e-playwright.yml+++ b/.github/workflows/ci-e2e-playwright.yml@@ -148,6 +148,11 @@ jobs:- .github/clickhouse-versions.json- docker-compose.dev.yml- Dockerfile+ # Spec-selection selector + map: changes must run the suite (they're+ # force-full anyway) so the map validation step actually executes.+ - tools/playwright_spec_selection.py+ - tools/playwright_area_map.json+ - tools/test_playwright_spec_selection.py# Docs-only changes match the broad globs above but exercise no# code the E2E suite runs — exclude them so a docs-only PR doesn't# boot the whole stack.@@ -303,10 +308,142 @@ jobs:echo "migrations_key=posthog-schema-mig-${SCHEMA_CACHE_EPOCH}-${MIG_HASH}" >> $GITHUB_OUTPUTfi+ select-specs:+ name: Select affected E2E specs+ needs: [changes]+ # Narrow the suite only on incremental `synchronize` pushes to a ready+ # (non-draft) internal PR. Every other trigger — opened, reopened,+ # ready_for_review, workflow_dispatch, push to master, merge_group — skips+ # this job, leaving empty outputs so the playwright job runs the FULL suite.+ # The merge gate (ready_for_review run) and the post-merge master run always+ # run everything, so a selection miss is caught there. Fail-open is FULL,+ # never skip: over-selection would silently drop coverage.+ if: |+ needs.changes.outputs.shouldRun == 'true'+ && github.event_name == 'pull_request'+ && github.event.action == 'synchronize'+ && github.event.pull_request.draft != true+ && github.event.pull_request.head.repo.full_name == github.repository+ runs-on: ubuntu-latest+ timeout-minutes: 5+ outputs:+ mode: ${{ steps.classify.outputs.mode }}+ spec_files: ${{ steps.classify.outputs.spec_files }}+ # Telemetry (see the capture-run-time job): empty when the selector errored.+ selected_count: ${{ steps.classify.outputs.selected_count }}+ total_spec_count: ${{ steps.classify.outputs.total_spec_count }}+ skipped_count: ${{ steps.classify.outputs.skipped_count }}+ changed_file_count: ${{ steps.classify.outputs.changed_file_count }}+ full_run_reason_category: ${{ steps.classify.outputs.full_run_reason_category }}+ steps:+ # Full checkout at PR head so the selector can glob specs on disk and read+ # the map/script from the branch under test. Bounded depth + blob:none keeps+ # the merge-base with the base branch reachable cheaply.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ ref: ${{ github.event.pull_request.head.sha }}+ repository: ${{ github.event.pull_request.head.repo.full_name }}+ fetch-depth: 1000+ filter: blob:none++ - name: Run spec selector+ id: select+ # continue-on-error: a selector crash, a git failure, or a missing+ # script/map on an unrebased branch must NOT fail the job — the classify+ # step reads steps.select.outcome and falls open to a full run.+ continue-on-error: true+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref }}+ shell: bash+ run: |+ set -euo pipefail+ # Fetch the current tip of the base branch (scoped, blobless, no tags),+ # then diff origin/$BASE_REF...HEAD (3-dot = merge-base) so master+ # commits merged into the branch aren't counted as changes.+ git fetch --no-tags --depth=1000 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"+ if [ ! -f tools/playwright_spec_selection.py ] || [ ! -f tools/playwright_area_map.json ]; then+ echo "::notice::spec selector/map absent on this checkout (unrebased branch) — full run"+ exit 1+ fi+ python3 tools/playwright_spec_selection.py \+ --base-ref "origin/$BASE_REF" \+ --summary-path "$GITHUB_STEP_SUMMARY" \+ > /tmp/spec-selection.json++ - name: Classify selection+ id: classify+ env:+ SELECT_OUTCOME: ${{ steps.select.outcome }}+ shell: bash+ run: |+ set -euo pipefail+ # Metric outputs are emitted in every path (see the capture-run-time+ # telemetry step). They stay empty only when the selector itself errored.+ SPECS=""+ SELECTED_COUNT=""+ TOTAL_COUNT=""+ SKIPPED_COUNT=""+ CHANGED_COUNT=""+ REASON_CATEGORY=""++ if [[ "$SELECT_OUTCOME" != "success" ]] || [[ ! -s /tmp/spec-selection.json ]]; then+ echo "::warning::spec selector produced no output — running the FULL suite"+ MODE=full+ REASON_CATEGORY=selector_error+ else+ MODE=$(jq -r '.mode' /tmp/spec-selection.json)+ SELECTED_COUNT=$(jq -r '.selected_count' /tmp/spec-selection.json)+ TOTAL_COUNT=$(jq -r '.total_spec_count' /tmp/spec-selection.json)+ CHANGED_COUNT=$(jq -r '.changed_file_count' /tmp/spec-selection.json)+ REASON_CATEGORY=$(jq -r '.full_run_reason_category' /tmp/spec-selection.json)+ SKIPPED_COUNT=$((TOTAL_COUNT - SELECTED_COUNT))+ if [[ "$MODE" == "selected" ]]; then+ SPECS=$(jq -r '.spec_files | join(" ")' /tmp/spec-selection.json)+ if [[ -z "$SPECS" ]]; then+ echo "::warning::selected mode but empty spec list — full run"+ MODE=full+ REASON_CATEGORY=no_specs+ fi+ else+ echo "Selector requested a full run:"+ jq -r '.full_run_reasons[]?' /tmp/spec-selection.json+ fi+ fi++ # On a full run nothing is passed downstream — the playwright job runs everything.+ if [[ "$MODE" != "selected" ]]; then+ SPECS=""+ fi++ {+ echo "mode=$MODE"+ echo "spec_files=$SPECS"+ echo "selected_count=$SELECTED_COUNT"+ echo "total_spec_count=$TOTAL_COUNT"+ echo "skipped_count=$SKIPPED_COUNT"+ echo "changed_file_count=$CHANGED_COUNT"+ echo "full_run_reason_category=$REASON_CATEGORY"+ } >> "$GITHUB_OUTPUT"+ echo "mode=$MODE category=${REASON_CATEGORY:-none} selected=${SELECTED_COUNT:-?}/${TOTAL_COUNT:-?}"++ - name: Upload selection artifact+ if: always() && steps.select.outcome == 'success'+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0+ with:+ name: playwright-spec-selection+ path: /tmp/spec-selection.json+ if-no-files-found: ignore+playwright:name: Playwright E2E tests- needs: [changes]- if: needs.changes.outputs.shouldRun == 'true'+ needs: [changes, select-specs]+ # Skip-ownership stays with `changes`: gate on shouldRun only. select-specs is+ # skipped on full-run events, so `!cancelled()` is required for this job to run+ # past a skipped dependency; a skipped/failed select-specs yields an empty mode,+ # which the test step below treats as a full run.+ if: |+ !cancelled()+ && needs.changes.outputs.shouldRun == 'true'# 8-core depot: 18% avg / 30% peak memory observed on 16-core runs (#46853 noted# the workload "is not resource constrained" even after sharding was removed).# Talk to #team-devex before changing.@@ -317,6 +454,8 @@ jobs:pull-requests: writeoutputs:vr_run_id: ${{ steps.vr-create.outputs.run_id }}+ # Wall-clock of the test step, for the CI-minutes-saved telemetry.+ test_seconds: ${{ steps.playwright-tests.outputs.test_seconds }}env:DOCKERHUB_USERNAME: ${{ vars.DOCKERHUB_USER }}DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}@@ -336,6 +475,26 @@ jobs:# GITHUB_TOKEN in .git/config where that code could read it — the report step# below receives the token explicitly via its GITHUB_TOKEN env instead.persist-credentials: false+ # Fail fast (seconds, before the ~10-min stack boot) when the spec-selection+ # map has drifted: a target pointing at a renamed/deleted spec, or a new spec+ # no map entry reaches. Without this gate the selector silently falls open to+ # permanent full runs and the selection savings evaporate unnoticed. The+ # runtime selector stays fail-open; this is the merge-blocking counterpart+ # that forces the map fix onto the PR that caused the drift. Skipped on+ # unrebased branches that predate the selector (workflow edits hit every+ # open PR immediately; the tools files only arrive on rebase).+ - name: Validate spec-selection map+ shell: bash+ run: |+ if [ ! -f tools/test_playwright_spec_selection.py ]; then+ echo "spec-selection tools absent on this checkout (unrebased branch) — skipping"+ exit 0+ fi+ python3 tools/test_playwright_spec_selection.py || {+ echo "::error file=tools/playwright_area_map.json::Spec-selection map is stale. Renamed/deleted a spec? Update the matching target in tools/playwright_area_map.json. Added a spec? Map it (products/scenes/explicit) or list it under full_suite_only. Run tools/test_playwright_spec_selection.py locally."+ exit 1+ }+- name: Clean up data directories with container permissionsrun: |# Use docker to clean up files created by containers@@ -670,11 +829,31 @@ jobs:# the flake signal quarantining relies on; the quarantine gate below is the# flake net instead. workflow_dispatch can override for a one-off run.PLAYWRIGHT_RETRIES: ${{ inputs.playwright_retries || '0' }}+ # Empty when select-specs was skipped (full-run events) or chose a full run.+ SELECT_MODE: ${{ needs.select-specs.outputs.mode }}+ SELECT_SPECS: ${{ needs.select-specs.outputs.spec_files }}# WARNING: Worker count is tuned to avoid CPU scheduling contention. Talk to #team-devex before changing.# Reduced from 6+4 to 4+2 to minimize CPU scheduling contention (see PR #46853)# Capture-only: VR is the gate for visual changes, Playwright just captures screenshotsrun: |- pnpm --filter=@posthog/playwright exec playwright test --workers=4 --update-snapshots+ # Time the test step so the telemetry can turn "specs skipped" into+ # minutes. set +e around the run so a test failure still records the+ # duration; the original exit code is preserved for the quarantine gate.+ start=$(date +%s)+ set +e+ if [[ "$SELECT_MODE" == "selected" && -n "$SELECT_SPECS" ]]; then+ echo "Selective run: $SELECT_SPECS"+ # Word-splitting is intentional: SELECT_SPECS is a space-separated list+ # of controlled spec paths (from the area map + on-disk globs).+ # shellcheck disable=SC2086+ pnpm --filter=@posthog/playwright exec playwright test $SELECT_SPECS --workers=4 --update-snapshots+ else+ echo "Full run (mode='${SELECT_MODE:-<skipped>}')"+ pnpm --filter=@posthog/playwright exec playwright test --workers=4 --update-snapshots+ fi+ rc=$?+ echo "test_seconds=$(( $(date +%s) - start ))" >> "$GITHUB_OUTPUT"+ exit "$rc"- name: Verify changed Playwright tests are stableif: steps.playwright-tests.outcome == 'success' && github.event_name == 'pull_request'@@ -712,6 +891,11 @@ jobs:VR_PURPOSE: ${{ github.event_name == 'push' && 'observe' || 'review' }}# Recorded on the run so the VR UI can re-trigger this job via the GitHub API.JOB_CHECK_RUN_ID: ${{ job.check_run_id }}+ # A selective run only regenerates a subset of snapshots. --partial tells VR+ # not to flag the un-run baseline snapshots as REMOVED and routes the run to a+ # non-gating status context. Empty on full runs and master pushes (the+ # default-branch fence forces is_partial=false there anyway).+ VR_PARTIAL: ${{ needs.select-specs.outputs.mode == 'selected' && '--partial' || '' }}run: |RUN_ID=$(vr run create \--type playwright \@@ -720,6 +904,7 @@ jobs:--commit "$VR_COMMIT" \--pr "$VR_PR" \--purpose "$VR_PURPOSE" \+ $VR_PARTIAL \--token "$VR_TOKEN")echo "run_id=$RUN_ID" >> $GITHUB_OUTPUT@@ -845,7 +1030,7 @@ jobs:name: Capture run timeruns-on: ubuntu-latesttimeout-minutes: 5- needs: [changes, playwright, playwright_tests]+ needs: [changes, select-specs, playwright, playwright_tests]if: # Run on pull requests to PostHog/posthog + on PostHog/posthog outside of PRs - but never on forks or Dependabot (no secrets access)always() && github.actor != 'dependabot[bot]' &&needs.changes.outputs.shouldRun == 'true' && (@@ -883,6 +1068,38 @@ jobs:status-job: 'Playwright tests pass'runner: 'depot'+ # Spec-selection telemetry -> DevEx project (347861), where the CI-savings and+ # fallback-rate insights live. Emitted whenever the heavy job actually ran, so+ # full runs (this event's `mode=full`, `selection_eligible=false`) provide the+ # test-time baseline that selective runs are measured against. `selection_eligible`+ # is true only on synchronize pushes where select-specs ran — the fallback-rate+ # denominator. Telemetry never reds CI (continue-on-error).+ - name: Capture spec selection to DevEx PostHog+ if: github.run_attempt == '1' && (needs.playwright.result == 'success' || needs.playwright.result == 'failure')+ continue-on-error: true+ uses: PostHog/posthog-github-action@58dea254b598fb5d469c0699c98af8288a7f7650 # v1.2.0+ with:+ posthog-token: ${{ secrets.POSTHOG_DEVEX_PROJECT_API_TOKEN }}+ event: 'posthog-ci-e2e-spec-selection'+ properties: |+ {+ "mode": ${{ toJSON(needs.select-specs.outputs.mode || 'full') }},+ "selection_eligible": ${{ needs.select-specs.result == 'success' }},+ "selected_count": ${{ needs.select-specs.outputs.selected_count || 'null' }},+ "total_spec_count": ${{ needs.select-specs.outputs.total_spec_count || 'null' }},+ "skipped_count": ${{ needs.select-specs.outputs.skipped_count || 'null' }},+ "changed_file_count": ${{ needs.select-specs.outputs.changed_file_count || 'null' }},+ "full_run_reason_category": ${{ toJSON(needs.select-specs.outputs.full_run_reason_category || '') }},+ "playwright_test_seconds": ${{ needs.playwright.outputs.test_seconds || 'null' }},+ "playwright_result": ${{ toJSON(needs.playwright.result) }},+ "runner_billing_multiplier": 4,+ "event_type": ${{ toJSON(github.event_name) }},+ "branch": ${{ toJSON(github.head_ref || github.ref_name) }},+ "sha": ${{ toJSON(github.sha) }},+ "pr_number": ${{ github.event.pull_request.number || 'null' }},+ "run_id": ${{ toJSON(github.run_id) }}+ }+vr-complete:name: Complete Visual Review runruns-on: ubuntu-latestdiff --git a/tools/playwright_area_map.json b/tools/playwright_area_map.jsonnew file mode 100644index 000000000000..27efe930fe75--- /dev/null+++ b/tools/playwright_area_map.json@@ -0,0 +1,121 @@+{+ "_comment": [+ "Path -> Playwright spec map for affected-only E2E selection on ready-PR incremental pushes.",+ "Consumed by tools/playwright_spec_selection.py; wired into .github/workflows/ci-e2e-playwright.yml.",+ "The selector is FAIL-CLOSED: any changed file not matched below forces the FULL suite, and a",+ "selection miss is caught by the post-merge full run on master (the backstop). Start narrow and",+ "widen `scenes`/`explicit` as recall data comes in. Every target must resolve to >=1 real spec",+ "(enforced by tools/test_playwright_spec_selection.py) and point only into the two spec roots.",+ "Glob syntax: `*` matches within a path segment, `**` matches across segments (only at pattern end).",+ "A target ending in `/` is a directory prefix (all specs beneath it); otherwise it's an exact file.",+ "Every spec must be reachable by some target OR listed in `full_suite_only` — the test enforces",+ "this, so adding a spec forces a conscious choice: map it, or accept it only runs in full suites",+ "(and when directly edited)."+ ],+ "force_full": [+ "playwright/utils/**",+ "playwright/page-models/**",+ "playwright/mocks/**",+ "playwright/*.ts",+ "playwright/playwright.config.ts",+ "playwright/snapshots.yml",+ "playwright/package.json",+ "tsconfig.json",+ "tsconfig.*.json",+ ".github/workflows/ci-e2e-playwright.yml",+ "tools/playwright_spec_selection.py",+ "tools/playwright_area_map.json",+ "frontend/src/lib/**",+ "frontend/src/queries/**",+ "frontend/src/models/**",+ "frontend/src/layout/**",+ "frontend/src/types.ts",+ "frontend/src/globals.ts",+ "posthog/**",+ "ee/**",+ "products/*/backend/**",+ "package.json",+ "pnpm-lock.yaml",+ "uv.lock",+ "docker-compose.dev.yml",+ "docker-compose.base.yml",+ "docker-compose.profiles.yml",+ "Dockerfile",+ ".github/clickhouse-versions.json",+ "bin/**"+ ],+ "products": {+ "posthog_ai": ["products/posthog_ai/frontend/e2e/"],+ "replay": ["products/replay/frontend/e2e/"],+ "surveys": ["products/surveys/frontend/e2e/"]+ },+ "scenes": {+ "surveys": ["products/surveys/frontend/e2e/"],+ "session-recordings": ["products/replay/frontend/e2e/"],+ "sessions": ["products/replay/frontend/e2e/"],+ "billing": ["playwright/e2e/billing/"],+ "experiments": ["playwright/e2e/experiments/"],+ "cohorts": ["playwright/e2e/product-analytics/cohorts.spec.ts"],+ "dashboard": [+ "playwright/e2e/product-analytics/dashboards.spec.ts",+ "playwright/e2e/shared-dashboard-styling.spec.ts",+ "playwright/e2e/shared-dashboard-unauthenticated.spec.ts"+ ],+ "notebooks": [+ "playwright/e2e/product-analytics/notebooks.spec.ts",+ "playwright/e2e/shared-notebook-unauthenticated.spec.ts"+ ],+ "saved-insights": ["playwright/e2e/product-analytics/insights-list.spec.ts"],+ "insights": [+ "playwright/e2e/product-analytics/",+ "playwright/e2e/api-insight-creation.spec.ts",+ "playwright/e2e/insight-sharing-password.spec.ts",+ "playwright/e2e/shared-insight-unauthenticated.spec.ts"+ ],+ "funnels": ["playwright/e2e/product-analytics/"],+ "paths": ["playwright/e2e/product-analytics/"],+ "paths-v2": ["playwright/e2e/product-analytics/"],+ "retention": ["playwright/e2e/product-analytics/retention.spec.ts"],+ "web-analytics": ["playwright/e2e/web-analytics.spec.ts"],+ "persons": ["playwright/e2e/persons/persons.spec.ts"],+ "persons-management": ["playwright/e2e/persons/persons.spec.ts"],+ "authentication": ["playwright/e2e/auth.spec.ts", "playwright/e2e/auth-password-reset.spec.ts"],+ "onboarding": ["playwright/e2e/before-onboarding.spec.ts", "playwright/e2e/signup.spec.ts"],+ "data-management": [+ "playwright/e2e/event-definitions.spec.ts",+ "playwright/e2e/events.spec.ts",+ "playwright/e2e/annotations.spec.ts"+ ],+ "annotations": ["playwright/e2e/annotations.spec.ts"],+ "toolbar-launch": ["playwright/e2e/toolbar.spec.ts"],+ "project-homepage": ["playwright/e2e/project-home-page.spec.ts"]+ },+ "explicit": {+ "products/product_analytics/frontend/**": ["playwright/e2e/product-analytics/"],+ "products/batch_exports/frontend/**": ["playwright/e2e/batch-exports/"],+ "products/logs/frontend/**": ["playwright/e2e/logs/"],+ "products/cdp/frontend/**": ["playwright/e2e/cdp/"],+ "products/experiments/frontend/**": ["playwright/e2e/experiments/"],+ "products/web_analytics/frontend/**": ["playwright/e2e/web-analytics.spec.ts"],+ "products/persons/frontend/**": ["playwright/e2e/persons/persons.spec.ts"],+ "products/cohorts/frontend/**": ["playwright/e2e/product-analytics/cohorts.spec.ts"],+ "products/notebooks/frontend/**": [+ "playwright/e2e/product-analytics/notebooks.spec.ts",+ "playwright/e2e/shared-notebook-unauthenticated.spec.ts"+ ],+ "products/early_access_features/frontend/**": ["playwright/e2e/early-access-management.spec.ts"],+ "products/event_definitions/frontend/**": ["playwright/e2e/event-definitions.spec.ts"],+ "products/annotations/frontend/**": ["playwright/e2e/annotations.spec.ts"],+ "products/data_warehouse/frontend/**": ["playwright/e2e/sql-editor*.spec.ts"],+ "products/workflows/frontend/**": [+ "playwright/e2e/workflows-hidden-templates-load.spec.ts",+ "playwright/e2e/workflows-property-filter-category-dropdown.spec.ts"+ ],+ "frontend/src/toolbar/**": ["playwright/e2e/toolbar.spec.ts"]+ },+ "full_suite_only": [+ "playwright/e2e/oauth-mcp-consent.spec.ts",+ "playwright/e2e/preflight.spec.ts",+ "playwright/e2e/system-status.spec.ts"+ ]+}diff --git a/tools/playwright_spec_selection.py b/tools/playwright_spec_selection.pynew file mode 100644index 000000000000..360e9d95c530--- /dev/null+++ b/tools/playwright_spec_selection.py@@ -0,0 +1,255 @@+#!/usr/bin/env -S uv run --script+# /// script+# requires-python = ">=3.11"+# dependencies = []+# ///+"""Affected-only Playwright E2E spec selection.++Maps a PR's changed files to the Playwright specs they could affect, so CI can+run a subset on incremental `synchronize` pushes to ready PRs instead of the+full suite. Wired into `.github/workflows/ci-e2e-playwright.yml`; the map lives+in `tools/playwright_area_map.json`.++Trust model (deliberately different from the backend snob selector, which+skips): this selector is FAIL-CLOSED per file — any changed file not explicitly+mapped forces the FULL suite — and the workflow falls open to the full suite on+any selector error. Over-selection silently drops coverage, so the only safe+default is "run everything". A selection miss that slips through is caught by+the post-merge full run on master (the backstop).++Emits a single JSON object to stdout:++ {+ "mode": "selected" | "full",+ "spec_files": [...], # [] when mode == "full"+ "full_run_reasons": [...], # why a full run was chosen (empty when selected)+ "changed_files": [...],+ "changed_file_count": N,+ "selected_count": M,+ "total_spec_count": T+ }+"""++from __future__ import annotations++import re+import sys+import json+import argparse+import subprocess+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parent.parent+MAP_PATH = Path(__file__).with_name("playwright_area_map.json")++# Above this many changed files the diff is too broad to narrow safely -> full run.+MAX_CHANGED_FILES = 100++# The two roots Playwright discovers specs from (see playwright/playwright.config.ts testMatch).+SPEC_GLOBS = ("playwright/e2e/**/*.spec.ts", "products/*/frontend/e2e/**/*.spec.ts")++_PRODUCT_FRONTEND_RE = re.compile(r"^products/([^/]+)/frontend/")+_SCENE_RE = re.compile(r"^frontend/src/scenes/([^/]+)/")+++class MapError(Exception):+ """A map entry doesn't resolve to a real spec on disk — treat as untrustworthy."""+++def _compile_glob(pattern: str) -> re.Pattern[str]:+ """Compile a gitignore-style glob: `*` stays within a path segment, `**` spans segments."""+ out: list[str] = []+ i, n = 0, len(pattern)+ while i < n:+ c = pattern[i]+ if c == "*":+ if i + 1 < n and pattern[i + 1] == "*":+ out.append(".*")+ i += 2+ else:+ out.append("[^/]*")+ i += 1+ elif c == "?":+ out.append("[^/]")+ i += 1+ else:+ out.append(re.escape(c))+ i += 1+ return re.compile("^" + "".join(out) + r"\Z")+++def discover_specs(root: Path) -> set[str]:+ """All spec files on disk, as repo-relative POSIX paths."""+ found: set[str] = set()+ for glob in SPEC_GLOBS:+ for path in root.glob(glob):+ found.add(path.relative_to(root).as_posix())+ return found+++def expand_target(target: str, all_specs: set[str]) -> set[str]:+ """Resolve a map target (dir prefix, glob, or exact file) to concrete specs on disk."""+ if target.endswith("/"):+ matches = {s for s in all_specs if s.startswith(target)}+ elif "*" in target or "?" in target:+ rx = _compile_glob(target)+ matches = {s for s in all_specs if rx.match(s)}+ else:+ matches = {target} if target in all_specs else set()+ if not matches:+ raise MapError(f"map target {target!r} resolved to no specs on disk")+ return matches+++def load_map(path: Path) -> dict:+ return json.loads(path.read_text())+++def _result(+ mode: str,+ spec_files: list[str],+ reasons: list[str],+ changed_files: list[str],+ total_spec_count: int,+ reason_category: str = "",+) -> dict:+ return {+ "mode": mode,+ "spec_files": spec_files,+ "full_run_reasons": reasons,+ # Low-cardinality label for analytics grouping (the reasons carry file paths).+ "full_run_reason_category": reason_category,+ "changed_files": changed_files,+ "changed_file_count": len(changed_files),+ "selected_count": len(spec_files),+ "total_spec_count": total_spec_count,+ }+++def select(changed_files: list[str], area_map: dict, all_specs: set[str]) -> dict:+ """Pure selection: changed files + map + on-disk specs -> a full/selected decision."""+ total = len(all_specs)++ def full(reason: str, category: str) -> dict:+ return _result("full", [], [reason], changed_files, total, category)++ if not changed_files:+ return full("empty diff (defensive full run)", "empty_diff")+ if len(changed_files) > MAX_CHANGED_FILES:+ return full(f"{len(changed_files)} changed files exceed the {MAX_CHANGED_FILES} ceiling", "over_ceiling")++ force_full = [(p, _compile_glob(p)) for p in area_map.get("force_full", [])]+ products = area_map.get("products", {})+ scenes = area_map.get("scenes", {})+ explicit = [(p, _compile_glob(p), targets) for p, targets in area_map.get("explicit", {}).items()]++ def explicit_match(path: str, selected: set[str]) -> bool:+ for _pat, rx, targets in explicit:+ if rx.match(path):+ for t in targets:+ selected |= expand_target(t, all_specs)+ return True+ return False++ selected: set[str] = set()+ for f in changed_files:+ # 1. Shared infra / backend / unattributable code -> full (highest priority).+ for pat, rx in force_full:+ if rx.match(f):+ return full(f"{f} matches force-full pattern '{pat}'", "force_full")++ # 2. Product-owned frontend -> that product's specs (or an explicit rule for+ # products whose behavior is exercised by top-level specs).+ pm = _PRODUCT_FRONTEND_RE.match(f)+ if pm:+ name = pm.group(1)+ if name in products:+ for t in products[name]:+ selected |= expand_target(t, all_specs)+ continue+ if explicit_match(f, selected):+ continue+ return full(f"{f}: product '{name}' has no spec mapping", "unmapped_product")++ # 3. Frontend scene -> mapped specs.+ sm = _SCENE_RE.match(f)+ if sm:+ area = sm.group(1)+ if area in scenes:+ for t in scenes[area]:+ selected |= expand_target(t, all_specs)+ continue+ return full(f"{f}: scene '{area}' has no spec mapping", "unmapped_scene")++ # 4. Explicit path rules.+ if explicit_match(f, selected):+ continue++ # 5. A directly-edited spec runs itself.+ if f in all_specs:+ selected.add(f)+ continue++ # 6. Anything unrecognized -> full (fail closed).+ return full(f"{f}: unmapped path", "unmapped_path")++ # Belt-and-suspenders: a directly-edited spec always runs even if its area also mapped.+ selected |= {f for f in changed_files if f in all_specs}++ if not selected:+ return full("no specs selected (defensive full run)", "no_specs")+ return _result("selected", sorted(selected), [], changed_files, total)+++def changed_files_from_git(base_ref: str) -> list[str]:+ result = subprocess.run(+ ["git", "diff", "--name-only", f"{base_ref}...HEAD"],+ cwd=REPO_ROOT,+ capture_output=True,+ text=True,+ check=True,+ )+ return [line for line in result.stdout.splitlines() if line.strip()]+++def write_summary(summary_path: Path, result: dict) -> None:+ lines = ["## Playwright spec selection", ""]+ if result["mode"] == "selected":+ lines.append(+ f"**Selected {result['selected_count']} of {result['total_spec_count']} specs** "+ f"from {result['changed_file_count']} changed files:"+ )+ lines.append("")+ lines += [f"- `{s}`" for s in result["spec_files"]]+ else:+ reason = result["full_run_reasons"][0] if result["full_run_reasons"] else "unknown"+ lines.append(f"**Full run** — {reason}")+ lines.append("")+ lines.append("> A selection miss is caught by the post-merge full run on master (the backstop).")+ lines.append("")+ with summary_path.open("a") as fh:+ fh.write("\n".join(lines) + "\n")+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--base-ref", required=True, help="Base ref to diff against, e.g. origin/master")+ parser.add_argument("--map", default=str(MAP_PATH), help="Path to the area map JSON")+ parser.add_argument("--summary-path", default="", help="Append a Markdown summary here (e.g. $GITHUB_STEP_SUMMARY)")+ parser.add_argument("--pretty", action="store_true", help="Pretty-print the JSON output")+ args = parser.parse_args()++ area_map = load_map(Path(args.map))+ all_specs = discover_specs(REPO_ROOT)+ changed = changed_files_from_git(args.base_ref)+ result = select(changed, area_map, all_specs)++ if args.summary_path:+ write_summary(Path(args.summary_path), result)++ sys.stdout.write(json.dumps(result, indent=2 if args.pretty else None, sort_keys=args.pretty) + "\n")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/test_playwright_spec_selection.py b/tools/test_playwright_spec_selection.pynew file mode 100644index 000000000000..6cf3a1f5663e--- /dev/null+++ b/tools/test_playwright_spec_selection.py@@ -0,0 +1,174 @@+from __future__ import annotations++import sys+import importlib.util+from pathlib import Path+from types import ModuleType++import unittest++SCRIPT_PATH = Path(__file__).with_name("playwright_spec_selection.py")+++def _load_module() -> ModuleType:+ spec = importlib.util.spec_from_file_location("playwright_spec_selection", SCRIPT_PATH)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return module+++selection = _load_module()++# A small stand-in map + spec set so select() cases don't depend on the real repo layout.+FAKE_SPECS = {+ "playwright/e2e/auth.spec.ts",+ "playwright/e2e/billing/billing.spec.ts",+ "playwright/e2e/product-analytics/dashboards.spec.ts",+ "playwright/e2e/product-analytics/insights/trends.spec.ts",+ "products/surveys/frontend/e2e/crud.spec.ts",+}+FAKE_MAP = {+ "force_full": ["posthog/**", "pnpm-lock.yaml", "playwright/*.ts"],+ "products": {"surveys": ["products/surveys/frontend/e2e/"]},+ "scenes": {+ "billing": ["playwright/e2e/billing/"],+ "insights": ["playwright/e2e/product-analytics/"],+ },+ "explicit": {"products/web_analytics/frontend/**": ["playwright/e2e/auth.spec.ts"]},+}+++class TestPlaywrightSpecSelection(unittest.TestCase):+ def _select(self, changed: list[str]) -> dict:+ return selection.select(changed, FAKE_MAP, FAKE_SPECS)++ def test_select_behavior_matrix(self) -> None:+ # (name, changed files, expected mode, expected specs (selected) or reason category (full))+ cases: list[tuple[str, list[str], str, set[str] | str]] = [+ (+ "mapped product frontend narrows to that product's specs",+ ["products/surveys/frontend/logic.ts"],+ "selected",+ {"products/surveys/frontend/e2e/crud.spec.ts"},+ ),+ (+ "mapped scene narrows to its spec dir (nested change still resolves)",+ ["frontend/src/scenes/insights/views/deep/nested.ts"],+ "selected",+ {+ "playwright/e2e/product-analytics/dashboards.spec.ts",+ "playwright/e2e/product-analytics/insights/trends.spec.ts",+ },+ ),+ (+ "explicit rule maps a spec-less product frontend",+ ["products/web_analytics/frontend/tiles.ts"],+ "selected",+ {"playwright/e2e/auth.spec.ts"},+ ),+ (+ "directly edited spec runs itself",+ ["playwright/e2e/auth.spec.ts"],+ "selected",+ {"playwright/e2e/auth.spec.ts"},+ ),+ # Fail-closed: the core safety property. Any of these dropping to "selected" is a+ # coverage hole. The category is the analytics grouping key, so lock it too.+ ("unmapped scene forces full", ["frontend/src/scenes/settings/x.ts"], "full", "unmapped_scene"),+ ("unmapped product forces full", ["products/messaging/frontend/x.ts"], "full", "unmapped_product"),+ ("unrecognized path forces full", ["some/random/file.ts"], "full", "unmapped_path"),+ # force_full wins even when another changed file would have narrowed.+ (+ "force-full pattern forces full alongside a mappable file",+ ["products/surveys/frontend/logic.ts", "posthog/models/team.py"],+ "full",+ "force_full",+ ),+ # `*` must not cross `/`: a nested spec dir change must not be swallowed by `playwright/*.ts`.+ (+ "single-star force-full does not swallow nested spec changes",+ ["playwright/e2e/billing/billing.spec.ts"],+ "selected",+ {"playwright/e2e/billing/billing.spec.ts"},+ ),+ ("empty diff defaults to full", [], "full", "empty_diff"),+ ]+ for name, changed, mode, expected in cases:+ with self.subTest(name):+ result = self._select(changed)+ self.assertEqual(result["mode"], mode, msg=name)+ if mode == "selected":+ self.assertEqual(set(result["spec_files"]), expected, msg=name)+ else:+ self.assertTrue(result["full_run_reasons"], msg=f"{name}: expected a reason")+ self.assertEqual(result["full_run_reason_category"], expected, msg=name)++ def test_over_ceiling_forces_full(self) -> None:+ changed = [f"products/surveys/frontend/f{i}.ts" for i in range(selection.MAX_CHANGED_FILES + 1)]+ self.assertEqual(self._select(changed)["mode"], "full")++ def test_real_map_targets_resolve_on_disk(self) -> None:+ # Guards against map drift: if a spec is renamed/deleted and a target stops+ # resolving, expand_target raises at runtime and CI silently falls open to+ # permanent full runs. This locks every target to a real spec in the two roots.+ area_map = selection.load_map(selection.MAP_PATH)+ all_specs = selection.discover_specs(selection.REPO_ROOT)+ self.assertTrue(all_specs, "no Playwright specs discovered — wrong REPO_ROOT?")++ targets: list[str] = []+ for spec_globs in area_map.get("products", {}).values():+ targets += spec_globs+ for spec_globs in area_map.get("scenes", {}).values():+ targets += spec_globs+ for spec_globs in area_map.get("explicit", {}).values():+ targets += spec_globs++ for target in targets:+ with self.subTest(target):+ resolved = selection.expand_target(target, all_specs) # raises MapError if empty+ for spec in resolved:+ self.assertTrue(+ spec.startswith("playwright/e2e/") or "/frontend/e2e/" in spec,+ msg=f"{target} -> {spec} is outside the spec roots",+ )++ def test_every_spec_is_mapped_or_explicitly_full_suite_only(self) -> None:+ # Forces a conscious decision on every new spec: reachable by a map target+ # (it runs on selective runs for its area) or listed in full_suite_only (it+ # only runs on full suites and when directly edited). Without this, a new+ # spec next to file-level map entries silently never runs selectively.+ area_map = selection.load_map(selection.MAP_PATH)+ all_specs = selection.discover_specs(selection.REPO_ROOT)++ reachable: set[str] = set()+ for section in ("products", "scenes", "explicit"):+ for targets in area_map.get(section, {}).values():+ for target in targets:+ reachable |= selection.expand_target(target, all_specs)+ full_suite_only = set(area_map.get("full_suite_only", []))++ self.assertEqual(+ full_suite_only - all_specs,+ set(),+ msg="full_suite_only lists specs that no longer exist — remove them from tools/playwright_area_map.json",+ )+ self.assertEqual(+ full_suite_only & reachable,+ set(),+ msg="full_suite_only lists specs already reachable by a map target — remove the redundant entries",+ )+ self.assertEqual(+ all_specs - reachable - full_suite_only,+ set(),+ msg=(+ "new spec(s) not reachable by any map target: add a mapping in "+ "tools/playwright_area_map.json (products/scenes/explicit) or list them "+ "under full_suite_only to accept they only run in full suites"+ ),+ )+++if __name__ == "__main__":+ unittest.main()