From 118362e14ed2a0876f0ba1ce974ed3f836c6dcc0 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Thu, 19 Nov 2026 18:35:27 +0900 Subject: [PATCH 1/5] fix: sea-state batch workers write their own numba cache run_sea_state_batch with workers > 1 started its spawn workers with the caller's environment, so all of them shared one numba cache directory. numba numbers a new on-disk cache entry from the index it last read and saves the index before the data (numba/core/caching.py, IndexDataCacheFile.save): two workers compiling one kernel for different signatures at the same time could both take the same data file and leave the index pointing at the other's machine code, which a later process would load. Each worker is now a one-process spawn pool started while NUMBA_CACHE_DIR names its own directory in a temporary directory of the batch, removed afterwards; runs go to whichever worker is free, as with the shared pool. A worker that fails to start shuts down the pools already started, and the caller's NUMBA_CACHE_DIR is restored in every case. Each worker compiles the kernels it uses; results are unchanged. tests/test_sea_state_batch_workers.py: each worker sees its own cache directory; a cold-cache batch on two workers writes kernels into each worker's own directory, leaves nothing behind and matches the in-process batch; a failed start leaves no pool running. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 9 ++ src/cablexsec/analysis/sea_state_batch.py | 89 +++++++++++++-- tests/test_sea_state_batch_workers.py | 125 ++++++++++++++++++++++ 3 files changed, 212 insertions(+), 11 deletions(-) create mode 100644 tests/test_sea_state_batch_workers.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 52bf622..371ef6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -472,6 +472,15 @@ 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 its own numba cache + directory for the batch (removed afterwards) 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. Each worker + now compiles the kernels it uses; 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/src/cablexsec/analysis/sea_state_batch.py b/src/cablexsec/analysis/sea_state_batch.py index fcced0b..2944b04 100644 --- a/src/cablexsec/analysis/sea_state_batch.py +++ b/src/cablexsec/analysis/sea_state_batch.py @@ -39,7 +39,9 @@ Parallel execution ------------------ Runs are processed in worker processes (``workers``, at most -:data:`MAX_WORKERS`), each limited to one numerical thread. Results do not +:data:`MAX_WORKERS`), each limited to one numerical thread and writing its own +numba cache directory for the batch, so concurrent workers never share one +on-disk kernel cache; each compiles the kernels it uses. 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. @@ -54,9 +56,10 @@ import pickle import platform import sys +import tempfile import warnings from collections.abc import Mapping, Sequence -from concurrent.futures import ProcessPoolExecutor +from concurrent.futures import FIRST_COMPLETED, Future, ProcessPoolExecutor, wait from dataclasses import asdict, dataclass, field, fields from pathlib import Path from types import MappingProxyType @@ -109,6 +112,7 @@ "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS", ) +_NUMBA_CACHE_VARIABLE = "NUMBA_CACHE_DIR" __all__ = [ "MAX_WORKERS", @@ -468,6 +472,66 @@ def _fretting_summary(result: Any) -> dict[str, dict[str, Any]]: return out +def _worker_pools(count: int, cache_root: Path) -> list[ProcessPoolExecutor]: + """``count`` one-process spawn pools, each worker with its own numba cache. + + 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. Each worker is + therefore started while ``NUMBA_CACHE_DIR`` names its own directory below + ``cache_root``, which it inherits before numba is imported. + """ + import multiprocessing # noqa: PLC0415 + + context = multiprocessing.get_context("spawn") + previous = os.environ.get(_NUMBA_CACHE_VARIABLE) + pools: list[ProcessPoolExecutor] = [] + try: + for index in range(count): + pool = ProcessPoolExecutor( + max_workers=1, mp_context=context, initializer=_limit_threads + ) + pools.append(pool) + os.environ[_NUMBA_CACHE_VARIABLE] = str(cache_root / f"worker-{index}") + pool.submit(os.getpid).result() # the worker now runs with it + except BaseException: + for pool in pools: + 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 pools + + +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 +1043,23 @@ 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} + pools: list[ProcessPoolExecutor] = [] 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 tempfile.TemporaryDirectory( + prefix="cablexsec-batch-numba-", ignore_cleanup_errors=True + ) as cache_root: + try: + pools = _worker_pools( + min(opts.workers, len(tasks)), Path(cache_root) + ) + outcomes = _evaluate_in_pools(tasks, pools) + finally: + for pool in pools: + pool.shutdown(cancel_futures=True) finally: for name, value in saved.items(): if value is None: diff --git a/tests/test_sea_state_batch_workers.py b/tests/test_sea_state_batch_workers.py new file mode 100644 index 0000000..95e02d0 --- /dev/null +++ b/tests/test_sea_state_batch_workers.py @@ -0,0 +1,125 @@ +# 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. +""" + +from __future__ import annotations + +import os +import tempfile +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, +) + + +@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) + + +def test_each_worker_starts_with_its_own_numba_cache(tmp_path, monkeypatch): + caller = str(tmp_path / "caller") + monkeypatch.setenv("NUMBA_CACHE_DIR", caller) + pools = batch._worker_pools(3, tmp_path / "workers") + try: + seen = [pool.submit(os.getenv, "NUMBA_CACHE_DIR").result() for pool in pools] + finally: + for pool in pools: + pool.shutdown() + assert seen == [str(tmp_path / "workers" / f"worker-{i}") for i in range(3)] + assert os.environ["NUMBA_CACHE_DIR"] == caller + + +def test_cold_cache_workers_match_the_in_process_batch( + tmp_path, monkeypatch, cable, stiffness +): + # Three runs on two workers, each starting from an empty cache directory of + # its own below a fresh temporary directory, removed after the batch. + scratch = tmp_path / "tmp" + scratch.mkdir() + monkeypatch.setattr(tempfile, "tempdir", str(scratch)) + written: dict[str, list[str]] = {} + evaluate = batch._evaluate_in_pools + + def recording(tasks, pools): + outcomes = evaluate(tasks, pools) + for root in scratch.iterdir(): + for worker in sorted(root.iterdir()): + written[worker.name] = sorted(p.name for p in worker.rglob("*.nbi")) + return outcomes + + monkeypatch.setattr(batch, "_evaluate_in_pools", recording) + runs = _runs( + tmp_path, + stiffness, + amplitudes=(0.01, 0.02, 0.015), + probabilities=(0.5, 0.3, 0.2), + ) + sections = [SectionRequest("a", 2.0)] + two = run_sea_state_batch( + cable, runs, sections, options=SeaStateBatchOptions(workers=2) + ) + if kernels_compiled(): + # Each worker compiled its kernels into its own directory. + assert sorted(written) == ["worker-0", "worker-1"] + assert all(written.values()) + assert list(scratch.iterdir()) == [] + one = run_sea_state_batch( + cable, runs, sections, options=SeaStateBatchOptions(workers=1) + ) + a, b = one.sections["a"].long_term, two.sections["a"].long_term + # Equal to round-off: spawned workers run BLAS on one thread, the calling + # process on its own setting (as in test_worker_count_does_not_change_results). + for layer in a.annual_damage_per_fibre: + np.testing.assert_allclose( + a.annual_damage_per_fibre[layer], + b.annual_damage_per_fibre[layer], + rtol=1e-10, + atol=0.0, + ) + assert one.manifest["inputs_sha256"] == two.manifest["inputs_sha256"] + + +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.delenv("NUMBA_CACHE_DIR", raising=False) + with pytest.raises(RuntimeError, match="failed to start"): + batch._worker_pools(3, Path(tmp_path)) + assert len(started) == 2 + # Both pools are shut down, and the caller's environment is restored. + with pytest.raises(RuntimeError, match="after shutdown"): + started[0].submit(os.getpid) + assert "NUMBA_CACHE_DIR" not in os.environ From 875a313fc2681c8530d8078e44bd5502e48e4704 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Thu, 19 Nov 2026 18:46:01 +0900 Subject: [PATCH 2/5] fix: batch workers keep persistent per-slot numba caches A temporary cache per worker made every batch recompile every kernel in every worker. Worker i now writes the slot folder slot- under cablexsec/numba-batch in the user cache directory (LOCALAPPDATA on Windows, ~/Library/Caches on macOS, XDG_CACHE_HOME or ~/.cache elsewhere; CABLEXSEC_BATCH_CACHE_DIR overrides it), which later batches reuse. The batch holds a non-blocking exclusive lock file per slot (msvcrt or flock; released by the operating system if the process ends), so one slot is written by one process at a time. A batch beside another takes the next free slots out of 16; a worker without a free slot, or with an unwritable folder, gets a temporary cache that is removed afterwards. The tests give the batch caches a folder of the test process. New tests: slots are kept and a second batch compiles nothing (its index files are unchanged); results equal the in-process batch exactly when every process runs BLAS on one thread (as CI does), else to rtol 1e-10 with the reason stated; concurrent batches take the next free slots; the temporary fallback; an unusable folder; the platform folder and the override. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 15 ++- doc/global_local_guide.md | 7 +- src/cablexsec/analysis/sea_state_batch.py | 140 +++++++++++++++++++--- tests/conftest.py | 14 ++- tests/test_sea_state_batch_workers.py | 133 ++++++++++++++------ 5 files changed, 242 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 371ef6f..4180750 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -473,12 +473,15 @@ All notable changes to CableXSec are recorded in this file. The format follows 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 its own numba cache - directory for the batch (removed afterwards) 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. Each worker - now compiles the kernels it uses; results are unchanged, and runs go to whichever worker is +- `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; a lock file holds each slot for one worker at a time, 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 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 2944b04..b69157c 100644 --- a/src/cablexsec/analysis/sea_state_batch.py +++ b/src/cablexsec/analysis/sea_state_batch.py @@ -39,10 +39,14 @@ Parallel execution ------------------ Runs are processed in worker processes (``workers``, at most -:data:`MAX_WORKERS`), each limited to one numerical thread and writing its own -numba cache directory for the batch, so concurrent workers never share one -on-disk kernel cache; each compiles the kernels it uses. Results do not -depend on the worker count. The output directory, if given, must not exist: +: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. A slot is locked while its worker 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. """ @@ -58,8 +62,9 @@ import sys import tempfile import warnings -from collections.abc import Mapping, Sequence +from collections.abc import Iterator, Mapping, Sequence from concurrent.futures import FIRST_COMPLETED, Future, ProcessPoolExecutor, wait +from contextlib import ExitStack, contextmanager from dataclasses import asdict, dataclass, field, fields from pathlib import Path from types import MappingProxyType @@ -113,6 +118,10 @@ "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", @@ -472,15 +481,114 @@ def _fretting_summary(result: Any) -> dict[str, dict[str, Any]]: return out -def _worker_pools(count: int, cache_root: Path) -> list[ProcessPoolExecutor]: - """``count`` one-process spawn pools, each worker with its own numba cache. +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) + + +@contextmanager +def _slot_lock(path: Path) -> Iterator[bool]: + """Hold the lock file ``path`` while the block runs; yield whether it was won. + + The operating system also releases the lock if the holding process ends. + """ + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = open(path, "a+b") # noqa: SIM115 - closed below + except OSError: + yield False + return + with handle: + won = _lock(handle) + try: + yield won + finally: + if won: + _unlock(handle) + + +@contextmanager +def _worker_caches(count: int) -> Iterator[list[Path]]: + """``count`` numba cache directories, each written by one process only. 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. Each worker is - therefore started while ``NUMBA_CACHE_DIR`` names its own directory below - ``cache_root``, which it inherits before numba is imported. + and leave the index pointing at the other's machine code. The first free + slots of :func:`_batch_cache_directory` are locked for the batch and kept + for later batches; a worker without a free slot gets a temporary + directory, removed afterwards. + """ + root = _batch_cache_directory() + with ExitStack() as stack: + caches: list[Path] = [] + for slot in range(_CACHE_SLOTS): + if len(caches) == count: + break + if stack.enter_context(_slot_lock(root / f"slot-{slot}.lock")): + caches.append(root / f"slot-{slot}") + if len(caches) < count: + scratch = stack.enter_context( + tempfile.TemporaryDirectory( + prefix="cablexsec-batch-numba-", ignore_cleanup_errors=True + ) + ) + missing = count - len(caches) + caches += [Path(scratch) / f"worker-{i}" for i in range(missing)] + yield caches + + +def _worker_pools(caches: Sequence[Path]) -> list[ProcessPoolExecutor]: + """One-process spawn pools; worker ``i`` writes the numba cache ``caches[i]``. + + Each worker is started while ``NUMBA_CACHE_DIR`` names its directory, and + inherits it before numba is imported (see :func:`_worker_caches`). """ import multiprocessing # noqa: PLC0415 @@ -488,12 +596,12 @@ def _worker_pools(count: int, cache_root: Path) -> list[ProcessPoolExecutor]: previous = os.environ.get(_NUMBA_CACHE_VARIABLE) pools: list[ProcessPoolExecutor] = [] try: - for index in range(count): + for cache in caches: pool = ProcessPoolExecutor( max_workers=1, mp_context=context, initializer=_limit_threads ) pools.append(pool) - os.environ[_NUMBA_CACHE_VARIABLE] = str(cache_root / f"worker-{index}") + os.environ[_NUMBA_CACHE_VARIABLE] = str(cache) pool.submit(os.getpid).result() # the worker now runs with it except BaseException: for pool in pools: @@ -1049,13 +1157,9 @@ def run_sea_state_batch( # Spawned workers inherit one-thread settings before any import. for name in _THREAD_VARIABLES: os.environ[name] = "1" - with tempfile.TemporaryDirectory( - prefix="cablexsec-batch-numba-", ignore_cleanup_errors=True - ) as cache_root: + with _worker_caches(min(opts.workers, len(tasks))) as caches: try: - pools = _worker_pools( - min(opts.workers, len(tasks)), Path(cache_root) - ) + pools = _worker_pools(caches) outcomes = _evaluate_in_pools(tasks, pools) finally: for pool in pools: 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 index 95e02d0..a54ec02 100644 --- a/tests/test_sea_state_batch_workers.py +++ b/tests/test_sea_state_batch_workers.py @@ -4,13 +4,17 @@ 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. +leave the index pointing at the other's machine code. Each worker therefore +writes a slot directory that it alone holds while it runs, and the slot is kept +for later batches. """ from __future__ import annotations import os +import sys import tempfile +from contextlib import ExitStack from pathlib import Path import numpy as np @@ -26,6 +30,8 @@ run_sea_state_batch, ) +_ONE_THREAD = ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS") + @pytest.fixture(scope="module") def cable(): @@ -37,38 +43,32 @@ def stiffness(cable): return cx.compute_stiffness(cable) +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) - pools = batch._worker_pools(3, tmp_path / "workers") + caches = [tmp_path / f"cache-{i}" for i in range(3)] + pools = batch._worker_pools(caches) try: seen = [pool.submit(os.getenv, "NUMBA_CACHE_DIR").result() for pool in pools] finally: for pool in pools: pool.shutdown() - assert seen == [str(tmp_path / "workers" / f"worker-{i}") for i in range(3)] + assert seen == [str(cache) for cache in caches] assert os.environ["NUMBA_CACHE_DIR"] == caller -def test_cold_cache_workers_match_the_in_process_batch( +def test_slots_are_kept_and_a_second_batch_reuses_them( tmp_path, monkeypatch, cable, stiffness ): - # Three runs on two workers, each starting from an empty cache directory of - # its own below a fresh temporary directory, removed after the batch. - scratch = tmp_path / "tmp" - scratch.mkdir() - monkeypatch.setattr(tempfile, "tempdir", str(scratch)) - written: dict[str, list[str]] = {} - evaluate = batch._evaluate_in_pools - - def recording(tasks, pools): - outcomes = evaluate(tasks, pools) - for root in scratch.iterdir(): - for worker in sorted(root.iterdir()): - written[worker.name] = sorted(p.name for p in worker.rglob("*.nbi")) - return outcomes - - monkeypatch.setattr(batch, "_evaluate_in_pools", recording) + slots = tmp_path / "slots" + monkeypatch.setenv("CABLEXSEC_BATCH_CACHE_DIR", str(slots)) runs = _runs( tmp_path, stiffness, @@ -76,28 +76,83 @@ def recording(tasks, pools): probabilities=(0.5, 0.3, 0.2), ) sections = [SectionRequest("a", 2.0)] - two = run_sea_state_batch( - cable, runs, sections, options=SeaStateBatchOptions(workers=2) - ) + 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(): - # Each worker compiled its kernels into its own directory. - assert sorted(written) == ["worker-0", "worker-1"] - assert all(written.values()) - assert list(scratch.iterdir()) == [] + 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, b = one.sections["a"].long_term, two.sections["a"].long_term - # Equal to round-off: spawned workers run BLAS on one thread, the calling - # process on its own setting (as in test_worker_count_does_not_change_results). - for layer in a.annual_damage_per_fibre: - np.testing.assert_allclose( - a.annual_damage_per_fibre[layer], - b.annual_damage_per_fibre[layer], - rtol=1e-10, - atol=0.0, - ) - assert one.manifest["inputs_sha256"] == two.manifest["inputs_sha256"] + 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 batch._slot_lock(slots / "slot-0.lock") as held: + assert held + with batch._slot_lock(slots / "slot-0.lock") as again: + assert not again # one holder at a time, also within one process + with batch._worker_caches(2) as caches: + assert caches == [slots / "slot-1", slots / "slot-2"] + with batch._worker_caches(2) as caches: + assert caches == [slots / "slot-0", 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): + assert stack.enter_context(batch._slot_lock(slots / f"slot-{slot}.lock")) + with batch._worker_caches(3) as caches: + last = batch._CACHE_SLOTS - 1 + assert caches[0] == slots / f"slot-{last}" + 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._worker_caches(2) as caches: + 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): @@ -117,7 +172,7 @@ def pool(*args, **kwargs): monkeypatch.setattr(batch, "ProcessPoolExecutor", pool) monkeypatch.delenv("NUMBA_CACHE_DIR", raising=False) with pytest.raises(RuntimeError, match="failed to start"): - batch._worker_pools(3, Path(tmp_path)) + batch._worker_pools([tmp_path / f"cache-{i}" for i in range(3)]) assert len(started) == 2 # Both pools are shut down, and the caller's environment is restored. with pytest.raises(RuntimeError, match="after shutdown"): From 86f979c381ecf2bdf1b13375a1ec4a3a9d21e283 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Thu, 19 Nov 2026 18:55:09 +0900 Subject: [PATCH 3/5] fix: each batch worker holds its own slot lock The caller held the slot locks. If it was killed while a worker was still compiling, the locks were released at once while the orphaned worker kept writing its cache, and a later batch could take the same slot. The worker now locks its slot itself (_claim_slot, its first task) and holds it for its lifetime; the operating system releases it when the worker ends. The caller only checks that a slot looks free before starting a worker on it; if another process wins the slot meanwhile, the claim fails, that worker is shut down and the next slot is tried. Temporary fallback caches are removed after every pool has shut down. Tests: the worker, not the caller, holds the slot while it runs; a slot taken between the check and the claim is skipped. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 7 +- src/cablexsec/analysis/sea_state_batch.py | 157 ++++++++++++---------- tests/test_sea_state_batch_workers.py | 110 +++++++++++---- 3 files changed, 177 insertions(+), 97 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4180750..fdaf07b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -479,9 +479,10 @@ All notable changes to CableXSec are recorded in this file. The format follows 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; a lock file holds each slot for one worker at a time, 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 + 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 diff --git a/src/cablexsec/analysis/sea_state_batch.py b/src/cablexsec/analysis/sea_state_batch.py index b69157c..bab51ee 100644 --- a/src/cablexsec/analysis/sea_state_batch.py +++ b/src/cablexsec/analysis/sea_state_batch.py @@ -43,8 +43,8 @@ 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. A slot is locked while its worker runs, so no two processes write one -cache; a batch beside another takes the next free slots, and a worker +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 @@ -64,7 +64,7 @@ import warnings from collections.abc import Iterator, Mapping, Sequence from concurrent.futures import FIRST_COMPLETED, Future, ProcessPoolExecutor, wait -from contextlib import ExitStack, contextmanager +from contextlib import contextmanager from dataclasses import asdict, dataclass, field, fields from pathlib import Path from types import MappingProxyType @@ -532,87 +532,110 @@ def _unlock(handle: Any) -> None: fcntl.flock(handle.fileno(), fcntl.LOCK_UN) -@contextmanager -def _slot_lock(path: Path) -> Iterator[bool]: - """Hold the lock file ``path`` while the block runs; yield whether it was won. - - The operating system also releases the lock if the holding process ends. - """ +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) - handle = open(path, "a+b") # noqa: SIM115 - closed below + with open(path, "a+b") as handle: + if not _lock(handle): + return False + _unlock(handle) except OSError: - yield False - return - with handle: - won = _lock(handle) - try: - yield won - finally: - if won: - _unlock(handle) + return False + return True -@contextmanager -def _worker_caches(count: int) -> Iterator[list[Path]]: - """``count`` numba cache directories, each written by one process only. +#: The slot lock a worker process holds for its lifetime (see _claim_slot). +_SLOT_HANDLE: Any = None - 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. The first free - slots of :func:`_batch_cache_directory` are locked for the batch and kept - for later batches; a worker without a free slot gets a temporary - directory, removed afterwards. + +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. """ - root = _batch_cache_directory() - with ExitStack() as stack: - caches: list[Path] = [] - for slot in range(_CACHE_SLOTS): - if len(caches) == count: - break - if stack.enter_context(_slot_lock(root / f"slot-{slot}.lock")): - caches.append(root / f"slot-{slot}") - if len(caches) < count: - scratch = stack.enter_context( - tempfile.TemporaryDirectory( - prefix="cablexsec-batch-numba-", ignore_cleanup_errors=True - ) - ) - missing = count - len(caches) - caches += [Path(scratch) / f"worker-{i}" for i in range(missing)] - yield caches + 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 _worker_pools(caches: Sequence[Path]) -> list[ProcessPoolExecutor]: - """One-process spawn pools; worker ``i`` writes the numba cache ``caches[i]``. +def _start_worker(cache: Path) -> ProcessPoolExecutor: + """A one-process spawn pool whose worker writes the numba cache ``cache``. - Each worker is started while ``NUMBA_CACHE_DIR`` names its directory, and - inherits it before numba is imported (see :func:`_worker_caches`). + The worker is started while ``NUMBA_CACHE_DIR`` names ``cache`` and + inherits it before numba is imported; the caller's value is restored. """ import multiprocessing # noqa: PLC0415 - context = multiprocessing.get_context("spawn") + pool = ProcessPoolExecutor( + max_workers=1, + mp_context=multiprocessing.get_context("spawn"), + initializer=_limit_threads, + ) previous = os.environ.get(_NUMBA_CACHE_VARIABLE) - pools: list[ProcessPoolExecutor] = [] + os.environ[_NUMBA_CACHE_VARIABLE] = str(cache) try: - for cache in caches: - pool = ProcessPoolExecutor( - max_workers=1, mp_context=context, initializer=_limit_threads - ) - pools.append(pool) - os.environ[_NUMBA_CACHE_VARIABLE] = str(cache) - pool.submit(os.getpid).result() # the worker now runs with it + pool.submit(os.getpid).result() # the worker now runs with it except BaseException: - for pool in pools: - pool.shutdown(cancel_futures=True) + 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 pools + 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( @@ -1152,18 +1175,12 @@ def run_sea_state_batch( outcomes = [_evaluate(task) for task in tasks] else: saved = {name: os.environ.get(name) for name in _THREAD_VARIABLES} - pools: list[ProcessPoolExecutor] = [] try: # Spawned workers inherit one-thread settings before any import. for name in _THREAD_VARIABLES: os.environ[name] = "1" - with _worker_caches(min(opts.workers, len(tasks))) as caches: - try: - pools = _worker_pools(caches) - outcomes = _evaluate_in_pools(tasks, pools) - finally: - for pool in pools: - pool.shutdown(cancel_futures=True) + 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/test_sea_state_batch_workers.py b/tests/test_sea_state_batch_workers.py index a54ec02..f0b7833 100644 --- a/tests/test_sea_state_batch_workers.py +++ b/tests/test_sea_state_batch_workers.py @@ -5,8 +5,8 @@ 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 that it alone holds while it runs, and the slot is kept -for later batches. +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 @@ -14,7 +14,8 @@ import os import sys import tempfile -from contextlib import ExitStack +from collections.abc import Iterator +from contextlib import ExitStack, contextmanager from pathlib import Path import numpy as np @@ -43,6 +44,23 @@ 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 { @@ -54,16 +72,29 @@ 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._worker_pools(caches) + pools = [batch._start_worker(cache) for cache in caches] try: - seen = [pool.submit(os.getenv, "NUMBA_CACHE_DIR").result() for pool in pools] + assert _caches(pools) == caches finally: for pool in pools: pool.shutdown() - assert seen == [str(cache) for cache in caches] 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 ): @@ -106,14 +137,41 @@ def test_slots_are_kept_and_a_second_batch_reuses_them( 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 batch._slot_lock(slots / "slot-0.lock") as held: - assert held - with batch._slot_lock(slots / "slot-0.lock") as again: - assert not again # one holder at a time, also within one process - with batch._worker_caches(2) as caches: - assert caches == [slots / "slot-1", slots / "slot-2"] - with batch._worker_caches(2) as caches: - assert caches == [slots / "slot-0", slots / "slot-1"] + 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): @@ -124,10 +182,10 @@ def test_without_a_free_slot_a_worker_gets_a_temporary_cache(tmp_path, monkeypat monkeypatch.setattr(tempfile, "tempdir", str(scratch)) with ExitStack() as stack: for slot in range(batch._CACHE_SLOTS - 1): - assert stack.enter_context(batch._slot_lock(slots / f"slot-{slot}.lock")) - with batch._worker_caches(3) as caches: - last = batch._CACHE_SLOTS - 1 - assert caches[0] == slots / f"slot-{last}" + 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()) == [] @@ -137,9 +195,10 @@ def test_an_unusable_cache_folder_falls_back_to_temporary_caches(tmp_path, monke blocked = tmp_path / "file" blocked.write_text("not a folder", encoding="utf-8") monkeypatch.setenv("CABLEXSEC_BATCH_CACHE_DIR", str(blocked / "slots")) - with batch._worker_caches(2) as caches: - assert len(set(caches)) == 2 - assert all(blocked not in c.parents for c in caches) + 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): @@ -170,11 +229,14 @@ def pool(*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._worker_pools([tmp_path / f"cache-{i}" for i in range(3)]) + with pytest.raises(RuntimeError, match="failed to start"), batch._workers(3): + pass assert len(started) == 2 - # Both pools are shut down, and the caller's environment is restored. + # 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 From b5805b5fcdd3c43fcc395806c87e7db0c339d91b Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Thu, 19 Nov 2026 19:00:42 +0900 Subject: [PATCH 4/5] fix: start batch workers one at a time when changing NUMBA_CACHE_DIR Two batches that start workers from different threads of one process could interleave their changes of the process-wide NUMBA_CACHE_DIR, so that both workers inherited the same cache directory and the caller's value was not restored. _start_worker now holds a process-wide lock around the whole save, set, spawn and restore sequence. Also rewraps a module docstring line over the line limit. Test: workers started from two threads at once each run with their own cache directory, and the caller's value is restored. Signed-off-by: Jae Hoon Seo --- src/cablexsec/analysis/sea_state_batch.py | 42 +++++++++++++---------- tests/test_sea_state_batch_workers.py | 17 +++++++++ 2 files changed, 41 insertions(+), 18 deletions(-) diff --git a/src/cablexsec/analysis/sea_state_batch.py b/src/cablexsec/analysis/sea_state_batch.py index bab51ee..2c22c7a 100644 --- a/src/cablexsec/analysis/sea_state_batch.py +++ b/src/cablexsec/analysis/sea_state_batch.py @@ -44,11 +44,11 @@ ``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. +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 @@ -61,6 +61,7 @@ import platform import sys import tempfile +import threading import warnings from collections.abc import Iterator, Mapping, Sequence from concurrent.futures import FIRST_COMPLETED, Future, ProcessPoolExecutor, wait @@ -547,6 +548,8 @@ def _slot_is_free(path: Path) -> bool: #: 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: @@ -572,7 +575,9 @@ 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. + 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 @@ -581,18 +586,19 @@ def _start_worker(cache: Path) -> ProcessPoolExecutor: mp_context=multiprocessing.get_context("spawn"), initializer=_limit_threads, ) - 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 + 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 diff --git a/tests/test_sea_state_batch_workers.py b/tests/test_sea_state_batch_workers.py index f0b7833..b3c81d8 100644 --- a/tests/test_sea_state_batch_workers.py +++ b/tests/test_sea_state_batch_workers.py @@ -15,6 +15,7 @@ import sys import tempfile from collections.abc import Iterator +from concurrent.futures import ThreadPoolExecutor from contextlib import ExitStack, contextmanager from pathlib import Path @@ -81,6 +82,22 @@ def test_each_worker_starts_with_its_own_numba_cache(tmp_path, monkeypatch): 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") From fc12715bb250d99cfe734dd8f5780f488ab162ed Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Thu, 19 Nov 2026 20:28:49 +0900 Subject: [PATCH 5/5] docs: rewrap the batch cache CHANGELOG entry after the rebase Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fdaf07b..68daa36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -482,8 +482,7 @@ All notable changes to CableXSec are recorded in this file. The format follows 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. + 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