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(devex): stop flooring test durations and check the map against the clock (#88987)

Julian Bez245cb2e0cb48
diff --git a/.depot/workflows/ci-backend-update-test-timing.yml b/.depot/workflows/ci-backend-update-test-timing.yml
index de737913043b..7544672342e6 100644
--- a/.depot/workflows/ci-backend-update-test-timing.yml
+++ b/.depot/workflows/ci-backend-update-test-timing.yml
@@ -52,6 +52,25 @@ jobs:
fi
echo "run_id=$primary" >> "$GITHUB_OUTPUT"
+ - name: Restore the previous map for the drift fallback
+ # The merge below takes product entries only from the products file
+ # (--replace-prefix), so a Products slice that fails the drift check
+ # needs a stand-in or every product loses its durations. The last
+ # cached map is that stand-in. A miss leaves the checked-out file.
+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
+ continue-on-error: true
+ with:
+ path: .test_durations
+ # run_id never matches — forces the prefix restore-key to the newest entry.
+ key: posthog-test-durations-${{ github.run_id }}
+ restore-keys: |
+ posthog-test-durations-
+
+ - name: Set the previous map aside
+ run: |
+ cp .test_durations /tmp/previous_durations
+ git checkout -- .test_durations
+
- name: Download timing artifacts
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
@@ -74,8 +93,23 @@ jobs:
--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
+ # A products slice whose shape drifted from the JUnit clock must not
+ # reach the cache; a missing slice is worse (the merge takes product
+ # entries only from this file), so keep the previous slice instead.
+ set +e
uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/products_durations \
- --segment Products --junit-dir junit_artifacts
+ --segment Products --junit-dir junit_artifacts --fail-on-drift
+ products_status=$?
+ set -e
+ if [ "$products_status" -ne 0 ]; then
+ echo "::warning::Products durations refresh exited $products_status; keeping the previous products slice. Drift or an incomplete JUnit set are the expected causes, see the log above."
+ # Only entries the fresh slices do not carry: the outlier merge would
+ # otherwise let a stale value here beat a fresh one for the same test.
+ jq -s 'add' $(ls /tmp/core_durations /tmp/temporal_durations 2>/dev/null) > /tmp/fresh_durations
+ jq --slurpfile fresh /tmp/fresh_durations \
+ 'with_entries(select((.key | startswith("products/")) and ($fresh[0][.key] == null)))' \
+ /tmp/previous_durations > /tmp/products_durations
+ fi
uv run .github/scripts/optimize_test_durations.py .test_durations \
--merge-files /tmp/core_durations /tmp/temporal_durations /tmp/products_durations \
--replace-prefix products/
diff --git a/.github/scripts/optimize_test_durations.py b/.github/scripts/optimize_test_durations.py
index 4a75b8d732f0..c8adf2eac3ea 100644
--- a/.github/scripts/optimize_test_durations.py
+++ b/.github/scripts/optimize_test_durations.py
@@ -21,6 +21,16 @@ and skewing pytest-split.
This script merges the per-shard artifacts, floors any test recorded far
above its JUnit call time (or sitting at a flat-default placeholder) back
to that call time, and outputs clean durations for balanced distribution.
+There is no global minimum: a 1 ms test is written as 1 ms. A floor there
+gave tens of thousands of tiny parametrized tests ten times their real
+weight, so a contiguous shard of them planned at twice its real length
+while the fixture-heavy shard next to it ran past its budget.
+
+The map-versus-clock report at the end compares, per JUnit shard, the sum of
+the finished durations for the tests that shard ran against the sum of the
+shard's JUnit times. Both are per-test measurements of the same run, so a
+correct file lands near 1.0 on every shard; a ratio far from 1.0 means a
+processing step changed the shape of the data, not just its total.
"""
import re
@@ -40,7 +50,20 @@ from defusedxml.ElementTree import ParseError
logger = logging.getLogger(__name__)
-MIN_DURATION = 0.01
+# Lower bound for a duration the corrections below rewrite: a corrected value
+# must stay positive so pytest-split still counts the test. Not a floor for
+# measured values; those are written as recorded.
+MIN_DURATION = 0.001
+# A shard whose map/clock ratio leaves this band has the wrong shape, not just
+# the wrong total. Per-shard sums cover hundreds of tests, so run-to-run noise
+# stays well inside it.
+SHARD_DRIFT_TOLERANCE = 1.5
+# Share of a JUnit shard's time that must have a map entry before strict mode
+# trusts its ratio. The ratio only sees tests both sides hold, so a partial
+# timing artifact or an id that fails conversion would drop out of both sums
+# and leave the ratio at 1.0. A complete run covers 100%; the margin is for a
+# handful of unconvertible ids.
+SHARD_CLOCK_COVERAGE_MIN = 0.9
# 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
@@ -479,9 +502,39 @@ def _junit_to_pytest_id(classname: str, testname: str) -> str | None:
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 shard_map_clock_ratios(durations: dict[str, float], junit_shards: list["JUnitShard"]) -> dict[str, float]:
+ """Per JUnit shard: sum of finished durations / sum of JUnit times, over the tests both hold.
+
+ The map is what pytest-split plans from; the clock is what the same run
+ measured. A shard far from 1.0 is one the plan will cut wrong.
+ """
+ ratios: dict[str, float] = {}
+ for shard in junit_shards:
+ clock = 0.0
+ mapped = 0.0
+ for test_id, seconds in shard.call_times.items():
+ if test_id not in durations:
+ continue
+ clock += seconds
+ mapped += durations[test_id]
+ if clock > 0:
+ ratios[shard.name] = mapped / clock
+ return ratios
+
+
+def shard_clock_coverage(durations: dict[str, float], junit_shards: list["JUnitShard"]) -> dict[str, float]:
+ """Per JUnit shard: share of its JUnit time whose test has a map entry."""
+ coverage: dict[str, float] = {}
+ for shard in junit_shards:
+ total = sum(shard.call_times.values())
+ covered = sum(seconds for test_id, seconds in shard.call_times.items() if test_id in durations)
+ if total > 0:
+ coverage[shard.name] = covered / total
+ return coverage
+
+
+def drifting_shards(ratios: dict[str, float], tolerance: float = SHARD_DRIFT_TOLERANCE) -> dict[str, float]:
+ return {name: ratio for name, ratio in ratios.items() if ratio > tolerance or ratio < 1 / tolerance}
def shard_sets_match(timing_shards: list[ShardTimings], junit_shards: list[JUnitShard]) -> bool:
@@ -716,6 +769,15 @@ def main():
action="store_true",
help="Filter to only tests that exist in the codebase (runs pytest --collect-only)",
)
+ parser.add_argument(
+ "--fail-on-drift",
+ action="store_true",
+ help=(
+ "Exit non-zero when a JUnit shard's finished durations sum to more than "
+ f"{SHARD_DRIFT_TOLERANCE}x (or less than 1/{SHARD_DRIFT_TOLERANCE}x) of its JUnit times "
+ "(requires --junit-dir). Without it the drift is only logged."
+ ),
+ )
parser.add_argument(
"--scope-to-junit",
action="store_true",
@@ -881,12 +943,69 @@ def main():
logger.info(" Filtered to %d tests (removed %d stale)", len(durations), before_count - len(durations))
logger.info(" Total tests: %d", len(durations))
- processed = ensure_minimum_duration(durations)
+
+ if args.fail_on_drift:
+ # The check is only as good as its clock. A missing, partial, or
+ # truncated JUnit set would pass vacuously and let an unchecked slice
+ # through, so a strict run needs one readable JUnit per timing shard.
+ unreadable = [shard.name for shard in junit_shards or [] if shard.unreadable or not shard.call_times]
+ if not junit_shards:
+ logger.error("--fail-on-drift needs JUnit artifacts and none loaded")
+ sys.exit(1)
+ if unreadable:
+ logger.error(
+ "--fail-on-drift needs a readable JUnit artifact for every timing shard; unreadable: %s", unreadable
+ )
+ sys.exit(1)
+ if not shard_sets_match(shards, junit_shards):
+ logger.error(
+ "--fail-on-drift needs the same shard set on both sides: %d timing shards, %d JUnit shards",
+ len(shards),
+ len(junit_shards),
+ )
+ sys.exit(1)
+
+ if junit_shards:
+ ratios = shard_map_clock_ratios(durations, junit_shards)
+ for name, ratio in sorted(ratios.items()):
+ logger.info(" map/clock %s: %.2f", name, ratio)
+ # A shard with no ratio shares no keys with the map, or only zero times.
+ # Neither is a pass: it means the clock and the map do not describe the
+ # same tests, which is exactly what strict mode is there to catch.
+ unrated = [shard.name for shard in junit_shards if shard.name not in ratios]
+ if unrated and args.fail_on_drift:
+ logger.error("Map/clock ratio missing for %d shards (no overlapping tests): %s", len(unrated), unrated)
+ sys.exit(1)
+ uncovered = {
+ name: share
+ for name, share in shard_clock_coverage(durations, junit_shards).items()
+ if share < SHARD_CLOCK_COVERAGE_MIN
+ }
+ if uncovered and args.fail_on_drift:
+ logger.error(
+ "Map covers less than %.0f%% of the JUnit time on %d shards: %s",
+ SHARD_CLOCK_COVERAGE_MIN * 100,
+ len(uncovered),
+ ", ".join(f"{name}={share:.2f}" for name, share in sorted(uncovered.items())),
+ )
+ sys.exit(1)
+ drift = drifting_shards(ratios)
+ if drift:
+ level = logger.error if args.fail_on_drift else logger.warning
+ level(
+ "Map/clock drift outside %.2fx on %d of %d shards: %s",
+ SHARD_DRIFT_TOLERANCE,
+ len(drift),
+ len(ratios),
+ ", ".join(f"{name}={ratio:.2f}" for name, ratio in sorted(drift.items())),
+ )
+ if args.fail_on_drift:
+ sys.exit(1)
with open(args.output_file, "w") as f:
- json.dump(processed, f, indent=4, sort_keys=True)
+ json.dump(durations, f, indent=4, sort_keys=True)
f.write("\n")
- logger.info("Saved %d tests to %s", len(processed), args.output_file)
+ logger.info("Saved %d tests to %s", len(durations), args.output_file)
if __name__ == "__main__":
diff --git a/.github/scripts/test_optimize_test_durations.py b/.github/scripts/test_optimize_test_durations.py
index fbb5036b6f04..51427fbc6c61 100644
--- a/.github/scripts/test_optimize_test_durations.py
+++ b/.github/scripts/test_optimize_test_durations.py
@@ -15,12 +15,15 @@ from optimize_test_durations import (
ShardTimings,
_pick_outlier,
average_durations,
+ drifting_shards,
main,
outlier_merge_durations,
run_average_files,
run_merge_files,
scale_products_to_junit,
scope_products_to_junit,
+ shard_clock_coverage,
+ shard_map_clock_ratios,
shard_sets_match,
)
@@ -452,6 +455,113 @@ def test_scale_products_to_junit_matches_sums_to_measured_work(tmp_path: Path) -
assert scaled["products/.junit-scaled"] == 1.0
+def test_main_writes_sub_ten_millisecond_durations_as_recorded(tmp_path: Path, monkeypatch) -> None:
+ # A global floor once rewrote every fast test as 10 ms. Tens of thousands of
+ # parametrized tests really take 1 ms, so a shard of them planned at twice
+ # its real length.
+ shard_dir = tmp_path / "timing_artifacts" / "timing_data-Core-1"
+ shard_dir.mkdir(parents=True)
+ (shard_dir / ".test_durations").write_text(
+ json.dumps({"posthog/test_foo.py::TestThing::test_one": 0.5, "posthog/test_foo.py::TestThing::test_two": 0.001})
+ )
+ junit_dir = tmp_path / "junit_artifacts" / "junit-results-backend-core-1"
+ junit_dir.mkdir(parents=True)
+ (junit_dir / "junit.xml").write_bytes(
+ b'<?xml version="1.0"?><testsuite name="pytest">'
+ b'<testcase classname="posthog.test_foo.TestThing" name="test_one" time="0.5"/>'
+ b'<testcase classname="posthog.test_foo.TestThing" name="test_two" time="0.001"/></testsuite>'
+ )
+ out = tmp_path / "core_durations"
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "optimize_test_durations.py",
+ str(tmp_path / "timing_artifacts"),
+ str(out),
+ "--segment",
+ "Core",
+ "--junit-dir",
+ str(tmp_path / "junit_artifacts"),
+ "--fail-on-drift",
+ ],
+ )
+
+ main()
+
+ assert json.loads(out.read_text())["posthog/test_foo.py::TestThing::test_two"] == 0.001
+
+
[email protected]("junit_shards_present", [(), ("1",), ("1", "2")])
+def test_fail_on_drift_refuses_an_incomplete_junit_set(tmp_path: Path, monkeypatch, junit_shards_present) -> None:
+ # No JUnit, JUnit for only one of two shards, or JUnit that shares no test
+ # with the timing data (the XML here names test_foo, the timings test_1 and
+ # test_2) would let the drift check pass on nothing; a strict run must
+ # refuse so the workflow keeps the previous slice instead of caching an
+ # unchecked one.
+ artifacts = tmp_path / "timing_artifacts"
+ for shard in ("1", "2"):
+ shard_dir = artifacts / f"timing_data-Core-{shard}"
+ shard_dir.mkdir(parents=True)
+ (shard_dir / ".test_durations").write_text(json.dumps({f"posthog/test_{shard}.py::test_{shard}": 1.0}))
+ junit_dir = tmp_path / "junit_artifacts"
+ junit_dir.mkdir()
+ for shard in junit_shards_present:
+ (junit_dir / f"junit-results-backend-core-{shard}").mkdir()
+ (junit_dir / f"junit-results-backend-core-{shard}" / "junit.xml").write_bytes(_MIN_JUNIT_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),
+ "--fail-on-drift",
+ ],
+ )
+
+ with pytest.raises(SystemExit):
+ main()
+ assert not out.exists()
+
+
+ "mapped_seconds, drifts",
+ [
+ (110.0, False), # a tenth over: run-to-run noise
+ (250.0, True), # the shape is wrong: tiny tests carrying phantom weight
+ (40.0, True), # the other direction: heavy tests under-counted
+ ],
+)
+def test_shard_map_clock_ratio_flags_shape_drift(mapped_seconds: float, drifts: bool) -> None:
+ shard = JUnitShard(name="product-junit-results-3", call_times={"products/p/backend/test_a.py::test_a": 100.0})
+ durations = {"products/p/backend/test_a.py::test_a": mapped_seconds, "products/p/backend/test_b.py::test_b": 5.0}
+
+ ratios = shard_map_clock_ratios(durations, [shard])
+
+ # test_b never ran in this shard, so it does not count against the shard.
+ assert ratios == {"product-junit-results-3": pytest.approx(mapped_seconds / 100.0)}
+ assert bool(drifting_shards(ratios)) is drifts
+
+
+def test_shard_clock_coverage_counts_only_tests_the_map_holds() -> None:
+ # A test missing from the map drops out of the ratio on both sides, so the
+ # ratio alone cannot see a partial artifact; coverage can.
+ shard = JUnitShard(
+ name="product-junit-results-3",
+ call_times={"products/p/backend/test_a.py::test_a": 30.0, "products/p/backend/test_b.py::test_b": 70.0},
+ )
+
+ assert shard_clock_coverage({"products/p/backend/test_a.py::test_a": 31.0}, [shard]) == {
+ "product-junit-results-3": pytest.approx(0.3)
+ }
+
+
def test_scale_products_to_junit_leaves_products_without_junit_alone(tmp_path: Path) -> None:
durations = {"products/other_one/backend/test_b.py::test_b": 7.0}
diff --git a/.github/workflows/ci-backend-update-test-timing.yml b/.github/workflows/ci-backend-update-test-timing.yml
index a40abdd32e79..fbde480bc553 100644
--- a/.github/workflows/ci-backend-update-test-timing.yml
+++ b/.github/workflows/ci-backend-update-test-timing.yml
@@ -151,6 +151,27 @@ jobs:
echo "Found Dagster CI run: $run_id"
fi
+ - name: Restore the previous map for the drift fallback
+ # The merge below takes product entries only from the products file
+ # (--replace-prefix), so a Products slice that fails the drift check
+ # needs a stand-in or every product loses its durations. The last
+ # cached map is that stand-in. A miss leaves the checked-out file.
+ uses: actions/cache/restore@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3
+ continue-on-error: true
+ with:
+ path: .test_durations
+ # run_id never matches — forces the prefix restore-key to the newest entry.
+ key: posthog-test-durations-${{ github.run_id }}
+ restore-keys: |
+ posthog-test-durations-
+
+ - name: Set the previous map aside
+ # The restore lands on the tracked file; keep the copy elsewhere and put
+ # the committed file back so the change check below diffs a clean tree.
+ run: |
+ cp .test_durations /tmp/previous_durations
+ git checkout -- .test_durations
+
- name: Download timing artifacts
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
@@ -233,8 +254,24 @@ jobs:
fi
# Products has its own guarded scoping inside the script (only scopes when the
# JUnit shard set is complete), so no flag here.
+ # Products has no unscoped retry. A slice whose shape drifted from
+ # the clock must not reach the cache, and a missing slice is worse
+ # (the merge takes product entries only from this file), so keep
+ # the previous slice and still refresh Core and Temporal.
+ set +e
uv run .github/scripts/optimize_test_durations.py timing_artifacts /tmp/products_durations \
- --segment Products --junit-dir junit_artifacts
+ --segment Products --junit-dir junit_artifacts --fail-on-drift
+ products_status=$?
+ set -e
+ if [ "$products_status" -ne 0 ]; then
+ echo "::warning::Products durations refresh exited $products_status; keeping the previous products slice. Drift or an incomplete JUnit set are the expected causes, see the log above."
+ # Only entries the fresh slices do not carry: the outlier merge would
+ # otherwise let a stale value here beat a fresh one for the same test.
+ jq -s 'add' $(ls /tmp/core_durations /tmp/temporal_durations /tmp/dagster_durations 2>/dev/null) > /tmp/fresh_durations
+ jq --slurpfile fresh /tmp/fresh_durations \
+ 'with_entries(select((.key | startswith("products/")) and ($fresh[0][.key] == null)))' \
+ /tmp/previous_durations > /tmp/products_durations
+ fi
# Process Dagster segment if available
if [ -n "$DAGSTER_RUN_ID" ]; then