: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
chore(devex): integrate test selection verdict into backend CI (#57206)
Julian Bez4c6bdce0baa3
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 015003b92eb3..143bd7cc3e67 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -1717,6 +1717,67 @@ jobs:echo "All checks passed."+ test-selection-verdict:+ needs: [django, turbo-tests, changes]+ name: Test selection verdict+ if: always() && github.event_name == 'pull_request'+ runs-on: ubuntu-latest+ timeout-minutes: 10+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@v6+ with:+ fetch-depth: 0++ - name: Install uv+ uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0+ with:+ version: '0.10.2'++ - name: Download JUnit artifacts+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0+ with:+ pattern: junit-results-backend-*+ path: /tmp/junit-results/+ continue-on-error: true++ - name: Run test selection and verdict+ env:+ BASE_REF: ${{ github.event.pull_request.base.ref }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ PR_SHA: ${{ github.event.pull_request.head.sha }}+ PR_BRANCH: ${{ github.event.pull_request.head.ref }}+ run: |+ set -euo pipefail+ mkdir -p /tmp/verdict++ # Fetch the *current* tip of the base branch, not pull_request.base.sha:+ # base.sha is captured at webhook time and goes stale if the branch+ # later merges a newer master, which makes `base.sha...HEAD` balloon+ # to include every merged-in master change.+ git fetch --no-tags origin "$BASE_REF"++ uv run tools/snob_backend_test_selection_shadow.py \+ --base-ref "origin/$BASE_REF" \+ --pretty \+ > /tmp/verdict/selection.json++ uv run tools/test_selection_verdict.py \+ /tmp/verdict/selection.json \+ /tmp/junit-results/ \+ --summary-path "$GITHUB_STEP_SUMMARY" \+ --pretty \+ > /tmp/verdict/verdict.json++ - name: Upload verdict+ if: always()+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0+ with:+ name: test-selection-verdict-pr${{ github.event.pull_request.number }}+ path: /tmp/verdict/+ retention-days: 90+async-migrations:name: Async migrations tests - ${{ matrix.clickhouse-server-image }} (${{ matrix.runner }})needs: [changes, turbo-discover, get_clickhouse_versions]diff --git a/.github/workflows/ci-test-selection-shadow.yml b/.github/workflows/ci-test-selection-shadow.ymldeleted file mode 100644index a3623e8a007c..000000000000--- a/.github/workflows/ci-test-selection-shadow.yml+++ /dev/null@@ -1,66 +0,0 @@-name: Backend CI - Test selection shadow--on:- pull_request:- branches: [master]--permissions:- contents: read--jobs:- shadow-test-selection:- name: Shadow test selection- if: |- github.event_name == 'pull_request'- runs-on: ubuntu-latest- timeout-minutes: 5- steps:- - uses: actions/checkout@v6- with:- fetch-depth: 0-- - name: Install uv- uses: astral-sh/setup-uv@eac588ad8def6316056a12d4907a9d4d84ff7a3b # v7.3.0- with:- version: '0.10.2'-- - name: Run shadow selection- env:- BASE_REF: ${{ github.event.pull_request.base.ref }}- PR_NUMBER: ${{ github.event.pull_request.number }}- PR_SHA: ${{ github.event.pull_request.head.sha }}- PR_BRANCH: ${{ github.event.pull_request.head.ref }}- run: |- set -euo pipefail- mkdir -p /tmp/shadow-selection-- # Write metadata first so the artifact still has run context if- # selection itself blows up (set -e would otherwise skip it).- jq -n \- --arg pr "$PR_NUMBER" \- --arg sha "$PR_SHA" \- --arg branch "$PR_BRANCH" \- --arg base "$BASE_REF" \- --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \- '{pr: $pr, sha: $sha, branch: $branch, base: $base, timestamp: $timestamp}' \- > /tmp/shadow-selection/metadata.json-- # Fetch the *current* tip of the base branch, not pull_request.base.sha:- # base.sha is captured at webhook time and goes stale if the branch later- # merges a newer master, which makes `base.sha...HEAD` balloon to include- # every merged-in master change.- git fetch --no-tags origin "$BASE_REF"-- uv run tools/snob_backend_test_selection_shadow.py \- --base-ref "origin/$BASE_REF" \- --summary-path "$GITHUB_STEP_SUMMARY" \- --pretty \- > /tmp/shadow-selection/selection.json-- - name: Upload shadow selection artifact- if: always()- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- with:- name: shadow-test-selection-pr${{ github.event.pull_request.number }}- path: /tmp/shadow-selection/- retention-days: 30diff --git a/tools/test_selection_verdict.py b/tools/test_selection_verdict.pynew file mode 100644index 000000000000..779ddac2fc47--- /dev/null+++ b/tools/test_selection_verdict.py@@ -0,0 +1,235 @@+#!/usr/bin/env -S uv run --script+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "defusedxml>=0.7.1",+# ]+# ///+"""Compare test selection against actual JUnit failures to produce a verdict.++Evaluates whether the shadow test selector would have caught the tests+that actually failed in CI. Outputs a JSON verdict suitable for batch+collection across PRs.+"""++from __future__ import annotations++import os+import sys+import json+import argparse+from pathlib import Path++from defusedxml import ElementTree+++def classname_to_filepath(classname: str) -> str:+ """Map a JUnit classname to a Python file path.++ Split on '.', take parts until hitting one that starts uppercase,+ join with '/', append '.py'.++ Example:+ posthog.api.test.test_web_experiment.TestWebExperiment+ -> posthog/api/test/test_web_experiment.py+ """+ parts = classname.split(".")+ file_parts: list[str] = []+ for part in parts:+ if part and part[0].isupper():+ break+ file_parts.append(part)+ if not file_parts:+ return classname + ".py"+ return "/".join(file_parts) + ".py"+++def parse_junit_failures(junit_dir: Path) -> tuple[list[str], int, int]:+ """Parse all JUnit XML files and return (failed_test_files, total_tests_run, xml_files_seen)."""+ failed_files: set[str] = set()+ total_tests = 0+ xml_files_seen = 0++ if not junit_dir.exists():+ return [], 0, 0++ for xml_file in sorted(junit_dir.rglob("*.xml")):+ xml_files_seen += 1+ try:+ tree = ElementTree.parse(xml_file)+ except ElementTree.ParseError:+ continue++ root = tree.getroot()++ # Handle both <testsuites> and <testsuite> as root+ if root.tag == "testsuites":+ suites = root.findall("testsuite")+ elif root.tag == "testsuite":+ suites = [root]+ else:+ continue++ # Use ".//testcase" so nested <testsuite> elements (e.g. pytest-xdist,+ # Gradle) are not silently skipped.+ for suite in suites:+ for testcase in suite.findall(".//testcase"):+ total_tests += 1+ has_failure = testcase.find("failure") is not None+ has_error = testcase.find("error") is not None+ if has_failure or has_error:+ classname = testcase.get("classname", "")+ if classname:+ failed_files.add(classname_to_filepath(classname))++ return sorted(failed_files), total_tests, xml_files_seen+++def compute_verdict(+ selection_path: Path,+ junit_dir: Path,+) -> dict[str, object]:+ """Build the verdict JSON comparing selection against actual failures."""+ with open(selection_path) as f:+ selection = json.load(f)++ failed_test_files, total_tests_run, xml_files_seen = parse_junit_failures(junit_dir)++ combined = selection.get("combined", {})+ selected_tests: list[str] = combined.get("tests", [])+ selected_set = set(selected_tests)++ ast_data = selection.get("ast", {})+ full_run_reasons: list[str] = ast_data.get("full_run_reasons", [])+ full_run_triggered = len(full_run_reasons) > 0++ # No JUnit XMLs means we don't actually know what happened — the upstream+ # artifact upload may have failed or the job may have run before tests+ # finished. Emit "unknown" rather than the misleading "success" we'd+ # otherwise infer from "0 failures observed".+ if xml_files_seen == 0:+ conclusion = "unknown"+ recall: float | None = None+ caught: list[str] = []+ missed: list[str] = []+ elif not failed_test_files:+ conclusion = "success"+ recall = None+ caught = []+ missed = []+ elif full_run_triggered:+ # Selector explicitly opted into running the whole suite, so every+ # failure would have been executed. Recording these as "missed"+ # against `combined.tests` would skew the recall metric.+ conclusion = "failure"+ caught = list(failed_test_files)+ missed = []+ recall = 1.0+ else:+ conclusion = "failure"+ caught = sorted(f for f in failed_test_files if f in selected_set)+ missed = sorted(f for f in failed_test_files if f not in selected_set)+ recall = len(caught) / len(failed_test_files)++ pr = os.environ.get("PR_NUMBER", "")+ sha = os.environ.get("PR_SHA", "")+ branch = os.environ.get("PR_BRANCH", "")++ return {+ "pr": pr,+ "sha": sha,+ "branch": branch,+ "backend_conclusion": conclusion,+ "junit_xml_files_seen": xml_files_seen,+ "total_tests_run": total_tests_run,+ "failure_count": len(failed_test_files),+ "failed_test_files": failed_test_files,+ "selected_test_count": len(selected_tests),+ "caught": caught,+ "missed": missed,+ "recall": recall,+ "full_run_triggered": full_run_triggered,+ "full_run_reasons": full_run_reasons,+ }+++def format_summary(verdict: dict[str, object]) -> str:+ """Produce a concise markdown summary for GITHUB_STEP_SUMMARY."""+ lines: list[str] = []+ lines.append("## Test selection verdict")+ lines.append("")++ conclusion = verdict["backend_conclusion"]+ failure_count = verdict["failure_count"]+ recall = verdict["recall"]+ selected = verdict["selected_test_count"]+ full_run_triggered = verdict.get("full_run_triggered", False)++ if conclusion == "unknown":+ lines.append("Backend conclusion unknown — no JUnit XML artifacts were found.")+ lines.append("")+ lines.append(f"{selected} tests would have been selected by the shadow selector.")+ elif conclusion == "success":+ lines.append(f"Backend passed. {selected} tests were selected by the shadow selector.")+ lines.append("")+ lines.append("No failures to evaluate recall against.")+ else:+ recall_str = f"{recall:.0%}" if recall is not None else "n/a"+ lines.append(f"**Recall: {recall_str}** ({failure_count} failed test files, {selected} selected)")+ if full_run_triggered:+ lines.append("")+ lines.append("Full-run mode was active, so every failure counts as caught.")+ lines.append("")++ caught = verdict.get("caught", [])+ missed = verdict.get("missed", [])++ if caught:+ lines.append(f"**Caught** ({len(caught)}):")+ for f in caught:+ lines.append(f"- `{f}`")++ if missed:+ lines.append("")+ lines.append(f"**Missed** ({len(missed)}):")+ for f in missed:+ lines.append(f"- `{f}`")++ full_run_reasons = verdict.get("full_run_reasons", [])+ if full_run_reasons:+ lines.append("")+ lines.append("**Full-run triggered** — selector would have run everything anyway:")+ for reason in full_run_reasons:+ lines.append(f"- {reason}")++ lines.append("")+ return "\n".join(lines)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("selection_json", help="Path to the selection JSON from snob_backend_test_selection_shadow.py")+ parser.add_argument("junit_dir", help="Directory containing JUnit XML files (searched recursively)")+ parser.add_argument("--summary-path", help="Append markdown summary to this file (e.g. $GITHUB_STEP_SUMMARY)")+ parser.add_argument("--pretty", action="store_true", help="Pretty-print JSON output")+ args = parser.parse_args()++ selection_path = Path(args.selection_json)+ junit_dir = Path(args.junit_dir)++ if not selection_path.exists():+ sys.stderr.write(f"Error: selection JSON not found: {selection_path}\n")+ sys.exit(1)++ verdict = compute_verdict(selection_path, junit_dir)++ indent = 2 if args.pretty else None+ sys.stdout.write(json.dumps(verdict, indent=indent, sort_keys=True) + "\n")++ if args.summary_path:+ with Path(args.summary_path).expanduser().open("a") as fh:+ fh.write(format_summary(verdict))+++if __name__ == "__main__":+ main()diff --git a/tools/test_test_selection_verdict.py b/tools/test_test_selection_verdict.pynew file mode 100644index 000000000000..cb527546ba0e--- /dev/null+++ b/tools/test_test_selection_verdict.py@@ -0,0 +1,216 @@+from __future__ import annotations++import sys+import json+import tempfile+import importlib.util+from pathlib import Path+from types import ModuleType++import unittest++from parameterized import parameterized++SCRIPT_PATH = Path(__file__).with_name("test_selection_verdict.py")+++def _load_verdict_module() -> ModuleType:+ spec = importlib.util.spec_from_file_location("test_selection_verdict", SCRIPT_PATH)+ assert spec is not None+ assert spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return module+++def _write_junit(junit_dir: Path, name: str, content: str) -> None:+ junit_dir.mkdir(parents=True, exist_ok=True)+ (junit_dir / name).write_text(content)+++def _write_selection(path: Path, *, combined_tests: list[str], full_run_reasons: list[str] | None = None) -> None:+ selection = {+ "combined": {"tests": combined_tests, "count": len(combined_tests)},+ "ast": {"tests": combined_tests, "full_run_reasons": full_run_reasons or []},+ "snob": {"tests": [], "count": 0, "status": "ok"},+ }+ path.write_text(json.dumps(selection))+++JUNIT_FAILURE = """<?xml version="1.0" encoding="utf-8"?>+<testsuites>+ <testsuite name="pytest" tests="2" failures="1" errors="0">+ <testcase classname="posthog.api.test.test_foo.TestFoo" name="test_pass" time="0.1"/>+ <testcase classname="posthog.api.test.test_foo.TestFoo" name="test_fail" time="0.2">+ <failure message="assert False">Traceback...</failure>+ </testcase>+ </testsuite>+</testsuites>+"""++JUNIT_NESTED_FAILURE = """<?xml version="1.0" encoding="utf-8"?>+<testsuites>+ <testsuite name="outer" tests="1" failures="1">+ <testsuite name="inner" tests="1" failures="1">+ <testcase classname="posthog.api.test.test_nested.TestNested" name="test_x">+ <error message="boom">Traceback...</error>+ </testcase>+ </testsuite>+ </testsuite>+</testsuites>+"""++JUNIT_ALL_PASS = """<?xml version="1.0" encoding="utf-8"?>+<testsuites>+ <testsuite name="pytest" tests="1" failures="0">+ <testcase classname="posthog.api.test.test_bar.TestBar" name="test_ok"/>+ </testsuite>+</testsuites>+"""+++class TestClassnameToFilepath(unittest.TestCase):+ @parameterized.expand(+ [+ (+ "standard_django_class",+ "posthog.api.test.test_web_experiment.TestWebExperiment",+ "posthog/api/test/test_web_experiment.py",+ ),+ (+ "function_test_no_class",+ "posthog.api.test.test_module",+ "posthog/api/test/test_module.py",+ ),+ (+ "ee_path",+ "ee.clickhouse.queries.test.test_cohort.TestCohort",+ "ee/clickhouse/queries/test/test_cohort.py",+ ),+ (+ "products_path",+ "products.feature_flags.backend.test.test_api.TestFlags",+ "products/feature_flags/backend/test/test_api.py",+ ),+ ]+ )+ def test_maps_classname(self, _name: str, classname: str, expected: str) -> None:+ verdict = _load_verdict_module()+ self.assertEqual(verdict.classname_to_filepath(classname), expected)+++class TestParseJunitFailures(unittest.TestCase):+ def test_returns_zero_when_dir_missing(self) -> None:+ verdict = _load_verdict_module()+ with tempfile.TemporaryDirectory() as root:+ failures, total, seen = verdict.parse_junit_failures(Path(root) / "missing")+ self.assertEqual(failures, [])+ self.assertEqual(total, 0)+ self.assertEqual(seen, 0)++ def test_extracts_failures_with_classname_mapping(self) -> None:+ verdict = _load_verdict_module()+ with tempfile.TemporaryDirectory() as root:+ junit_dir = Path(root)+ _write_junit(junit_dir, "junit-core.xml", JUNIT_FAILURE)+ failures, total, seen = verdict.parse_junit_failures(junit_dir)+ self.assertEqual(failures, ["posthog/api/test/test_foo.py"])+ self.assertEqual(total, 2)+ self.assertEqual(seen, 1)++ def test_finds_testcases_in_nested_testsuites(self) -> None:+ verdict = _load_verdict_module()+ with tempfile.TemporaryDirectory() as root:+ junit_dir = Path(root)+ _write_junit(junit_dir, "junit.xml", JUNIT_NESTED_FAILURE)+ failures, total, _seen = verdict.parse_junit_failures(junit_dir)+ self.assertEqual(failures, ["posthog/api/test/test_nested.py"])+ self.assertEqual(total, 1)++ def test_skips_malformed_xml(self) -> None:+ verdict = _load_verdict_module()+ with tempfile.TemporaryDirectory() as root:+ junit_dir = Path(root)+ _write_junit(junit_dir, "good.xml", JUNIT_ALL_PASS)+ _write_junit(junit_dir, "bad.xml", "<not valid xml")+ failures, total, seen = verdict.parse_junit_failures(junit_dir)+ self.assertEqual(failures, [])+ self.assertEqual(total, 1)+ self.assertEqual(seen, 2)+++class TestComputeVerdict(unittest.TestCase):+ def _run(+ self,+ *,+ combined_tests: list[str],+ full_run_reasons: list[str] | None = None,+ junit_files: list[tuple[str, str]] | None = None,+ ) -> dict[str, object]:+ verdict = _load_verdict_module()+ with tempfile.TemporaryDirectory() as root:+ tmp_path = Path(root)+ selection_path = tmp_path / "selection.json"+ _write_selection(selection_path, combined_tests=combined_tests, full_run_reasons=full_run_reasons)++ junit_dir = tmp_path / "junit"+ for name, content in junit_files or []:+ _write_junit(junit_dir, name, content)++ return verdict.compute_verdict(selection_path, junit_dir)++ def test_unknown_when_no_junit_xmls_found(self) -> None:+ result = self._run(combined_tests=["posthog/api/test/test_foo.py"])+ self.assertEqual(result["backend_conclusion"], "unknown")+ self.assertIsNone(result["recall"])+ self.assertEqual(result["caught"], [])+ self.assertEqual(result["missed"], [])+ self.assertEqual(result["junit_xml_files_seen"], 0)++ def test_success_when_all_pass(self) -> None:+ result = self._run(+ combined_tests=["posthog/api/test/test_bar.py"],+ junit_files=[("junit.xml", JUNIT_ALL_PASS)],+ )+ self.assertEqual(result["backend_conclusion"], "success")+ self.assertIsNone(result["recall"])+ self.assertEqual(result["failure_count"], 0)++ def test_failure_caught_when_in_selection(self) -> None:+ result = self._run(+ combined_tests=["posthog/api/test/test_foo.py", "posthog/api/test/test_other.py"],+ junit_files=[("junit.xml", JUNIT_FAILURE)],+ )+ self.assertEqual(result["backend_conclusion"], "failure")+ self.assertEqual(result["recall"], 1.0)+ self.assertEqual(result["caught"], ["posthog/api/test/test_foo.py"])+ self.assertEqual(result["missed"], [])++ def test_failure_missed_when_not_in_selection(self) -> None:+ result = self._run(+ combined_tests=["posthog/api/test/test_unrelated.py"],+ junit_files=[("junit.xml", JUNIT_FAILURE)],+ )+ self.assertEqual(result["backend_conclusion"], "failure")+ self.assertEqual(result["recall"], 0.0)+ self.assertEqual(result["caught"], [])+ self.assertEqual(result["missed"], ["posthog/api/test/test_foo.py"])++ def test_full_run_treats_failures_as_caught(self) -> None:+ # Selection's combined.tests does NOT include the failing file, but+ # full_run_reasons indicates the selector opted into running everything.+ result = self._run(+ combined_tests=["posthog/api/test/test_unrelated.py"],+ full_run_reasons=["conftest.py matches full-run pattern"],+ junit_files=[("junit.xml", JUNIT_FAILURE)],+ )+ self.assertEqual(result["backend_conclusion"], "failure")+ self.assertTrue(result["full_run_triggered"])+ self.assertEqual(result["recall"], 1.0)+ self.assertEqual(result["caught"], ["posthog/api/test/test_foo.py"])+ self.assertEqual(result["missed"], [])+++if __name__ == "__main__":+ unittest.main()