Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ jobs:
needs: [coverage-suite, validation-report]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: The coverage gate and the validation report check passed
shell: bash
Expand Down
6 changes: 4 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,8 +340,10 @@ 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
passes run on one pytest-xdist worker per core (`pytest-xdist` joins the `dev` extra).
Every concurrent process writes its own numba cache: numba numbers a new cache entry from
the index it last read, so two processes compiling one kernel for different signatures at
once can overwrite each other's entries. `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
Expand Down
14 changes: 9 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University
"""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.
Under pytest-xdist every worker writes its own numba cache directory, set before
numba is imported: numba numbers a new cache entry from the index it last read, so
two processes that compile the same kernel for different signatures at the same
time can overwrite each other's entries. The directory is a subdirectory of
``NUMBA_CACHE_DIR`` when that is set, else of the temporary directory, and is
removed at the end of the run. A serial run keeps numba's own location.
"""

from __future__ import annotations
Expand All @@ -17,9 +20,10 @@

_WORKER = os.environ.get("PYTEST_XDIST_WORKER")
_NUMBA_CACHE: Path | None = None
if _WORKER and "NUMBA_CACHE_DIR" not in os.environ:
if _WORKER:
_RUN = os.environ.get("PYTEST_XDIST_TESTRUNUID", "run")
_NUMBA_CACHE = Path(tempfile.gettempdir()) / f"cablexsec-numba-{_RUN}-{_WORKER}"
_ROOT = os.environ.get("NUMBA_CACHE_DIR") or tempfile.gettempdir()
_NUMBA_CACHE = Path(_ROOT) / f"cablexsec-numba-{_RUN}-{_WORKER}"
os.environ["NUMBA_CACHE_DIR"] = str(_NUMBA_CACHE)

_SCRIPTS = Path(__file__).resolve().parents[1] / "validation" / "scripts"
Expand Down
96 changes: 72 additions & 24 deletions validation/scripts/run_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2197,16 +2197,19 @@ def _comp_row(tier: str, ident: str, quantity: str, keys: tuple[str, ...]) -> Ro


_TAXONOMY_MARKERS = ("analytical_sanity", "independent_method", "full_scale")
_NUMBA_CACHE_ENV = "NUMBA_CACHE_DIR"


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.
before the rows are evaluated never blocks on a full pipe. A run beside other
processes takes its own ``numba_cache`` directory (see :func:`_isolated_pool`);
under xdist, ``tests/conftest.py`` gives each worker a subdirectory of it.
"""

def __init__(self, marker: str, jobs: int) -> None:
def __init__(self, marker: str, jobs: int, numba_cache: Path | None = None) -> None:
command = [
sys.executable,
"-m",
Expand All @@ -2227,8 +2230,11 @@ def __init__(self, marker: str, jobs: int) -> None:
# summary() or stop() closes them.
self._stdout: IO[str] = tempfile.TemporaryFile("w+") # noqa: SIM115
self._stderr: IO[str] = tempfile.TemporaryFile("w+") # noqa: SIM115
env = None
if numba_cache is not None:
env = {**os.environ, _NUMBA_CACHE_ENV: str(numba_cache)}
self._process = subprocess.Popen(
command, cwd=ROOT, stdout=self._stdout, stderr=self._stderr
command, cwd=ROOT, env=env, stdout=self._stdout, stderr=self._stderr
)

def stop(self) -> None:
Expand Down Expand Up @@ -2420,24 +2426,59 @@ 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)),
def _isolated_pool(numba_cache: Path, core_lay: bool) -> ProcessPoolExecutor:
"""A one-process pool whose worker writes its own numba cache directory.

numba numbers a new cache entry from the index it last read, so two processes
that compile the same kernel for different signatures at the same time can
overwrite each other's entries. The worker is started while ``NUMBA_CACHE_DIR``
names its own directory, and inherits it.
"""
pool = ProcessPoolExecutor(
max_workers=1,
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))
)
previous = os.environ.get(_NUMBA_CACHE_ENV)
os.environ[_NUMBA_CACHE_ENV] = str(numba_cache)
try:
pool.submit(os.getpid).result() # the worker process now exists
finally:
if previous is None:
del os.environ[_NUMBA_CACHE_ENV]
else:
os.environ[_NUMBA_CACHE_ENV] = previous
return pool


def _evaluate_rows(
jobs: int, core_lay: bool, numba_cache: Path | None = None
) -> list[Row]:
"""``_rows()``, with the independent groups in ``jobs`` worker processes.

The groups go to the workers in turn, slowest first; each worker keeps its
own numba cache below ``numba_cache`` (a temporary directory by default).
"""
if jobs == 1:
return _rows()
module = globals()
pools: list[ProcessPoolExecutor] = []
with tempfile.TemporaryDirectory(
prefix="cablexsec-rows-", ignore_cleanup_errors=True
) as scratch:
root = numba_cache or Path(scratch)
try:
for index in range(min(jobs, len(_PARALLEL_GROUPS))):
pools.append(_isolated_pool(root / f"rows-{index}", core_lay))
for index, name in enumerate(_PARALLEL_GROUPS):
future = pools[index % len(pools)].submit(_group_rows, name)
module[name] = partial(_group_result, future)
return _rows()
finally:
module.update(_PARALLEL_GROUPS)
pool.shutdown(cancel_futures=True)
for pool in pools:
pool.shutdown(cancel_futures=True)


def main() -> None:
Expand All @@ -2461,16 +2502,23 @@ def main() -> None:
if core_lay:
_apply_core_lay_stage()
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()
with tempfile.TemporaryDirectory(
prefix="cablexsec-validation-", ignore_cleanup_errors=True
) as scratch:
try:
if jobs > 1:
# The marker groups run beside the rows, each on its own xdist
# workers and with its own numba cache.
workers = jobs if importlib.util.find_spec("xdist") is not None else 1
started = {
m: _TaxonomyRun(m, workers, Path(scratch) / m)
for m in _TAXONOMY_MARKERS
}
rows = _evaluate_rows(jobs, core_lay, Path(scratch) / "rows")
tax = _taxonomy_counts(started)
finally:
for run in started.values():
run.stop()
lines = [
"<!-- SPDX-License-Identifier: Apache-2.0 -->",
"",
Expand Down
Loading