: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
feat(ci): auto-size Django test shard counts from .test_durations (#54280)
Julian Bezf6fd7cc3a4ce
diff --git a/.github/scripts/optimize_test_durations.py b/.github/scripts/optimize_test_durations.pyindex c22f15819e14..9a58593e114d 100644--- a/.github/scripts/optimize_test_durations.py+++ b/.github/scripts/optimize_test_durations.py@@ -4,75 +4,401 @@# dependencies = [# "pytest>=7.0.0",# "pytest-split>=0.8.0",+# "defusedxml>=0.7.1",# ]# ///"""Prepare test durations for pytest-split sharding.-Merges timing artifacts from CI shards and applies a ceiling cap to inflated-first-test durations (caused by Django DB setup warm-up).+Merges timing artifacts from CI shards and corrects migration-inflated+first-test durations using JUnit results to identify carriers.-Note: pytest-split's duration_based_chunks algorithm has inherent limitations --fast tests clustered alphabetically at the end can cause the last shard to be-much faster than others. This script doesn't try to "game" the algorithm;-it just provides clean timing data.+Each shard's first test absorbs Django migration overhead (~6.5 min),+making that test look artificially slow. This script detects those+carriers, subtracts the migration tax, and outputs clean durations+for balanced pytest-split distribution."""+import re+import sysimport globimport jsonimport loggingimport argparse+import subprocess+from collections import Counter+from dataclasses import dataclassfrom pathlib import Path+import defusedxml.ElementTree as ET+from defusedxml.ElementTree import ParseError+logger = logging.getLogger(__name__)-DEFAULT_CEILING = 60.0+MIN_DURATION = 0.01+# Tests with recorded duration above this threshold in a single shard+# are candidates for migration carriers (real tests rarely exceed this)+CARRIER_THRESHOLD_SECONDS = 200.0-def load_timing_artifacts(artifacts_dir: Path, segment: str | None = None) -> dict[str, float]:- """Load and merge timing data from shard artifacts.+@dataclass+class ShardTimings:+ """Timing data from a single CI shard's .test_durations artifact."""- Args:- artifacts_dir: Directory containing timing artifacts- segment: If provided, only load artifacts from this segment (e.g., "Core")- Artifact dirs are named like "timing_data-Core-1", "timing_data-Temporal-5"- """- durations = {}- for timing_file in artifacts_dir.rglob(".test_durations"):- # Filter by segment if specified- if segment:- # Parent dir name is like "timing_data-Core-1"+ name: str+ durations: dict[str, float]++ @classmethod+ def load_all(cls, artifacts_dir: Path, segment: str | None = None) -> list["ShardTimings"]:+ """Load per-shard timing artifacts, optionally filtered by segment.++ Artifact dirs are named like "timing_data-Core-1", "timing_data-Temporal-5".+ """+ shards = []+ for timing_file in sorted(artifacts_dir.rglob(".test_durations")):parent_name = timing_file.parent.name- if not parent_name.startswith(f"timing_data-{segment}-"):+ if segment and not parent_name.startswith(f"timing_data-{segment}-"):continue- with open(timing_file) as f:- durations.update(json.load(f))- return durations+ with open(timing_file) as f:+ shards.append(cls(name=parent_name, durations=json.load(f)))+ 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"}+++@dataclass+class JUnitShard:+ """JUnit results from a single CI shard."""++ name: str+ first_test_id: str++ @classmethod+ def load_all(cls, junit_dir: Path, segment: str | None = None) -> list["JUnitShard"]:+ """Load JUnit XMLs and extract the first test (carrier) from each shard.++ JUnit artifact dirs are named like "junit-results-backend-core-1".+ Segment match is anchored at the artifact prefix so "Core" doesn't+ accidentally pick up "core-poe" or any future "*-core-*" name, and+ "CorePOE" matches "core-poe" instead of the absent substring "corepoe".+ """+ shards = []+ for shard_dir in sorted(junit_dir.iterdir()):+ if not shard_dir.is_dir():+ continue++ if segment:+ artifact_key = _JUNIT_ARTIFACT_KEY.get(segment, 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+$")+ if not pattern.match(shard_dir.name.lower()):+ continue++ xml_files = sorted(shard_dir.glob("*.xml"))+ if not xml_files:+ continue++ first_test_id = cls._find_first_test(xml_files[0])+ if first_test_id:+ shards.append(cls(name=shard_dir.name, first_test_id=first_test_id))++ return shards++ @staticmethod+ def _find_first_test(xml_path: Path) -> str | None:+ """Extract the first parseable testcase id from a JUnit XML file."""+ try:+ tree = ET.parse(xml_path)+ except ParseError as e:+ logger.warning(" Could not parse JUnit XML %s: %s", xml_path, e)+ return None+ for tc in tree.getroot().iter("testcase"):+ classname = tc.get("classname", "")+ name = tc.get("name", "")+ pytest_id = _junit_to_pytest_id(classname, name)+ if pytest_id:+ return pytest_id+ return None+++@dataclass+class MigrationTaxResult:+ """Result of migration tax detection and correction."""++ corrected_durations: dict[str, float]+ migration_tax_seconds: float+ carriers_found: int+++def outlier_merge_durations(sources: list[dict[str, float]]) -> dict[str, float]:+ """Outlier-merge per-test durations across N input dicts.++ Each source carries the full test map with fresh values only for tests+ actually measured by that source; the rest are stale passthroughs from+ a shared input file. A naive last-write-wins merge overwrites real+ values with stale ones — instead pick the per-test value that differs+ from the majority across sources. Falls back to first value if all+ sources agree.++ Single source of truth for outlier merging — used both by per-segment+ artifact processing (TimingMerger over ShardTimings) and by the+ cross-segment merge step in the timing update workflow.+ """+ if not sources:+ return {}+ if len(sources) == 1:+ return dict(sources[0])++ test_keys: set[str] = set()+ for source in sources:+ test_keys.update(source.keys())++ merged: dict[str, float] = {}+ for test in test_keys:+ values = [source[test] for source in sources if test in source]+ if not values:+ continue+ merged[test] = _pick_outlier(values)+ return merged++def _pick_outlier(values: list[float]) -> float:+ if len(set(values)) == 1:+ return values[0]+ counter = Counter(values)+ most_common_val = counter.most_common(1)[0][0]+ outliers = [v for v in values if v != most_common_val]+ return outliers[0] if outliers else most_common_val-def apply_ceiling_cap(durations: dict[str, float], ceiling: float = DEFAULT_CEILING) -> dict[str, float]:- """Apply ceiling cap to inflated durations.- First test in each shard has Django DB setup baked into its timing (~60-240s).- Cap these to avoid skewing the timing file.+class TimingMerger:+ """Merges per-shard timing artifacts using outlier detection.++ Thin wrapper around outlier_merge_durations() that adapts the+ ShardTimings interface used by per-segment processing."""- result = {}- for test, duration in durations.items():- if duration > ceiling:- result[test] = ceiling++ def __init__(self, shards: list[ShardTimings]):+ self.shards = shards++ def merge(self) -> dict[str, float]:+ return outlier_merge_durations([shard.durations for shard in self.shards])+++class MigrationTaxCorrector:+ """Detects and corrects migration-inflated first-test durations.++ The first test in each CI shard absorbs Django migration overhead+ (creating template DB, running migrations, etc.). This inflates that+ test's recorded duration by ~6.5 min, which skews pytest-split's+ shard balancing.++ Two detection modes:+ - JUnit-based (preferred): uses JUnit XML to identify the first test+ per shard — precise, no false positives.+ - Statistical fallback: when JUnit is unavailable, identifies tests+ whose duration is a clear outlier (>CARRIER_THRESHOLD_SECONDS above+ the next-highest test in the merged data). Expects exactly one+ carrier per shard, using the shard count as a guide.+ """++ def __init__(+ self,+ durations: dict[str, float],+ junit_shards: list[JUnitShard] | None = None,+ expected_shard_count: int = 0,+ ):+ self.durations = durations+ self.junit_shards = junit_shards or []+ self.expected_shard_count = expected_shard_count++ def correct(self) -> MigrationTaxResult:+ if self.junit_shards:+ carriers = self._find_carriers_from_junit()+ elif self.expected_shard_count > 0:+ carriers = self._find_carriers_statistically()else:- result[test] = max(0.01, duration)- return result+ logger.info(" No JUnit data or shard count — skipping carrier correction")+ return MigrationTaxResult(+ corrected_durations=dict(self.durations),+ migration_tax_seconds=0,+ carriers_found=0,+ )++ if not carriers:+ logger.info(" No migration carriers found")+ return MigrationTaxResult(+ corrected_durations=dict(self.durations),+ migration_tax_seconds=0,+ carriers_found=0,+ )++ migration_tax = self._estimate_tax(carriers)+ corrected = self._apply_correction(carriers, migration_tax)++ return MigrationTaxResult(+ corrected_durations=corrected,+ migration_tax_seconds=migration_tax,+ carriers_found=len(carriers),+ )++ def _find_carriers_from_junit(self) -> dict[str, float]:+ """Identify carriers from JUnit first-test-per-shard data.++ JUnit XMLs are produced with `-o junit_duration_report=call`, so the+ `time` attribute reflects only call time, not Django setup/migration.+ Use JUnit only to identify the first test per shard, then check the+ merged .test_durations value for that test to decide if it's actually+ a carrier (carriers absorb setup time into their recorded duration).+ """+ carriers = {}+ for junit_shard in self.junit_shards:+ test_id = junit_shard.first_test_id++ matched_key = self._match_duration_key(test_id)+ if not matched_key:+ logger.warning(" Could not match first test %s to durations", test_id[:60])+ continue++ recorded_duration = self.durations.get(matched_key, 0.0)+ if recorded_duration < CARRIER_THRESHOLD_SECONDS:+ continue++ carriers[matched_key] = recorded_duration+ logger.debug(+ " Carrier (JUnit): %s recorded=%.0fs from %s",+ matched_key[:60],+ recorded_duration,+ junit_shard.name,+ )++ return carriers++ def _find_carriers_statistically(self) -> dict[str, float]:+ """Identify carriers by finding the N highest-duration outliers.++ Uses expected_shard_count as the number of carriers to look for.+ Only selects tests above CARRIER_THRESHOLD_SECONDS to avoid+ false positives from genuinely slow tests.+ """+ candidates = sorted(self.durations.items(), key=lambda x: -x[1])++ # Take the top N candidates that are above threshold+ carriers = {}+ for test_id, duration in candidates:+ if duration < CARRIER_THRESHOLD_SECONDS:+ break+ carriers[test_id] = duration+ if len(carriers) >= self.expected_shard_count:+ break++ if carriers:+ # Sanity check: carriers should be clustered together (all ~same duration)+ carrier_durs = list(carriers.values())+ spread = max(carrier_durs) - min(carrier_durs)+ if spread > 120:+ logger.warning(" Carrier duration spread is %.0fs — may include genuinely slow tests", spread)++ logger.info(+ " Found %d statistical carriers (expected %d shards)",+ len(carriers),+ self.expected_shard_count,+ )++ return carriers++ def _match_duration_key(self, junit_test_id: str) -> str | None:+ """Find the matching key in durations for a JUnit test ID.++ Prefers exact match. Falls back to suffix match on the `::class::test`+ tail — anchored, so a JUnit id of `test_create` cannot pick up+ `test_create_user`. JUnit IDs and pytest node IDs sometimes differ+ only in file-path prefix (e.g. relative vs absolute), so suffix is+ the right comparison.+ """+ if junit_test_id in self.durations:+ return junit_test_id++ parts = junit_test_id.split("::")+ if len(parts) < 2:+ return None++ suffix = "::" + "::".join(parts[-2:]) if len(parts) >= 3 else "::" + parts[-1]+ matches = [k for k in self.durations if k.endswith(suffix)]+ if len(matches) == 1:+ return matches[0]+ if len(matches) > 1:+ logger.warning(+ " Ambiguous suffix match for %s — %d candidates, skipping", junit_test_id[:60], len(matches)+ )+ return None++ @staticmethod+ def _estimate_tax(carriers: dict[str, float]) -> float:+ """Estimate migration tax as the average carrier duration.++ The carrier's recorded duration ≈ real_duration + migration_tax.+ Since real_duration is typically small (<15s), the carrier duration+ is a good approximation of the tax itself.+ """+ durations = list(carriers.values())+ tax = sum(durations) / len(durations)+ logger.info(" Migration tax estimate: %.0fs (%.1fm) from %d carriers", tax, tax / 60, len(carriers))+ return tax++ def _apply_correction(self, carriers: dict[str, float], migration_tax: float) -> dict[str, float]:+ """Subtract migration tax from carrier durations."""+ corrected = dict(self.durations)+ for test_id, carrier_dur in carriers.items():+ original = corrected.get(test_id, carrier_dur)+ adjusted = max(MIN_DURATION, original - migration_tax)+ corrected[test_id] = adjusted+ logger.info(" Corrected %s: %.0fs -> %.1fs", test_id[:60], original, adjusted)+ return corrected+++def _junit_to_pytest_id(classname: str, testname: str) -> str | None:+ """Convert JUnit classname + testname to a pytest node ID.++ JUnit: classname="posthog.api.test.test_user.TestUserAPI" name="test_xyz"+ pytest: "posthog/api/test/test_user.py::TestUserAPI::test_xyz"+ """+ parts = classname.split(".")++ # Find where the module ends and class begins (first CamelCase part)+ split_idx = len(parts)+ for i, part in enumerate(parts):+ if part and part[0].isupper():+ split_idx = i+ break++ if split_idx == 0:+ return None++ module_path = "/".join(parts[:split_idx]) + ".py"+ class_parts = parts[split_idx:]+ class_path = "::".join(class_parts) if class_parts else ""++ if class_path:+ return f"{module_path}::{class_path}::{testname}"+ return f"{module_path}::{testname}"+++def ensure_minimum_duration(durations: dict[str, float]) -> dict[str, float]:+ """Ensure all durations have a minimum value for pytest-split."""+ return {test: max(MIN_DURATION, dur) for test, dur in durations.items()}def collect_existing_tests(segment: str | None = None) -> set[str]:"""Collect test names that actually exist in the codebase.- This filters out stale tests from artifacts that no longer exist.+ Filters out stale tests from artifacts that no longer exist."""- import subprocess-- # Build pytest command based on segmentcmd = ["pytest","posthog",@@ -89,7 +415,6 @@ def collect_existing_tests(segment: str | None = None) -> set[str]:"-q",]- # Add segment-specific filtersif segment == "Temporal":cmd = ["pytest",@@ -119,37 +444,119 @@ def collect_existing_tests(segment: str | None = None) -> set[str]:return tests+def run_merge_files(input_files: list[Path], output_file: Path) -> 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+ let a botched timing-update workflow commit an empty .test_durations to+ master, wiping the sharding signal everywhere downstream.+ """+ sources: list[dict[str, float]] = []+ for path in input_files:+ if not path.exists():+ logger.info(" skipping missing input %s", path)+ continue+ with open(path) as f:+ sources.append(json.load(f))+ if not sources:+ logger.error("No input files found to merge — refusing to write empty %s", output_file)+ sys.exit(1)++ merged = outlier_merge_durations(sources)+ with open(output_file, "w") as f:+ json.dump(merged, f, indent=4, sort_keys=True)+ f.write("\n")+ logger.info("Merged %d tests across %d segment(s) into %s", len(merged), len(sources), output_file)++def main():logging.basicConfig(level=logging.INFO, format="%(message)s")parser = argparse.ArgumentParser(description="Prepare test durations for pytest-split sharding")- parser.add_argument("artifacts_dir", type=Path, help="Directory containing timing artifacts")+ parser.add_argument("artifacts_dir", type=Path, nargs="?", help="Directory containing timing artifacts")parser.add_argument("output_file", type=Path, help="Output file for processed durations")- parser.add_argument(- "--ceiling",- type=float,- default=DEFAULT_CEILING,- help=f"Duration ceiling for inflated tests (default: {DEFAULT_CEILING}s)",- )parser.add_argument("--segment",type=str,default=None,help="Only load artifacts from this segment (e.g., 'Core'). Filters by artifact dir name.",)+ parser.add_argument(+ "--junit-dir",+ type=Path,+ default=None,+ help="Directory containing JUnit XML artifacts. Enables precise migration tax correction.",+ )+ parser.add_argument(+ "--shard-count",+ type=int,+ default=0,+ help="Expected number of shards. Enables statistical carrier detection when JUnit is unavailable.",+ )parser.add_argument("--filter-existing",action="store_true",help="Filter to only tests that exist in the codebase (runs pytest --collect-only)",)+ parser.add_argument(+ "--merge-files",+ type=Path,+ nargs="+",+ default=None,+ help="Merge mode: outlier-merge the given duration files and write to output_file. "+ "Ignores artifacts_dir and the other artifact-processing flags.",+ )args = parser.parse_args()+ if args.merge_files:+ run_merge_files(args.merge_files, args.output_file)+ return++ if args.artifacts_dir is None:+ parser.error("artifacts_dir is required unless --merge-files is given")++ # Load per-shard timing datalogger.info("Loading timing artifacts from %s...", args.artifacts_dir)if args.segment:logger.info(" Filtering to segment: %s", args.segment)- real_durations = load_timing_artifacts(args.artifacts_dir, segment=args.segment)- logger.info(" Loaded %d tests from artifacts", len(real_durations))+ shards = ShardTimings.load_all(args.artifacts_dir, segment=args.segment)+ logger.info(" Loaded %d shards", len(shards))++ # Merge using outlier detection (not naive last-wins)+ logger.info("Merging with outlier detection...")+ durations = TimingMerger(shards).merge()+ logger.info(" Merged %d tests", len(durations))++ # Correct migration-inflated first-test durations+ junit_shards = None+ shard_count = args.shard_count or len(shards)++ if args.junit_dir and args.junit_dir.exists():+ logger.info("Correcting migration tax using JUnit from %s...", args.junit_dir)+ junit_shards = JUnitShard.load_all(args.junit_dir, segment=args.segment)+ logger.info(" Found %d JUnit shards", len(junit_shards))+ elif args.junit_dir:+ logger.warning("JUnit dir %s not found", args.junit_dir)++ if junit_shards or shard_count > 0:+ if not junit_shards:+ logger.info("Correcting migration tax statistically (expected %d shards)...", shard_count)++ result = MigrationTaxCorrector(+ durations,+ junit_shards=junit_shards,+ expected_shard_count=shard_count,+ ).correct()+ durations = result.corrected_durations++ if result.migration_tax_seconds > 0:+ logger.info(+ " Corrected %d carriers, migration tax: %.0fs (%.1fm)",+ result.carriers_found,+ result.migration_tax_seconds,+ result.migration_tax_seconds / 60,+ )# Filter to only existing tests if requestedif args.filter_existing:@@ -157,17 +564,13 @@ def main():existing_tests = collect_existing_tests(segment=args.segment)logger.info(" Found %d tests in codebase", len(existing_tests))- before_count = len(real_durations)- real_durations = {k: v for k, v in real_durations.items() if k in existing_tests}- logger.info(- " Filtered to %d tests (removed %d stale)", len(real_durations), before_count - len(real_durations)- )- logger.info(" Total tests: %d", len(real_durations))+ before_count = len(durations)+ durations = {k: v for k, v in durations.items() if k in existing_tests}+ logger.info(" Filtered to %d tests (removed %d stale)", len(durations), before_count - len(durations))- logger.info("Applying ceiling cap (%.0fs)...", args.ceiling)- processed = apply_ceiling_cap(real_durations, ceiling=args.ceiling)+ logger.info(" Total tests: %d", len(durations))+ processed = ensure_minimum_duration(durations)- # Savewith open(args.output_file, "w") as f:json.dump(processed, f, indent=4, sort_keys=True)f.write("\n")diff --git a/.github/scripts/test_optimize_test_durations.py b/.github/scripts/test_optimize_test_durations.pynew file mode 100644index 000000000000..7f121f32a490--- /dev/null+++ b/.github/scripts/test_optimize_test_durations.py@@ -0,0 +1,113 @@+"""Tests for the outlier-merge logic in optimize_test_durations.++Run with: uv run --with pytest --with defusedxml pytest .github/scripts/test_optimize_test_durations.py+"""++from pathlib import Path++import pytest++from optimize_test_durations import JUnitShard, _pick_outlier, outlier_merge_durations++# Minimal valid JUnit XML — one testcase with a CamelCase classname so+# _junit_to_pytest_id resolves cleanly.+_MIN_JUNIT_XML = b"""<?xml version="1.0"?>+<testsuite name="pytest"><testcase classname="posthog.test_foo.TestThing" name="test_one" time="0.5"/></testsuite>+"""+++class TestPickOutlier:+ def test_all_same_returns_value(self):+ assert _pick_outlier([3.0, 3.0, 3.0]) == 3.0++ def test_single_outlier_against_majority(self):+ # 4 shards agree on 1.0 (stale passthrough), 1 reports 5.0 (fresh).+ # Outlier wins.+ assert _pick_outlier([1.0, 1.0, 5.0, 1.0, 1.0]) == 5.0++ def test_outlier_position_does_not_matter(self):+ assert _pick_outlier([5.0, 1.0, 1.0, 1.0, 1.0]) == 5.0+ assert _pick_outlier([1.0, 1.0, 1.0, 1.0, 5.0]) == 5.0++ def test_no_clear_majority_returns_an_outlier(self):+ # 2-2 tie: most_common picks one arbitrarily, outlier is the other.+ result = _pick_outlier([1.0, 1.0, 5.0, 5.0])+ assert result in (1.0, 5.0)++ def test_single_value(self):+ assert _pick_outlier([7.0]) == 7.0+++class TestOutlierMergeDurations:+ def test_empty_input(self):+ assert outlier_merge_durations([]) == {}++ def test_single_source_passthrough(self):+ source = {"test_a": 1.5, "test_b": 2.5}+ assert outlier_merge_durations([source]) == source++ def test_merge_picks_outlier_per_test(self):+ # Three "segments". test_a: fresh in segment 0; test_b: fresh in segment 2.+ sources = [+ {"test_a": 5.0, "test_b": 1.0},+ {"test_a": 1.0, "test_b": 1.0},+ {"test_a": 1.0, "test_b": 9.0},+ ]+ merged = outlier_merge_durations(sources)+ assert merged == {"test_a": 5.0, "test_b": 9.0}++ def test_test_present_in_only_one_source(self):+ # A new test that only one segment knows about — kept with its value.+ sources = [+ {"test_a": 1.0, "test_b": 1.0},+ {"test_a": 1.0, "test_b": 1.0, "new_test": 4.2},+ ]+ merged = outlier_merge_durations(sources)+ assert merged["new_test"] == 4.2++ def test_all_segments_agree_keeps_value(self):+ sources = [+ {"test_a": 1.0},+ {"test_a": 1.0},+ {"test_a": 1.0},+ ]+ assert outlier_merge_durations(sources) == {"test_a": 1.0}+++class TestJUnitShardSegmentFilter:+ """Pin the segment-prefix anchoring so `Core` can't eat `core-poe-N`."""++ @pytest.fixture+ def junit_dir(self, tmp_path: Path) -> Path:+ for name in (+ "junit-results-backend-core-1",+ "junit-results-backend-core-2",+ "junit-results-backend-core-poe-1",+ "junit-results-backend-temporal-1",+ "junit-results-backend-compat-1", # unrelated, shouldn't match anything+ ):+ shard = tmp_path / name+ shard.mkdir()+ (shard / "junit.xml").write_bytes(_MIN_JUNIT_XML)+ return tmp_path++ def test_core_does_not_match_core_poe(self, junit_dir: Path):+ names = {s.name for s in JUnitShard.load_all(junit_dir, segment="Core")}+ assert names == {"junit-results-backend-core-1", "junit-results-backend-core-2"}++ def test_corepoe_matches_core_poe(self, junit_dir: Path):+ names = {s.name for s in JUnitShard.load_all(junit_dir, segment="CorePOE")}+ assert names == {"junit-results-backend-core-poe-1"}++ def test_temporal_only_matches_temporal(self, junit_dir: Path):+ names = {s.name for s in JUnitShard.load_all(junit_dir, segment="Temporal")}+ assert names == {"junit-results-backend-temporal-1"}++ 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.+ assert JUnitShard.load_all(junit_dir, segment="Bogus") == []+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.jsindex db9bca566740..b677e0063815 100644--- a/.github/scripts/turbo-discover.js+++ b/.github/scripts/turbo-discover.js@@ -14,24 +14,55 @@// Durations come from .test_durations (maintained by pytest-split).//// Input: LEGACY_CHANGED env var ("true"/"false")-// Output: JSON on stdout: { matrix, run_legacy }+// Output: JSON on stdout: { matrix, run_legacy, django_shards }// Diagnostics on stderrconst { execFileSync } = require('child_process')const fs = require('fs')-const SMALL_THRESHOLD_SECONDS = 2 * 60-const TARGET_SHARD_SECONDS = 10 * 60-// Per-product overhead not captured by .test_durations: turbo dispatch, pytest-// collection, Django init. First product pays ~45s, subsequent ~15s; use 60s-// as a conservative average. Durations also underpredict by ~2x because-// pytest-split data was collected under Django Core's shared session.-const SETUP_OVERHEAD_SECONDS = 60-const DURATION_SAFETY_FACTOR = 2+// --- Product shard sizing (same Amdahl shape as Django below) ---+// Each product is atomic for packing, but unlike Django the test pool isn't+// fungible across products — bin-pack products into target-sized shards, and+// multi-shard split any single product that overflows on its own.+const PRODUCT_TARGET_WALL_SECONDS = 10 * 60+// Per-product cost within a runner: turbo dispatch, pytest collection, Django+// init. First product pays ~45s, subsequent ~15s; use 60s as a conservative+// average that also absorbs the amortized portion of runner startup.+const PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS = 60+// Aligned with DJANGO_SAFETY_FACTOR below. Was 2x originally because pytest-+// split data was noisy under Django Core's shared session; the outlier-based+// merge produces cleaner numbers now.+const PRODUCT_SAFETY_FACTOR = 1.3// Tests under these paths need special infrastructure (Temporal server, etc.)// and are handled by Django CI's dedicated segments — exclude from duration estimatesconst EXCLUDED_PATH_SEGMENTS = ['/temporal/']+// --- Django shard auto-sizing (Amdahl's law) ---+// wall_clock = overhead + (total_from_durations_file / shards)+//+// .test_durations has migration-inflated first-test durations corrected+// by optimize_test_durations.py (using JUnit to identify carriers and+// subtract the migration tax). Durations reflect actual test work.+//+// Per-segment overhead constants below cover the fixed per-shard cost+// outside test work: job setup, pytest collection, per-shard DB setup,+// per-segment infra. Measured from JUnit + job wall clocks on a recent+// run (lower bound — includes some per-test fixture setup that JUnit's+// junit_duration_report=call doesn't capture):+// Core: median 303s, max 591s → 4 min covers it comfortably+// CorePOE: median 233s, max 280s → 4 min has headroom+// Temporal: median 375s, max 693s → 6 min, temporal-server boot adds+// meaningful fixed cost beyond Core+const DJANGO_OVERHEAD_SECONDS_BY_SEGMENT = {+ Core: 4 * 60,+ CorePOE: 4 * 60,+ Temporal: 6 * 60,+}+const DJANGO_TARGET_WALL_SECONDS = 20 * 60+const DJANGO_SAFETY_FACTOR = 1.3+const DJANGO_MIN_SHARDS = 3+const DJANGO_MAX_SHARDS = 50+const TURBO_EXEC_OPTS = { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 50 * 1024 * 1024 }const TURBO_BIN = './node_modules/.bin/turbo'@@ -84,12 +115,31 @@ function logAffectedReasons(label, tasks) {}function loadTestDurations() {+ let parsedtry {- return JSON.parse(fs.readFileSync('.test_durations', 'utf-8'))+ parsed = JSON.parse(fs.readFileSync('.test_durations', 'utf-8'))} catch {console.error('Warning: .test_durations not found, sharding disabled')return null}+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {+ console.error('Warning: .test_durations is not a JSON object, sharding disabled')+ return null+ }+ // Strip non-finite values so a single corrupted entry can't NaN-poison the+ // matrix (Math.ceil(NaN) silently propagates through sort/compare, making+ // a product vanish from packing without an error).+ let dropped = 0+ for (const [k, v] of Object.entries(parsed)) {+ if (typeof v !== 'number' || !Number.isFinite(v)) {+ delete parsed[k]+ dropped+++ }+ }+ if (dropped > 0) {+ console.error(`Warning: dropped ${dropped} non-numeric entries from .test_durations`)+ }+ return parsed}function getProductDuration(product, durations) {@@ -107,40 +157,122 @@ function getProductDuration(product, durations) {return total}-function packSmallProducts(products, durations) {- const buckets = []- let current = []- let currentDuration = 0+function productEffectiveCost(product, durations) {+ return getProductDuration(product, durations) * PRODUCT_SAFETY_FACTOR + PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS+}- for (const product of products) {- const effective = getProductDuration(product, durations) * DURATION_SAFETY_FACTOR + SETUP_OVERHEAD_SECONDS- if (current.length > 0 && currentDuration + effective > TARGET_SHARD_SECONDS) {- buckets.push(current)- current = []- currentDuration = 0+// First-fit-decreasing bin packing into TARGET-sized shards. Sorts products by+// effective cost descending so the largest products land first and small ones+// fill the gaps. Each bucket caps at PRODUCT_TARGET_WALL_SECONDS total.+function packProducts(products, durations) {+ const items = products+ .map((product) => ({ product, cost: productEffectiveCost(product, durations) }))+ .sort((a, b) => b.cost - a.cost)++ const buckets = []+ for (const { product, cost } of items) {+ let placed = false+ for (const bucket of buckets) {+ if (bucket.cost + cost <= PRODUCT_TARGET_WALL_SECONDS) {+ bucket.products.push(product)+ bucket.cost += cost+ placed = true+ break+ }+ }+ if (!placed) {+ buckets.push({ products: [product], cost })}- current.push(product)- currentDuration += effective- }- if (current.length > 0) {- buckets.push(current)}return buckets}+// Path filters matching the Django workflow pytest invocations.+// Core: posthog/ + ee/ minus temporal, dags, hogvm+// Core POE: subset of Core (ignores hogql, hogql_queries) — same pool, fewer tests+// Temporal: posthog/temporal + products/batch_exports/backend/tests/temporal + products/tasks/backend/temporal+const DJANGO_SEGMENTS = {+ Core: {+ include: ['posthog/', 'ee/'],+ exclude: ['posthog/temporal/', 'posthog/dags/', 'common/hogvm/'],+ },+ CorePOE: {+ // Keep in sync with the person-on-events pytest targets in+ // ci-backend.yml's "Run Core tests" step.+ include: [+ 'posthog/clickhouse/',+ 'posthog/queries/',+ 'products/product_analytics/backend/api/test/',+ 'posthog/api/test/dashboards/test_dashboard.py',+ 'ee/clickhouse/',+ ],+ exclude: ['posthog/temporal/', 'posthog/dags/', 'common/hogvm/', 'posthog/hogql_queries/', 'posthog/hogql/'],+ },+ Temporal: {+ include: ['posthog/temporal/', 'products/batch_exports/backend/tests/temporal/', 'products/tasks/backend/temporal/'],+ exclude: [],+ },+}++function getSegmentDuration(segment, durations) {+ if (!durations) return 0+ const { include, exclude } = DJANGO_SEGMENTS[segment]+ let total = 0+ for (const [test, dur] of Object.entries(durations)) {+ if (!include.some((p) => test.startsWith(p))) continue+ if (exclude.some((p) => test.startsWith(p))) continue+ total += dur+ }+ return total+}++// Fallback shard counts used when .test_durations is missing.+const DJANGO_FALLBACK_SHARDS = { Core: 38, CorePOE: 7, Temporal: 7 }++function calculateShards(totalWorkSeconds, overheadSeconds) {+ const testBudget = DJANGO_TARGET_WALL_SECONDS - overheadSeconds+ if (testBudget <= 0) return DJANGO_MAX_SHARDS+ const shards = Math.ceil((totalWorkSeconds * DJANGO_SAFETY_FACTOR) / testBudget)+ return Math.max(DJANGO_MIN_SHARDS, Math.min(DJANGO_MAX_SHARDS, shards))+}++function buildDjangoShards(durations) {+ const result = {}+ for (const [segment] of Object.entries(DJANGO_SEGMENTS)) {+ const overhead = DJANGO_OVERHEAD_SECONDS_BY_SEGMENT[segment]+ const duration = getSegmentDuration(segment, durations)+ const shards = durations ? calculateShards(duration, overhead) : DJANGO_FALLBACK_SHARDS[segment]+ // calculateShards applies DJANGO_SAFETY_FACTOR — mirror it in the+ // wall estimate so the diagnostic matches the budget the shard count+ // actually targets (was previously under-reporting by ~30%).+ const wall = overhead + (duration * DJANGO_SAFETY_FACTOR) / shards+ result[segment] = { duration_seconds: duration, shards, estimated_wall_seconds: wall }+ const source = durations ? 'auto' : 'fallback'+ console.error(+ ` Django ${segment}: ${(duration / 60).toFixed(1)} min total, ${shards} shards (${source}), ~${(wall / 60).toFixed(1)} min est. wall`+ )+ }+ return result+}+function buildMatrix(products, durations) {const matrix = []- const small = []+ const packable = []+ // Split a product across multiple shards only when its raw duration plus+ // one per-product overhead exceeds the target wall clock. Don't apply the+ // safety factor here — that inflation is for packing-capacity decisions+ // (avoid stuffing a bucket beyond budget under variance), not for the+ // "must we split?" check. Using the inflated cost for splitting causes+ // borderline products to fragment into uneven sub-shards (pytest-split+ // can't balance well when many tests have flat-default 0.01s values),+ // paying duplicate Docker setup for little parallel work gained.for (const product of products) {- const duration = getProductDuration(product, durations)- const shards = duration > TARGET_SHARD_SECONDS ? Math.ceil(duration / TARGET_SHARD_SECONDS) : 1- console.error(` ${product}: ${(duration / 60).toFixed(1)} min, ${shards} shard(s)`)- const filters = `--filter=@posthog/products-${product}`-- if (duration < SMALL_THRESHOLD_SECONDS) {- small.push(product)- } else if (shards > 1) {+ const raw = getProductDuration(product, durations) + PRODUCT_PER_PRODUCT_OVERHEAD_SECONDS+ if (raw > PRODUCT_TARGET_WALL_SECONDS) {+ const shards = Math.ceil(raw / PRODUCT_TARGET_WALL_SECONDS)+ console.error(` ${product}: ${(raw / 60).toFixed(1)} min raw → split across ${shards} shards`)+ const filters = `--filter=@posthog/products-${product}`for (let i = 1; i <= shards; i++) {matrix.push({group: `${product} (${i}/${shards})`,@@ -149,14 +281,17 @@ function buildMatrix(products, durations) {})}} else {- matrix.push({ group: product, filters, pytest_args: '' })+ packable.push(product)}}- for (const bucket of packSmallProducts(small, durations)) {+ for (const bucket of packProducts(packable, durations)) {+ console.error(+ ` bucket (${(bucket.cost / 60).toFixed(1)} min effective): ${bucket.products.join(', ')}`+ )matrix.push({- group: bucket.join(', '),- filters: bucket.map((p) => `--filter=@posthog/products-${p}`).join(' '),+ group: bucket.products.join(', '),+ filters: bucket.products.map((p) => `--filter=@posthog/products-${p}`).join(' '),pytest_args: '',})}@@ -235,9 +370,14 @@ console.error(`Products to test: ${JSON.stringify(products)}`)console.error(`Run legacy (Django): ${runLegacy}`)const durations = loadTestDurations()++console.error('\nDjango shard calculation:')+const djangoShards = buildDjangoShards(durations)+const result = {matrix: buildMatrix(products, durations),run_legacy: runLegacy,+ django_shards: djangoShards,}// eslint-disable-next-line no-consoleprocess.stdout.write(JSON.stringify(result) + '\n')diff --git a/.github/workflows/ci-backend-update-test-timing.yml b/.github/workflows/ci-backend-update-test-timing.ymlindex 3bfe98e7d09a..1f3549adc0b4 100644--- a/.github/workflows/ci-backend-update-test-timing.yml+++ b/.github/workflows/ci-backend-update-test-timing.yml@@ -1,9 +1,6 @@name: Backend & Dagster CI - Update test timingon:- pull_request:- paths:- - '.github/scripts/optimize_test_durations.py'workflow_dispatch:inputs:backend_run_id:@@ -150,6 +147,15 @@ jobs:--pattern "timing_data-Products-*" \--dir timing_artifacts+ # JUnit artifacts power precise per-shard carrier detection.+ # Without these, optimize_test_durations.py silently takes the+ # statistical fallback and the JUnit-arg becomes a no-op.+ gh run download "$BACKEND_RUN_ID" \+ --pattern "junit-results-backend-core-*" \+ --pattern "junit-results-backend-temporal-*" \+ --dir junit_artifacts || \+ echo "::warning::No JUnit artifacts found — falling back to statistical carrier detection"+# Download dagster timing artifacts if availableif [ -n "$DAGSTER_RUN_ID" ]; thengh run download "$DAGSTER_RUN_ID" --pattern "timing_data-Dagster-*" --dir timing_artifacts@@ -162,11 +168,13 @@ jobs:env:DAGSTER_RUN_ID: ${{ steps.find-dagster-run.outputs.run_id }}run: |- # Process each segment separately, then merge+ # 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).uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/core_durations \- --segment Core+ --segment Core --junit-dir junit_artifactsuv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/temporal_durations \- --segment Temporal+ --segment Temporal --junit-dir junit_artifactsuv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/products_durations \--segment Products@@ -177,19 +185,12 @@ jobs:echo "Processed Dagster timing data"fi- # Merge into single file (Core → Temporal → Products → Dagster, later segments overwrite overlaps)- python3 -c "- import json- durations = {}- for path in ['/tmp/core_durations', '/tmp/temporal_durations', '/tmp/products_durations', '/tmp/dagster_durations']:- try:- with open(path) as f: durations.update(json.load(f))- except FileNotFoundError: pass- with open('.test_durations', 'w') as f:- json.dump(durations, f, indent=4, sort_keys=True)- f.write('\n')- print(f'Merged {len(durations)} tests')- "+ # Outlier-merge across per-segment outputs. Single implementation+ # in optimize_test_durations.py (outlier_merge_durations) is shared+ # 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_durationsrm -rf timing_artifacts /tmp/core_durations /tmp/temporal_durations /tmp/products_durations /tmp/dagster_durations- name: Check for changesdiff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 2da2ca817801..26efc69c47ae 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -77,6 +77,7 @@ jobs:legacy: ${{ steps.filter.outputs.legacy || 'true' }}product_yamls: ${{ steps.filter.outputs.product_yamls || 'false' }}product_yamls_files: ${{ steps.filter.outputs.product_yamls_files }}+ timing_scripts: ${{ steps.filter.outputs.timing_scripts }}steps:# For pull requests it's not necessary to checkout the code, but we# also want this to run on master so we need to checkout@@ -197,6 +198,9 @@ jobs:persons-SQL:- 'rust/persons_migrations/*.sql'- 'rust/bin/migrate-persons'+ timing_scripts:+ - '.github/scripts/optimize_test_durations.py'+ - '.github/scripts/turbo-discover.js'tasks_temporal:- 'products/tasks/backend/temporal/**/*'product_yamls:@@ -277,6 +281,7 @@ jobs:run_legacy: ${{ steps.discover.outputs.run_legacy }}matrix: ${{ steps.discover.outputs.matrix }}schema_cache_key: ${{ steps.schema-key.outputs.key }}+ django_shards: ${{ steps.discover.outputs.django_shards }}steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2@@ -338,6 +343,7 @@ jobs:echo "Result: $RESULT"echo "matrix=$(echo "$RESULT" | jq -c '.matrix')" >> $GITHUB_OUTPUTecho "run_legacy=$(echo "$RESULT" | jq -r '.run_legacy')" >> $GITHUB_OUTPUT+ echo "django_shards=$(echo "$RESULT" | jq -c '.django_shards // empty')" >> $GITHUB_OUTPUT# Runs product tests in parallel — one matrix job per group# Each job gets its own runner + Docker stack, so no shared DB conflicts@@ -1370,8 +1376,11 @@ jobs:build_django_matrix:name: Build Django matrix- needs: [changes, get_clickhouse_versions]- if: needs.changes.outputs.backend == 'true'+ needs: [changes, get_clickhouse_versions, turbo-discover]+ if: |+ always() &&+ needs.changes.outputs.backend == 'true' &&+ needs.get_clickhouse_versions.result == 'success'runs-on: ubuntu-latesttimeout-minutes: 5outputs:@@ -1382,42 +1391,55 @@ jobs:env:OLDEST_SUPPORTED_IMAGE: ${{ needs.get_clickhouse_versions.outputs.oldest_supported_image }}COMPAT_MATRIX_JSON: ${{ needs.get_clickhouse_versions.outputs.compat_matrix }}+ DJANGO_SHARDS_JSON: ${{ needs.turbo-discover.outputs.django_shards }}run: |- # :NOTE: Keep shard counts/group ranges in sync with historical Django matrix tuning.- # Consult #team-devex before changing.- core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" '- [range(1; 39) | {+ # Auto-shard counts from turbo-discover (Amdahl's law on .test_durations).+ # Falls back to hardcoded defaults if turbo-discover failed or data is missing.+ CORE_SHARDS=38+ CORE_POE_SHARDS=7+ TEMPORAL_SHARDS=7+ if [ -n "$DJANGO_SHARDS_JSON" ] && echo "$DJANGO_SHARDS_JSON" | jq -e '.Core.shards' > /dev/null 2>&1; then+ CORE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Core.shards')+ CORE_POE_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.CorePOE.shards')+ TEMPORAL_SHARDS=$(echo "$DJANGO_SHARDS_JSON" | jq -r '.Temporal.shards')+ echo "Auto-sharding: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"+ else+ echo "::warning::Django shard auto-sizing unavailable, using defaults: Core=$CORE_SHARDS, CorePOE=$CORE_POE_SHARDS, Temporal=$TEMPORAL_SHARDS"+ fi++ core=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_SHARDS" '+ [range(1; $shards + 1) | {segment: "Core","person-on-events": false,"python-version": "3.12.12","clickhouse-server-image": $image,- concurrency: 38,+ concurrency: $shards,group: .,artifact_key: ("core-" + (.|tostring)),compat: false}]')- core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" '- [range(1; 8) | {+ core_persons_on_events=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$CORE_POE_SHARDS" '+ [range(1; $shards + 1) | {segment: "Core","person-on-events": true,"python-version": "3.12.12","clickhouse-server-image": $image,- concurrency: 7,+ concurrency: $shards,group: .,artifact_key: ("core-poe-" + (.|tostring)),compat: false}]')- temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" '- [range(1; 8) | {+ temporal=$(jq -cn --arg image "$OLDEST_SUPPORTED_IMAGE" --argjson shards "$TEMPORAL_SHARDS" '+ [range(1; $shards + 1) | {segment: "Temporal","person-on-events": false,"python-version": "3.12.12","clickhouse-server-image": $image,- concurrency: 7,+ concurrency: $shards,group: .,artifact_key: ("temporal-" + (.|tostring)),compat: false@@ -1799,8 +1821,8 @@ jobs:- name: Upload updated timing data as artifactsuses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0- # Only upload timing data on main branch to avoid artifact bloat from PRs- if: ${{ github.ref == 'refs/heads/master' && needs.changes.outputs.backend == 'true' && !matrix.person-on-events && matrix.clickhouse-server-image == needs.get_clickhouse_versions.outputs.oldest_supported_image }}+ # Upload on master, or on PRs that change timing/sharding scripts (for validation)+ if: ${{ (github.ref == 'refs/heads/master' || needs.changes.outputs.timing_scripts == 'true') && needs.changes.outputs.backend == 'true' && !matrix.person-on-events && matrix.clickhouse-server-image == needs.get_clickhouse_versions.outputs.oldest_supported_image }}with:name: timing_data-${{ matrix.segment }}-${{ matrix.group }}path: .test_durations