"""Small runtime helpers for the isolated M2RL execution directory.""" from __future__ import annotations import hashlib import json import os import re import tempfile from pathlib import Path def require_allocation(): job = os.environ.get('SLURM_JOB_ID', '') cgroup = Path('/proc/self/cgroup').read_text() if not job.isdigit() or not re.search(r'(?:/|^)job_' + job + r'(?:/|$)', cgroup): raise RuntimeError('M2RL sustained work requires a real Slurm cgroup') if not os.environ.get('SLURM_CPUS_PER_TASK') or not os.environ.get('SLURM_MEM_PER_NODE'): raise RuntimeError('Explicit CPU and memory allocation required') return {'job_id': job, 'cgroup': cgroup.strip(), 'cpus': os.environ['SLURM_CPUS_PER_TASK'], 'memory_mb': os.environ['SLURM_MEM_PER_NODE']} def sha256(path): digest = hashlib.sha256() with open(path, 'rb') as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b''): digest.update(chunk) return digest.hexdigest() def atomic_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix=path.name + '.', dir=path.parent) try: with os.fdopen(fd, 'w') as stream: json.dump(value, stream, indent=2, ensure_ascii=False, allow_nan=False) stream.write('\n') stream.flush() os.fsync(stream.fileno()) os.replace(temporary, path) directory = os.open(path.parent, os.O_DIRECTORY) try: os.fsync(directory) finally: os.close(directory) finally: if os.path.exists(temporary): os.unlink(temporary)