From 31cc8c00a8ab0feeaf10a092a7aebde80a06ce60 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 12 Nov 2026 09:59:59 +0000 Subject: [PATCH] fix(campaign): optional cache_root keeps job temp files and caches off $HOME A campaign.yaml can name `cache_root:`; the generated Slurm script then fills unset TMPDIR, XDG_CACHE_HOME and the pip/matplotlib/numba/CUDA/Triton/astropy/ JAX cache variables under it (JAX with ${VAR-...} so an empty value still disables the cache). Stage env still wins. On RAL, compute nodes keep $HOME and /tmp on a tiny local disk that these tools filled (admin 2026-11-12). No change for campaigns without cache_root. Refs #1767 Co-Authored-By: Claude Opus 5.5 --- autofit/campaign/scheduler/base.py | 1 + autofit/campaign/scheduler/slurm.py | 41 +++++++++++++++++++++ autofit/campaign/spec.py | 7 ++++ autofit/campaign/submit.py | 1 + test_autofit/campaign/test_slurm.py | 54 ++++++++++++++++++++++++++++ test_autofit/campaign/test_spec.py | 7 ++++ test_autofit/campaign/test_submit.py | 8 +++++ 7 files changed, 119 insertions(+) diff --git a/autofit/campaign/scheduler/base.py b/autofit/campaign/scheduler/base.py index 0a496e849..8205e5459 100644 --- a/autofit/campaign/scheduler/base.py +++ b/autofit/campaign/scheduler/base.py @@ -179,6 +179,7 @@ class SubmitRequest: env: Dict[str, str] = field(default_factory=dict) after: Dict[str, str] = field(default_factory=dict) log_dir: Optional[str] = None + cache_root: Optional[str] = None @property def task_ids(self) -> List[int]: diff --git a/autofit/campaign/scheduler/slurm.py b/autofit/campaign/scheduler/slurm.py index b4f99f19f..416fb6120 100644 --- a/autofit/campaign/scheduler/slurm.py +++ b/autofit/campaign/scheduler/slurm.py @@ -12,6 +12,7 @@ partition: CPU-only work never goes on a GPU partition. """ import logging +import re import shlex import subprocess from typing import Callable, Dict, List, Optional, Sequence @@ -46,6 +47,45 @@ def _export(key: str, value: str) -> str: return f"export {key}={shlex.quote(value)}" +# Where a job's temp files and tool caches go when the campaign names a ``cache_root``. +# On many clusters (RAL: every compute node) $HOME and /tmp sit on a small local OS +# disk that compute nodes do not share with the login node; pip, matplotlib, numba, +# CUDA/Triton, astropy, the PyAutoNerves JAX compile cache and Python's tempfile all +# default there and can fill it and crash the node (RAL admin, 2026-09-25 and +# 2026-11-12). Values are relative to ``cache_root``. +CACHE_DIRS = ( + ("TMPDIR", "tmp"), + ("XDG_CACHE_HOME", ".cache"), + ("PIP_CACHE_DIR", ".cache/pip"), + ("MPLCONFIGDIR", ".cache/matplotlib"), + ("NUMBA_CACHE_DIR", ".cache/numba"), + ("CUDA_CACHE_PATH", ".cache/nv"), + ("TRITON_CACHE_DIR", ".cache/triton"), + ("ASTROPY_CACHE_DIR", ".cache/astropy"), + ("JAX_COMPILATION_CACHE_DIR", ".cache/pyauto_jax"), +) + + +def _cache_exports(cache_root: str) -> List[str]: + """ + Fill-if-unset exports sending temp files and caches under ``cache_root``. + + A value already in the job's environment (for example from the submitting shell) + wins. ``JAX_COMPILATION_CACHE_DIR`` uses ``${VAR-...}`` so an explicitly empty value + still disables the JAX cache. A stage's own ``env`` is exported afterwards and so + overrides these. + """ + root = cache_root.rstrip("/") or "/" + lines = [] + for key, relative in CACHE_DIRS: + operator = "-" if key == "JAX_COMPILATION_CACHE_DIR" else ":-" + # The default sits inside "${...}", so escape for a double-quoted context. + path = re.sub(r'([\\"$`])', r"\\\1", f"{root}/{relative}") + lines.append(f'export {key}="${{{key}{operator}{path}}}"') + lines.append('mkdir -p "$TMPDIR" "$XDG_CACHE_HOME" 2>/dev/null || true') + return lines + + def sbatch_script(request: SubmitRequest) -> str: """ The batch script of one array. @@ -99,6 +139,7 @@ def sbatch_script(request: SubmitRequest) -> str: lines += [ "", "set -euo pipefail", + *(_cache_exports(request.cache_root) if request.cache_root else []), *(_export(key, value) for key, value in env.items()), 'export CAMPAIGN_INDEX=$((CAMPAIGN_OFFSET + SLURM_ARRAY_TASK_ID))', f"cd {shlex.quote(str(request.project_root))}", diff --git a/autofit/campaign/spec.py b/autofit/campaign/spec.py index ebc950bda..9965e1955 100644 --- a/autofit/campaign/spec.py +++ b/autofit/campaign/spec.py @@ -9,6 +9,7 @@ manifest_fields: [sample, tile] # optional names for a line's fields chunk: 1000 # tasks per array, ≤ the site's max_array_size site: ral # autonerves site layer + cache_root: /mnt/ral/jnightin # optional: TMPDIR + caches go here scheduler: slurm # slurm (default) or local status_root: output # where fits write *.status.json log_dir: hpc/logs @@ -59,6 +60,7 @@ "manifest_separator", "chunk", "site", + "cache_root", "scheduler", "status_root", "log_dir", @@ -185,6 +187,7 @@ def __init__(self, raw: Dict, source: Optional[Path] = None): self.manifest_separator = raw.get("manifest_separator") self.chunk = raw.get("chunk") self.site_name = raw.get("site") + self.cache_root = raw.get("cache_root") self.scheduler = raw.get("scheduler", "slurm") self.status_root = raw.get("status_root", "output") self.log_dir = raw.get("log_dir", "hpc/logs") @@ -387,6 +390,10 @@ def validate(self) -> List[str]: errors.append(f"scheduler: {self.scheduler!r} is not one of {sorted(SCHEDULERS)}") if self.chunk is not None and (not isinstance(self.chunk, int) or self.chunk < 1): errors.append(f"chunk: must be a positive integer, not {self.chunk!r}") + if self.cache_root is not None and ( + not isinstance(self.cache_root, str) or not self.cache_root.startswith("/") + ): + errors.append(f"cache_root: must be an absolute path, not {self.cache_root!r}") site = None if self.site_name: diff --git a/autofit/campaign/submit.py b/autofit/campaign/submit.py index dc1fdeef7..8718c93b8 100644 --- a/autofit/campaign/submit.py +++ b/autofit/campaign/submit.py @@ -81,6 +81,7 @@ def requests_for( manifest=str(campaign.path(campaign.manifest_path)), env=dict(stage.env), log_dir=campaign.log_dir, + cache_root=campaign.cache_root, ) ) return requests diff --git a/test_autofit/campaign/test_slurm.py b/test_autofit/campaign/test_slurm.py index 5afb35838..fc1b9a28c 100644 --- a/test_autofit/campaign/test_slurm.py +++ b/test_autofit/campaign/test_slurm.py @@ -78,6 +78,60 @@ def test_sbatch_script(): assert "--gres" not in script +def test_sbatch_script_without_cache_root_sets_no_cache_variables(): + script = sbatch_script(_request()) + assert "TMPDIR" not in script + assert "XDG_CACHE_HOME" not in script + + +def test_sbatch_script_cache_root_exports_fill_if_unset(): + request = _request() + request.cache_root = "/mnt/ral/x/" + lines = sbatch_script(request).splitlines() + for line in [ + 'export TMPDIR="${TMPDIR:-/mnt/ral/x/tmp}"', + 'export XDG_CACHE_HOME="${XDG_CACHE_HOME:-/mnt/ral/x/.cache}"', + 'export NUMBA_CACHE_DIR="${NUMBA_CACHE_DIR:-/mnt/ral/x/.cache/numba}"', + # "-" not ":-": an explicitly empty value still disables the JAX cache. + 'export JAX_COMPILATION_CACHE_DIR="${JAX_COMPILATION_CACHE_DIR-/mnt/ral/x/.cache/pyauto_jax}"', + 'mkdir -p "$TMPDIR" "$XDG_CACHE_HOME" 2>/dev/null || true', + ]: + assert line in lines, line + # After `set -euo pipefail` and before the stage env, so a stage env value wins. + assert lines.index("set -euo pipefail") < lines.index('export TMPDIR="${TMPDIR:-/mnt/ral/x/tmp}"') + assert lines.index('export TMPDIR="${TMPDIR:-/mnt/ral/x/tmp}"') < lines.index("export NAME='a b'") + + +def _cache_env(tmp_path, cache_root, environment): + """Run the cache block of a generated script under bash; return its TMPDIR and JAX cache.""" + import shutil + + if shutil.which("bash") is None: + pytest.skip("needs bash") + request = _request() + request.cache_root = cache_root + request.env = {} + script = sbatch_script(request).split("export PYTHONUNBUFFERED", 1)[0] + script += 'printf "%s\\n%s" "$TMPDIR" "${JAX_COMPILATION_CACHE_DIR-unset}"' + completed = subprocess.run( + ["bash", "-c", script], env=environment, capture_output=True, text=True, check=True + ) + return completed.stdout.split("\n") + + +def test_sbatch_script_cache_block_runs_under_bash(tmp_path): + root = str(tmp_path / "a b$c") + tmpdir, jax = _cache_env(tmp_path, root, {"PATH": "/usr/bin:/bin"}) + assert tmpdir == f"{root}/tmp" + assert jax == f"{root}/.cache/pyauto_jax" + assert (tmp_path / "a b$c" / "tmp").is_dir() + # The job's own environment wins; an explicitly empty JAX cache stays empty. + tmpdir, jax = _cache_env( + tmp_path, root, {"PATH": "/usr/bin:/bin", "TMPDIR": "/scratch", "JAX_COMPILATION_CACHE_DIR": ""} + ) + assert (tmpdir, jax) == ("/scratch", "") + + def _run_generated_script(tmp_path, fit_body, signal_usr1): """Run the generated batch script under bash, with a stand-in fit.""" import os diff --git a/test_autofit/campaign/test_spec.py b/test_autofit/campaign/test_spec.py index eaa5d107a..5bd4a4df6 100644 --- a/test_autofit/campaign/test_spec.py +++ b/test_autofit/campaign/test_spec.py @@ -66,6 +66,13 @@ def test_unknown_retry_class(tmp_path): assert "unknown failure class 'segfault'" in _errors(tmp_path, "retry: {{timeout", "retry: {{segfault: none, timeout") +def test_cache_root(tmp_path): + path = write_campaign(tmp_path / "p", CAMPAIGN.replace("site: ral\n", "site: ral\ncache_root: /mnt/ral/x\n")) + assert Campaign.load(path).cache_root == "/mnt/ral/x" + assert Campaign.load(write_campaign(tmp_path / "q")).cache_root is None + assert "cache_root: must be an absolute path" in _errors(tmp_path, "site: ral\n", "site: ral\ncache_root: scratch\n") + + def test_cycle(tmp_path): text = CAMPAIGN.replace(" script: scripts/fit.py --stage=vis_lp", " after: {{sed: aftercorr}}\n script: scripts/fit.py --stage=vis_lp") message = _errors(tmp_path, CAMPAIGN, text) diff --git a/test_autofit/campaign/test_submit.py b/test_autofit/campaign/test_submit.py index 8ad95e345..5ffd4cb53 100644 --- a/test_autofit/campaign/test_submit.py +++ b/test_autofit/campaign/test_submit.py @@ -71,3 +71,11 @@ def test_dry_run(campaign_file): assert "#SBATCH --dependency=aftercorr:" in entries[4]["script"] assert entries[0]["lint"] == "ok" assert not campaign.directory.exists() + + +def test_dry_run_carries_cache_root(tmp_path): + from test_autofit.campaign.conftest import CAMPAIGN, write_campaign + + path = write_campaign(tmp_path / "p", CAMPAIGN.replace("site: ral\n", "site: ral\ncache_root: /mnt/ral/x\n")) + entries = submit(Campaign.load(path), None, dry_run=True) + assert 'export TMPDIR="${TMPDIR:-/mnt/ral/x/tmp}"' in entries[0]["script"].splitlines()