From 16dea8e060b6fc1c81e008095ca486cbed5250b4 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Thu, 19 Nov 2026 16:49:58 +0900 Subject: [PATCH] ci: run the tests, the coverage passes and the validation check in parallel The test matrix, the NumPy reference path and both coverage passes run on one pytest-xdist worker per core (pytest-xdist joins the dev extra, bounded <4). Under xdist every worker gets its own numba cache directory before numba is imported (tests/conftest.py), so concurrent workers never write the same cache files and each starts from an empty cache, as a serial CI run does. release/check_coverage.py takes --numprocesses N; pytest-cov combines the workers of each pass and the NUMBA_DISABLE_JIT=1 kernel pass is appended to the first exactly as before. The 95 % threshold and the kernel test list are unchanged. run_validation.py takes --jobs=N (default 1, the serial run). The independent row groups (Saevik, Zeidan, anchored wire, Dai, torque, Hu, Witz) run in spawn worker processes while _rows assembles the report, and _rows takes each group's rows where it calls the group, so rows, order and report are those of the serial run. The three taxonomy groups start beside the rows, each on N xdist workers, with their output in temporary files. --check semantics are unchanged. The coverage run and the validation report check run side by side in two jobs; the required check "Coverage and validation report" now needs both and fails unless both succeeded (it also runs, and fails, when either failed or was cancelled). Every job name of the ruleset is unchanged. Signed-off-by: Jae Hoon Seo --- .github/workflows/python.yml | 75 ++++++++--- CHANGELOG.md | 9 ++ DEVELOPMENT.md | 15 ++- pyproject.toml | 1 + release/check_coverage.py | 15 ++- tests/conftest.py | 23 +++- validation/scripts/run_validation.py | 194 ++++++++++++++++++++++----- 7 files changed, 277 insertions(+), 55 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index a2e73c7..c7bc229 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -17,7 +17,8 @@ permissions: contents: read env: - # One thread per process: the suite is numerically heavy and runs serially. + # One thread per process: the suite is numerically heavy and runs on one pytest-xdist + # worker per core, so a worker must not start threads of its own. OMP_NUM_THREADS: "1" MKL_NUM_THREADS: "1" OPENBLAS_NUM_THREADS: "1" @@ -72,7 +73,7 @@ jobs: - name: Install the package and test dependencies run: python -m pip install --upgrade pip ".[dev,fast,contact]" - name: Run the test suite - run: python -m pytest -q -p no:cacheprovider + run: python -m pytest -q -p no:cacheprovider -n auto --dist worksteal --durations=25 reference-path: name: Tests without the compiled kernels @@ -92,10 +93,12 @@ jobs: - name: Install the package without numba run: python -m pip install --upgrade pip ".[dev,contact]" - name: Run the test suite on the NumPy reference path - run: python -m pytest -q -p no:cacheprovider + run: python -m pytest -q -p no:cacheprovider -n auto --dist worksteal --durations=25 - coverage: - name: Coverage and validation report + coverage-suite: + # Not a required check itself: the required check "Coverage and validation report" + # passes only if this job and validation-report both pass. + name: Coverage of the whole suite runs-on: ubuntu-latest timeout-minutes: 150 steps: @@ -109,21 +112,10 @@ jobs: cache-dependency-path: pyproject.toml - name: Install the package and test dependencies run: python -m pip install --upgrade pip ".[dev,fast,contact]" - - name: The committed validation report is current - # The script exits non-zero while registered benchmark rows fail; the step - # fails only if the committed report differs from the live calculation. It runs - # before the coverage run (about 45 min), so a stale report fails within minutes. - shell: bash - run: | - set +e - python validation/scripts/run_validation.py --check 2>&1 | tee validation-check.txt - status=${PIPESTATUS[0]} - if grep -q "validation artefacts are stale" validation-check.txt; then exit 1; fi - echo "run_validation exit status ${status} (registered FAIL rows are expected)" - name: Run the whole suite with line and branch coverage, kernels traced # Functions compiled by numba run outside the coverage tracer, so the kernel # tests run a second time with NUMBA_DISABLE_JIT=1 and are appended. - run: python release/check_coverage.py --fail-under 95 + run: python release/check_coverage.py --fail-under 95 --numprocesses auto - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 if: always() with: @@ -131,6 +123,55 @@ jobs: path: coverage.xml if-no-files-found: ignore + validation-report: + # Not a required check itself; see coverage-suite. + name: Validation report is current + runs-on: ubuntu-latest + timeout-minutes: 150 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.11' + cache: pip + cache-dependency-path: pyproject.toml + - name: Install the package and test dependencies + run: python -m pip install --upgrade pip ".[dev,fast,contact]" + - name: The committed validation report is current + # The script exits non-zero while registered benchmark rows fail; the step + # fails only if the committed report differs from the live calculation. + # --jobs=auto evaluates the independent row groups and the taxonomy groups + # concurrently; the rows and the report are those of the serial run. + shell: bash + run: | + set +e + python validation/scripts/run_validation.py --check --jobs=auto 2>&1 | tee validation-check.txt + status=${PIPESTATUS[0]} + if grep -q "validation artefacts are stale" validation-check.txt; then exit 1; fi + echo "run_validation exit status ${status} (registered FAIL rows are expected)" + + coverage: + # The required check. The coverage run and the validation report check run side by + # side in the two jobs above; this job fails unless both succeeded, and it also + # runs (and fails) when either of them failed, was cancelled or was skipped. + name: Coverage and validation report + needs: [coverage-suite, validation-report] + if: always() + runs-on: ubuntu-latest + steps: + - name: The coverage gate and the validation report check passed + shell: bash + env: + COVERAGE_RESULT: ${{ needs.coverage-suite.result }} + VALIDATION_RESULT: ${{ needs.validation-report.result }} + run: | + echo "Coverage of the whole suite: ${COVERAGE_RESULT}" + echo "Validation report is current: ${VALIDATION_RESULT}" + test "${COVERAGE_RESULT}" = success + test "${VALIDATION_RESULT}" = success + distribution: name: Build Python distributions runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index a038d82..c5c397b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -339,6 +339,15 @@ All notable changes to CableXSec are recorded in this file. The format follows ### Changed +- CI runs the tests in parallel: the test matrix, the NumPy reference path and both coverage + passes run on one pytest-xdist worker per core (`pytest-xdist` joins the `dev` extra), and + each worker keeps its own numba cache. `release/check_coverage.py --numprocesses N` and + `run_validation.py --jobs=N` take a worker count; `--jobs` evaluates the independent row + groups in worker processes and runs the three taxonomy groups concurrently. The coverage + run and the validation report check run side by side in two jobs, and the required check + "Coverage and validation report" passes only when both pass. The tests, the 95 % threshold, + the kernel coverage pass, the rows, the report and its staleness check are unchanged. + - The rows that compare with the measured loops of Ménard and Cartraud (2023), BM1-loop, BM1-loop-uniform and BM1-ID, are stated, not gated (status INFO, the verdict against the registered target kept): the test is an unreliable reference. The benchmark register states the diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 786bac7..5c17e15 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -37,10 +37,13 @@ python -m pytest -q -m full_scale # published full-scale dat python -m pytest -q --cov --cov-branch --cov-report=term-missing ``` -The whole suite takes about 20 minutes on one core. Do not run it with several -workers on a shared machine without limiting the threads of each worker; set -`OMP_NUM_THREADS`, `MKL_NUM_THREADS`, `OPENBLAS_NUM_THREADS` and `NUMBA_NUM_THREADS` -to `1`. The tests import the reproduction scripts of `validation/scripts/` by name +The whole suite takes about 20 minutes on one core. `python -m pytest -q -n 4` runs it +on four pytest-xdist workers (CI uses `-n auto --dist worksteal`); each worker keeps its +own numba cache (`tests/conftest.py`). Do not run it with several workers without +limiting the threads of each worker; set `OMP_NUM_THREADS`, `MKL_NUM_THREADS`, +`OPENBLAS_NUM_THREADS` and `NUMBA_NUM_THREADS` to `1`. The coverage gate +`python release/check_coverage.py --fail-under 95` takes `--numprocesses 4` in the same +way. The tests import the reproduction scripts of `validation/scripts/` by name (`tests/conftest.py` puts that folder on the import path). | Marker | Tests | @@ -59,6 +62,10 @@ python validation/scripts/run_validation.py # regenerate validation/val python validation/scripts/run_validation.py --check # fail if the committed report is stale ``` +`--jobs=N` (or `--jobs=auto`) evaluates the independent row groups in N processes and runs +the three marker groups concurrently, each on N pytest-xdist workers; the rows and the +report are those of the serial run. + The script recomputes every row from the live code, runs the three marker groups for the test taxonomy, and exits non-zero while any row is `FAIL` or `REVIEW`; the failed rows of the 0.1.0 report are registered, unresolved discrepancies (see diff --git a/pyproject.toml b/pyproject.toml index 5eed02c..38cd585 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -71,6 +71,7 @@ dev = [ "build>=1.2", "pytest>=8.0", "pytest-cov>=5", + "pytest-xdist>=3.6,<4", "ruff>=0.15,<0.16", "mypy>=1.11", "twine>=5", diff --git a/release/check_coverage.py b/release/check_coverage.py index 9dce36f..63b8f31 100644 --- a/release/check_coverage.py +++ b/release/check_coverage.py @@ -8,7 +8,11 @@ ``NUMBA_DISABLE_JIT=1`` so that the kernel bodies execute as Python, appends both to one coverage record, and fails below the threshold. -Usage: ``python release/check_coverage.py [--fail-under 95]`` +``--numprocesses`` (pytest-xdist) runs both passes on several workers; pytest-cov +combines the workers of each pass, and the second pass is appended to the first as in +a serial run. + +Usage: ``python release/check_coverage.py [--fail-under 95] [--numprocesses auto]`` """ from __future__ import annotations @@ -50,9 +54,18 @@ def run(command: list[str], extra_env: dict[str, str] | None = None) -> int: def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--fail-under", type=float, default=95.0) + parser.add_argument( + "-n", + "--numprocesses", + default=None, + help="pytest-xdist workers for both passes (a number, auto or logical); " + "serial when omitted", + ) args = parser.parse_args() python = sys.executable pytest = [python, "-m", "pytest", "-q", "-p", "no:cacheprovider"] + if args.numprocesses is not None: + pytest += ["-n", args.numprocesses] status = run( [*pytest, "--cov", "--cov-branch", "--cov-report=", "--cov-fail-under=0"] ) diff --git a/tests/conftest.py b/tests/conftest.py index c194b41..e08c47b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,12 +1,33 @@ # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University -"""Test configuration: make the validation scripts importable by name.""" +"""Test configuration: make the validation scripts importable by name. + +Under pytest-xdist every worker gets its own numba cache directory before numba is +imported, so that concurrent workers (and the subprocesses they start) never write +the same on-disk kernel cache; a serial run keeps numba's default location. +""" from __future__ import annotations +import os +import shutil import sys +import tempfile from pathlib import Path +_WORKER = os.environ.get("PYTEST_XDIST_WORKER") +_NUMBA_CACHE: Path | None = None +if _WORKER and "NUMBA_CACHE_DIR" not in os.environ: + _RUN = os.environ.get("PYTEST_XDIST_TESTRUNUID", "run") + _NUMBA_CACHE = Path(tempfile.gettempdir()) / f"cablexsec-numba-{_RUN}-{_WORKER}" + os.environ["NUMBA_CACHE_DIR"] = str(_NUMBA_CACHE) + _SCRIPTS = Path(__file__).resolve().parents[1] / "validation" / "scripts" if str(_SCRIPTS) not in sys.path: sys.path.insert(0, str(_SCRIPTS)) + + +def pytest_unconfigure(config: object) -> None: + """Remove the worker's own numba cache at the end of the run.""" + if _NUMBA_CACHE is not None: + shutil.rmtree(_NUMBA_CACHE, ignore_errors=True) diff --git a/validation/scripts/run_validation.py b/validation/scripts/run_validation.py index d2ada95..fc41fcd 100644 --- a/validation/scripts/run_validation.py +++ b/validation/scripts/run_validation.py @@ -7,19 +7,32 @@ their targets and unresolved discrepancies remain visible. Every input is a published value or a file in this repository. -Usage: ``python validation/scripts/run_validation.py [--check]``. +Usage: ``python validation/scripts/run_validation.py [--check] [--jobs=N]``. + +``--jobs=N`` (a number or ``auto``) evaluates the independent row groups in N worker +processes and runs the three test-taxonomy groups concurrently, each on N +pytest-xdist workers. The rows, their order and the report are those of the serial +run (the default, ``--jobs=1``). """ from __future__ import annotations +import importlib.util import json import math +import multiprocessing +import os import re import subprocess import sys -from dataclasses import dataclass +import tempfile +from collections.abc import Callable +from concurrent.futures import Future, ProcessPoolExecutor +from dataclasses import astuple, dataclass +from functools import partial from pathlib import Path from types import ModuleType +from typing import IO import numpy as np @@ -2183,35 +2196,66 @@ def _comp_row(tier: str, ident: str, quantity: str, keys: tuple[str, ...]) -> Ro return rows -def _taxonomy_counts() -> dict[str, str]: - out: dict[str, str] = {} - for marker in ("analytical_sanity", "independent_method", "full_scale"): - proc = subprocess.run( - [ - sys.executable, - "-m", - "pytest", - "tests/", - "-m", - marker, - "-q", - "-o", - "addopts=", - "-p", - "no:cacheprovider", - ], - cwd=ROOT, - capture_output=True, - text=True, - check=False, - ) - if proc.returncode != 0: - detail = (proc.stdout + "\n" + proc.stderr).strip() +_TAXONOMY_MARKERS = ("analytical_sanity", "independent_method", "full_scale") + + +class _TaxonomyRun: + """One marker group of the test taxonomy, run by pytest in a subprocess. + + The output goes to temporary files rather than pipes, so that a run started + before the rows are evaluated never blocks on a full pipe. + """ + + def __init__(self, marker: str, jobs: int) -> None: + command = [ + sys.executable, + "-m", + "pytest", + "tests/", + "-m", + marker, + "-q", + "-o", + "addopts=", + "-p", + "no:cacheprovider", + ] + if jobs > 1: + command += ["-n", str(jobs)] + self.marker = marker + # Read back in the locale encoding, as ``subprocess.run(text=True)`` would; + # summary() or stop() closes them. + self._stdout: IO[str] = tempfile.TemporaryFile("w+") # noqa: SIM115 + self._stderr: IO[str] = tempfile.TemporaryFile("w+") # noqa: SIM115 + self._process = subprocess.Popen( + command, cwd=ROOT, stdout=self._stdout, stderr=self._stderr + ) + + def stop(self) -> None: + """End the run if it is still going (another part of the report failed).""" + if self._process.poll() is None: + self._process.kill() + self._process.wait() + self._stdout.close() + self._stderr.close() + + def summary(self) -> str: + """Wait for the run; its passed count, as the report states it.""" + returncode = self._process.wait() + output = [] + for stream in (self._stdout, self._stderr): + stream.seek(0) + output.append(stream.read()) + stream.close() + stdout, stderr = output + marker = self.marker + if returncode != 0: + detail = (stdout + "\n" + stderr).strip() raise RuntimeError( f"pytest taxonomy {marker!r} failed with exit code " - f"{proc.returncode}:\n{detail}" + f"{returncode}:\n{detail}" ) - summaries = [line for line in proc.stdout.splitlines() if " passed" in line] + summaries = [line for line in stdout.splitlines() if " passed" in line] if not summaries: raise RuntimeError(f"pytest taxonomy {marker!r} emitted no pass summary") stable_summary = summaries[-1].split(" in ", maxsplit=1)[0] @@ -2220,7 +2264,15 @@ def _taxonomy_counts() -> dict[str, str]: stable_parts = [ part.strip() for part in stable_summary.split(",") if "passed" in part ] - out[marker] = ", ".join(stable_parts) + return ", ".join(stable_parts) + + +def _taxonomy_counts(started: dict[str, _TaxonomyRun] | None = None) -> dict[str, str]: + """Passed count of each marker group; groups not ``started`` run in turn.""" + out: dict[str, str] = {} + for marker in _TAXONOMY_MARKERS: + run = (started or {}).get(marker) or _TaxonomyRun(marker, 1) + out[marker] = run.summary() return out @@ -2324,6 +2376,70 @@ def prepare(cable: CableData, tension_N: float, **options: object) -> object: beam_test._prepare_mkappa_law = prepare # type: ignore[assignment] +# Row groups that depend on nothing else in the report, slowest first. With +# --jobs=N they run in worker processes while _rows assembles the report, and +# _rows takes each group's rows at the place where it calls the group. +_PARALLEL_GROUPS: dict[str, Callable[[], list[Row]]] = { + "_saevik_split_rows": _saevik_split_rows, + "_zeidan_rows": _zeidan_rows, + "_saevik_rows": _saevik_rows, + "_anchored_wire_fe_rows": _anchored_wire_fe_rows, + "_dai2020_rows": _dai2020_rows, + "_torque_rows": _torque_rows, + "_hu_rows": _hu_rows, + "_witz_rows": _witz_rows, + "_dai2018_rows": _dai2018_rows, +} +_JOBS_FLAG = "--jobs=" + + +def _jobs(arguments: list[str]) -> int: + """Worker count of ``--jobs=N`` (``auto``: one per CPU); 1 without the flag.""" + values = [arg[len(_JOBS_FLAG) :] for arg in arguments if arg.startswith(_JOBS_FLAG)] + if not values: + return 1 + value = values[-1] + if value == "auto": + return max(1, os.cpu_count() or 1) + if not value.isdigit() or int(value) < 1: + raise SystemExit(f"--jobs takes a positive integer or auto, not {value!r}") + return int(value) + + +def _worker_start(core_lay: bool) -> None: + if core_lay: + _apply_core_lay_stage() + + +def _group_rows(name: str) -> list[tuple[str, ...]]: + """Rows of one group, as plain tuples (worker process side).""" + return [astuple(row) for row in _PARALLEL_GROUPS[name]()] + + +def _group_result(future: Future[list[tuple[str, ...]]]) -> list[Row]: + return [Row(*fields) for fields in future.result()] + + +def _evaluate_rows(jobs: int, core_lay: bool) -> list[Row]: + """``_rows()``, with the independent groups in ``jobs`` worker processes.""" + if jobs == 1: + return _rows() + module = globals() + with ProcessPoolExecutor( + max_workers=min(jobs, len(_PARALLEL_GROUPS)), + mp_context=multiprocessing.get_context("spawn"), + initializer=_worker_start, + initargs=(core_lay,), + ) as pool: + for name in _PARALLEL_GROUPS: + module[name] = partial(_group_result, pool.submit(_group_rows, name)) + try: + return _rows() + finally: + module.update(_PARALLEL_GROUPS) + pool.shutdown(cancel_futures=True) + + def main() -> None: # Some Windows consoles retain a locale encoding (for example CP949) even # when the source and generated artefacts are UTF-8. Reporting must never @@ -2334,13 +2450,27 @@ def main() -> None: core_lay = _CORE_LAY_FLAG in sys.argv[1:] check_only = "--check" in sys.argv[1:] or core_lay - unknown = [arg for arg in sys.argv[1:] if arg not in ("--check", _CORE_LAY_FLAG)] + unknown = [ + arg + for arg in sys.argv[1:] + if arg not in ("--check", _CORE_LAY_FLAG) and not arg.startswith(_JOBS_FLAG) + ] if unknown: raise SystemExit(f"unknown argument(s): {' '.join(unknown)}") + jobs = _jobs(sys.argv[1:]) if core_lay: _apply_core_lay_stage() - rows = _rows() - tax = _taxonomy_counts() + started: dict[str, _TaxonomyRun] = {} + try: + if jobs > 1: + # The marker groups run beside the rows; each on its own xdist workers. + workers = jobs if importlib.util.find_spec("xdist") is not None else 1 + started = {m: _TaxonomyRun(m, workers) for m in _TAXONOMY_MARKERS} + rows = _evaluate_rows(jobs, core_lay) + tax = _taxonomy_counts(started) + finally: + for run in started.values(): + run.stop() lines = [ "", "",