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.

fix(ci): size product test shards from unfloored durations (#83138)

Paul D'Ambra13b248a75217
diff --git a/.depot/workflows/ci-backend-update-test-timing.yml b/.depot/workflows/ci-backend-update-test-timing.yml
index a123325c0fe0..de737913043b 100644
--- a/.depot/workflows/ci-backend-update-test-timing.yml
+++ b/.depot/workflows/ci-backend-update-test-timing.yml
@@ -65,6 +65,7 @@ jobs:
gh run download "$BACKEND_RUN_ID" \
--pattern "junit-results-backend-core-*" \
--pattern "junit-results-backend-temporal-*" \
+ --pattern "product-junit-results-*" \
--dir junit_artifacts || echo "::warning::No JUnit artifacts — statistical carrier detection"
- name: Merge into .test_durations
@@ -74,9 +75,10 @@ jobs:
uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/temporal_durations \
--segment Temporal --junit-dir junit_artifacts
uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/products_durations \
- --segment Products
+ --segment Products --junit-dir junit_artifacts
uv run .github/scripts/optimize_test_durations.py .test_durations \
- --merge-files /tmp/core_durations /tmp/temporal_durations /tmp/products_durations
+ --merge-files /tmp/core_durations /tmp/temporal_durations /tmp/products_durations \
+ --replace-prefix products/
rm -rf timing_artifacts junit_artifacts /tmp/core_durations /tmp/temporal_durations /tmp/products_durations
- name: Compute cache key
diff --git a/.github/scripts/optimize_test_durations.py b/.github/scripts/optimize_test_durations.py
index 0f0ab9587c4a..c3e35cbe103c 100644
--- a/.github/scripts/optimize_test_durations.py
+++ b/.github/scripts/optimize_test_durations.py
@@ -80,10 +80,13 @@ class ShardTimings:
return shards
-# Maps the script's segment names to the artifact-key fragment used by
-# ci-backend.yml ("junit-results-backend-<artifact-key>-<group>"). Add new
-# segments here when adding JUnit-mode carrier detection for them.
-_JUNIT_ARTIFACT_KEY = {"Core": "core", "CorePOE": "core-poe", "Temporal": "temporal"}
+# Maps segment names to the JUnit artifact prefix used by ci-backend.yml.
+_JUNIT_ARTIFACT_PREFIX = {
+ "Core": "junit-results-backend-core",
+ "CorePOE": "junit-results-backend-core-poe",
+ "Temporal": "junit-results-backend-temporal",
+ "Products": "product-junit-results",
+}
@dataclass
@@ -115,10 +118,10 @@ class JUnitShard:
continue
if segment:
- artifact_key = _JUNIT_ARTIFACT_KEY.get(segment, segment.lower())
+ 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"^junit-results-backend-{re.escape(artifact_key)}-\d+$")
+ pattern = re.compile(rf"^{re.escape(artifact_prefix)}-\d+$")
if not pattern.match(shard_dir.name.lower()):
continue
@@ -126,7 +129,11 @@ class JUnitShard:
if not xml_files:
continue
- shards.append(cls(name=shard_dir.name, call_times=cls._parse_call_times(xml_files[0])))
+ 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))
return shards
@@ -319,7 +326,11 @@ class MigrationTaxCorrector:
)
else:
logger.info(" No JUnit-detected contamination")
- return MigrationTaxResult(corrected, migration_tax_seconds=avg_removed, carriers_found=len(removed))
+ return MigrationTaxResult(
+ corrected,
+ migration_tax_seconds=avg_removed,
+ carriers_found=len(removed),
+ )
@staticmethod
def _lookup_call_time(test_id: str, junit_call: dict[str, float]) -> float | None:
@@ -446,6 +457,12 @@ def ensure_minimum_duration(durations: dict[str, float]) -> dict[str, float]:
return {test: max(MIN_DURATION, dur) for test, dur in durations.items()}
+def shard_sets_match(timing_shards: list[ShardTimings], junit_shards: list[JUnitShard]) -> bool:
+ timing_ids = {shard.name.rsplit("-", 1)[-1] for shard in timing_shards}
+ junit_ids = {shard.name.rsplit("-", 1)[-1] for shard in junit_shards}
+ return timing_ids == junit_ids
+
+
def collect_existing_tests(segment: str | None = None) -> set[str]:
"""Collect test names that actually exist in the codebase.
@@ -496,7 +513,7 @@ def collect_existing_tests(segment: str | None = None) -> set[str]:
return tests
-def run_merge_files(input_files: list[Path], output_file: Path) -> None:
+def run_merge_files(input_files: list[Path], output_file: Path, replace_prefix: str | None = None) -> None:
"""Merge mode: outlier-merge already-merged per-segment files into one output.
Fails loudly if no inputs survive — silently emitting an empty file would
@@ -514,6 +531,10 @@ def run_merge_files(input_files: list[Path], output_file: Path) -> None:
logger.error("No input files found to merge — refusing to write empty %s", output_file)
sys.exit(1)
+ if replace_prefix and len(sources) > 1:
+ sources[0] = {
+ test_id: duration for test_id, duration in sources[0].items() if not test_id.startswith(replace_prefix)
+ }
merged = outlier_merge_durations(sources)
with open(output_file, "w") as f:
json.dump(merged, f, indent=4, sort_keys=True)
@@ -618,11 +639,16 @@ def main():
default="mean",
help="Aggregation for --average-files (default: mean).",
)
+ parser.add_argument(
+ "--replace-prefix",
+ default=None,
+ help="In merge mode, remove matching entries from the first input before merging fresh segment data.",
+ )
args = parser.parse_args()
if args.merge_files:
- run_merge_files(args.merge_files, args.output_file)
+ run_merge_files(args.merge_files, args.output_file, args.replace_prefix)
return
if args.average_files:
@@ -705,6 +731,19 @@ def main():
before_count - len(durations),
)
+ if args.segment == "Products" and junit_shards:
+ if shard_sets_match(shards, junit_shards):
+ ran = set().union(*(shard.call_times.keys() for shard in junit_shards))
+ before_count = len(durations)
+ durations = {test_id: duration for test_id, duration in durations.items() if test_id in ran}
+ logger.info(
+ " Scoped Products to complete JUnit coverage (%d shards, dropped %d stale nodeids)",
+ len(junit_shards),
+ before_count - len(durations),
+ )
+ else:
+ logger.warning("Product JUnit coverage incomplete; retaining unscoped timings")
+
# Filter to only existing tests if requested
if args.filter_existing:
logger.info("Collecting existing tests from codebase...")
diff --git a/.github/scripts/test_optimize_test_durations.py b/.github/scripts/test_optimize_test_durations.py
index 3605751b9010..b97eb694236e 100644
--- a/.github/scripts/test_optimize_test_durations.py
+++ b/.github/scripts/test_optimize_test_durations.py
@@ -4,6 +4,7 @@ Run with: uv run --with pytest --with defusedxml pytest .github/scripts/test_opt
"""
import sys
+import json
from pathlib import Path
import pytest
@@ -11,11 +12,14 @@ import pytest
from optimize_test_durations import (
JUnitShard,
MigrationTaxCorrector,
+ ShardTimings,
_pick_outlier,
average_durations,
main,
outlier_merge_durations,
run_average_files,
+ run_merge_files,
+ shard_sets_match,
)
# Minimal valid JUnit XML — one testcase with a CamelCase classname so
@@ -155,6 +159,7 @@ class TestJUnitShardSegmentFilter:
"junit-results-backend-core-2",
"junit-results-backend-core-poe-1",
"junit-results-backend-temporal-1",
+ "product-junit-results-1",
"junit-results-backend-compat-1", # unrelated, shouldn't match anything
):
shard = tmp_path / name
@@ -174,6 +179,19 @@ class TestJUnitShardSegmentFilter:
names = {s.name for s in JUnitShard.load_all(junit_dir, segment="Temporal")}
assert names == {"junit-results-backend-temporal-1"}
+ def test_products_matches_product_junit_prefix(self, junit_dir: Path) -> None:
+ (junit_dir / "product-junit-results-1" / "second.xml").write_bytes(
+ b'<testsuite><testcase classname="products.tasks.test_two.TestThing" name="test_two" time="1.5"/></testsuite>'
+ )
+
+ shards = JUnitShard.load_all(junit_dir, segment="Products")
+
+ assert [shard.name for shard in shards] == ["product-junit-results-1"]
+ assert set(shards[0].call_times) == {
+ "posthog/test_foo.py::TestThing::test_one",
+ "products/tasks/test_two.py::TestThing::test_two",
+ }
+
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.
@@ -267,5 +285,35 @@ class TestStatisticalCorrection:
assert result.carriers_found == 1
+def test_merge_files_replaces_stale_segment_entries(tmp_path: Path) -> None:
+ previous = tmp_path / "previous.json"
+ fresh = tmp_path / "fresh.json"
+ output = tmp_path / "output.json"
+ previous.write_text(json.dumps({"posthog/test.py::test_core": 1.0, "products/tasks/old.py::test_old": 90.0}))
+ fresh.write_text(json.dumps({"products/tasks/new.py::test_new": 10.0}))
+
+ run_merge_files([previous, fresh], output, replace_prefix="products/")
+
+ assert json.loads(output.read_text()) == {
+ "posthog/test.py::test_core": 1.0,
+ "products/tasks/new.py::test_new": 10.0,
+ }
+
+
+def test_shard_sets_match_requires_every_junit_artifact() -> None:
+ timings = [
+ ShardTimings(name="timing_data-Products-1", durations={}),
+ ShardTimings(name="timing_data-Products-2", durations={}),
+ ]
+ complete = [
+ JUnitShard(name="product-junit-results-1", call_times={}),
+ JUnitShard(name="product-junit-results-2", call_times={}),
+ ]
+ partial = [JUnitShard(name="product-junit-results-1", call_times={})]
+
+ assert shard_sets_match(timings, complete)
+ assert not shard_sets_match(timings, partial)
+
+
if __name__ == "__main__":
pytest.main([__file__, "-v"])
diff --git a/.github/workflows/ci-backend-update-test-timing.yml b/.github/workflows/ci-backend-update-test-timing.yml
index e4ce9c0e813d..84cf3b2ffd06 100644
--- a/.github/workflows/ci-backend-update-test-timing.yml
+++ b/.github/workflows/ci-backend-update-test-timing.yml
@@ -180,6 +180,7 @@ jobs:
gh run download "$BACKEND_RUN_ID" \
--pattern "junit-results-backend-core-*" \
--pattern "junit-results-backend-temporal-*" \
+ --pattern "product-junit-results-*" \
--dir junit_artifacts || \
echo "::warning::No JUnit artifacts found — falling back to statistical carrier detection"
@@ -213,14 +214,13 @@ jobs:
BACKEND_RUN_IDS: ${{ steps.find-backend-run.outputs.run_ids }}
run: |
# Process each segment separately with migration tax correction, then merge.
- # Core/Temporal use JUnit for precise carrier detection.
- # Products lack JUnit artifacts, so use statistical detection (--shard-count).
+ # 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
uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/products_durations \
- --segment Products
+ --segment Products --junit-dir junit_artifacts
# Process Dagster segment if available
if [ -n "$DAGSTER_RUN_ID" ]; then
@@ -234,7 +234,8 @@ jobs:
# with per-segment artifact processing and covered by tests next
# to the script — see test_optimize_test_durations.py.
uv run .github/scripts/optimize_test_durations.py .test_durations \
- --merge-files /tmp/core_durations /tmp/temporal_durations /tmp/products_durations /tmp/dagster_durations
+ --merge-files /tmp/core_durations /tmp/temporal_durations /tmp/products_durations /tmp/dagster_durations \
+ --replace-prefix products/
# Additionally emit nodeid-clean per-segment files for
# --split-granularity=file. The shared .test_durations above is a union