From e98d4ccd89812bfa893f159b36640c8f8062e59d Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 28 Oct 2026 21:36:06 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20results-library=20phase=200a=20?= =?UTF-8?q?=E2=80=94=20artefact=20integrity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - zip_directory writes .zip..tmp and os.replace-s it into place, so a result zip is complete or absent; .png/.fits/.hdf/.hdf5/.h5 members are ZIP_STORED, text DEFLATED (also used by preserve_in_zip appends). - restore() is non-destructive: a complete output directory is left untouched, a zip is extracted into a temporary sibling and renamed into place (safe for concurrent restorers), the zip is deleted only when owned (remove_files and an identifier-keyed path), and a BadZipFile zip is renamed .zip.corrupt_ and the search continues as not complete. - New read-only open_result() (output directory or zipfile.Path, never extracts). - DirectoryPaths.is_complete reads a zipped result: .completed member + clean testzip(), cached per path by (size, mtime). - Checkpointer.probe / probe_hdf5 / quarantine_search_internal / resume_state_usable: Nautilus (h5py probe) and dynesty (savestate restore probe) move an unreadable search_internal/ to search_internal.failed_/ and start fresh; Nautilus retries once from scratch on a LinAlgError when resumed. - Timer writes files/.start_time and files/.time atomically behind has_timer, reading the legacy files/search_internal/ location as a fallback. Refs #1734 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016nhQ8N4RdvbZz9cstLYtNF --- autofit/non_linear/checkpoint.py | 106 ++++ autofit/non_linear/paths/abstract.py | 201 +++++++- autofit/non_linear/paths/directory.py | 10 +- autofit/non_linear/search/abstract_search.py | 7 +- .../search/nest/dynesty/search/abstract.py | 5 +- .../non_linear/search/nest/nautilus/search.py | 26 +- autofit/non_linear/timer.py | 73 ++- autofit/tools/util.py | 55 +- .../paths/test_artefact_integrity.py | 477 ++++++++++++++++++ .../search/test_conformance_backend.py | 4 +- 10 files changed, 899 insertions(+), 65 deletions(-) create mode 100644 test_autofit/non_linear/paths/test_artefact_integrity.py diff --git a/autofit/non_linear/checkpoint.py b/autofit/non_linear/checkpoint.py index 6e5d2fed8..f40d8d3bf 100644 --- a/autofit/non_linear/checkpoint.py +++ b/autofit/non_linear/checkpoint.py @@ -30,11 +30,17 @@ search's ``paths`` on every call, so one class-level instance serves every copy of a search (``copy_with_paths``) and is never serialised with it. +A resume state is probed before a search resumes from it (``resume_state_usable``): +a file that cannot be opened (a truncated HDF5, a poisoned dill) has its whole +``search_internal/`` folder moved aside to ``search_internal.failed_/`` and the +search starts fresh, instead of failing on the same file at every rerun. + Only ``DirectoryPaths`` stores anything. ``NullPaths`` (no output) and ``DatabasePaths`` (results live in the database) make ``save`` a no-op and ``load`` return ``None``, as their ``save_search_internal`` / ``load_search_internal`` always have. """ +import datetime as dt import logging import os import pickle @@ -128,6 +134,73 @@ def load_legacy_search_internal(directory) -> Any: return _load_dill(directory / DILL_FILENAME) +HDF5_PROBE_ERRORS = (OSError, ValueError, RuntimeError, KeyError) +""" +What ``h5py`` raises on a truncated or otherwise unreadable file. +""" + + +def probe_hdf5(path: Path): + """ + Open the HDF5 file at ``path`` read-only and visit every object in it, raising + (one of ``HDF5_PROBE_ERRORS``) if it is truncated or corrupt. Used for files only + their backend can load (nautilus's ``checkpoint.hdf5``), where a cheap structural + check stands in for loading. + """ + import h5py + + with h5py.File(path, "r") as f: + f.visit(lambda name: f[name]) + + +def quarantine_search_internal(paths, reason=None) -> Optional[Path]: + """ + Move the ``search_internal/`` folder of ``paths`` aside to + ``search_internal.failed_/`` (next to it, under ``files/``), so the search + starts fresh while the state it could not resume from is kept for inspection. + + Returns the folder it was moved to, or ``None`` when there was nothing to move. + Logs one warning naming ``reason``. + """ + directory = _directory(paths) + if directory is None or not directory.exists(): + return None + + stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") + failed = directory.with_name(f"{directory.name}.failed_{stamp}") + suffix = 1 + while failed.exists(): + failed = directory.with_name(f"{directory.name}.failed_{stamp}_{suffix}") + suffix += 1 + + os.replace(directory, failed) + + logger.warning( + f"The search's resume state in {directory} could not be used ({reason!r}). " + f"It has been moved to {failed} and the search is starting fresh." + ) + + return failed + + +def resume_state_usable(paths, resume_state: "Checkpointer") -> bool: + """ + Whether the search can resume from ``resume_state``: the file exists and passes + ``resume_state.probe``. A file that fails the probe has its ``search_internal/`` + folder quarantined (``quarantine_search_internal``) and ``False`` is returned, so + the caller starts fresh. + """ + if resume_state is None or not resume_state.exists(paths): + return False + + error = resume_state.probe(paths) + if error is None: + return True + + quarantine_search_internal(paths, reason=error) + return False + + class Checkpointer: """ A strategy for one internal-state file of a search (see the module docstring). @@ -193,6 +266,27 @@ def load(self, paths): return self._load(path) return load_legacy_search_internal(path.parent) + def probe(self, paths) -> Optional[Exception]: + """ + Check that this strategy's file can be read back, without raising. + + Returns ``None`` when the file is absent or loads, and the exception + otherwise. The default probe is a full ``load``: any failure (a truncated + or poisoned dill, an unpicklable class) means the file cannot be resumed + from. Used by ``resume_state_usable`` before a search resumes. + """ + path = self.path(paths) + if path is None or not path.is_file(): + return None + try: + self._probe(path) + except Exception as e: + return e + return None + + def _probe(self, path: Path): + self._load(path) + def finalize(self, paths, obj=None): """ Write the final state when a fit completes. For an archive strategy that is @@ -319,6 +413,10 @@ class NativeFileCheckpointer(Checkpointer): ``loader(path)`` opens the file (for example ``load_emcee_backend``). retain_after_completion See ``Checkpointer``. + probe + ``probe(path)`` raises if the file cannot be resumed from; defaults to + ``loader``. Given when the file can only be loaded by the backend mid-run + (nautilus: ``probe_hdf5``). """ kind = "native" @@ -328,11 +426,19 @@ def __init__( filename: str, loader: Callable[[Path], Any], retain_after_completion: bool = False, + probe: Optional[Callable[[Path], Any]] = None, ): super().__init__( filename=filename, retain_after_completion=retain_after_completion ) self.loader = loader + self.prober = probe + + def _probe(self, path: Path): + if self.prober is not None: + self.prober(path) + else: + self.loader(path) def save(self, paths, obj): """ diff --git a/autofit/non_linear/paths/abstract.py b/autofit/non_linear/paths/abstract.py index f92f8abf2..a280d1574 100644 --- a/autofit/non_linear/paths/abstract.py +++ b/autofit/non_linear/paths/abstract.py @@ -1,3 +1,4 @@ +import datetime as dt import logging import os import re @@ -17,7 +18,7 @@ from autofit.non_linear.samples.summary import SamplesSummary from autofit.text import text_util -from autofit.tools.util import open_, zip_directory +from autofit.tools.util import compress_type_for, open_, zip_directory logger = logging.getLogger(__name__) @@ -103,6 +104,46 @@ def _replace_zip_member(zip_path, arcname: str, file_path): raise +_zip_complete_cache = {} +""" +``zip_is_complete`` results keyed by zip path, each stored with the ``(size, +mtime)`` it was computed for so a rewritten zip is checked again. +""" + + +def zip_is_complete(zip_path) -> bool: + """ + Whether the zip at ``zip_path`` holds a completed result: it has a + ``.completed`` member and every member passes its CRC check + (``ZipFile.testzip``). + + ``testzip`` reads the whole archive, so the answer is cached per path and + reused while the zip's size and modification time are unchanged. + """ + zip_path = str(zip_path) + + try: + stat = os.stat(zip_path) + except OSError: + return False + + key = (stat.st_size, stat.st_mtime_ns) + + cached = _zip_complete_cache.get(zip_path) + if cached is not None and cached[0] == key: + return cached[1] + + try: + with zipfile.ZipFile(zip_path, "r") as f: + complete = ".completed" in f.namelist() and f.testzip() is None + except (zipfile.BadZipFile, OSError): + complete = False + + _zip_complete_cache[zip_path] = (key, complete) + + return complete + + class AbstractPaths(ABC): stores_search_internal = True """ @@ -113,7 +154,7 @@ class AbstractPaths(ABC): has_timer = True """ - Whether the search times itself into ``search_internal/`` (``Timer``). + Whether the search times itself into ``files/`` (``Timer``, ``timer_path``). ``NullPaths`` and ``DatabasePaths`` do not. """ @@ -367,6 +408,15 @@ def output_path(self) -> Path: return Path(*strings) if strings else Path("") + @property + def timer_path(self) -> Path: + """ + The folder the search's ``Timer`` writes ``.start_time`` / ``.time`` to: + ``files/``, outside ``search_internal/`` so the timing survives that folder + being removed at completion or quarantined on a corrupt checkpoint. + """ + return self._files_path + @property def _files_path(self) -> Path: """ @@ -404,10 +454,11 @@ def preserve_in_zip(self, file_path): Add a file (already inside this search's output directory) to the search's ``.zip`` archive so it survives the resume cycle. - ``restore()`` deletes the output directory and re-extracts the zip, so - any file written into e.g. ``files/`` *after* a search completed — such - as a cache artifact derived from the finished result — would be - destroyed by the next resume unless it is also a member of the zip. + Under ``remove_files`` the zip is what the next resume extracts + (``restore()``), and at completion the output directory is re-archived + and removed, so any file written into e.g. ``files/`` *after* a search + completed — such as a cache artifact derived from the finished result — + would be lost unless it is also a member of the zip. No-op when the zip does not exist (e.g. the search is still running, so the file will be zipped with everything else at completion) and @@ -445,7 +496,7 @@ def preserve_in_zip(self, file_path): try: info = f.getinfo(arcname) except KeyError: - f.write(file_path, arcname) + f.write(file_path, arcname, compress_type=compress_type_for(file_path)) info = None if info is not None and not _matches_archived(info, file_path): @@ -502,27 +553,139 @@ def _remove_preserved_copy(self, file_path: Path): def restore(self): """ - Copy files from the ``.zip`` file to the samples folder. + Make a zipped result readable from ``output_path`` again, so a resumed fit + (``result_via_completed_fit``) can read its extracted files. + + Non-destructive: + + - an output directory that is already complete (``.completed``) is the + search's primary store and is left untouched; + - otherwise the zip is extracted into a temporary sibling directory which + is then renamed into place, so a reader never sees a half-extracted + folder and two processes restoring the same zip both end with a whole + one (whichever rename lands second finds the first's complete copy); + - the zip is deleted only when the caller owns it (``_owns_zip``): + ``remove_files`` is on, so the zip is rebuilt at the end of the fit, + and the output path is keyed by this search's identifier. Readers that + do not own the result use ``open_result``, which writes nothing. + + A zip that cannot be read (``BadZipFile``, e.g. truncated by a crash + before archives were written atomically) is renamed to + ``.zip.corrupt_`` and logged, and the search continues as not + complete, so one corrupt archive no longer fails every rerun. """ + zip_path = Path(self._zip_path) - if Path(self._zip_path).exists(): - shutil.rmtree(self.output_path, ignore_errors=True) + if not zip_path.exists(): + return + output_path = Path(self.output_path) + + if not (output_path / ".completed").exists(): try: - try: - with zipfile.ZipFile(self._zip_path, "r") as f: - f.extractall(self.output_path) - except FileExistsError: - pass + self._extract_zip(zip_path=zip_path, output_path=output_path) except zipfile.BadZipFile as e: - raise zipfile.BadZipFile( - f"Unable to restore the zip file at the path {self._zip_path}" - ) from e + self._quarantine_zip(zip_path=zip_path, error=e) + return + except FileNotFoundError: + # Another process restored the same zip and removed it first. + if not (output_path / ".completed").exists(): + raise + return + if self._owns_zip: try: - os.remove(self._zip_path) + os.remove(zip_path) except FileNotFoundError: pass + except OSError as e: + # A concurrent reader holds it open (Windows); it is rebuilt at the + # end of the fit regardless. + logger.debug(f"Could not remove the restored zip {zip_path}: {e}") + + @property + def _owns_zip(self) -> bool: + """ + Whether ``restore`` may delete the zip after extracting it: ``remove_files`` + is on (the search re-archives its output at completion, so the zip is + rebuilt) and the output path ends in this search's identifier, so the zip + is this search's own rather than one shared by every search written to an + identifier-free path. + """ + return bool(self.remove_files) and self.is_identifier_in_paths + + @staticmethod + def _extract_zip(zip_path: Path, output_path: Path): + """ + Extract ``zip_path`` into ``output_path`` via a temporary sibling directory + and a rename, so ``output_path`` is either the previous directory or the + whole extracted archive, never a partial extraction. + + An existing incomplete ``output_path`` (no ``.completed``) is replaced; a + complete one that another process renamed into place meanwhile is kept and + this process's copy discarded. + """ + pid = os.getpid() + tmp = output_path.with_name(f"{output_path.name}.restore.{pid}.tmp") + aside = output_path.with_name(f"{output_path.name}.restore.{pid}.old") + + shutil.rmtree(tmp, ignore_errors=True) + + try: + with zipfile.ZipFile(zip_path, "r") as f: + f.extractall(tmp) + + if output_path.exists() and not (output_path / ".completed").exists(): + os.replace(output_path, aside) + + try: + os.rename(tmp, output_path) + except OSError: + # Another process put a directory in place first. + if not (output_path / ".completed").exists(): + raise + finally: + shutil.rmtree(tmp, ignore_errors=True) + shutil.rmtree(aside, ignore_errors=True) + + @staticmethod + def _quarantine_zip(zip_path: Path, error: Exception): + """ + Rename an unreadable zip to ``.corrupt_`` so it is kept for + inspection but no longer read, and log why. + """ + stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") + corrupt = zip_path.with_name(f"{zip_path.name}.corrupt_{stamp}") + + try: + os.replace(zip_path, corrupt) + except FileNotFoundError: + return + + logger.warning( + f"The result zip {zip_path} could not be read ({error}). It has been moved " + f"to {corrupt} and the search will run as not complete." + ) + + def open_result(self): + """ + A read-only view of this search's completed result, for downstream stages + that read a result they do not own. + + Returns the output directory (a ``Path``) when it holds a completed result, + otherwise a ``zipfile.Path`` into the result zip when that is complete, and + ``None`` when neither is. Both support ``/``, ``exists``, ``open`` and + ``read_text``. Unlike ``restore``, nothing is extracted, moved or deleted. + """ + output_path = Path(self.output_path) + + if (output_path / ".completed").exists(): + return output_path + + if zip_is_complete(self._zip_path): + return zipfile.Path(self._zip_path) + + return None def __eq__(self, other): return isinstance(other, AbstractPaths) and all( diff --git a/autofit/non_linear/paths/directory.py b/autofit/non_linear/paths/directory.py index a1a8bb792..d3f508ae7 100644 --- a/autofit/non_linear/paths/directory.py +++ b/autofit/non_linear/paths/directory.py @@ -19,7 +19,7 @@ from autofit.model_figure.config import model_figure_enabled from autofit.non_linear.test_mode import skip_visualization -from .abstract import AbstractPaths, _test_mode_segment +from .abstract import AbstractPaths, _test_mode_segment, zip_is_complete from ..checkpoint import load_legacy_search_internal from ..samples import load_from_table @@ -204,8 +204,14 @@ def is_object(self, name: str) -> bool: def is_complete(self) -> bool: """ Has the search been completed? + + True when the output directory holds ``.completed`` or, under + ``remove_files`` where only the archive remains, when the result zip + holds a ``.completed`` member and passes its CRC check + (``zip_is_complete``, cached per zip). ``fit`` still ``restore``-s such a + zip first, because ``result_via_completed_fit`` reads extracted files. """ - return self._has_completed_path.exists() + return self._has_completed_path.exists() or zip_is_complete(self._zip_path) def save_search_internal(self, obj): """ diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index 04ac88544..55cb21615 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -227,10 +227,13 @@ def logger(self): def timer(self) -> Optional[Timer]: """ The timer of the search (how long the search took, how much parallelization - sped it up), or ``None`` in ``NullPaths`` mode (no output written to disk). + sped it up), or ``None`` when the paths keep no timer (``has_timer``: ``NullPaths``, + ``DatabasePaths``). It writes to ``files/`` (``AbstractPaths.timer_path``). """ + if not getattr(self.paths, "has_timer", False): + return None try: - return Timer(self.paths.search_internal_path) + return Timer(self.paths.timer_path) except TypeError: pass diff --git a/autofit/non_linear/search/nest/dynesty/search/abstract.py b/autofit/non_linear/search/nest/dynesty/search/abstract.py index cef8a86f3..61f616487 100644 --- a/autofit/non_linear/search/nest/dynesty/search/abstract.py +++ b/autofit/non_linear/search/nest/dynesty/search/abstract.py @@ -13,6 +13,7 @@ from autofit import exc from autofit.mapper.prior_model.abstract import AbstractPriorModel +from autofit.non_linear.checkpoint import resume_state_usable from autofit.non_linear.search.abstract_search import NonLinearSearch from autofit.non_linear.search.posterior_kind import WEIGHTED from autofit.non_linear.samples.nest import SamplesNest @@ -300,8 +301,10 @@ def run(self, ctx): model = ctx.model fitness = ctx.fitness + # A savestate that cannot be restored (e.g. truncated by a killed job) is + # moved aside with its search_internal folder and the search starts fresh. if ctx.paths.supports_checkpointing: - checkpoint_exists = Path(self.checkpoint_file).exists() + checkpoint_exists = resume_state_usable(ctx.paths, self.resume_state) else: checkpoint_exists = False diff --git a/autofit/non_linear/search/nest/nautilus/search.py b/autofit/non_linear/search/nest/nautilus/search.py index 00152e2c2..b22b9c2ad 100644 --- a/autofit/non_linear/search/nest/nautilus/search.py +++ b/autofit/non_linear/search/nest/nautilus/search.py @@ -13,7 +13,13 @@ from autofit import exc from autofit.mapper.prior_model.abstract import AbstractPriorModel from autofit.mapper.prior.vectorized import PriorVectorized -from autofit.non_linear.checkpoint import DillCheckpointer, NativeFileCheckpointer +from autofit.non_linear.checkpoint import ( + DillCheckpointer, + NativeFileCheckpointer, + probe_hdf5, + quarantine_search_internal, + resume_state_usable, +) from autofit.non_linear.parallel import fork_context from autofit.non_linear.search.abstract_search import NonLinearSearch from autofit.non_linear.search.posterior_kind import WEIGHTED @@ -295,7 +301,7 @@ class Nautilus(NonLinearSearch): # once the fit completes. checkpointer = DillCheckpointer(strip_attributes=("pool_l", "pool_s")) resume_state = NativeFileCheckpointer( - NAUTILUS_FILENAME, loader=_resumed_by_nautilus + NAUTILUS_FILENAME, loader=_resumed_by_nautilus, probe=probe_hdf5 ) __identifier_fields__ = ( @@ -532,8 +538,10 @@ def run(self, ctx): # directly. self.check_model(model=ctx.model) + # A checkpoint that cannot be opened (e.g. truncated by a killed job) is + # moved aside with its search_internal folder and the search starts fresh. if ctx.paths.supports_checkpointing and self.checkpoint_file is not None: - checkpoint_exists = Path(self.checkpoint_file).exists() + checkpoint_exists = resume_state_usable(ctx.paths, self.resume_state) else: checkpoint_exists = False @@ -547,6 +555,18 @@ def run(self, ctx): "Starting new Nautilus non-linear search (no previous samples found)." ) + try: + return self._run_sampler(ctx) + except np.linalg.LinAlgError as e: + # A checkpoint that opens but whose bounds nautilus cannot rebuild; only + # a resumed run is retried, once, from scratch. + if not checkpoint_exists: + raise + quarantine_search_internal(ctx.paths, reason=e) + + return self._run_sampler(ctx) + + def _run_sampler(self, ctx): if self.force_x1_cpu or ctx.pool.is_jax: return self.fit_x1_cpu( fitness=ctx.fitness, diff --git a/autofit/non_linear/timer.py b/autofit/non_linear/timer.py index 615023c6e..aa7961102 100644 --- a/autofit/non_linear/timer.py +++ b/autofit/non_linear/timer.py @@ -1,41 +1,72 @@ -import datetime as dt import os import time +from pathlib import Path +from typing import Optional + +from autofit.tools.util import open_atomic class Timer: - def __init__(self, timer_path: str): + def __init__(self, timer_path: str, legacy_path: Optional[str] = None): """Times the run-time of the non-linear searches, by outputting a start-time file to the hard-disk and using this to determine the total run time when a `NonLinearSearch` update is performed. + The files live in ``files/`` (``AbstractPaths.timer_path``), not ``files/search_internal/``: that folder + is removed when a fit completes without ``output.search_internal`` and moved aside when its checkpoint is + quarantined, either of which would lose the timing. Output written before the move is still read from + ``legacy_path``. + Parameters ---------- timer_path The directory in which the timer should save results + legacy_path + The directory older output wrote the timer files to (``/search_internal`` by default), + read when ``timer_path`` holds none. """ - self.timer_path = timer_path + self.timer_path = Path(timer_path) + self.legacy_path = ( + Path(legacy_path) if legacy_path is not None else self.timer_path / "search_internal" + ) os.makedirs( timer_path, exist_ok=True ) + def _read(self, name: str) -> Optional[str]: + for directory in (self.timer_path, self.legacy_path): + try: + with open(directory / name, "r") as f: + return f.read() + except FileNotFoundError: + pass + return None + def start(self): """ Record the start time of a `NonLinearSearch` as universal date time, so that the run-time of the search can be - recorded. + recorded. A resumed search keeps its original start time, including one written by older output to the + legacy location, which is copied forward. """ - start_time_path = self.timer_path / ".start_time" + start_time = self.start_time + + try: + float(start_time) + except (TypeError, ValueError): + start_time = str(time.time()) try: - with open(start_time_path) as f: - float(f.read()) + with open(self.timer_path / ".start_time") as f: + if f.read() == start_time: + return except FileNotFoundError: - start = time.time() - with open(start_time_path, "w+") as f: - f.write(str(start)) + pass + + with open_atomic(self.timer_path / ".start_time", "w+") as f: + f.write(start_time) def update(self): """ @@ -44,12 +75,10 @@ def update(self): try: execution_time = str(time.time() - float(self.start_time)) - except TypeError: + except (TypeError, ValueError): return - with open( - self.timer_path / ".time", "w+" - ) as f: + with open_atomic(self.timer_path / ".time", "w+") as f: f.write(execution_time) @property @@ -57,23 +86,11 @@ def start_time(self): """ Load the start time written to hard disk from the .start_time file. """ - try: - with open( - self.timer_path / ".start_time", "r" - ) as f: - return f.read() - except FileNotFoundError: - return None + return self._read(".start_time") @property def time(self): """ Load the total time of the `NonLinearSearch` written to hard disk fom the .start_time file. """ - try: - with open( - self.timer_path / ".time", "r" - ) as f: - return f.read() - except FileNotFoundError: - return None + return self._read(".time") diff --git a/autofit/tools/util.py b/autofit/tools/util.py index cc2c6a555..0bff1d1f7 100644 --- a/autofit/tools/util.py +++ b/autofit/tools/util.py @@ -73,15 +73,54 @@ def __call__(self): return self.count % self.interval == 0 +STORED_SUFFIXES = frozenset({".png", ".fits", ".hdf", ".hdf5", ".h5"}) +""" +Suffixes of files that are already compressed (``.png``) or are large binary +blobs that deflate barely shrinks (``.fits``, HDF5). They are archived +``ZIP_STORED`` so a reader can seek straight into the member instead of +inflating it, and so zipping a result does not spend CPU re-compressing them. +""" + + +def compress_type_for(file_path) -> int: + """ + The ``zipfile`` compression a file is archived with: ``ZIP_STORED`` for the + ``STORED_SUFFIXES``, ``ZIP_DEFLATED`` (text: json, csv, logs) otherwise. + """ + if Path(file_path).suffix.lower() in STORED_SUFFIXES: + return zipfile.ZIP_STORED + return zipfile.ZIP_DEFLATED + + def zip_directory(source_directory, output=None): - output = output or f"{source_directory}.zip" - with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as f: - for root, dirs, files in os.walk(source_directory): - for file in files: - f.write( - Path(root) / file, - Path(root[len(str(source_directory)):]) / file, - ) + """ + Archive ``source_directory`` into ``output`` (default ``.zip``). + + The archive is written to a temporary file beside ``output`` and + ``os.replace``-d into place only once it is complete, so a zip at ``output`` + is always whole: a process killed mid-write leaves the previous zip (or no + zip) rather than a truncated one, which every later resume would otherwise + fail to open. See ``open_atomic`` for why the temporary file lives in the + same directory. + """ + output = Path(output or f"{source_directory}.zip") + + tmp = output.with_name(f"{output.name}.{os.getpid()}.tmp") + + try: + with zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as f: + for root, dirs, files in os.walk(source_directory): + for file in files: + f.write( + Path(root) / file, + Path(root[len(str(source_directory)):]) / file, + compress_type=compress_type_for(file), + ) + except BaseException: + tmp.unlink(missing_ok=True) + raise + + os.replace(tmp, output) def open_(filename, *flags): diff --git a/test_autofit/non_linear/paths/test_artefact_integrity.py b/test_autofit/non_linear/paths/test_artefact_integrity.py new file mode 100644 index 000000000..77d893c68 --- /dev/null +++ b/test_autofit/non_linear/paths/test_artefact_integrity.py @@ -0,0 +1,477 @@ +""" +Artefact integrity (results-library phase 0a): a result zip is complete or +absent, a corrupt zip or checkpoint is quarantined instead of failing every +rerun, and restoring a zip never destroys what it restores from. +""" +import multiprocessing +import os +import signal +import zipfile +from pathlib import Path + +import numpy as np +import pytest + +import autofit as af +from autonerves import conf +from autofit.non_linear.checkpoint import ( + quarantine_search_internal, + resume_state_usable, +) +from autofit.non_linear.paths import abstract as paths_abstract +from autofit.non_linear.paths.abstract import zip_is_complete +from autofit.non_linear.timer import Timer +from autofit.tools.util import zip_directory + +CONFIG_PATH = Path(__file__).parents[2] / "config" + + +def _completed_output(paths, n_files=1): + """ + Write a minimal completed output folder for ``paths``. + """ + files_path = Path(paths._files_path) + for index in range(n_files): + (files_path / f"member_{index}.json").write_text(f'{{"index": {index}}}') + (Path(paths.output_path) / ".completed").write_text("") + + +def _paths(tmp_path, name, remove_files): + paths = af.DirectoryPaths(name=name, path_prefix=str(tmp_path)) + paths.remove_files = remove_files + return paths + + +# --- zip_directory --------------------------------------------------------------------- + + +def test__zip_directory__binary_members_are_stored_and_text_deflated(tmp_path): + source = tmp_path / "source" + source.mkdir() + for name in ("image.png", "data.fits", "checkpoint.hdf5", "samples.json"): + (source / name).write_bytes(b"0" * 1000) + + zip_directory(source) + + with zipfile.ZipFile(f"{source}.zip") as f: + compress = {info.filename: info.compress_type for info in f.infolist()} + + assert compress["image.png"] == zipfile.ZIP_STORED + assert compress["data.fits"] == zipfile.ZIP_STORED + assert compress["checkpoint.hdf5"] == zipfile.ZIP_STORED + assert compress["samples.json"] == zipfile.ZIP_DEFLATED + + +def _zip_and_die(source, output): + """ + Child process: start archiving ``source`` and SIGKILL itself after the first + member, as a job killed by the scheduler mid-zip would be. + """ + original_write = zipfile.ZipFile.write + written = [] + + def write(self, *args, **kwargs): + original_write(self, *args, **kwargs) + written.append(args[0]) + if len(written) == 1: + os.kill(os.getpid(), signal.SIGKILL) + + zipfile.ZipFile.write = write + zip_directory(source, output) + + +def test__zip_directory__killed_mid_zip_leaves_the_previous_zip_whole(tmp_path): + source = tmp_path / "source" + source.mkdir() + for index in range(5): + (source / f"file_{index}.json").write_text("x" * 1000) + + output = tmp_path / "source.zip" + zip_directory(source, output) + before = output.read_bytes() + + (source / "new.json").write_text("new") + + process = multiprocessing.get_context("fork").Process( + target=_zip_and_die, args=(source, output) + ) + process.start() + process.join() + + assert process.exitcode == -signal.SIGKILL + assert output.read_bytes() == before + with zipfile.ZipFile(output) as f: + assert f.testzip() is None + + +# --- restore / is_complete / open_result ----------------------------------------------- + + +def test__restore__corrupt_zip_is_quarantined_and_not_complete(tmp_path): + paths = _paths(tmp_path, "corrupt", remove_files=True) + _completed_output(paths) + paths.zip_remove() + + zip_path = Path(paths._zip_path) + zip_path.write_bytes(zip_path.read_bytes()[: zip_path.stat().st_size // 2]) + + paths.restore() + + assert not zip_path.exists() + assert len(list(tmp_path.rglob(f"{zip_path.name}.corrupt_*"))) == 1 + assert not paths.is_complete + + +@pytest.mark.parametrize("remove_files", [True, False]) +def test__restore__extracts_and_keeps_zip_unless_owned(tmp_path, remove_files): + paths = _paths(tmp_path, f"owned_{remove_files}", remove_files=remove_files) + _completed_output(paths) + paths.zip_remove() + + if not remove_files: + import shutil + + shutil.rmtree(paths.output_path) + + paths.restore() + + assert (Path(paths.output_path) / ".completed").exists() + assert (Path(paths._files_path) / "member_0.json").exists() + assert Path(paths._zip_path).exists() is (not remove_files) + assert not list(tmp_path.rglob("*.restore.*")) + + +def test__restore__leaves_a_complete_directory_untouched(tmp_path): + paths = _paths(tmp_path, "untouched", remove_files=False) + _completed_output(paths) + paths.zip_remove() + + later = Path(paths._files_path) / "later.json" + later.write_text("written after the zip") + + paths.restore() + + assert later.read_text() == "written after the zip" + + +def test__is_complete__reads_a_zipped_result(tmp_path): + paths = _paths(tmp_path, "zipped", remove_files=True) + _completed_output(paths) + paths.zip_remove() + + assert not Path(paths.output_path).exists() + assert paths.is_complete + assert zip_is_complete(paths._zip_path) + + # A zip without a ``.completed`` member is not a completed result. + incomplete = tmp_path / "incomplete" + incomplete.mkdir() + (incomplete / "a.json").write_text("{}") + zip_directory(incomplete) + assert not zip_is_complete(f"{incomplete}.zip") + + +def test__is_complete__cache_follows_a_rewritten_zip(tmp_path): + paths = _paths(tmp_path, "cached", remove_files=True) + _completed_output(paths) + paths.zip_remove() + + zip_path = Path(paths._zip_path) + assert zip_is_complete(zip_path) + + zip_path.write_bytes(b"not a zip") + + assert not zip_is_complete(zip_path) + assert not paths.is_complete + + +def test__open_result__reads_a_zip_without_extracting(tmp_path): + paths = _paths(tmp_path, "read_only", remove_files=True) + _completed_output(paths) + paths.zip_remove() + + zip_path = Path(paths._zip_path) + before = zip_path.read_bytes() + + root = paths.open_result() + + assert (root / "files" / "member_0.json").read_text() == '{"index": 0}' + assert zip_path.read_bytes() == before + assert not Path(paths.output_path).exists() + + assert _paths(tmp_path, "absent", remove_files=True).open_result() is None + + +def _restore_and_read(paths, barrier, queue): + barrier.wait() + paths.restore() + queue.put(sorted(p.name for p in Path(paths._files_path).iterdir())) + + +@pytest.mark.parametrize("remove_files", [True, False]) +def test__restore__two_processes_restore_one_zip_concurrently(tmp_path, remove_files): + paths = _paths(tmp_path, f"concurrent_{remove_files}", remove_files=remove_files) + _completed_output(paths, n_files=200) + paths.zip_remove() + + import shutil + + shutil.rmtree(paths.output_path, ignore_errors=True) + + context = multiprocessing.get_context("fork") + barrier = context.Barrier(2) + queue = context.Queue() + + processes = [ + context.Process(target=_restore_and_read, args=(paths, barrier, queue)) + for _ in range(2) + ] + for process in processes: + process.start() + for process in processes: + process.join(timeout=60) + + assert [process.exitcode for process in processes] == [0, 0] + + listings = [queue.get(timeout=5) for _ in range(2)] + expected = sorted(f"member_{index}.json" for index in range(200)) + for listing in listings: + assert expected == [name for name in listing if name.startswith("member_")] + + assert (Path(paths.output_path) / ".completed").exists() + assert not list(tmp_path.rglob("*.restore.*")) + + +# --- checkpoint quarantine ------------------------------------------------------------- + + +def _truncated_hdf5(path: Path): + import h5py + + path.parent.mkdir(parents=True, exist_ok=True) + with h5py.File(path, "w") as f: + f.create_dataset("points", data=np.arange(10000.0)) + path.write_bytes(path.read_bytes()[:1000]) + + +def test__resume_state_usable__truncated_hdf5_is_quarantined(tmp_path): + pytest.importorskip("nautilus") + + search = af.Nautilus(name="probe_hdf5", path_prefix=str(tmp_path)) + search.paths.model = af.Model(af.ex.Gaussian) + + checkpoint = Path(search.checkpoint_file) + _truncated_hdf5(checkpoint) + + assert not resume_state_usable(search.paths, search.resume_state) + + failed = list(checkpoint.parent.parent.glob("search_internal.failed_*")) + assert len(failed) == 1 + assert (failed[0] / checkpoint.name).exists() + assert not checkpoint.exists() + + +def test__resume_state_usable__valid_hdf5_resumes(tmp_path): + pytest.importorskip("nautilus") + import h5py + + search = af.Nautilus(name="probe_valid", path_prefix=str(tmp_path)) + search.paths.model = af.Model(af.ex.Gaussian) + + with h5py.File(search.checkpoint_file, "w") as f: + f.create_dataset("points", data=np.arange(10.0)) + + assert resume_state_usable(search.paths, search.resume_state) + assert Path(search.checkpoint_file).exists() + + +def test__quarantine__repeated_quarantines_do_not_collide(tmp_path): + paths = _paths(tmp_path, "collide", remove_files=False) + + for _ in range(2): + (paths.search_internal_path / "state.dill").write_bytes(b"x") + assert quarantine_search_internal(paths, reason="test") is not None + + assert len(list(Path(paths._files_path).glob("search_internal.failed_*"))) == 2 + + +# --- fit-level ------------------------------------------------------------------------- + + +@pytest.fixture(name="fit_output") +def make_fit_output(tmp_path, monkeypatch): + monkeypatch.setenv("PYAUTO_TEST_MODE", "1") + conf.instance.push(new_path=str(CONFIG_PATH), output_path=str(tmp_path)) + return tmp_path + + +def _analysis(): + return af.ex.Analysis(data=np.full(20, 5.0), noise_map=np.full(20, 1.0)) + + +def _count_fits(monkeypatch, cls): + calls = [] + original = cls._fit + + def counted(self, *args, **kwargs): + calls.append(1) + return original(self, *args, **kwargs) + + monkeypatch.setattr(cls, "_fit", counted) + return calls + + +def _prepare_paths(search, model): + search.paths.model = model + search.paths.unique_tag = search.unique_tag + + +class _Killed(BaseException): + pass + + +def test__fit__killed_mid_zip_resumes_as_complete(fit_output, monkeypatch): + calls = _count_fits(monkeypatch, af.Drawer) + + def killed_zip(source_directory, output=None): + raise _Killed + + with monkeypatch.context() as patch: + patch.setattr(paths_abstract, "zip_directory", killed_zip) + search = af.Drawer(name="killed_mid_zip") + with pytest.raises(_Killed): + search.fit(model=af.Model(af.ex.Gaussian), analysis=_analysis()) + + assert (Path(search.paths.output_path) / ".completed").exists() + assert not Path(search.paths._zip_path).exists() + + # The debris a SIGKILL (rather than an exception) would leave. + Path(f"{search.paths._zip_path}.12345.tmp").write_bytes(b"partial") + + resumed = af.Drawer(name="killed_mid_zip") + result = resumed.fit(model=af.Model(af.ex.Gaussian), analysis=_analysis()) + + assert len(calls) == 1 + assert isinstance(result, af.Result) + assert zip_is_complete(resumed.paths._zip_path) + + +def test__fit__corrupt_zip_is_quarantined_and_the_fit_reruns(fit_output, monkeypatch): + calls = _count_fits(monkeypatch, af.Drawer) + + search = af.Drawer(name="corrupt_zip_rerun") + search.fit(model=af.Model(af.ex.Gaussian), analysis=_analysis()) + + zip_path = Path(search.paths._zip_path) + zip_path.write_bytes(zip_path.read_bytes()[: zip_path.stat().st_size // 2]) + + rerun = af.Drawer(name="corrupt_zip_rerun") + result = rerun.fit(model=af.Model(af.ex.Gaussian), analysis=_analysis()) + + assert len(calls) == 2 + assert isinstance(result, af.Result) + assert len(list(zip_path.parent.glob(f"{zip_path.name}.corrupt_*"))) == 1 + assert zip_is_complete(zip_path) + + +def _failed_members(zip_path, filename): + with zipfile.ZipFile(zip_path) as f: + return [ + name + for name in f.namelist() + if "search_internal.failed_" in name and name.endswith(filename) + ] + + +def test__fit__nautilus_truncated_checkpoint_starts_fresh(fit_output, monkeypatch): + pytest.importorskip("nautilus") + + model = af.Model(af.ex.Gaussian) + search = af.Nautilus(name="nautilus_truncated", n_live=10) + _prepare_paths(search, model) + _truncated_hdf5(Path(search.checkpoint_file)) + + result = search.fit(model=model, analysis=_analysis()) + + assert isinstance(result, af.Result) + assert len(_failed_members(search.paths._zip_path, "checkpoint.hdf5")) == 1 + + +def test__fit__nautilus_linalg_error_on_resume_retries_fresh(fit_output, monkeypatch): + pytest.importorskip("nautilus") + import h5py + + model = af.Model(af.ex.Gaussian) + search = af.Nautilus(name="nautilus_linalg", n_live=10) + _prepare_paths(search, model) + + with h5py.File(search.checkpoint_file, "w") as f: + f.create_dataset("points", data=np.arange(10.0)) + + original = type(search)._run_sampler + attempts = [] + + def run_sampler(self, ctx): + attempts.append(Path(self.checkpoint_file).exists()) + if len(attempts) == 1: + raise np.linalg.LinAlgError("singular bound") + return original(self, ctx) + + monkeypatch.setattr(type(search), "_run_sampler", run_sampler) + + result = search.fit(model=model, analysis=_analysis()) + + assert attempts == [True, False] + assert isinstance(result, af.Result) + assert len(_failed_members(search.paths._zip_path, "checkpoint.hdf5")) == 1 + + +def test__fit__dynesty_poisoned_savestate_starts_fresh(fit_output): + pytest.importorskip("dynesty") + from autofit.non_linear.search.nest.dynesty.search.abstract import ( + DYNESTY_FILENAME, + ) + + model = af.Model(af.ex.Gaussian) + search = af.DynestyStatic(name="dynesty_poisoned", nlive=10) + _prepare_paths(search, model) + + checkpoint = Path(search.checkpoint_file) + checkpoint.write_bytes(b"\x80\x04\x95poisoned dill") + + result = search.fit(model=model, analysis=_analysis()) + + assert isinstance(result, af.Result) + assert len(_failed_members(search.paths._zip_path, DYNESTY_FILENAME)) == 1 + + +# --- Timer ----------------------------------------------------------------------------- + + +def test__timer__writes_to_files_and_reads_legacy_output(tmp_path): + files = tmp_path / "files" + legacy = files / "search_internal" + legacy.mkdir(parents=True) + (legacy / ".start_time").write_text("100.0") + (legacy / ".time").write_text("42.0") + + timer = Timer(files) + + assert timer.time == "42.0" + + timer.start() + assert (files / ".start_time").read_text() == "100.0" + + timer.update() + assert float((files / ".time").read_text()) > 42.0 + + +def test__timer__fit_writes_timer_outside_search_internal(fit_output): + search = af.Drawer(name="timer_location") + search.fit(model=af.Model(af.ex.Gaussian), analysis=_analysis()) + + with zipfile.ZipFile(search.paths._zip_path) as f: + names = f.namelist() + + assert "files/.start_time" in names + assert "files/.time" in names diff --git a/test_autofit/non_linear/search/test_conformance_backend.py b/test_autofit/non_linear/search/test_conformance_backend.py index b73ee0853..68451adfc 100644 --- a/test_autofit/non_linear/search/test_conformance_backend.py +++ b/test_autofit/non_linear/search/test_conformance_backend.py @@ -92,8 +92,8 @@ "files/samples.csv", "files/samples_info.json", "files/samples_summary.json", - "files/search_internal/.start_time", - "files/search_internal/.time", + "files/.start_time", + "files/.time", } )