diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f2874306..7f6d424e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -290,21 +290,49 @@ jobs: marker_expression="not slow and not gpu and not mps and not mlx and not network and not download and not remote and not operator_ui" # Suppress the configured terminal report, retaining strictness and source scope. pytest_addopts="--strict-config --strict-markers --cov=obliteratus" - # Keep concurrent pytest/subprocess coverage and temp roots isolated until both finish. - rm -f test-results/.coverage test-results/.coverage.gloo test-results/.coverage.core - COVERAGE_FILE=test-results/.coverage.gloo "$TEST_ENV/bin/python" -m pytest \ - "${selected_tests[@]}" \ - -o "addopts=$pytest_addopts" \ - -m "$marker_expression and gloo" \ - --cov=app \ - --cov-branch \ - --cov-fail-under=0 \ - --cov-config=pyproject.toml \ - --cov-report= \ - --junitxml=test-results/junit-pr-core-gloo.xml \ - --basetemp="$RUNNER_TEMP/pytest-pr-core-gloo" \ - > test-results/pytest-pr-core-gloo.log 2>&1 & - gloo_pid=$! + "$TEST_ENV/bin/python" scripts/shard_pr_tests.py + mapfile -t gloo0_tests < test-results/selected-gloo-0.txt + mapfile -t gloo1_tests < test-results/selected-gloo-1.txt + # Isolate concurrent coverage and temp roots until all three finish. + rm -f test-results/.coverage test-results/.coverage.gloo0 test-results/.coverage.gloo1 test-results/.coverage.core + ( + if [ "${#gloo0_tests[@]}" -eq 0 ]; then + echo "Empty Gloo shard 0; pytest not invoked (exit code 5)" + printf '\n' > test-results/junit-pr-core-gloo-0.xml + exit 5 + fi + COVERAGE_FILE=test-results/.coverage.gloo0 "$TEST_ENV/bin/python" -m pytest \ + "${gloo0_tests[@]}" \ + -o "addopts=$pytest_addopts" \ + -m "$marker_expression and gloo" \ + --cov=app \ + --cov-branch \ + --cov-fail-under=0 \ + --cov-config=pyproject.toml \ + --cov-report= \ + --junitxml=test-results/junit-pr-core-gloo-0.xml \ + --basetemp="$RUNNER_TEMP/pytest-pr-core-gloo0" + ) > test-results/pytest-pr-core-gloo0.log 2>&1 & + gloo0_pid=$! + ( + if [ "${#gloo1_tests[@]}" -eq 0 ]; then + echo "Empty Gloo shard 1; pytest not invoked (exit code 5)" + printf '\n' > test-results/junit-pr-core-gloo-1.xml + exit 5 + fi + COVERAGE_FILE=test-results/.coverage.gloo1 "$TEST_ENV/bin/python" -m pytest \ + "${gloo1_tests[@]}" \ + -o "addopts=$pytest_addopts" \ + -m "$marker_expression and gloo" \ + --cov=app \ + --cov-branch \ + --cov-fail-under=0 \ + --cov-config=pyproject.toml \ + --cov-report= \ + --junitxml=test-results/junit-pr-core-gloo-1.xml \ + --basetemp="$RUNNER_TEMP/pytest-pr-core-gloo1" + ) > test-results/pytest-pr-core-gloo1.log 2>&1 & + gloo1_pid=$! COVERAGE_FILE=test-results/.coverage.core "$TEST_ENV/bin/python" -m pytest \ "${selected_tests[@]}" \ -o "addopts=$pytest_addopts" \ @@ -315,36 +343,40 @@ jobs: --cov-config=pyproject.toml \ --cov-report= \ --junitxml=test-results/junit-pr-core.xml \ - --basetemp="$RUNNER_TEMP/pytest-pr-core" \ - > test-results/pytest-pr-core.log 2>&1 & + --basetemp="$RUNNER_TEMP/pytest-pr-core-core" \ + > test-results/pytest-pr-core-core.log 2>&1 & core_pid=$! # Conditional waits preserve each status under GitHub's bash -e shell. - gloo_status=0 - wait "$gloo_pid" || gloo_status=$? + gloo0_status=0 + wait "$gloo0_pid" || gloo0_status=$? + gloo1_status=0 + wait "$gloo1_pid" || gloo1_status=$? core_status=0 wait "$core_pid" || core_status=$? - echo "Gloo pytest exit code: $gloo_status" - cat test-results/pytest-pr-core-gloo.log + echo "Gloo shard 0 pytest exit code: $gloo0_status" + cat test-results/pytest-pr-core-gloo0.log + echo "Gloo shard 1 pytest exit code: $gloo1_status" + cat test-results/pytest-pr-core-gloo1.log echo "Core pytest exit code: $core_status" - cat test-results/pytest-pr-core.log - if (( (gloo_status != 0 && gloo_status != 5) || (core_status != 0 && core_status != 5) )); then + cat test-results/pytest-pr-core-core.log + if (( (gloo0_status != 0 && gloo0_status != 5) || (gloo1_status != 0 && gloo1_status != 5) || (core_status != 0 && core_status != 5) )); then exit 1 fi - if (( gloo_status == 5 && core_status == 5 )); then - echo "Neither pytest process ran any tests" + if (( gloo0_status == 5 && gloo1_status == 5 && core_status == 5 )); then + echo "No pytest process ran any tests" exit 1 fi # An empty partition may not write data. Combine only existing files. coverage_files=() - for coverage_file in test-results/.coverage.gloo test-results/.coverage.core; do + for coverage_file in test-results/.coverage.gloo0 test-results/.coverage.gloo1 test-results/.coverage.core; do if [ -f "$coverage_file" ]; then coverage_files+=("$coverage_file") fi done if [ "${#coverage_files[@]}" -eq 0 ]; then - echo "Neither pytest process produced coverage data" + echo "No pytest process produced coverage data" exit 1 fi export COVERAGE_FILE=test-results/.coverage diff --git a/ci/gloo-test-durations.json b/ci/gloo-test-durations.json new file mode 100644 index 00000000..cfb74a0c --- /dev/null +++ b/ci/gloo-test-durations.json @@ -0,0 +1,10 @@ +{ + "schema_version": 1, + "source": "Mean JUnit per-file sums from CI runs 37669900420 and 37670680272 (seconds: 123/159, 61/80, 59/83; model mean rounded to 71)", + "default_seconds": 80, + "files": { + "tests/test_distributed_gloo.py": 141, + "tests/test_distributed_model_gloo.py": 71, + "tests/test_distributed_probe_gloo.py": 71 + } +} diff --git a/ci/pr-test-policy.json b/ci/pr-test-policy.json index edcff09e..c536330c 100644 --- a/ci/pr-test-policy.json +++ b/ci/pr-test-policy.json @@ -18,6 +18,7 @@ "scripts/generate_checkpoint_fixtures.py", "scripts/jetson_*.py", "scripts/select_pr_tests.py", + "scripts/shard_pr_tests.py", "scripts/setup_jetson.py", "pyproject.toml", "requirements.txt", @@ -35,6 +36,7 @@ "tests/test_conditional_gate_scripts.py", "tests/test_jetson_support_tooling.py", "tests/test_pr_test_selection.py", + "tests/test_shard_pr_tests.py", "tests/test_quality_policy.py", "tests/test_quality_gate_scripts.py", "tests/test_supply_chain_policy.py", diff --git a/ci/test-risk-map.json b/ci/test-risk-map.json index d526162c..2ead338d 100644 --- a/ci/test-risk-map.json +++ b/ci/test-risk-map.json @@ -6,10 +6,14 @@ "app.py", "obliteratus", "scripts/check_llama_tp_hardware_evidence.py", - "scripts/run_readonly_mount_namespace.py" + "scripts/run_readonly_mount_namespace.py", + "scripts/shard_pr_tests.py" ], "coverage_roots": [ "obliteratus" + ], + "data_files": [ + "ci/gloo-test-durations.json" ] }, "contract_surfaces": [ @@ -608,6 +612,23 @@ "tests/test_mcp_policy.py", "tests/test_mcp_server.py" ] + }, + { + "id": "pr-gloo-sharding", + "owner": "CI maintainers", + "description": "Deterministic duration-balanced partitioning of every selected PR test file", + "contract_types": [ + "orchestration", + "reproducibility" + ], + "paths": [ + "scripts/shard_pr_tests.py", + "ci/gloo-test-durations.json" + ], + "required_tests": [ + "tests/test_shard_pr_tests.py", + "tests/test_ci_policy.py" + ] } ], "modules": [ diff --git a/scripts/check_test_risk_map.py b/scripts/check_test_risk_map.py index c7123007..764567e1 100644 --- a/scripts/check_test_risk_map.py +++ b/scripts/check_test_risk_map.py @@ -114,6 +114,19 @@ def _inventory_sources( ) else: errors.append(f"source_inventory root does not exist: {value}") + # Policy data can own focused tests without entering Python coverage scope. + data_files = inventory.get("data_files", []) + if not isinstance(data_files, list): + errors.append("source_inventory data_files must be a list") + else: + for value in data_files: + if (not isinstance(value, str) or not value or Path(value).is_absolute() + or ".." in Path(value).parts or not (project_root / value).is_file()): + errors.append(f"source_inventory has invalid data file: {value!r}") + elif value in sources: + errors.append(f"source_inventory has duplicate data file: {value}") + else: + sources.add(value) return sources diff --git a/scripts/shard_pr_tests.py b/scripts/shard_pr_tests.py new file mode 100644 index 00000000..871e1e83 --- /dev/null +++ b/scripts/shard_pr_tests.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Split selected files into two deterministic, duration-balanced Gloo shards. + +Every selected file is assigned once, even without a duration or Gloo marker. +Unlisted files containing ``pytest.mark.gloo`` use the table's default_seconds; +other unlisted files have zero weight. Marker detection affects balance only. +Paths must be canonical relative files inside tests/ (symlink escapes rejected). +Duplicate input paths are deduplicated. Empty input produces two empty files. +""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path + + +def load_durations(path: Path) -> tuple[float, dict[str, float]]: + table = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(table, dict) or table.get("schema_version") != 1: + raise ValueError("duration table schema_version must be 1") + if not isinstance(table.get("source"), str) or not table["source"].strip(): + raise ValueError("duration table requires a source") + default = table.get("default_seconds") + files = table.get("files") + if not isinstance(files, dict): + raise ValueError("duration table files must be an object") + for seconds in [default, *files.values()]: + if (isinstance(seconds, bool) or not isinstance(seconds, (int, float)) + or not math.isfinite(seconds) or seconds < 0): + raise ValueError("duration weights must be finite nonnegative seconds") + return default, files + + +def shard_tests( + selected: list[str], default_seconds: float, durations: dict[str, float], + *, root: Path, +) -> tuple[list[str], list[str]]: + weighted = [] + for name in sorted(set(selected)): + path = Path(name) + if (not name.startswith("tests/") or path.as_posix() != name + or ".." in path.parts or not (root / path).is_file() + or not (root / path).resolve().is_relative_to((root / "tests").resolve())): + raise ValueError(f"selected path must be a file inside tests/: {name!r}") + weight = durations.get(name) + if weight is None: + weight = default_seconds if "pytest.mark.gloo" in ( + root / path + ).read_text(encoding="utf-8") else 0 + weighted.append((name, weight)) + shards: tuple[list[str], list[str]] = ([], []) + loads = [0.0, 0.0] + for name, weight in sorted(weighted, key=lambda item: (-item[1], item[0])): + side = 0 if loads[0] <= loads[1] else 1 + shards[side].append(name) + loads[side] += weight + return shards + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--selected", type=Path, default=Path("test-results/selected-tests.txt")) + parser.add_argument("--durations", type=Path, default=Path("ci/gloo-test-durations.json")) + parser.add_argument("--output-dir", type=Path, default=Path("test-results")) + args = parser.parse_args() + try: + default, durations = load_durations(args.durations) + shards = shard_tests( + args.selected.read_text(encoding="utf-8").splitlines(), + default, durations, root=Path.cwd(), + ) + args.output_dir.mkdir(parents=True, exist_ok=True) + for side, paths in enumerate(shards): + (args.output_dir / f"selected-gloo-{side}.txt").write_text( + "".join(f"{path}\n" for path in paths), encoding="utf-8", + ) + except (OSError, ValueError) as exc: + print(f"PR test sharding failed: {exc}") + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_ci_policy.py b/tests/test_ci_policy.py index d4d31783..f3ad341a 100644 --- a/tests/test_ci_policy.py +++ b/tests/test_ci_policy.py @@ -174,32 +174,37 @@ def test_pr_core_runs_marker_partitions_and_combines_before_changed_line_check() run = pr_core.split(" - name: Select and run core and risk-mapped tests\n", 1)[1].split( " - name: Enforce pull-request changed-line floor\n", 1, )[0] - assert run.count('"$TEST_ENV/bin/python" -m pytest') == 2 - assert run.count('"${selected_tests[@]}" \\') == 2 + assert run.count('"$TEST_ENV/bin/python" -m pytest') == 3 + assert run.count('"${selected_tests[@]}" \\') == 1 + assert run.index('scripts/shard_pr_tests.py') < run.index('-m pytest') for partition, junit, log in ( - ("gloo", "junit-pr-core-gloo.xml", "pytest-pr-core-gloo.log"), - ("core", "junit-pr-core.xml", "pytest-pr-core.log"), + ("gloo0", "junit-pr-core-gloo-0.xml", "pytest-pr-core-gloo0.log"), + ("gloo1", "junit-pr-core-gloo-1.xml", "pytest-pr-core-gloo1.log"), + ("core", "junit-pr-core.xml", "pytest-pr-core-core.log"), ): assert f'COVERAGE_FILE=test-results/.coverage.{partition} ' in run assert f'--junitxml=test-results/{junit}' in run assert f'> test-results/{log} 2>&1 &' in run assert f'{partition}_pid=$!' in run assert f'wait "${partition}_pid" || {partition}_status=$?' in run - assert run.index(f'{partition}_pid=$!') < run.index('wait "$gloo_pid"') + assert run.index(f'{partition}_pid=$!') < run.index('wait "$gloo0_pid"') assert run.index(f'wait "${partition}_pid"') < run.index('-m coverage combine') - assert '-m "$marker_expression and gloo"' in run + for side in (0, 1): + assert f'"${{gloo{side}_tests[@]}}" \\' in run + assert f'mapfile -t gloo{side}_tests < test-results/selected-gloo-{side}.txt' in run + assert run.count('-m "$marker_expression and gloo"') == 2 assert '-m "$marker_expression and not gloo"' in run assert ( 'marker_expression="not slow and not gpu and not mps and not mlx and not network ' 'and not download and not remote and not operator_ui"' ) in run - assert run.count('--cov=app') == 2 - assert run.count('--cov-branch') == 2 - assert run.count('--cov-fail-under=0') == 2 - assert run.count('--cov-report= \\') == 2 - assert run.count('--cov-config=pyproject.toml') == 2 + assert run.count('--cov=app') == 3 + assert run.count('--cov-branch') == 3 + assert run.count('--cov-fail-under=0') == 3 + assert run.count('--cov-report= \\') == 3 + assert run.count('--cov-config=pyproject.toml') == 3 assert 'pytest_addopts="--strict-config --strict-markers --cov=obliteratus"' in run - assert run.count('-o "addopts=$pytest_addopts"') == 2 + assert run.count('-o "addopts=$pytest_addopts"') == 3 assert 'export COVERAGE_FILE=test-results/.coverage' in run assert '-m coverage combine --rcfile=pyproject.toml "${coverage_files[@]}"' in run assert run.index('-m coverage combine') < run.index('-m coverage xml') < run.index( @@ -234,6 +239,24 @@ def test_gloo_marker_is_registered_and_marks_real_cpu_worker_files(): ).read_text() +def test_gloo_durations_cover_exactly_the_marked_test_files(): + # AST detects real marker expressions, excluding quoted fixtures/comments. + import ast + + marked = { + path.relative_to(ROOT).as_posix() + for path in (ROOT / "tests").rglob("test_*.py") + if any( + isinstance(node, ast.Attribute) and ast.unparse(node) == "pytest.mark.gloo" + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))) + ) + } + table = json.loads((ROOT / "ci/gloo-test-durations.json").read_text()) + assert set(table["files"]) == marked + for name in table["files"]: + assert (ROOT / name).is_file() + + def test_arm64_preflight_proves_portability_without_claiming_jetson_cuda(): workflow = WORKFLOW.read_text(encoding="utf-8") arm = workflow.split(" arm64-preflight:\n", maxsplit=1)[1].split( @@ -352,13 +375,25 @@ args = sys.argv[1:] results = Path("test-results") if args[0] == "scripts/select_pr_tests.py": assert args == ["scripts/select_pr_tests.py", "--base-ref", "exact-base"] - print("tests/test_gloo.py\ntests/test_core.py") + print("tests/test_gloo.py") + if os.environ.get("EMPTY_SHARD") != "1": + print("tests/test_gloo_other.py\ntests/test_core.py") +elif args[0] == "scripts/shard_pr_tests.py": + # Run the real stdlib sharder against fixture files, with the same CLI. + import runpy + sys.argv = args + runpy.run_path(os.environ["SHARDER"], run_name="__main__") elif args[:2] == ["-m", "pytest"]: - side = "core" if args[args.index("-m", 2) + 1].endswith("not gloo") else "gloo" - peer = "gloo" if side == "core" else "core" + coverage_file = os.environ["COVERAGE_FILE"] + side = coverage_file.rsplit(".", 1)[1] + paths = args[2:args.index("-o")] + assert paths and all(path.startswith("tests/") for path in paths), args + expected_marker = "not gloo" if side == "core" else "gloo" + assert args[args.index("-m", 2) + 1].endswith("and " + expected_marker) + peers = {"gloo0", "core"} if os.environ.get("EMPTY_SHARD") == "1" else {"gloo0", "gloo1", "core"} (results / (side + ".started")).touch() deadline = time.monotonic() + 5 - while not (results / (peer + ".started")).exists(): + while not all((results / (peer + ".started")).exists() for peer in peers): if time.monotonic() > deadline: print("pytest partitions did not start concurrently") sys.exit(97) @@ -392,7 +427,9 @@ else: ''' -def _run_pr_core_step(tmp_path, gloo_status, core_status, *, no_coverage=False): +def _run_pr_core_step( + tmp_path, gloo0_status, gloo1_status, core_status, *, no_coverage=False, empty_shard=False, +): workflow = yaml.safe_load((ROOT / ".github/workflows/ci.yml").read_text()) step = next( step for step in workflow["jobs"]["pr-core"]["steps"] @@ -402,17 +439,30 @@ def _run_pr_core_step(tmp_path, gloo_status, core_status, *, no_coverage=False): executable.parent.mkdir(parents=True) executable.write_text(f"#!{sys.executable}\n" + FAKE_PYTHON) executable.chmod(0o755) + tests = tmp_path / "tests" + tests.mkdir() + for name in ("test_gloo.py", "test_gloo_other.py", "test_core.py"): + (tests / name).write_text("pytestmark = pytest.mark.gloo\n" if "gloo" in name else "") + ci = tmp_path / "ci" + ci.mkdir() + (ci / "gloo-test-durations.json").write_text(json.dumps({ + "schema_version": 1, "source": "fixture", "default_seconds": 80, + "files": {"tests/test_gloo.py": 141, "tests/test_gloo_other.py": 71}, + })) results = tmp_path / "test-results" results.mkdir() # Old coverage must never fill in for a partition that collected nothing. - for name in (".coverage", ".coverage.gloo", ".coverage.core"): + for name in (".coverage", ".coverage.gloo0", ".coverage.gloo1", ".coverage.core"): (results / name).write_text("stale data") return subprocess.run( ["bash", "-e", "-c", step["run"]], cwd=tmp_path, env={ **os.environ, "TEST_ENV": str(executable.parents[1]), - "COVERAGE_BASE": "exact-base", "GLOO_STATUS": str(gloo_status), - "CORE_STATUS": str(core_status), "NO_COVERAGE": "1" if no_coverage else "0", + "SHARDER": str(ROOT / "scripts/shard_pr_tests.py"), + "COVERAGE_BASE": "exact-base", "GLOO0_STATUS": str(gloo0_status), + "GLOO1_STATUS": str(gloo1_status), "CORE_STATUS": str(core_status), + "NO_COVERAGE": "1" if no_coverage else "0", + "EMPTY_SHARD": "1" if empty_shard else "0", "RUNNER_TEMP": str(tmp_path / "runner-temp"), }, capture_output=True, text=True, timeout=20, @@ -420,46 +470,55 @@ def _run_pr_core_step(tmp_path, gloo_status, core_status, *, no_coverage=False): @pytest.mark.parametrize( - "gloo_status,core_status,expected", - [(0, 0, 0), (0, 5, 0), (5, 0, 0), (5, 5, 1), (1, 0, 1), (0, 1, 1), - (2, 5, 1), (5, 3, 1)], + "statuses,expected", + [((0, 0, 0), 0), ((5, 0, 0), 0), ((0, 5, 0), 0), ((0, 0, 5), 0), + ((5, 5, 0), 0), ((5, 0, 5), 0), ((0, 5, 5), 0), ((5, 5, 5), 1), + ((1, 0, 0), 1), ((0, 2, 0), 1), ((0, 0, 3), 1), + ((2, 5, 5), 1), ((5, 3, 5), 1), ((5, 5, 4), 1)], ) -def test_parallel_pr_step_status_matrix(tmp_path, gloo_status, core_status, expected): - process = _run_pr_core_step(tmp_path, gloo_status, core_status) +def test_parallel_pr_step_status_matrix(tmp_path, statuses, expected): + process = _run_pr_core_step(tmp_path, *statuses) assert process.returncode == expected, process.stdout + process.stderr - assert f"Gloo pytest exit code: {gloo_status}" in process.stdout - assert f"Core pytest exit code: {core_status}" in process.stdout - assert "gloo pytest output" in process.stdout - assert "core pytest output" in process.stdout results = tmp_path / "test-results" - for side, junit, log in ( - ("gloo", "junit-pr-core-gloo.xml", "pytest-pr-core-gloo.log"), - ("core", "junit-pr-core.xml", "pytest-pr-core.log"), + basetemps = set() + selected = (results / "selected-tests.txt").read_text().splitlines() + assigned = [] + for side, status, label, junit in zip( + ("gloo0", "gloo1", "core"), statuses, ("Gloo shard 0", "Gloo shard 1", "Core"), + ("junit-pr-core-gloo-0.xml", "junit-pr-core-gloo-1.xml", "junit-pr-core.xml"), ): + assert f"{label} pytest exit code: {status}" in process.stdout + assert f"{side} pytest output" in process.stdout invocation = json.loads((results / (side + ".json")).read_text()) assert invocation["coverage_file"] == f"test-results/.coverage.{side}" - basetemps = [arg for arg in invocation["args"] if arg.startswith("--basetemp=")] - assert len(basetemps) == 1 - basetemp = basetemps[0].removeprefix("--basetemp=") - expected_basetemp = "pytest-pr-core-gloo" if side == "gloo" else "pytest-pr-core" - assert basetemp == str(tmp_path / "runner-temp" / expected_basetemp) - assert invocation["args"][2:4] == ["tests/test_gloo.py", "tests/test_core.py"] - assert "--cov=app" in invocation["args"] - assert "--cov-branch" in invocation["args"] - assert "--cov-fail-under=0" in invocation["args"] - assert "--cov-report=" in invocation["args"] - assert "--cov-config=pyproject.toml" in invocation["args"] - assert invocation["args"][invocation["args"].index("-o") + 1] == ( + args = invocation["args"] + temps = [arg for arg in args if arg.startswith("--basetemp=")] + assert temps == [f"--basetemp={tmp_path / 'runner-temp' / ('pytest-pr-core-' + side)}"] + basetemps.update(temps) + paths = args[2:args.index("-o")] + if side == "core": + assert paths == selected + else: + assert paths == (results / f"selected-gloo-{side[-1]}.txt").read_text().splitlines() + assigned.extend(paths) + assert "--cov=app" in args + assert "--cov-branch" in args + assert "--cov-fail-under=0" in args + assert "--cov-report=" in args + assert "--cov-config=pyproject.toml" in args + assert args[args.index("-o") + 1] == ( "addopts=--strict-config --strict-markers --cov=obliteratus" ) assert (results / junit).is_file() - assert (results / log).read_text().strip() == f"{side} pytest output" + assert (results / f"pytest-pr-core-{side}.log").read_text().strip() == f"{side} pytest output" + assert len(basetemps) == 3 + assert sorted(assigned) == sorted(selected) if expected == 0: calls = [json.loads(line) for line in (results / "coverage-calls.jsonl").read_text().splitlines()] assert [call[2] for call in calls] == ["combine", "xml", "json"] assert calls[0][4:] == [ f"test-results/.coverage.{side}" - for side, status in (("gloo", gloo_status), ("core", core_status)) + for side, status in zip(("gloo0", "gloo1", "core"), statuses) if status != 5 ] assert (results / "coverage-pr-core.xml").is_file() @@ -468,8 +527,28 @@ def test_parallel_pr_step_status_matrix(tmp_path, gloo_status, core_status, expe assert not (results / "coverage-calls.jsonl").exists() +@pytest.mark.parametrize("core_status,expected", [(0, 0), (5, 1)]) +def test_empty_gloo_shard_skips_pytest_and_preserves_status(tmp_path, core_status, expected): + process = _run_pr_core_step(tmp_path, 5, 1, core_status, empty_shard=True) + assert process.returncode == expected, process.stdout + process.stderr + results = tmp_path / "test-results" + assert (results / "selected-gloo-1.txt").read_bytes() == b"" + assert "Empty Gloo shard 1; pytest not invoked (exit code 5)" in process.stdout + assert "Gloo shard 1 pytest exit code: 5" in process.stdout + assert not (results / "gloo1.started").exists() + assert not (results / "gloo1.json").exists() + assert (results / "junit-pr-core-gloo-1.xml").is_file() + assert "Empty Gloo shard 1" in (results / "pytest-pr-core-gloo1.log").read_text() + if expected == 0: + calls = [json.loads(line) for line in (results / "coverage-calls.jsonl").read_text().splitlines()] + assert calls[0][4:] == ["test-results/.coverage.core"] + else: + assert "No pytest process ran any tests" in process.stdout + assert not (results / "coverage-calls.jsonl").exists() + + def test_pr_step_fails_without_coverage_instead_of_using_stale_data(tmp_path): - process = _run_pr_core_step(tmp_path, 0, 5, no_coverage=True) + process = _run_pr_core_step(tmp_path, 0, 5, 5, no_coverage=True) assert process.returncode == 1 - assert "Neither pytest process produced coverage data" in process.stdout + assert "No pytest process produced coverage data" in process.stdout assert not (tmp_path / "test-results" / "coverage-calls.jsonl").exists() diff --git a/tests/test_shard_pr_tests.py b/tests/test_shard_pr_tests.py new file mode 100644 index 00000000..e66b5679 --- /dev/null +++ b/tests/test_shard_pr_tests.py @@ -0,0 +1,151 @@ +"""Contracts for duration balancing independent of the Gloo duration inventory.""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys + +import pytest + +from scripts import select_pr_tests, shard_pr_tests + + +ROOT = Path(__file__).parents[1] + + +def _files(root, names, *, marked=()): + for name in names: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("pytestmark = pytest.mark.gloo\n" if name in marked else "", encoding="utf-8") + + +def _table(path, **overrides): + table = {"schema_version": 1, "source": "fixture", "default_seconds": 80, "files": {}} + table.update(overrides) + path.write_text(json.dumps(table), encoding="utf-8") + return path + + +def test_measured_lpt_balances_known_files_instead_of_alphabetical_halves(): + default, durations = shard_pr_tests.load_durations(ROOT / "ci/gloo-test-durations.json") + assert default == 80 + assert list(durations.values()) == [141, 71, 71] + shards = shard_pr_tests.shard_tests(list(durations), default, durations, root=ROOT) + assert shards == ( + ["tests/test_distributed_gloo.py"], + ["tests/test_distributed_model_gloo.py", "tests/test_distributed_probe_gloo.py"], + ) + assert [sum(durations[name] for name in shard) for shard in shards] == [141, 142] + + +def test_unlisted_marked_files_get_default_but_all_files_are_assigned_once(tmp_path): + names = ["tests/test_known.py", "tests/test_new.py", "tests/nested/test_core.py"] + _files(tmp_path, names, marked=[names[1]]) + assert shard_pr_tests.shard_tests(names, 80, {names[0]: 100}, root=tmp_path) == ( + [names[0]], [names[1], names[2]], + ) + # Removing every measurement changes balance, never membership. + shards = shard_pr_tests.shard_tests(names, 80, {}, root=tmp_path) + assert sorted(shards[0] + shards[1]) == sorted(names) + + +def test_equal_weights_use_path_order_and_equal_loads_choose_zero(tmp_path): + names = [f"tests/test_{letter}.py" for letter in "dcba"] + _files(tmp_path, names) + durations = dict.fromkeys(names, 10) + assert shard_pr_tests.shard_tests(names, 80, durations, root=tmp_path) == ( + ["tests/test_a.py", "tests/test_c.py"], ["tests/test_b.py", "tests/test_d.py"], + ) + + +def test_zero_weight_files_are_collected_once_and_duplicates_are_deduplicated(tmp_path): + names = ["tests/test_b.py", "tests/test_a.py"] + _files(tmp_path, names) + assert shard_pr_tests.shard_tests(names * 2, 80, {}, root=tmp_path) == ( + sorted(names), [], + ) + + +@pytest.mark.parametrize("name", [ + "tests/missing.py", "tests", "scripts/tool.py", "tests/../outside.py", + "tests//test_ok.py", "./tests/test_ok.py", "tests/test_ok.py::test_one", "", +]) +def test_missing_outside_noncanonical_and_nonfile_paths_are_rejected(tmp_path, name): + _files(tmp_path, ["tests/test_ok.py", "scripts/tool.py", "outside.py"]) + with pytest.raises(ValueError, match="file inside tests/"): + shard_pr_tests.shard_tests([name], 80, {}, root=tmp_path) + + +def test_absolute_and_symlink_escape_paths_are_rejected(tmp_path): + _files(tmp_path, ["tests/test_ok.py", "outside.py"]) + (tmp_path / "tests/link.py").symlink_to(tmp_path / "outside.py") + for name in [str(tmp_path / "tests/test_ok.py"), "tests/link.py"]: + with pytest.raises(ValueError, match="file inside tests/"): + shard_pr_tests.shard_tests([name], 80, {}, root=tmp_path) + + +@pytest.mark.parametrize("overrides", [ + {"schema_version": 2}, {"source": ""}, {"files": []}, + {"default_seconds": -1}, {"default_seconds": True}, {"default_seconds": "80"}, + {"files": {"tests/test_a.py": float("inf")}}, + {"files": {"tests/test_a.py": float("nan")}}, + {"files": {"tests/test_a.py": -1}}, +]) +def test_invalid_duration_tables_fail(tmp_path, overrides): + with pytest.raises(ValueError): + shard_pr_tests.load_durations(_table(tmp_path / "durations.json", **overrides)) + + +def test_cli_outputs_are_byte_identical_for_reordered_input_and_empty_input( + tmp_path, monkeypatch, +): + monkeypatch.chdir(tmp_path) + names = ["tests/test_b.py", "tests/test_a.py", "tests/test_core.py"] + _files(tmp_path, names, marked=names[:2]) + table = _table(tmp_path / "durations.json") + selected = tmp_path / "selected.txt" + output = tmp_path / "out" + monkeypatch.setattr(sys, "argv", [ + "shard_pr_tests.py", "--selected", str(selected), "--durations", str(table), + "--output-dir", str(output), + ]) + selected.write_text("\n".join(names) + "\n") + assert shard_pr_tests.main() == 0 + files = [output / f"selected-gloo-{side}.txt" for side in (0, 1)] + first = [path.read_bytes() for path in files] + selected.write_text("\n".join(reversed(names)) + "\n") + assert shard_pr_tests.main() == 0 + assert [path.read_bytes() for path in files] == first + selected.write_text("") + assert shard_pr_tests.main() == 0 + assert [path.read_bytes() for path in files] == [b"", b""] + + +def test_cli_rejects_invalid_input_before_writing_shards(tmp_path, monkeypatch, capsys): + monkeypatch.chdir(tmp_path) + (tmp_path / "ci").mkdir() + _table(tmp_path / "ci/gloo-test-durations.json") + (tmp_path / "test-results").mkdir() + selected = tmp_path / "test-results/selected-tests.txt" + selected.write_text("tests/missing.py\n") + monkeypatch.setattr(sys, "argv", ["shard_pr_tests.py"]) + assert shard_pr_tests.main() == 1 + assert "PR test sharding failed:" in capsys.readouterr().out + assert not (tmp_path / "test-results/selected-gloo-0.txt").exists() + + +@pytest.mark.parametrize("changed", ["scripts/shard_pr_tests.py", "ci/gloo-test-durations.json"]) +def test_sharder_and_duration_changes_select_focused_and_policy_tests(changed): + risk_map = json.loads((ROOT / "ci/test-risk-map.json").read_text()) + surface = next(item for item in risk_map["contract_surfaces"] if changed in item["paths"]) + expected_tests = {"tests/test_shard_pr_tests.py", "tests/test_ci_policy.py"} + assert expected_tests <= set(surface["required_tests"]) + selected = select_pr_tests.select_tests( + [changed], + policy=json.loads((ROOT / "ci/pr-test-policy.json").read_text()), + risk_maps=[risk_map], + project_root=ROOT, + ) + assert expected_tests <= set(selected) diff --git a/tests/test_test_risk_map.py b/tests/test_test_risk_map.py index 25daea11..0c108f9e 100644 --- a/tests/test_test_risk_map.py +++ b/tests/test_test_risk_map.py @@ -241,6 +241,23 @@ def test_source_inventory_rejects_invalid_shape_duplicates_and_non_python_file(t assert "test risk map source_inventory must be an object" in errors +def test_source_inventory_validates_data_files(): + errors = [] + inventory = { + "roots": ["scripts/shard_pr_tests.py"], + "data_files": ["ci/gloo-test-durations.json", "ci/gloo-test-durations.json", + "missing.json", "/absolute.json", "ci/../README.md", 42], + } + sources = check_test_risk_map._inventory_sources(inventory, project_root=ROOT, errors=errors) + assert sources == {"scripts/shard_pr_tests.py", "ci/gloo-test-durations.json"} + assert len(errors) == 5 + assert "source_inventory has duplicate data file: ci/gloo-test-durations.json" in errors + errors = [] + inventory["data_files"] = {} + check_test_risk_map._inventory_sources(inventory, project_root=ROOT, errors=errors) + assert errors == ["source_inventory data_files must be a list"] + + def test_contract_surface_rejects_duplicate_and_malformed_fields(tmp_path): risk = json.loads((ROOT / "ci" / "test-risk-map.json").read_text()) first = next(