From ce71aad1cfc9db491ded31595cf532df65ccd942 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 19:08:15 -0600 Subject: [PATCH 1/2] fix(mcpx): validate e2e shard timing seeds --- pkgs/mcpx/scripts/ci/e2e-shard-packer.py | 56 ++++++- .../scripts/tests/test_e2e_shard_packer.py | 155 ++++++++++++++++++ 2 files changed, 206 insertions(+), 5 deletions(-) create mode 100644 pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py diff --git a/pkgs/mcpx/scripts/ci/e2e-shard-packer.py b/pkgs/mcpx/scripts/ci/e2e-shard-packer.py index 366d471d39..257613cffe 100755 --- a/pkgs/mcpx/scripts/ci/e2e-shard-packer.py +++ b/pkgs/mcpx/scripts/ci/e2e-shard-packer.py @@ -59,25 +59,71 @@ def discover(tests_dir: str) -> list[str]: return sorted(names) +def _weight_seconds(value: object) -> float | None: + # Timing weights must be finite positive numbers. bool is an int + # subclass, so reject it before the numeric check: True would + # otherwise silently become a 1.0s measurement. Non-finite floats + # (Infinity via a bare token or 1e999, -Infinity, NaN) must not + # poison the median or the shard-count arithmetic in pack(). + if isinstance(value, bool): + return None + if not isinstance(value, (int, float)): + return None + try: + seconds = float(value) + except (OverflowError, ValueError): + return None + if not math.isfinite(seconds) or seconds <= 0: + return None + return seconds + + def load_weights(path: str | None, names: list[str]) -> tuple[dict[str, float], str]: measured: dict[str, float] = {} + skipped: list[str] = [] if path and os.path.exists(path): with open(path) as fh: doc = json.load(fh) - raw = doc.get("tests", doc) if isinstance(doc, dict) else {} + if isinstance(doc, dict) and "tests" in doc: + tests_val = doc["tests"] + if not isinstance(tests_val, dict): + return {name: DEFAULT_SECONDS for name in names}, ( + f"equal weights at the run-41530429335 rate ({DEFAULT_SECONDS:.0f}s/test; " + f"timing seed defect: 'tests' is {type(tests_val).__name__}, " + f"expected object; ignoring seed)") + raw = tests_val + elif isinstance(doc, dict): + raw = doc + else: + raw = {} for name, seconds in raw.items(): - if name in names and isinstance(seconds, (int, float)) and seconds > 0: - measured[name] = float(seconds) + if name not in names: + continue + weight = _weight_seconds(seconds) + if weight is None: + skipped.append(name) + else: + measured[name] = weight + skipped_note = ( + f"; skipped invalid weight(s): {', '.join(sorted(skipped))}" + if skipped else "" + ) if not measured: # Equal weights, scaled by the only per-test rate this repo has: # run 41530429335 spent ~174 s over ~58 tests in each of six shards, # i.e. ~3 s per test. Unit weights would under-count the suite and # silently drop the shard count, so the fallback keeps that scale. + fallback_reason = ( + f"no usable timing seed{skipped_note}" if skipped else "no timing seed" + ) return {name: DEFAULT_SECONDS for name in names}, ( - f"equal weights at the run-41530429335 rate ({DEFAULT_SECONDS:.0f}s/test; no timing seed)") + f"equal weights at the run-41530429335 rate ({DEFAULT_SECONDS:.0f}s/test; " + f"{fallback_reason})") median = statistics.median(measured.values()) weights = {name: measured.get(name, median) for name in names} - return weights, f"seed: {len(measured)} measured, median {median:.1f}s for the rest" + return weights, ( + f"seed: {len(measured)} measured, median {median:.1f}s for the rest" + f"{skipped_note}") def lpt_pack(weights: dict[str, float], shards: int) -> list[list[str]]: diff --git a/pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py b/pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py new file mode 100644 index 0000000000..5624bb28a1 --- /dev/null +++ b/pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Regression tests for the measured-time e2e shard packer (#6822). + +Run: python3 -m unittest discover -s pkgs/mcpx/scripts/tests -p 'test_e2e_shard_packer.py' -v +""" + +import importlib.util +import json +import math +import os +import subprocess +import sys +import tempfile +import unittest + + +TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) +MCPX_DIR = os.path.abspath(os.path.join(TESTS_DIR, "..", "..")) +REPO_ROOT = os.path.abspath(os.path.join(MCPX_DIR, "..", "..")) +PACKER_PATH = os.path.join(MCPX_DIR, "scripts", "ci", "e2e-shard-packer.py") +TIMINGS_PATH = os.path.join(MCPX_DIR, "scripts", "ci", "e2e-timings.json") + +SPEC = importlib.util.spec_from_file_location("e2e_shard_packer", PACKER_PATH) +packer = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(packer) + + +class WeightLoadingTest(unittest.TestCase): + def load_seed(self, value): + with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as seed: + json.dump(value, seed) + seed.flush() + return packer.load_weights(seed.name, ["TestA", "TestB"]) + + def test_non_object_tests_field_falls_back_with_named_reason(self): + for invalid_tests in ([ ["TestA", 10] ], "TestA=10"): + with self.subTest(tests=invalid_tests): + weights, note = self.load_seed({"tests": invalid_tests}) + self.assertEqual(weights, {"TestA": 3.0, "TestB": 3.0}) + self.assertIn("'tests'", note) + self.assertIn("expected object", note) + self.assertIn("ignoring seed", note) + + def test_non_finite_and_boolean_weights_are_skipped_by_name(self): + value = { + "tests": { + "TestLow": 10, + "TestHigh": 30, + "TestInfinity": float("inf"), + "TestNegativeInfinity": float("-inf"), + "TestNaN": float("nan"), + "TestZero": 0, + "TestNegative": -1, + "TestTrue": True, + "TestFalse": False, + } + } + names = [ + "TestLow", "TestHigh", "TestInfinity", "TestNegativeInfinity", + "TestNaN", "TestZero", "TestNegative", "TestTrue", "TestFalse", + ] + with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as seed: + json.dump(value, seed) + seed.flush() + weights, note = packer.load_weights(seed.name, names) + + invalid_names = [ + "TestInfinity", "TestNegativeInfinity", "TestNaN", "TestZero", + "TestNegative", "TestTrue", "TestFalse" + ] + for name in invalid_names: + with self.subTest(name=name): + self.assertEqual(weights[name], 20.0) + self.assertIn(name, note) + self.assertEqual(weights["TestLow"], 10.0) + self.assertEqual(weights["TestHigh"], 30.0) + self.assertTrue(all(math.isfinite(weight) and weight > 0 for weight in weights.values())) + + # Every accepted weight remains usable by median/packing arithmetic. + shards, buckets = packer.pack(names, weights, target_seconds=40, max_shards=6) + self.assertEqual(shards, 5) + self.assertEqual(sorted(name for bucket in buckets for name in bucket), sorted(names)) + + def test_all_invalid_seed_falls_back_and_names_rejected_entries(self): + names = ["TestTrue", "TestZero"] + with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as seed: + json.dump({"tests": {"TestTrue": True, "TestZero": 0}}, seed) + seed.flush() + weights, note = packer.load_weights(seed.name, names) + + self.assertEqual(weights, {name: 3.0 for name in names}) + self.assertIn("no usable timing seed", note) + self.assertIn("TestTrue", note) + self.assertIn("TestZero", note) + + def test_well_formed_seed_preserves_weights_and_lpt_assignment(self): + with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as seed: + json.dump({"tests": {"TestA": 12, "TestB": 8}}, seed) + seed.flush() + weights, note = packer.load_weights(seed.name, ["TestA", "TestB", "TestC"]) + + self.assertEqual(weights, {"TestA": 12.0, "TestB": 8.0, "TestC": 10.0}) + self.assertEqual(note, "seed: 2 measured, median 10.0s for the rest") + self.assertEqual( + packer.pack(["TestA", "TestB", "TestC"], weights, 15, 3), + (2, [["TestA"], ["TestB", "TestC"]]), + ) + + def test_no_seed_fallback_preserves_default_matrix_and_note(self): + weights, note = packer.load_weights(None, ["TestA", "TestB", "TestC"]) + self.assertEqual(weights, {"TestA": 3.0, "TestB": 3.0, "TestC": 3.0}) + self.assertEqual( + note, + "equal weights at the run-41530429335 rate (3s/test; no timing seed)", + ) + self.assertEqual( + packer.pack(["TestA", "TestB", "TestC"], weights, 4, 6), + (3, [["TestA"], ["TestB"], ["TestC"]]), + ) + + def test_committed_timing_seed_cli_emits_a_finite_matrix(self): + with tempfile.NamedTemporaryFile(mode="w+", suffix=".out") as output: + result = subprocess.run( + [ + sys.executable, PACKER_PATH, + "--tests-dir", os.path.join(MCPX_DIR, "internal", "e2e"), + "--timings", TIMINGS_PATH, + "--target-seconds", "170", + "--max-shards", "6", + "--github-output", output.name, + ], + cwd=REPO_ROOT, + capture_output=True, + text=True, + timeout=60, + ) + self.assertEqual(result.returncode, 0, result.stderr) + output.seek(0) + values = dict(line.rstrip("\n").split("=", 1) for line in output) + + matrix = json.loads(values["matrix"]) + include = matrix["include"] + names = packer.discover(os.path.join(MCPX_DIR, "internal", "e2e")) + assigned = [name for shard in include for name in shard["run"].split("|")] + self.assertTrue(include) + self.assertEqual(sorted(assigned), names) + self.assertEqual(int(values["total"]), len(names)) + self.assertEqual(int(values["shards"]), len(include)) + for shard in include: + self.assertTrue(math.isfinite(shard["seconds"])) + self.assertTrue(math.isfinite(shard["longest"])) + + +if __name__ == "__main__": + unittest.main() From ca91de10e4188cd3a5ae47c250ec5529eefcdfe6 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Mon, 9 Nov 2026 21:16:11 -0600 Subject: [PATCH 2/2] test(mcpx): close temp files before reopening their paths in shard-packer tests (#8096) --- .../scripts/tests/test_e2e_shard_packer.py | 78 +++++++++++-------- 1 file changed, 45 insertions(+), 33 deletions(-) diff --git a/pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py b/pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py index 5624bb28a1..6719d4aa6d 100644 --- a/pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py +++ b/pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py @@ -26,11 +26,20 @@ class WeightLoadingTest(unittest.TestCase): - def load_seed(self, value): - with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as seed: + def write_seed(self, value): + # Write-close-read: close the temp file before anything reopens + # its path (an open NamedTemporaryFile cannot be reopened on + # Windows). + with tempfile.NamedTemporaryFile( + mode="w", suffix=".json", delete=False + ) as seed: json.dump(value, seed) - seed.flush() - return packer.load_weights(seed.name, ["TestA", "TestB"]) + path = seed.name + self.addCleanup(os.unlink, path) + return path + + def load_seed(self, value): + return packer.load_weights(self.write_seed(value), ["TestA", "TestB"]) def test_non_object_tests_field_falls_back_with_named_reason(self): for invalid_tests in ([ ["TestA", 10] ], "TestA=10"): @@ -59,10 +68,7 @@ def test_non_finite_and_boolean_weights_are_skipped_by_name(self): "TestLow", "TestHigh", "TestInfinity", "TestNegativeInfinity", "TestNaN", "TestZero", "TestNegative", "TestTrue", "TestFalse", ] - with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as seed: - json.dump(value, seed) - seed.flush() - weights, note = packer.load_weights(seed.name, names) + weights, note = packer.load_weights(self.write_seed(value), names) invalid_names = [ "TestInfinity", "TestNegativeInfinity", "TestNaN", "TestZero", @@ -83,10 +89,9 @@ def test_non_finite_and_boolean_weights_are_skipped_by_name(self): def test_all_invalid_seed_falls_back_and_names_rejected_entries(self): names = ["TestTrue", "TestZero"] - with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as seed: - json.dump({"tests": {"TestTrue": True, "TestZero": 0}}, seed) - seed.flush() - weights, note = packer.load_weights(seed.name, names) + weights, note = packer.load_weights( + self.write_seed({"tests": {"TestTrue": True, "TestZero": 0}}), names + ) self.assertEqual(weights, {name: 3.0 for name in names}) self.assertIn("no usable timing seed", note) @@ -94,10 +99,10 @@ def test_all_invalid_seed_falls_back_and_names_rejected_entries(self): self.assertIn("TestZero", note) def test_well_formed_seed_preserves_weights_and_lpt_assignment(self): - with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as seed: - json.dump({"tests": {"TestA": 12, "TestB": 8}}, seed) - seed.flush() - weights, note = packer.load_weights(seed.name, ["TestA", "TestB", "TestC"]) + weights, note = packer.load_weights( + self.write_seed({"tests": {"TestA": 12, "TestB": 8}}), + ["TestA", "TestB", "TestC"], + ) self.assertEqual(weights, {"TestA": 12.0, "TestB": 8.0, "TestC": 10.0}) self.assertEqual(note, "seed: 2 measured, median 10.0s for the rest") @@ -119,23 +124,30 @@ def test_no_seed_fallback_preserves_default_matrix_and_note(self): ) def test_committed_timing_seed_cli_emits_a_finite_matrix(self): - with tempfile.NamedTemporaryFile(mode="w+", suffix=".out") as output: - result = subprocess.run( - [ - sys.executable, PACKER_PATH, - "--tests-dir", os.path.join(MCPX_DIR, "internal", "e2e"), - "--timings", TIMINGS_PATH, - "--target-seconds", "170", - "--max-shards", "6", - "--github-output", output.name, - ], - cwd=REPO_ROOT, - capture_output=True, - text=True, - timeout=60, - ) - self.assertEqual(result.returncode, 0, result.stderr) - output.seek(0) + # Write-close-read: close the output file before the subprocess + # opens it by path (an open NamedTemporaryFile cannot be reopened + # on Windows). + with tempfile.NamedTemporaryFile( + mode="w", suffix=".out", delete=False + ) as output: + output_path = output.name + self.addCleanup(os.unlink, output_path) + result = subprocess.run( + [ + sys.executable, PACKER_PATH, + "--tests-dir", os.path.join(MCPX_DIR, "internal", "e2e"), + "--timings", TIMINGS_PATH, + "--target-seconds", "170", + "--max-shards", "6", + "--github-output", output_path, + ], + cwd=REPO_ROOT, + capture_output=True, + text=True, + timeout=60, + ) + self.assertEqual(result.returncode, 0, result.stderr) + with open(output_path) as output: values = dict(line.rstrip("\n").split("=", 1) for line in output) matrix = json.loads(values["matrix"])