diff --git a/CHANGELOG.md b/CHANGELOG.md index 52bf622..68daa36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -472,6 +472,18 @@ All notable changes to CableXSec are recorded in this file. The format follows at 0.1 (2e-9 at 0.02). The README and quickstart outputs, which had drifted before this change (peak 548 N m and 219.8 J/m printed against 541 N m and 212.0 J/m computed), are regenerated. + +- `run_sea_state_batch` with `workers > 1`: each worker process writes a numba cache of its own + instead of sharing the caller's. numba numbers a new on-disk cache entry from the index it + last read and saves the index before the data, so two workers compiling one kernel for + different signatures at the same time could leave the index pointing at the other's machine + code, which a later process would load. Worker caches are slot folders `slot-` under + `cablexsec/numba-batch` in the user cache directory (`CABLEXSEC_BATCH_CACHE_DIR` overrides + it), kept for later batches. Each worker locks its slot itself for as long as it runs (so + the slot stays taken even if the calling process ends first), a batch beside another takes + the next free slots, and a worker without a free slot or a writable folder gets a temporary + cache. Results are unchanged, and runs go to whichever worker is free, as before. + - `SectionLaw.from_cable` reads the cable's own materials (its `materials:` block) when the law is built and every time it is evaluated. Outside `simulate_bending_test` it read the library instead, and a layer whose material the library lacks silently dropped out of the stiffness diff --git a/doc/global_local_guide.md b/doc/global_local_guide.md index 1ea5f15..55340b7 100644 --- a/doc/global_local_guide.md +++ b/doc/global_local_guide.md @@ -347,7 +347,12 @@ result.sections["sag"].long_term.annual_damage, result.sections["sag"].life_year mismatch stops the batch unless `allow_property_mismatch=True` is declared, and the comparison is written to the manifest either way. - Workers: `workers` processes (at most `MAX_WORKERS = 8`), one numerical - thread each, spawned; results do not depend on the worker count. + thread each, spawned; results do not depend on the worker count. Each + worker keeps its compiled kernels in a cache folder of its own, `slot-` + under `cablexsec/numba-batch` in the user cache directory (set + `CABLEXSEC_BATCH_CACHE_DIR` to move it), so later batches start warm; a + slot is held by one worker at a time, and deleting the folder only costs a + recompilation. - Output folder (must not exist): `manifest.json` (SHA-256 of every CableDyn file and deck, the cable definition and YAML file, options, property check, reader checks per run, results, and `inputs_sha256` over all of them); diff --git a/src/cablexsec/analysis/sea_state_batch.py b/src/cablexsec/analysis/sea_state_batch.py index fcced0b..2c22c7a 100644 --- a/src/cablexsec/analysis/sea_state_batch.py +++ b/src/cablexsec/analysis/sea_state_batch.py @@ -39,10 +39,16 @@ Parallel execution ------------------ Runs are processed in worker processes (``workers``, at most -:data:`MAX_WORKERS`), each limited to one numerical thread. Results do not -depend on the worker count. The output directory, if given, must not exist: -results are written once, with a manifest of SHA-256 digests of every input -file, the cable definition and the options. +:data:`MAX_WORKERS`), each limited to one numerical thread. Each worker keeps +its compiled kernels in a numba cache of its own: a slot directory +``slot-`` under ``cablexsec/numba-batch`` in the user cache directory, or +under ``CABLEXSEC_BATCH_CACHE_DIR`` when that is set, which later batches +reuse. Each worker locks its slot itself for as long as it runs, so no two +processes write one cache; a batch beside another takes the next free slots, +and a worker without one gets a temporary cache. Results do not depend on the +worker count. The output directory, if given, must not exist: results are +written once, with a manifest of SHA-256 digests of every input file, the +cable definition and the options. """ from __future__ import annotations @@ -54,9 +60,12 @@ import pickle import platform import sys +import tempfile +import threading import warnings -from collections.abc import Mapping, Sequence -from concurrent.futures import ProcessPoolExecutor +from collections.abc import Iterator, Mapping, Sequence +from concurrent.futures import FIRST_COMPLETED, Future, ProcessPoolExecutor, wait +from contextlib import contextmanager from dataclasses import asdict, dataclass, field, fields from pathlib import Path from types import MappingProxyType @@ -109,6 +118,11 @@ "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS", ) +_NUMBA_CACHE_VARIABLE = "NUMBA_CACHE_DIR" +#: Overrides the folder of the persistent worker caches (_batch_cache_directory). +_BATCH_CACHE_VARIABLE = "CABLEXSEC_BATCH_CACHE_DIR" +#: Persistent worker cache slots; a worker beyond them gets a temporary cache. +_CACHE_SLOTS = 2 * MAX_WORKERS __all__ = [ "MAX_WORKERS", @@ -468,6 +482,193 @@ def _fretting_summary(result: Any) -> dict[str, dict[str, Any]]: return out +def _batch_cache_directory() -> Path: + """Folder of the persistent numba caches of the batch workers. + + ``CABLEXSEC_BATCH_CACHE_DIR`` when set; otherwise ``cablexsec/numba-batch`` + in the user cache directory (``%LOCALAPPDATA%`` on Windows, + ``~/Library/Caches`` on macOS, ``$XDG_CACHE_HOME`` or ``~/.cache`` + elsewhere). Deleting it only costs the workers a recompilation. + """ + override = os.environ.get(_BATCH_CACHE_VARIABLE) + if override: + return Path(override) + if sys.platform == "win32": + local = os.environ.get("LOCALAPPDATA") + base = Path(local) if local else Path.home() / "AppData" / "Local" + elif sys.platform == "darwin": + base = Path.home() / "Library" / "Caches" + else: + xdg = os.environ.get("XDG_CACHE_HOME") + base = Path(xdg) if xdg else Path.home() / ".cache" + return base / "cablexsec" / "numba-batch" + + +def _lock(handle: Any) -> bool: + """Take an exclusive, non-blocking lock on an open file; False if held.""" + try: + if sys.platform == "win32": + import msvcrt # noqa: PLC0415 + + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl # noqa: PLC0415 + + fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + return False + return True + + +def _unlock(handle: Any) -> None: + if sys.platform == "win32": + import msvcrt # noqa: PLC0415 + + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl # noqa: PLC0415 + + fcntl.flock(handle.fileno(), fcntl.LOCK_UN) + + +def _slot_is_free(path: Path) -> bool: + """True if no process holds the slot lock ``path`` (it is not kept).""" + try: + path.parent.mkdir(parents=True, exist_ok=True) + with open(path, "a+b") as handle: + if not _lock(handle): + return False + _unlock(handle) + except OSError: + return False + return True + + +#: The slot lock a worker process holds for its lifetime (see _claim_slot). +_SLOT_HANDLE: Any = None +#: Serialises the NUMBA_CACHE_DIR change around a worker start (one per process). +_START_LOCK = threading.Lock() + + +def _claim_slot(path: str) -> bool: + """Worker side: lock the slot ``path`` for the rest of this process. + + The worker, not the caller, holds the lock, so the slot stays taken while + the worker can still write its cache, even if the caller has ended; the + operating system releases it when the worker ends. + """ + global _SLOT_HANDLE + try: + handle = open(path, "a+b") # noqa: SIM115 - held for the process + except OSError: + return False + if not _lock(handle): + handle.close() + return False + _SLOT_HANDLE = handle + return True + + +def _start_worker(cache: Path) -> ProcessPoolExecutor: + """A one-process spawn pool whose worker writes the numba cache ``cache``. + + The worker is started while ``NUMBA_CACHE_DIR`` names ``cache`` and + inherits it before numba is imported; the caller's value is restored. The + whole change is serialised, so that workers started from several threads + at once each inherit their own directory. + """ + import multiprocessing # noqa: PLC0415 + + pool = ProcessPoolExecutor( + max_workers=1, + mp_context=multiprocessing.get_context("spawn"), + initializer=_limit_threads, + ) + with _START_LOCK: + previous = os.environ.get(_NUMBA_CACHE_VARIABLE) + os.environ[_NUMBA_CACHE_VARIABLE] = str(cache) + try: + pool.submit(os.getpid).result() # the worker now runs with it + except BaseException: + pool.shutdown(cancel_futures=True) + raise + finally: + if previous is None: + os.environ.pop(_NUMBA_CACHE_VARIABLE, None) + else: + os.environ[_NUMBA_CACHE_VARIABLE] = previous + return pool + + +@contextmanager +def _workers(count: int) -> Iterator[list[ProcessPoolExecutor]]: + """``count`` worker pools, each writing a numba cache no other process writes. + + numba numbers a new on-disk cache entry from the index it last read and + saves the index before the data, so two processes that compile one kernel + for different signatures at the same time can both take the same data file + and leave the index pointing at the other's machine code. A worker takes + the next free slot of :func:`_batch_cache_directory` and locks it itself + before it runs anything (:func:`_claim_slot`); if another process won the + slot meanwhile, the worker is replaced and the next slot tried. The slots + are kept for later batches; a worker without a free slot gets a temporary + cache, removed after the batch. + """ + root = _batch_cache_directory() + pools: list[ProcessPoolExecutor] = [] + scratch: tempfile.TemporaryDirectory[str] | None = None + try: + for slot in range(_CACHE_SLOTS): + if len(pools) == count: + break + lock = root / f"slot-{slot}.lock" + if not _slot_is_free(lock): + continue + pool = _start_worker(root / f"slot-{slot}") + pools.append(pool) + if not pool.submit(_claim_slot, str(lock)).result(): + pools.pop().shutdown() + if len(pools) < count: + scratch = tempfile.TemporaryDirectory( + prefix="cablexsec-batch-numba-", ignore_cleanup_errors=True + ) + for index in range(count - len(pools)): + pools.append(_start_worker(Path(scratch.name) / f"worker-{index}")) + yield pools + finally: + for pool in pools: + pool.shutdown(cancel_futures=True) + if scratch is not None: + scratch.cleanup() + + +def _evaluate_in_pools( + tasks: Sequence[_Task], pools: Sequence[ProcessPoolExecutor] +) -> list[dict[str, Any]]: + """Outcomes of ``tasks`` in order; each pool takes the next task when free.""" + outcomes: dict[int, dict[str, Any]] = {} + queue = iter(enumerate(tasks)) + pending: dict[Future[dict[str, Any]], tuple[int, ProcessPoolExecutor]] = {} + + def feed(pool: ProcessPoolExecutor) -> None: + item = next(queue, None) + if item is not None: + index, task = item + pending[pool.submit(_evaluate_in_worker, task)] = (index, pool) + + for pool in pools: + feed(pool) + while pending: + done, _ = wait(pending, return_when=FIRST_COMPLETED) + for future in done: + index, pool = pending.pop(future) + outcomes[index] = future.result() + feed(pool) + return [outcomes[index] for index in range(len(tasks))] + + def _evaluate_in_worker(task: _Task) -> dict[str, Any]: """:func:`_evaluate` in a worker process, with its warnings recorded. @@ -979,20 +1180,13 @@ def run_sea_state_batch( if opts.workers == 1 or len(tasks) == 1: outcomes = [_evaluate(task) for task in tasks] else: - import multiprocessing # noqa: PLC0415 - - context = multiprocessing.get_context("spawn") saved = {name: os.environ.get(name) for name in _THREAD_VARIABLES} try: # Spawned workers inherit one-thread settings before any import. for name in _THREAD_VARIABLES: os.environ[name] = "1" - with ProcessPoolExecutor( - max_workers=min(opts.workers, len(tasks)), - mp_context=context, - initializer=_limit_threads, - ) as pool: - outcomes = list(pool.map(_evaluate_in_worker, tasks)) + with _workers(min(opts.workers, len(tasks))) as pools: + outcomes = _evaluate_in_pools(tasks, pools) finally: for name, value in saved.items(): if value is None: diff --git a/tests/conftest.py b/tests/conftest.py index 5a2ccb0..de9dbbf 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -26,12 +26,20 @@ _NUMBA_CACHE = Path(_ROOT) / f"cablexsec-numba-{_RUN}-{_WORKER}" os.environ["NUMBA_CACHE_DIR"] = str(_NUMBA_CACHE) +# The sea-state batch workers keep persistent numba caches in the user cache +# directory; the tests give them a folder of this process, removed at the end. +_BATCH_CACHE: Path | None = None +if "CABLEXSEC_BATCH_CACHE_DIR" not in os.environ: + _BATCH_CACHE = Path(tempfile.gettempdir()) / f"cablexsec-batch-{os.getpid()}" + os.environ["CABLEXSEC_BATCH_CACHE_DIR"] = str(_BATCH_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) + """Remove the numba caches of this process at the end of the run.""" + for folder in (_NUMBA_CACHE, _BATCH_CACHE): + if folder is not None: + shutil.rmtree(folder, ignore_errors=True) diff --git a/tests/test_sea_state_batch_workers.py b/tests/test_sea_state_batch_workers.py new file mode 100644 index 0000000..b3c81d8 --- /dev/null +++ b/tests/test_sea_state_batch_workers.py @@ -0,0 +1,259 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""The worker processes of a sea-state batch each write their own numba cache. + +numba numbers a new on-disk cache entry from the index it last read, so two +processes compiling one kernel for different signatures at the same time can +leave the index pointing at the other's machine code. Each worker therefore +writes a slot directory whose lock it holds itself for as long as it runs, and +the slot is kept for later batches. +""" + +from __future__ import annotations + +import os +import sys +import tempfile +from collections.abc import Iterator +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack, contextmanager +from pathlib import Path + +import numpy as np +import pytest +from test_sea_state_batch import _runs + +import cablexsec as cx +import cablexsec.analysis.sea_state_batch as batch +from cablexsec._numba import kernels_compiled +from cablexsec.analysis.sea_state_batch import ( + SeaStateBatchOptions, + SectionRequest, + run_sea_state_batch, +) + +_ONE_THREAD = ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS") + + +@pytest.fixture(scope="module") +def cable(): + return cx.load_cable(cx.iea_task49_66kv_yaml_path(), geometry_override=None) + + +@pytest.fixture(scope="module") +def stiffness(cable): + return cx.compute_stiffness(cable) + + +@contextmanager +def _held(path: Path) -> Iterator[None]: + """Hold the slot lock ``path`` in this process, as another batch would.""" + path.parent.mkdir(parents=True, exist_ok=True) + with open(path, "a+b") as handle: + assert batch._lock(handle) + try: + yield + finally: + batch._unlock(handle) + + +def _caches(pools) -> list[Path]: + """The numba cache directory each worker runs with.""" + return [Path(pool.submit(os.getenv, "NUMBA_CACHE_DIR").result()) for pool in pools] + + +def _indexes(folder: Path) -> dict[str, int]: + """Modification times of the numba index files below ``folder``.""" + return { + str(p.relative_to(folder)): p.stat().st_mtime_ns for p in folder.rglob("*.nbi") + } + + +def test_each_worker_starts_with_its_own_numba_cache(tmp_path, monkeypatch): + caller = str(tmp_path / "caller") + monkeypatch.setenv("NUMBA_CACHE_DIR", caller) + caches = [tmp_path / f"cache-{i}" for i in range(3)] + pools = [batch._start_worker(cache) for cache in caches] + try: + assert _caches(pools) == caches + finally: + for pool in pools: + pool.shutdown() + assert os.environ["NUMBA_CACHE_DIR"] == caller + + +def test_workers_started_from_several_threads_keep_their_own_caches( + tmp_path, monkeypatch +): + caller = str(tmp_path / "caller") + monkeypatch.setenv("NUMBA_CACHE_DIR", caller) + caches = [tmp_path / f"cache-{i}" for i in range(2)] + with ThreadPoolExecutor(max_workers=2) as threads: + pools = list(threads.map(batch._start_worker, caches)) + try: + assert _caches(pools) == caches + finally: + for pool in pools: + pool.shutdown() + assert os.environ["NUMBA_CACHE_DIR"] == caller + + +def test_the_worker_holds_its_slot_for_as_long_as_it_runs(tmp_path): + lock = tmp_path / "slot-0.lock" + pool = batch._start_worker(tmp_path / "slot-0") + try: + assert pool.submit(batch._claim_slot, str(lock)).result() + # The slot is taken by the worker process itself, so it stays taken + # whatever happens to the process that started it. + assert not batch._slot_is_free(lock) + assert not pool.submit(batch._claim_slot, str(lock)).result() + finally: + pool.shutdown() + assert batch._slot_is_free(lock) + + +def test_slots_are_kept_and_a_second_batch_reuses_them( + tmp_path, monkeypatch, cable, stiffness +): + slots = tmp_path / "slots" + monkeypatch.setenv("CABLEXSEC_BATCH_CACHE_DIR", str(slots)) + runs = _runs( + tmp_path, + stiffness, + amplitudes=(0.01, 0.02, 0.015), + probabilities=(0.5, 0.3, 0.2), + ) + sections = [SectionRequest("a", 2.0)] + options = SeaStateBatchOptions(workers=2) + # First batch: two workers, each starting from an empty slot of its own. + first = run_sea_state_batch(cable, runs, sections, options=options) + written = {name: _indexes(slots / name) for name in ("slot-0", "slot-1")} + if kernels_compiled(): + assert all(written.values()), written + assert not (slots / "slot-2").exists() + # Second batch: the slots are reused, and no kernel is compiled again. + second = run_sea_state_batch(cable, runs, sections, options=options) + assert {name: _indexes(slots / name) for name in written} == written + one = run_sea_state_batch( + cable, runs, sections, options=SeaStateBatchOptions(workers=1) + ) + a = one.sections["a"].long_term.annual_damage_per_fibre + for result in (first, second): + b = result.sections["a"].long_term.annual_damage_per_fibre + for layer in a: + if all(os.environ.get(name) == "1" for name in _ONE_THREAD): + # The same kernels on one BLAS thread in every process. + np.testing.assert_array_equal(b[layer], a[layer]) + else: + # The workers run BLAS on one thread, this process on its own + # setting; threaded BLAS reductions differ at round-off. + np.testing.assert_allclose(b[layer], a[layer], rtol=1e-10, atol=0.0) + assert result.manifest["inputs_sha256"] == one.manifest["inputs_sha256"] + + +def test_a_batch_beside_another_takes_the_next_free_slots(tmp_path, monkeypatch): + slots = tmp_path / "slots" + monkeypatch.setenv("CABLEXSEC_BATCH_CACHE_DIR", str(slots)) + with _held(slots / "slot-0.lock"): + assert not batch._slot_is_free(slots / "slot-0.lock") + with batch._workers(2) as pools: + assert _caches(pools) == [slots / "slot-1", slots / "slot-2"] + assert not batch._slot_is_free(slots / "slot-1.lock") + assert batch._slot_is_free(slots / "slot-1.lock") + with batch._workers(2) as pools: + assert _caches(pools) == [slots / "slot-0", slots / "slot-1"] + + +def test_a_slot_won_by_another_process_meanwhile_is_skipped(tmp_path, monkeypatch): + slots = tmp_path / "slots" + monkeypatch.setenv("CABLEXSEC_BATCH_CACHE_DIR", str(slots)) + stack = ExitStack() + is_free = batch._slot_is_free + + def taken_after_the_check(path): + # Another batch takes slot 0 between the check and the worker's claim. + free = is_free(path) + if path.name == "slot-0.lock": + stack.enter_context(_held(path)) + return free + + started = [] + start = batch._start_worker + + def recording(cache): + started.append(cache) + return start(cache) + + monkeypatch.setattr(batch, "_slot_is_free", taken_after_the_check) + monkeypatch.setattr(batch, "_start_worker", recording) + with stack, batch._workers(1) as pools: + assert started == [slots / "slot-0", slots / "slot-1"] + assert _caches(pools) == [slots / "slot-1"] + + +def test_without_a_free_slot_a_worker_gets_a_temporary_cache(tmp_path, monkeypatch): + slots = tmp_path / "slots" + scratch = tmp_path / "tmp" + scratch.mkdir() + monkeypatch.setenv("CABLEXSEC_BATCH_CACHE_DIR", str(slots)) + monkeypatch.setattr(tempfile, "tempdir", str(scratch)) + with ExitStack() as stack: + for slot in range(batch._CACHE_SLOTS - 1): + stack.enter_context(_held(slots / f"slot-{slot}.lock")) + with batch._workers(3) as pools: + caches = _caches(pools) + assert caches[0] == slots / f"slot-{batch._CACHE_SLOTS - 1}" + assert [c.parent.parent for c in caches[1:]] == [scratch, scratch] + assert len(set(caches)) == 3 + assert list(scratch.iterdir()) == [] + + +def test_an_unusable_cache_folder_falls_back_to_temporary_caches(tmp_path, monkeypatch): + blocked = tmp_path / "file" + blocked.write_text("not a folder", encoding="utf-8") + monkeypatch.setenv("CABLEXSEC_BATCH_CACHE_DIR", str(blocked / "slots")) + with batch._workers(2) as pools: + caches = _caches(pools) + assert len(set(caches)) == 2 + assert all(blocked not in c.parents for c in caches) + + +def test_cache_folder_follows_the_override_and_the_platform(tmp_path, monkeypatch): + monkeypatch.setenv("CABLEXSEC_BATCH_CACHE_DIR", str(tmp_path / "mine")) + assert batch._batch_cache_directory() == tmp_path / "mine" + monkeypatch.delenv("CABLEXSEC_BATCH_CACHE_DIR") + monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local")) + monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "xdg")) + expected = { + "win32": tmp_path / "local", + "darwin": Path.home() / "Library" / "Caches", + }.get(sys.platform, tmp_path / "xdg") + assert batch._batch_cache_directory() == expected / "cablexsec" / "numba-batch" + + +def test_a_worker_that_fails_to_start_leaves_no_pool(tmp_path, monkeypatch): + started = [] + real = batch.ProcessPoolExecutor + + class Failing(real): + def submit(self, *args, **kwargs): + if self in started[1:2]: + raise RuntimeError("worker failed to start") + return super().submit(*args, **kwargs) + + def pool(*args, **kwargs): + started.append(Failing(*args, **kwargs)) + return started[-1] + + monkeypatch.setattr(batch, "ProcessPoolExecutor", pool) + monkeypatch.setenv("CABLEXSEC_BATCH_CACHE_DIR", str(tmp_path / "slots")) + monkeypatch.delenv("NUMBA_CACHE_DIR", raising=False) + with pytest.raises(RuntimeError, match="failed to start"), batch._workers(3): + pass + assert len(started) == 2 + # The started pool is shut down (the second one never ran), the first + # slot is free again, and the caller's environment is restored. + with pytest.raises(RuntimeError, match="after shutdown"): + started[0].submit(os.getpid) + assert batch._slot_is_free(tmp_path / "slots" / "slot-0.lock") + assert "NUMBA_CACHE_DIR" not in os.environ