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.

feat(ci): widen playwright spec map and categorize selector errors (#72277)

Georges-Antoine Assif362027bdb7d
diff --git a/.github/workflows/ci-e2e-playwright.yml b/.github/workflows/ci-e2e-playwright.yml
index 008bc9323a83..8c274a730ffa 100644
--- a/.github/workflows/ci-e2e-playwright.yml
+++ b/.github/workflows/ci-e2e-playwright.yml
@@ -355,7 +355,13 @@ jobs:
# 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"
+ # This runs before Python, so tag a fetch failure with its own detail —
+ # otherwise classify sees only a failed step and reports an empty detail.
+ if ! git fetch --no-tags --depth=1000 --filter=blob:none origin "$BASE_REF:refs/remotes/origin/$BASE_REF"; then
+ echo "::warning::git fetch of base ref failed — full run"
+ echo "reason_detail=git_fetch_failed" >> "$GITHUB_OUTPUT"
+ exit 1
+ fi
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
@@ -369,6 +375,7 @@ jobs:
id: classify
env:
SELECT_OUTCOME: ${{ steps.select.outcome }}
+ SELECT_REASON_DETAIL: ${{ steps.select.outputs.reason_detail }}
shell: bash
run: |
set -euo pipefail
@@ -385,7 +392,16 @@ jobs:
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
+ # Distinguish an unrebased branch (script/map not present yet — expected,
+ # self-resolves on rebase) from a genuine selector failure worth investigating.
+ if [[ ! -f tools/playwright_spec_selection.py ]] || [[ ! -f tools/playwright_area_map.json ]]; then
+ REASON_CATEGORY=selector_unavailable
+ else
+ REASON_CATEGORY=selector_error
+ # A bash-stage fetch failure exits before Python and tags itself here;
+ # the Python paths carry their own detail in the JSON below.
+ REASON_DETAIL="${SELECT_REASON_DETAIL:-}"
+ fi
else
MODE=$(jq -r '.mode' /tmp/spec-selection.json)
SELECTED_COUNT=$(jq -r '.selected_count' /tmp/spec-selection.json)
diff --git a/tools/playwright_area_map.json b/tools/playwright_area_map.json
index 947239658ac6..7a7908234f83 100644
--- a/tools/playwright_area_map.json
+++ b/tools/playwright_area_map.json
@@ -10,7 +10,26 @@
"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)."
+ "(and when directly edited).",
+ "`ignore` lists paths that provably CANNOT affect the app under test (docs, agent instructions,",
+ "lint rules, workflows for other suites): they contribute nothing to selection instead of forcing",
+ "a full run. `force_full` outranks `ignore`, no ignore pattern may match a spec (test-enforced),",
+ "and an all-ignored diff still runs the full suite (category `all_ignored`) until telemetry",
+ "justifies a skip mode. Only add entries that cannot reach the app bundle, the backend, or the",
+ "e2e stack config.",
+ "`scenes_smoke_only` lists scenes with NO direct e2e coverage — no spec navigates to them, so",
+ "the full suite wouldn't exercise them either. Changes there run `smoke_subset` (app boots,",
+ "auth works) instead of everything. A scene must not appear in both `scenes` and",
+ "`scenes_smoke_only` (test-enforced); when a scene gains a real spec, move it to `scenes`."
+ ],
+ "ignore": [
+ "*.md",
+ "**/*.md",
+ "docs/**",
+ ".agents/**",
+ ".semgrep/**",
+ ".github/workflows/**",
+ "common/storybook/**"
],
"force_full": [
"playwright/utils/**",
@@ -44,6 +63,17 @@
".github/clickhouse-versions.json",
"bin/**"
],
+ "smoke_subset": ["playwright/e2e/auth.spec.ts"],
+ "scenes_smoke_only": [
+ "billing",
+ "groups",
+ "heatmaps",
+ "hog-functions",
+ "inbox",
+ "integrations",
+ "max",
+ "web-analytics"
+ ],
"products": {
"posthog_ai": ["products/posthog_ai/frontend/e2e/"],
"replay": ["products/replay/frontend/e2e/"],
@@ -55,6 +85,8 @@
"sessions": ["products/replay/frontend/e2e/"],
"experiments": ["playwright/e2e/experiments/"],
"cohorts": ["playwright/e2e/product-analytics/cohorts.spec.ts"],
+ "trends": ["playwright/e2e/product-analytics/"],
+ "data-warehouse": ["playwright/e2e/sql-editor*.spec.ts"],
"dashboard": [
"playwright/e2e/product-analytics/dashboards.spec.ts",
"playwright/e2e/shared-dashboard-styling.spec.ts",
@@ -80,10 +112,18 @@
"onboarding": ["playwright/e2e/before-onboarding.spec.ts", "playwright/e2e/signup.spec.ts"],
"data-management": ["playwright/e2e/event-definitions.spec.ts", "playwright/e2e/annotations.spec.ts"],
"annotations": ["playwright/e2e/annotations.spec.ts"],
- "toolbar-launch": ["playwright/e2e/toolbar.spec.ts"]
+ "toolbar-launch": ["playwright/e2e/toolbar.spec.ts"],
+ "settings": ["playwright/e2e/before-onboarding.spec.ts"],
+ "feature-flags": ["products/surveys/frontend/e2e/quickcreate.spec.ts"]
},
"explicit": {
"products/product_analytics/frontend/**": ["playwright/e2e/product-analytics/"],
+ "products/dashboards/frontend/**": [
+ "playwright/e2e/product-analytics/dashboards.spec.ts",
+ "playwright/e2e/shared-dashboard-styling.spec.ts",
+ "playwright/e2e/shared-dashboard-unauthenticated.spec.ts"
+ ],
+ "products/session_replay/frontend/**": ["products/replay/frontend/e2e/"],
"products/experiments/frontend/**": ["playwright/e2e/experiments/"],
"products/persons/frontend/**": ["playwright/e2e/persons/persons.spec.ts"],
"products/cohorts/frontend/**": ["playwright/e2e/product-analytics/cohorts.spec.ts"],
diff --git a/tools/playwright_spec_selection.py b/tools/playwright_spec_selection.py
index f9ab72264388..7f8b988b5b93 100644
--- a/tools/playwright_spec_selection.py
+++ b/tools/playwright_spec_selection.py
@@ -17,6 +17,22 @@ 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).
+Two carve-outs soften fail-closed where the full suite provably adds nothing:
+
+- `ignore`: paths that cannot affect the app under test (docs, agent
+ instructions, lint rules, workflows for other suites) contribute nothing to
+ selection instead of forcing a full run. `force_full` outranks `ignore`, and
+ a diff where EVERY file is ignored still falls closed to a full run (category
+ `all_ignored`) — running nothing is a trust-model change this selector
+ deliberately doesn't make; the category exists to measure how much a skip
+ mode would save before anyone builds it.
+- `scenes_smoke_only` + `smoke_subset`: a scene listed here declares it has NO
+ direct e2e coverage — no spec navigates to it, so the full suite wouldn't
+ exercise it either. Changes there run the cheap `smoke_subset` (app boots,
+ auth works) instead of everything. A mapping in `scenes` outranks the
+ smoke-only list; writing a real spec for the scene means moving it to
+ `scenes`.
+
Emits a single JSON object to stdout:
{
@@ -43,6 +59,7 @@ import re
import sys
import json
import argparse
+import traceback
import subprocess
from pathlib import Path
@@ -160,8 +177,11 @@ def select(changed_files: list[str], area_map: dict, all_specs: set[str]) -> dic
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", [])]
+ ignore = [_compile_glob(p) for p in area_map.get("ignore", [])]
products = area_map.get("products", {})
scenes = area_map.get("scenes", {})
+ scenes_smoke_only = set(area_map.get("scenes_smoke_only", []))
+ smoke_subset = area_map.get("smoke_subset", [])
explicit = [(p, _compile_glob(p), targets) for p, targets in area_map.get("explicit", {}).items()]
def explicit_match(path: str, selected: set[str]) -> bool:
@@ -173,13 +193,21 @@ def select(changed_files: list[str], area_map: dict, all_specs: set[str]) -> dic
return False
selected: set[str] = set()
+ ignored_count = 0
for f in changed_files:
- # 1. Shared infra / backend / unattributable code -> full (highest priority).
+ # 1. Shared infra / backend / unattributable code -> full (highest priority,
+ # deliberately above `ignore` so an ignore glob can never swallow a
+ # force-full path like the playwright workflow file itself).
for pat, rx in force_full:
if rx.match(f):
return full(f"{f} matches force-full pattern '{pat}'", "force_full", pat)
- # 2. Product-owned frontend -> that product's specs (or an explicit rule for
+ # 2. Provably inert paths contribute nothing (and don't force full).
+ if any(rx.match(f) for rx in ignore):
+ ignored_count += 1
+ continue
+
+ # 3. 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:
@@ -192,7 +220,9 @@ def select(changed_files: list[str], area_map: dict, all_specs: set[str]) -> dic
continue
return full(f"{f}: product '{name}' has no spec mapping", "unmapped_product", name)
- # 3. Frontend scene -> mapped specs.
+ # 4. Frontend scene -> mapped specs, or the smoke subset for scenes that
+ # declared they have no direct e2e coverage (the full suite wouldn't
+ # exercise them either, so it only buys the boot/auth smoke signal).
sm = _SCENE_RE.match(f)
if sm:
area = sm.group(1)
@@ -200,28 +230,48 @@ def select(changed_files: list[str], area_map: dict, all_specs: set[str]) -> dic
for t in scenes[area]:
selected |= expand_target(t, all_specs)
continue
+ if area in scenes_smoke_only:
+ for t in smoke_subset:
+ selected |= expand_target(t, all_specs)
+ continue
return full(f"{f}: scene '{area}' has no spec mapping", "unmapped_scene", area)
- # 4. Explicit path rules.
+ # 5. Explicit path rules.
if explicit_match(f, selected):
continue
- # 5. A directly-edited spec runs itself.
+ # 6. A directly-edited spec runs itself.
if f in all_specs:
selected.add(f)
continue
- # 6. Anything unrecognized -> full (fail closed).
+ # 7. Anything unrecognized -> full (fail closed).
return full(f"{f}: unmapped path", "unmapped_path", _dir_prefix(f))
# 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:
+ if ignored_count == len(changed_files):
+ return full(
+ f"all {ignored_count} changed files are ignore-listed (full run until a skip mode exists)",
+ "all_ignored",
+ )
return full("no specs selected (defensive full run)", "no_specs")
return _result("selected", sorted(selected), [], changed_files, total)
+def _error_result(detail: str, changed_files: list[str] | None = None, total_spec_count: int = 0) -> dict:
+ """The selector itself failed. Fall closed to a full run, but record why so the
+ failure is visible in telemetry instead of surfacing as an opaque empty output.
+
+ Carry through whatever counts were already known when the failure hit, so the
+ telemetry doesn't report false zeroes for inputs we'd successfully computed."""
+ return _result(
+ "full", [], [f"selector error: {detail}"], changed_files or [], total_spec_count, "selector_error", detail
+ )
+
+
def changed_files_from_git(base_ref: str) -> list[str]:
result = subprocess.run(
["git", "diff", "--name-only", f"{base_ref}...HEAD"],
@@ -252,6 +302,38 @@ def write_summary(summary_path: Path, result: dict) -> None:
fh.write("\n".join(lines) + "\n")
+def _compute_result(args: argparse.Namespace) -> dict:
+ """Run the selection, falling closed to a categorized full run on any failure.
+
+ Each step is tagged separately so telemetry points at the real cause — a git
+ environment failure reads as ``git_diff_failed``, not ``map_load_failed`` — and
+ carries whatever counts were known by the time the failure hit. The category is
+ the low-cardinality bucket; the traceback (git's captured stderr, the unresolved
+ map target, the unforeseen bug) is printed to stderr so the CI step log keeps the
+ specific cause a category alone can't carry."""
+ try:
+ area_map = load_map(Path(args.map))
+ all_specs = discover_specs(REPO_ROOT)
+ except (OSError, ValueError):
+ traceback.print_exc(file=sys.stderr)
+ return _error_result("map_load_failed")
+
+ try:
+ changed = changed_files_from_git(args.base_ref)
+ except (subprocess.CalledProcessError, OSError):
+ traceback.print_exc(file=sys.stderr)
+ return _error_result("git_diff_failed", total_spec_count=len(all_specs))
+
+ try:
+ return select(changed, area_map, all_specs)
+ except MapError:
+ traceback.print_exc(file=sys.stderr)
+ return _error_result("map_target_unresolved", changed, len(all_specs))
+ except Exception:
+ traceback.print_exc(file=sys.stderr)
+ return _error_result("unexpected_error", changed, len(all_specs))
+
+
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")
@@ -260,10 +342,7 @@ def main() -> int:
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)
+ result = _compute_result(args)
if args.summary_path:
write_summary(Path(args.summary_path), result)
diff --git a/tools/test_playwright_spec_selection.py b/tools/test_playwright_spec_selection.py
index ee4de4eae030..c072d9b8d0ed 100644
--- a/tools/test_playwright_spec_selection.py
+++ b/tools/test_playwright_spec_selection.py
@@ -1,11 +1,13 @@
from __future__ import annotations
import sys
+import argparse
import importlib.util
from pathlib import Path
from types import ModuleType
import unittest
+from unittest import mock
SCRIPT_PATH = Path(__file__).with_name("playwright_spec_selection.py")
@@ -31,6 +33,9 @@ FAKE_SPECS = {
}
FAKE_MAP = {
"force_full": ["posthog/**", "pnpm-lock.yaml", "playwright/*.ts"],
+ "ignore": ["docs/**", "**/*.md"],
+ "smoke_subset": ["playwright/e2e/auth.spec.ts"],
+ "scenes_smoke_only": ["inbox"],
"products": {"surveys": ["products/surveys/frontend/e2e/"]},
"scenes": {
"billing": ["playwright/e2e/billing/"],
@@ -108,6 +113,35 @@ class TestPlaywrightSpecSelection(unittest.TestCase):
{"playwright/e2e/billing/billing.spec.ts"},
),
("empty diff defaults to full", [], "full", ("empty_diff", "")),
+ # Ignore-listed paths must not force full (that's the feature) and must not
+ # outrank force_full (that would let an ignore glob swallow a critical path).
+ (
+ "ignored file contributes nothing alongside a mapped file",
+ ["docs/handbook/page.txt", "products/surveys/frontend/logic.ts"],
+ "selected",
+ {"products/surveys/frontend/e2e/crud.spec.ts"},
+ ),
+ (
+ "all-ignored diff falls closed to full with its own category",
+ ["docs/handbook/page.txt", "some/notes.md"],
+ "full",
+ ("all_ignored", ""),
+ ),
+ (
+ "force-full wins over ignore for the same file",
+ ["posthog/README.md"],
+ "full",
+ ("force_full", "posthog/**"),
+ ),
+ # A smoke-only scene (declared: no direct coverage) narrows to the smoke
+ # subset instead of forcing full — regressing this reverts the scene to
+ # paying for the whole suite that never exercises it.
+ (
+ "smoke-only scene narrows to the smoke subset",
+ ["frontend/src/scenes/inbox/components/Inbox.tsx"],
+ "selected",
+ {"playwright/e2e/auth.spec.ts"},
+ ),
]
for name, changed, mode, expected in cases:
with self.subTest(name):
@@ -133,7 +167,7 @@ class TestPlaywrightSpecSelection(unittest.TestCase):
all_specs = selection.discover_specs(selection.REPO_ROOT)
self.assertTrue(all_specs, "no Playwright specs discovered — wrong REPO_ROOT?")
- targets: list[str] = []
+ targets: list[str] = list(area_map.get("smoke_subset", []))
for spec_globs in area_map.get("products", {}).values():
targets += spec_globs
for spec_globs in area_map.get("scenes", {}).values():
@@ -150,6 +184,47 @@ class TestPlaywrightSpecSelection(unittest.TestCase):
msg=f"{target} -> {spec} is outside the spec roots",
)
+ def test_smoke_only_scenes_are_consistent(self) -> None:
+ # A scene in both `scenes` and `scenes_smoke_only` is a contradiction — the
+ # mapped entry silently wins and the smoke declaration is dead weight. And a
+ # non-empty smoke-only list with an empty smoke_subset would send every
+ # smoke-only scene to the defensive no_specs full run, silently killing the
+ # mechanism.
+ area_map = selection.load_map(selection.MAP_PATH)
+ overlap = set(area_map.get("scenes_smoke_only", [])) & set(area_map.get("scenes", {}))
+ self.assertEqual(overlap, set(), msg="scene(s) listed in both scenes and scenes_smoke_only")
+ if area_map.get("scenes_smoke_only"):
+ self.assertTrue(
+ area_map.get("smoke_subset"),
+ msg="scenes_smoke_only requires a non-empty smoke_subset",
+ )
+
+ def test_ignore_patterns_never_match_specs(self) -> None:
+ # An over-broad ignore entry (e.g. "playwright/**") would make a directly-edited
+ # spec contribute nothing — the one selection miss the master backstop can't
+ # attribute. Lock ignore to non-spec paths.
+ area_map = selection.load_map(selection.MAP_PATH)
+ all_specs = selection.discover_specs(selection.REPO_ROOT)
+ for pattern in area_map.get("ignore", []):
+ with self.subTest(pattern):
+ rx = selection._compile_glob(pattern)
+ matched = sorted(s for s in all_specs if rx.match(s))
+ self.assertEqual(matched, [], msg=f"ignore pattern {pattern!r} matches spec files")
+
+ def test_git_failure_tags_git_diff_failed_and_keeps_known_totals(self) -> None:
+ # A git environment failure (e.g. a missing binary) surfaces as OSError, not
+ # CalledProcessError. It must read as git_diff_failed — not map_load_failed — and
+ # must keep the spec count already discovered, so selector_error telemetry points
+ # at the real cause instead of reporting a false zero total.
+ args = argparse.Namespace(map=str(selection.MAP_PATH), base_ref="origin/master")
+ with mock.patch.object(selection, "changed_files_from_git", side_effect=FileNotFoundError("git missing")):
+ result = selection._compute_result(args)
+
+ self.assertEqual(result["mode"], "full")
+ self.assertEqual(result["full_run_reason_category"], "selector_error")
+ self.assertEqual(result["full_run_reason_detail"], "git_diff_failed")
+ self.assertGreater(result["total_spec_count"], 0)
+
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
@@ -159,6 +234,8 @@ class TestPlaywrightSpecSelection(unittest.TestCase):
all_specs = selection.discover_specs(selection.REPO_ROOT)
reachable: set[str] = set()
+ for target in area_map.get("smoke_subset", []):
+ reachable |= selection.expand_target(target, all_specs)
for section in ("products", "scenes", "explicit"):
for targets in area_map.get(section, {}).values():
for target in targets: