: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(ci): prune dead nodeids from .test_durations via junit scoping (#86035)
Paul D'Ambrac22b95e0009c
diff --git a/.github/scripts/optimize_test_durations.py b/.github/scripts/optimize_test_durations.pyindex 422a3455982f..a77a03a1ab9d 100644--- a/.github/scripts/optimize_test_durations.py+++ b/.github/scripts/optimize_test_durations.py@@ -86,6 +86,7 @@ _JUNIT_ARTIFACT_PREFIX = {"CorePOE": "junit-results-backend-core-poe","Temporal": "junit-results-backend-temporal","Products": "product-junit-results",+ "Dagster": "junit-results-dagster",}@@ -102,6 +103,8 @@ class JUnitShard:name: strcall_times: dict[str, float]+ # An XML of this shard (any attempt) did not parse, so call_times is incomplete.+ unreadable: bool = False@classmethoddef load_all(cls, junit_dir: Path, segment: str | None = None) -> list["JUnitShard"]:@@ -111,40 +114,64 @@ class JUnitShard:Segment match is anchored at the artifact prefix so "Core" doesn'taccidentally pick up "core-poe" or any future "*-core-*" name, and"CorePOE" matches "core-poe" instead of the absent substring "corepoe".++ Re-run attempts upload as `<shard>-attempt<N>` (attempt 1 carries no+ suffix). Attempts of one shard merge into one entry under the base+ shard name, so downstream shard-set matching sees one entry per shard.+ The newest attempt's time wins for a test every attempt ran; a test+ only an earlier attempt ran stays, because a rerun without the pinned+ plan can reshard it into a shard that is not rerun at all."""- shards = []+ # Group re-run attempt dirs by base shard name (attempt 1 is the+ # unsuffixed dir), oldest attempt first.+ by_base: dict[str, list[tuple[int, Path]]] = defaultdict(list)for shard_dir in sorted(junit_dir.iterdir()):if not shard_dir.is_dir():continue+ match = re.match(r"^(.*?)(?:-attempt(\d+))?$", shard_dir.name.lower())+ if not match:+ continue+ base, attempt_n = match.group(1), int(match.group(2) or 1)+ by_base[base].append((attempt_n, shard_dir))+ shards = []+ for base, attempts in sorted(by_base.items()):if segment:artifact_prefix = _JUNIT_ARTIFACT_PREFIX.get(segment, f"junit-results-backend-{segment.lower()}")# Anchor with `\d+$` so the Core prefix doesn't accidentally# eat core-poe-N (which also starts with junit-results-backend-core-).pattern = re.compile(rf"^{re.escape(artifact_prefix)}-\d+$")- if not pattern.match(shard_dir.name.lower()):+ if not pattern.match(base):continue- xml_files = sorted(shard_dir.glob("*.xml"))- if not xml_files:- continue-call_times: dict[str, float] = {}- for xml_file in xml_files:- for test_id, call_time in cls._parse_call_times(xml_file).items():- call_times[test_id] = max(call_times.get(test_id, 0.0), call_time)- shards.append(cls(name=shard_dir.name, call_times=call_times))+ found_xml = False+ unreadable = False+ for _attempt_n, shard_dir in sorted(attempts):+ attempt_times: dict[str, float] = {}+ for xml_file in sorted(shard_dir.glob("*.xml")):+ found_xml = True+ parsed = cls._parse_call_times(xml_file)+ if parsed is None:+ unreadable = True+ continue+ for test_id, call_time in parsed.items():+ attempt_times[test_id] = max(attempt_times.get(test_id, 0.0), call_time)+ call_times.update(attempt_times)+ if not found_xml:+ continue+ shards.append(cls(name=base, call_times=call_times, unreadable=unreadable))return shards@staticmethod- def _parse_call_times(xml_path: Path) -> dict[str, float]:- """Extract {pytest_id: call_time} for every parseable testcase."""+ def _parse_call_times(xml_path: Path) -> dict[str, float] | None:+ """Extract {pytest_id: call_time} for every parseable testcase, None when the XML does not parse."""try:tree = ET.parse(xml_path)except ParseError as e:logger.warning(" Could not parse JUnit XML %s: %s", xml_path, e)- return {}+ return Nonecall_times: dict[str, float] = {}for tc in tree.getroot().iter("testcase"):pytest_id = _junit_to_pytest_id(tc.get("classname", ""), tc.get("name", ""))@@ -808,6 +835,14 @@ def main():if not junit_shards:logger.error("--scope-to-junit requires --junit-dir with matching artifacts")sys.exit(1)+ # A timing shard whose JUnit never uploaded, or uploaded truncated (the+ # parser turns that into an empty shard), would read as "nothing ran" and+ # lose every nodeid it owns, so scoping needs one readable JUnit per+ # shard. The workflow retries unscoped on this exit.+ unreadable = [shard.name for shard in junit_shards if shard.unreadable or not shard.call_times]+ if not shard_sets_match(shards, junit_shards) or unreadable:+ logger.error("--scope-to-junit needs a readable JUnit artifact for every timing shard: %s", unreadable)+ sys.exit(1)ran = set().union(*(s.call_times.keys() for s in junit_shards))before_count = len(durations)durations = {k: v for k, v in durations.items() if k in ran}diff --git a/.github/scripts/test_optimize_test_durations.py b/.github/scripts/test_optimize_test_durations.pyindex 524b94d0f136..fbb5036b6f04 100644--- a/.github/scripts/test_optimize_test_durations.py+++ b/.github/scripts/test_optimize_test_durations.py@@ -138,6 +138,55 @@ class TestAverageDurations:main()assert not out.exists()+ @pytest.mark.parametrize(+ "shard_two_uploads",+ [+ {},+ {"junit-results-backend-core-2": b"<testsuite><testcase"},+ {+ "junit-results-backend-core-2": _MIN_JUNIT_XML,+ "junit-results-backend-core-2-attempt2": b"<testsuite><testcase",+ },+ ],+ )+ def test_scope_to_junit_refuses_a_shard_without_readable_junit(self, tmp_path, monkeypatch, shard_two_uploads):+ # Shard 2's JUnit never uploaded, uploaded truncated, or reran with a+ # truncated attempt on top of a good one. Scoping to what parsed would+ # drop nodeids shard 2 owns, so the script must exit and let the+ # workflow retry unscoped.+ artifacts = tmp_path / "timing_artifacts"+ for shard, test_id in (+ ("1", "posthog/test_foo.py::TestThing::test_one"),+ ("2", "posthog/test_bar.py::test_two"),+ ):+ shard_dir = artifacts / f"timing_data-Core-{shard}"+ shard_dir.mkdir(parents=True)+ (shard_dir / ".test_durations").write_text(json.dumps({test_id: 1.0}))+ junit_dir = tmp_path / "junit_artifacts"+ (junit_dir / "junit-results-backend-core-1").mkdir(parents=True)+ (junit_dir / "junit-results-backend-core-1" / "junit.xml").write_bytes(_MIN_JUNIT_XML)+ for name, xml in shard_two_uploads.items():+ (junit_dir / name).mkdir()+ (junit_dir / name / "junit.xml").write_bytes(xml)+ out = tmp_path / "core_durations"+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "optimize_test_durations.py",+ str(artifacts),+ str(out),+ "--segment",+ "Core",+ "--junit-dir",+ str(junit_dir),+ "--scope-to-junit",+ ],+ )+ with pytest.raises(SystemExit):+ main()+ assert not out.exists()+def test_run_average_files_refuses_empty_result(self, tmp_path):# Newest (anchor) run scoped to nothing must not silently wipe the plan,# even when older runs still carry data — refuse to write, don't emit {}.@@ -162,6 +211,7 @@ class TestJUnitShardSegmentFilter:"junit-results-backend-core-poe-1","junit-results-backend-temporal-1","product-junit-results-1",+ "junit-results-dagster-1","junit-results-backend-compat-1", # unrelated, shouldn't match anything):shard = tmp_path / name@@ -194,6 +244,44 @@ class TestJUnitShardSegmentFilter:"products/tasks/test_two.py::TestThing::test_two",}+ def test_dagster_matches_junit_results_dagster_prefix(self, junit_dir: Path) -> None:+ names = {s.name for s in JUnitShard.load_all(junit_dir, segment="Dagster")}+ assert names == {"junit-results-dagster-1"}++ def test_rerun_attempt_supersedes_earlier_attempts(self, junit_dir: Path) -> None:+ # The fixture's core-1 dir has time=0.5; an attempt-2 rerun of the same+ # shard must replace it, not sit alongside or be dropped.+ shard = junit_dir / "junit-results-backend-core-1-attempt2"+ shard.mkdir()+ (shard / "junit.xml").write_bytes(+ b'<testsuite><testcase classname="posthog.test_foo.TestThing" name="test_one" time="1.5"/></testsuite>'+ )++ shards = JUnitShard.load_all(junit_dir, segment="Core")++ assert [shard.name for shard in shards] == ["junit-results-backend-core-1", "junit-results-backend-core-2"]+ base = next(shard for shard in shards if shard.name == "junit-results-backend-core-1")+ assert base.call_times["posthog/test_foo.py::TestThing::test_one"] == 1.5++ def test_rerun_attempt_keeps_tests_only_an_earlier_attempt_ran(self, junit_dir: Path) -> None:+ # A rerun without the pinned plan can reshard a test into a shard that is+ # not rerun, so attempt 2 of shard 1 no longer lists it. Its attempt-1+ # membership must survive or scoping drops a test that ran.+ shard = junit_dir / "junit-results-backend-core-1-attempt2"+ shard.mkdir()+ (shard / "junit.xml").write_bytes(+ b'<testsuite><testcase classname="posthog.test_bar" name="test_two" time="2.0"/></testsuite>'+ )++ base = next(+ s for s in JUnitShard.load_all(junit_dir, segment="Core") if s.name == "junit-results-backend-core-1"+ )++ assert base.call_times == {+ "posthog/test_foo.py::TestThing::test_one": 0.5,+ "posthog/test_bar.py::test_two": 2.0,+ }+def test_unknown_segment_does_not_panic(self, junit_dir: Path):# Unknown segments fall back to lowercase passthrough — should just# match nothing in this fixture, not crash.diff --git a/.github/workflows/ci-backend-update-test-timing.yml b/.github/workflows/ci-backend-update-test-timing.ymlindex b2d0c320f854..a3bd33490dd5 100644--- a/.github/workflows/ci-backend-update-test-timing.yml+++ b/.github/workflows/ci-backend-update-test-timing.yml@@ -209,6 +209,10 @@ jobs:if [ -n "$DAGSTER_RUN_ID" ]; thengh run download "$DAGSTER_RUN_ID" --pattern "timing_data-Dagster-*" --dir timing_artifactsecho "Downloaded Dagster timing artifacts"+ # JUnit too, so the Dagster segment can prune dead nodeids like the others.+ # Naming differs from the backend artifacts: junit-results-dagster-N.+ gh run download "$DAGSTER_RUN_ID" --pattern "junit-results-dagster-*" --dir junit_artifacts || \+ echo "::warning::No Dagster JUnit artifacts found — Dagster runs unscoped"elseecho "Skipping Dagster timing artifacts (no suitable run found)"fi@@ -220,17 +224,37 @@ jobs:run: |# Process each segment separately with migration tax correction, then merge.# Core, Temporal, and Products use JUnit for precise carrier detection.- uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/core_durations \- --segment Core --junit-dir junit_artifacts- uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/temporal_durations \- --segment Temporal --junit-dir junit_artifacts+ # Scope Core, Temporal, and Dagster to the nodeids their run's JUnit saw run.+ # Every shard restores the merged union and refreshes only its own slice, so+ # without scoping a deleted or renamed test rides every refresh and never+ # leaves these files, and the union merge below keeps inflating sharding+ # budgets with dead nodeids. --scope-to-junit hard-fails when JUnit artifacts+ # are missing, so retry unscoped to keep the existing behavior.+ if ! uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/core_durations \+ --segment Core --junit-dir junit_artifacts --scope-to-junit; then+ echo "::warning::Scoped Core durations failed, retrying unscoped"+ uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/core_durations \+ --segment Core --junit-dir junit_artifacts+ fi+ if ! uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/temporal_durations \+ --segment Temporal --junit-dir junit_artifacts --scope-to-junit; then+ echo "::warning::Scoped Temporal durations failed, retrying unscoped"+ uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/temporal_durations \+ --segment Temporal --junit-dir junit_artifacts+ fi+ # Products has its own guarded scoping inside the script (only scopes when the+ # JUnit shard set is complete), so no flag here.uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/products_durations \--segment Products --junit-dir junit_artifacts# Process Dagster segment if availableif [ -n "$DAGSTER_RUN_ID" ]; then- uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/dagster_durations \- --segment Dagster+ if ! uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/dagster_durations \+ --segment Dagster --junit-dir junit_artifacts --scope-to-junit; then+ echo "::warning::Scoped Dagster durations failed, retrying unscoped"+ uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/dagster_durations \+ --segment Dagster+ fiecho "Processed Dagster timing data"fidiff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.ymlindex 0ef7d65685b1..5f9d3d6e63a0 100644--- a/.github/workflows/ci-dagster.yml+++ b/.github/workflows/ci-dagster.yml@@ -624,6 +624,8 @@ jobs:elseTEST_TARGETS=(posthog/dags products/*/dags)fi+ # Call-only times so the timing-update workflow's migration-tax corrector+ # sees the same setup-free signal it gets from the backend segments.pytest "${TEST_TARGETS[@]}" \--reuse-db \--splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \@@ -632,6 +634,7 @@ jobs:"${SPLIT_GRANULARITY[@]}" \--reruns 2 --reruns-delay 1 \-r fEsxX \+ -o junit_duration_report=call \--junitxml=junit-dagster-${{ matrix.group }}.xml- name: Upload test results