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(devex): average test durations over the last N runs for file-mode sharding (#65983)

Julian Bez21ad4d674eb5
diff --git a/.github/scripts/optimize_test_durations.py b/.github/scripts/optimize_test_durations.py
index 027615387e8e..cb5d3e4ef0d9 100644
--- a/.github/scripts/optimize_test_durations.py
+++ b/.github/scripts/optimize_test_durations.py
@@ -27,6 +27,7 @@ import glob
import json
import logging
import argparse
+import statistics
import subprocess
from collections import Counter
from dataclasses import dataclass
@@ -199,6 +200,28 @@ def _pick_outlier(values: list[float]) -> float:
return outliers[0] if outliers else most_common_val
+def average_durations(sources: list[dict[str, float]], strategy: str = "mean") -> dict[str, float]:
+ """Combine N already-merged, de-taxed per-RUN duration vectors into one.
+
+ Different from outlier_merge_durations: that picks the fresh value among a
+ single run's stale shard passthroughs. This one assumes every input is a
+ clean per-run vector and averages a test across runs. A single run's per-test
+ times are noisy and the file-granularity plan chases that noise; averaging the
+ last few runs damps it (measured ~-8pp makespan/mean on real PRs going 1 -> 5
+ runs, with the floor itself near 0%).
+
+ Membership is anchored to the FIRST source -- pass the LATEST run first -- so a
+ test deleted since an older run never lingers in the plan, while each surviving
+ test is averaged only over the runs that actually measured it. ``mean`` is the
+ validated default; ``median`` is offered for extra robustness to a stray run.
+ """
+ if not sources:
+ return {}
+ aggregate = statistics.median if strategy == "median" else statistics.fmean
+ anchor = sources[0]
+ return {test: aggregate([s[test] for s in sources if test in s]) for test in anchor}
+
+
class TimingMerger:
"""Merges per-shard timing artifacts using outlier detection.
@@ -488,6 +511,38 @@ def run_merge_files(input_files: list[Path], output_file: Path) -> None:
logger.info("Merged %d tests across %d segment(s) into %s", len(merged), len(sources), output_file)
+def run_average_files(input_files: list[Path], output_file: Path, strategy: str = "mean") -> None:
+ """Average mode: combine already-merged per-RUN files into one output.
+
+ Pass the LATEST run's file first -- membership anchors to it. Fails loudly if
+ no inputs survive, same guard as run_merge_files: an empty per-segment file
+ would silently un-balance every PR's file-mode shards.
+ """
+ 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 average — refusing to write empty %s", output_file)
+ sys.exit(1)
+
+ averaged = average_durations(sources, strategy=strategy)
+ # Membership anchors to the first (newest) source, so an empty newest file would
+ # empty the whole result even when older runs carry data. Refuse to write it —
+ # the workflow's `|| echo warning` then leaves file-mode to scope the union.
+ if not averaged:
+ logger.error("Averaged durations are empty (newest run scoped to nothing?) — refusing to write %s", output_file)
+ sys.exit(1)
+
+ with open(output_file, "w") as f:
+ json.dump(averaged, f, indent=4, sort_keys=True)
+ f.write("\n")
+ logger.info("Averaged %d tests across %d run(s) [%s] into %s", len(averaged), len(sources), strategy, output_file)
+
+
def main():
logging.basicConfig(level=logging.INFO, format="%(message)s")
@@ -538,6 +593,21 @@ def main():
help="Merge mode: outlier-merge the given duration files and write to output_file. "
"Ignores artifacts_dir and the other artifact-processing flags.",
)
+ parser.add_argument(
+ "--average-files",
+ type=Path,
+ nargs="+",
+ default=None,
+ help="Average mode: combine already-merged per-RUN duration files (LATEST first) into "
+ "output_file by per-test mean/median. Builds a multi-run .test_durations.<segment> that "
+ "is robust to one run's timing noise. Ignores artifacts_dir.",
+ )
+ parser.add_argument(
+ "--average-strategy",
+ choices=["mean", "median"],
+ default="mean",
+ help="Aggregation for --average-files (default: mean).",
+ )
args = parser.parse_args()
@@ -545,8 +615,12 @@ def main():
run_merge_files(args.merge_files, args.output_file)
return
+ if args.average_files:
+ run_average_files(args.average_files, args.output_file, args.average_strategy)
+ return
+
if args.artifacts_dir is None:
- parser.error("artifacts_dir is required unless --merge-files is given")
+ parser.error("artifacts_dir is required unless --merge-files or --average-files is given")
# Load per-shard timing data
logger.info("Loading timing artifacts from %s...", args.artifacts_dir)
diff --git a/.github/scripts/test_optimize_test_durations.py b/.github/scripts/test_optimize_test_durations.py
index fdbc48d24b39..a055dca9ccc7 100644
--- a/.github/scripts/test_optimize_test_durations.py
+++ b/.github/scripts/test_optimize_test_durations.py
@@ -7,7 +7,14 @@ from pathlib import Path
import pytest
-from optimize_test_durations import JUnitShard, MigrationTaxCorrector, _pick_outlier, outlier_merge_durations
+from optimize_test_durations import (
+ JUnitShard,
+ MigrationTaxCorrector,
+ _pick_outlier,
+ average_durations,
+ outlier_merge_durations,
+ run_average_files,
+)
# Minimal valid JUnit XML — one testcase with a CamelCase classname so
# _junit_to_pytest_id resolves cleanly.
@@ -74,6 +81,56 @@ class TestOutlierMergeDurations:
assert outlier_merge_durations(sources) == {"test_a": 1.0}
+class TestAverageDurations:
+ def test_empty_input(self):
+ assert average_durations([]) == {}
+
+ def test_single_source_passthrough(self):
+ source = {"test_a": 1.5, "test_b": 2.5}
+ assert average_durations([source]) == source
+
+ def test_mean_across_runs(self):
+ sources = [
+ {"test_a": 2.0, "test_b": 10.0},
+ {"test_a": 4.0, "test_b": 20.0},
+ ]
+ assert average_durations(sources) == {"test_a": 3.0, "test_b": 15.0}
+
+ def test_median_resists_a_stray_run(self):
+ # test_a spikes in one run (e.g. residual contamination); median ignores
+ # it where mean would drag toward the spike.
+ sources = [{"test_a": 2.0}, {"test_a": 2.0}, {"test_a": 100.0}]
+ assert average_durations(sources, strategy="median") == {"test_a": 2.0}
+
+ def test_membership_anchored_to_first_source(self):
+ # 'deleted' only appears in an older (non-first) run -> dropped.
+ # 'added' only appears in the first (latest) run -> kept.
+ sources = [
+ {"test_a": 1.0, "added": 3.0},
+ {"test_a": 1.0, "deleted": 9.0},
+ ]
+ result = average_durations(sources)
+ assert "deleted" not in result
+ assert result["added"] == 3.0
+
+ def test_average_over_present_runs_only(self):
+ # test_a measured in 2 of 3 runs; average over just those two.
+ sources = [{"test_a": 2.0}, {"test_b": 5.0}, {"test_a": 6.0}]
+ assert average_durations(sources)["test_a"] == 4.0
+
+ 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 {}.
+ newest = tmp_path / "core_newest"
+ newest.write_text("{}")
+ older = tmp_path / "core_older"
+ older.write_text('{"test_a": 1.0}')
+ out = tmp_path / "out.core"
+ with pytest.raises(SystemExit):
+ run_average_files([newest, older], out)
+ assert not out.exists()
+
+
class TestJUnitShardSegmentFilter:
"""Pin the segment-prefix anchoring so `Core` can't eat `core-poe-N`."""
diff --git a/.github/workflows/ci-backend-update-test-timing.yml b/.github/workflows/ci-backend-update-test-timing.yml
index e894312f9dc8..38dbf09acec1 100644
--- a/.github/workflows/ci-backend-update-test-timing.yml
+++ b/.github/workflows/ci-backend-update-test-timing.yml
@@ -58,44 +58,62 @@ jobs:
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
INPUT_RUN_ID: ${{ inputs.backend_run_id }}
+ # Optional org/repo variable to tune how many runs the per-segment plan averages
+ # (default 5). Unset renders empty and the shell default kicks in.
+ BACKEND_RUNS_TO_AVERAGE: ${{ vars.BACKEND_RUNS_TO_AVERAGE }}
run: |
if [ -n "$INPUT_RUN_ID" ]; then
echo "run_id=$INPUT_RUN_ID" >> $GITHUB_OUTPUT
+ echo "run_ids=$INPUT_RUN_ID" >> $GITHUB_OUTPUT
echo "Using provided Backend CI run: $INPUT_RUN_ID"
exit 0
fi
- # Find a recent successful ci-backend.yml run with timing artifacts
+ # Find recent successful ci-backend.yml runs with timing artifacts.
# Most runs skip tests due to path filtering (~20 sec), so filter by duration first
# Runs that actually execute tests take 15+ minutes
# Only consider runs from the past 14 days to ensure artifacts haven't expired
- echo "Searching for Backend CI run with timing artifacts..."
+ echo "Searching for Backend CI runs with timing artifacts..."
+
+ # The per-segment file-mode plan (.test_durations.core/.temporal) is averaged over
+ # the last N runs to damp one run's timing noise (~-8pp makespan/mean on real PRs,
+ # 1 -> 5 runs; the achievable floor is ~0%). The union .test_durations and the
+ # JUnit de-tax still use the newest run alone (the primary). N stays small so the
+ # extra downloads stay modest.
+ N="${BACKEND_RUNS_TO_AVERAGE:-5}"
+ # Guard a mis-set variable: a non-integer would make the `-ge` test below error
+ # out (never breaking the loop) and silently average every candidate run.
+ [[ "$N" =~ ^[1-9][0-9]*$ ]] || N=5
+ found=0 # counts qualifying runs inside the loop below
# Calculate date 14 days ago in ISO 8601 format
cutoff_date=$(date -u -d '14 days ago' +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v-14d +%Y-%m-%dT%H:%M:%SZ)
- # Get runs that took more than 5 minutes (300 seconds) - likely ran tests
- # Filter to runs created in the past 14 days to avoid expired artifacts
- run_id=$(gh api "repos/${{ github.repository }}/actions/workflows/ci-backend.yml/runs?status=success&branch=master&per_page=100&created=>=$cutoff_date" \
+ # Newest first: runs that ran tests (>5 min) and uploaded a full set of timing
+ # artifacts (>=38), up to N. Scan a wider candidate window since most runs skip.
+ run_ids=$(gh api "repos/${{ github.repository }}/actions/workflows/ci-backend.yml/runs?status=success&branch=master&per_page=100&created=>=$cutoff_date" \
--jq '.workflow_runs[] | select(
(.updated_at | fromdateiso8601) - (.run_started_at | fromdateiso8601) > 300
- ) | .id' | head -5 | \
+ ) | .id' | head -25 | \
while read id; do
count=$(gh api "repos/${{ github.repository }}/actions/runs/$id/artifacts?per_page=100" \
--jq '[.artifacts[] | select(.name | startswith("timing_data-")) | select(.expired == false)] | length' 2>/dev/null)
echo "Run $id has $count timing artifacts" >&2
if [ "$count" -ge "38" ]; then
echo "$id"
- break
+ found=$((found + 1))
+ [ "$found" -ge "$N" ] && break
fi
done)
- if [ -z "$run_id" ]; then
+ primary=$(echo "$run_ids" | head -1)
+ if [ -z "$primary" ]; then
echo "::error::No suitable Backend CI run found with timing artifacts"
exit 1
fi
- echo "run_id=$run_id" >> $GITHUB_OUTPUT
- echo "Found Backend CI run: $run_id"
+ echo "run_id=$primary" >> $GITHUB_OUTPUT
+ echo "run_ids=$(echo $run_ids | tr '\n' ' ')" >> $GITHUB_OUTPUT
+ echo "Found Backend CI runs (newest first): $(echo $run_ids | tr '\n' ' ')"
- name: Find Dagster CI run to use
id: find-dagster-run
@@ -143,6 +161,7 @@ jobs:
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
BACKEND_RUN_ID: ${{ steps.find-backend-run.outputs.run_id }}
+ BACKEND_RUN_IDS: ${{ steps.find-backend-run.outputs.run_ids }}
DAGSTER_RUN_ID: ${{ steps.find-dagster-run.outputs.run_id }}
run: |
# Download backend timing artifacts. Use segment-specific patterns
@@ -164,6 +183,22 @@ jobs:
--dir junit_artifacts || \
echo "::warning::No JUnit artifacts found — falling back to statistical carrier detection"
+ # Multi-run: pull timing + JUnit for each run we average into the per-segment
+ # file-mode plan (Core/Temporal only). Each run is de-taxed + scoped on its own
+ # below, then averaged. The primary is also downloaded here (into its own dir) so
+ # the union/JUnit steps above stay untouched. A run with no JUnit just gets its
+ # per-segment slice skipped, same fallback as the single-run path.
+ for rid in $BACKEND_RUN_IDS; do
+ gh run download "$rid" \
+ --pattern "timing_data-Core-*" \
+ --pattern "timing_data-Temporal-*" \
+ --dir "runs/$rid/timing" || { echo "::warning::No timing for run $rid — skipping it"; continue; }
+ gh run download "$rid" \
+ --pattern "junit-results-backend-core-*" \
+ --pattern "junit-results-backend-temporal-*" \
+ --dir "runs/$rid/junit" || echo "::warning::No JUnit for run $rid — its per-segment slice is skipped"
+ done
+
# Download dagster timing artifacts if available
if [ -n "$DAGSTER_RUN_ID" ]; then
gh run download "$DAGSTER_RUN_ID" --pattern "timing_data-Dagster-*" --dir timing_artifacts
@@ -175,6 +210,7 @@ jobs:
- name: Process timing data
env:
DAGSTER_RUN_ID: ${{ steps.find-dagster-run.outputs.run_id }}
+ 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.
@@ -209,22 +245,45 @@ jobs:
# JUnit saw run; the run-set is already in the artifacts, so this adds no
# collection. The union above is untouched (item-mode + turbo-discover still
# read it); these are purely additive, cached per-segment below.
- # Non-fatal: --scope-to-junit hard-exits if a segment's JUnit is missing,
- # but the union .test_durations above is already built and MUST still be
- # cached/committed below. A JUnit miss just skips that segment's per-segment
- # file for the day; ci-backend then falls back to scoping the union.
- uv run .github/scripts/optimize_test_durations.py timing_artifacts .test_durations.core \
- --segment Core --junit-dir junit_artifacts --scope-to-junit \
- || echo "::warning::Core per-segment durations skipped (no JUnit?) — file-mode falls back to union scoping"
- uv run .github/scripts/optimize_test_durations.py timing_artifacts .test_durations.temporal \
- --segment Temporal --junit-dir junit_artifacts --scope-to-junit \
- || echo "::warning::Temporal per-segment durations skipped (no JUnit?) — file-mode falls back to union scoping"
-
- # Also drop junit_artifacts — ghcommit-action defaults file_pattern
- # to "." and chokes on leftover download dirs ("read junit_artifacts/:
- # is a directory"). The commit steps below also pin file_pattern as a
- # belt-and-braces guard.
- rm -rf timing_artifacts junit_artifacts /tmp/core_durations /tmp/temporal_durations /tmp/products_durations /tmp/dagster_durations
+ #
+ # AVERAGED over the last N runs (newest first) to damp one run's timing noise:
+ # on real PRs a single-run plan lands ~+30-50% makespan/mean, multi-run ~-8pp of
+ # that, and good vs bad single run is just luck (the floor is ~0%). Each run is
+ # de-taxed + scoped on its own through the same path as before, then averaged;
+ # the newest run is passed first so it anchors membership (a test deleted since
+ # an older run never lingers). Non-fatal throughout: a run with no JUnit is
+ # skipped, and if none survive ci-backend falls back to scoping the union.
+ core_files=""
+ temporal_files=""
+ for rid in $BACKEND_RUN_IDS; do
+ if uv run .github/scripts/optimize_test_durations.py "runs/$rid/timing" "/tmp/core_$rid" \
+ --segment Core --junit-dir "runs/$rid/junit" --scope-to-junit; then
+ core_files="$core_files /tmp/core_$rid"
+ fi
+ if uv run .github/scripts/optimize_test_durations.py "runs/$rid/timing" "/tmp/temporal_$rid" \
+ --segment Temporal --junit-dir "runs/$rid/junit" --scope-to-junit; then
+ temporal_files="$temporal_files /tmp/temporal_$rid"
+ fi
+ done
+
+ if [ -n "$core_files" ]; then
+ uv run .github/scripts/optimize_test_durations.py .test_durations.core --average-files $core_files \
+ || echo "::warning::Core multi-run average failed — file-mode falls back to union scoping"
+ else
+ echo "::warning::Core per-segment durations skipped (no JUnit in any run?) — file-mode falls back to union scoping"
+ fi
+ if [ -n "$temporal_files" ]; then
+ uv run .github/scripts/optimize_test_durations.py .test_durations.temporal --average-files $temporal_files \
+ || echo "::warning::Temporal multi-run average failed — file-mode falls back to union scoping"
+ else
+ echo "::warning::Temporal per-segment durations skipped (no JUnit in any run?) — file-mode falls back to union scoping"
+ fi
+
+ # Also drop timing/JUnit download dirs (incl. the per-run runs/ tree) —
+ # ghcommit-action defaults file_pattern to "." and chokes on leftover download
+ # dirs ("read junit_artifacts/: is a directory"). The commit steps below also
+ # pin file_pattern as a belt-and-braces guard.
+ rm -rf timing_artifacts junit_artifacts runs /tmp/core_* /tmp/temporal_* /tmp/products_durations /tmp/dagster_durations
- name: Compute cache key and monthly-commit flag
id: durations-meta