From 0a6a047fe36979b46c64a01d6548635f1d540b19 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 30 Oct 2026 09:24:49 +0000 Subject: [PATCH 1/4] feat: results index, result states, dataset_identity.json and latest_per (results-library p1, PR 1a) - ResultState (completed, running, interrupted_valid_ckpt, corrupt_ckpt, corrupt_zip, failed, superseded, never_started) in the shared status vocabulary. - autofit/results: ResultsIndex (per-result JSON records as truth, incremental on a stat fingerprint, --index-dir for read-only trees, superseded siblings), classify(), ResultsCache (local SQLite, rebuilt from the records), python -m autofit.results {index,status,count}. - dataset_identity.json at fit start via Analysis.dataset_identity(): object id, external ids, inputs with size + SHA256, centre, library versions; general.output.dataset_identity(_sha256) switches. - Aggregator.latest_per and SearchOutput.completed_at (status record or the zip's .completed member, never zip mtime). Refs #1739 Co-Authored-By: Claude Opus 5.5 --- autofit/aggregator/aggregator.py | 55 +++ autofit/aggregator/search_output.py | 36 ++ autofit/config/general.yaml | 2 + autofit/non_linear/analysis/analysis.py | 13 + autofit/non_linear/search/abstract_search.py | 7 +- autofit/non_linear/status/__init__.py | 8 +- autofit/non_linear/status/identity.py | 218 +++++++++++ autofit/non_linear/status/states.py | 33 ++ autofit/results/__init__.py | 14 + autofit/results/__main__.py | 155 ++++++++ autofit/results/cache.py | 124 +++++++ autofit/results/classify.py | 364 +++++++++++++++++++ autofit/results/index.py | 310 ++++++++++++++++ autofit/results/record.py | 84 +++++ test_autofit/results/__init__.py | 0 test_autofit/results/conftest.py | 8 + test_autofit/results/test_identity.py | 146 ++++++++ test_autofit/results/test_index.py | 251 +++++++++++++ test_autofit/results/tree.py | 114 ++++++ 19 files changed, 1940 insertions(+), 2 deletions(-) create mode 100644 autofit/non_linear/status/identity.py create mode 100644 autofit/results/__init__.py create mode 100644 autofit/results/__main__.py create mode 100644 autofit/results/cache.py create mode 100644 autofit/results/classify.py create mode 100644 autofit/results/index.py create mode 100644 autofit/results/record.py create mode 100644 test_autofit/results/__init__.py create mode 100644 test_autofit/results/conftest.py create mode 100644 test_autofit/results/test_identity.py create mode 100644 test_autofit/results/test_index.py create mode 100644 test_autofit/results/tree.py diff --git a/autofit/aggregator/aggregator.py b/autofit/aggregator/aggregator.py index c827e17e8..f6f7212cd 100755 --- a/autofit/aggregator/aggregator.py +++ b/autofit/aggregator/aggregator.py @@ -596,6 +596,61 @@ def query(self, *predicates) -> "Aggregator": errors=self.errors, ) + def latest_per( + self, + key: Tuple[str, ...] = ("path_prefix", "unique_tag", "name"), + by: str = "completed_at", + ) -> "Aggregator": + """ + Keep, for each value of ``key``, only the search output with the greatest + ``by``: the latest of several fits of the same search to the same object + (sibling hashes, e.g. a rerun after a model or search setting changed). + + ``completed_at`` comes from the status record or the ``.completed`` member of + the result's zip, never the zip's modification time, which copying or + re-zipping resets. Outputs with no ``by`` value lose to any that have one; + remaining ties go to the greater path, so the choice is the same on every + machine. + + Parameters + ---------- + key + Attributes of a search output that together name one fit of one object. + The default suits both layouts in use: the object in ``path_prefix`` + (``unique_tag`` shared) or in ``unique_tag`` (``path_prefix`` shared). + by + The attribute that orders the outputs within a key. + """ + + def value_of(search_output, attribute): + value = getattr(search_output, attribute, None) + return None if value is None else str(value) + + latest = {} + for search_output in self.search_outputs: + group = tuple(value_of(search_output, k) for k in key) + order = ( + value_of(search_output, by) is not None, + value_of(search_output, by) or "", + str(search_output.directory), + ) + if group not in latest or order > latest[group][0]: + latest[group] = (order, search_output) + + search_outputs = sorted( + (search_output for _, search_output in latest.values()), + key=lambda output: str(output.directory), + ) + logger.info( + f"latest_per kept {len(search_outputs)} of {len(self.search_outputs)} " + f"search outputs." + ) + return Aggregator( + search_outputs=search_outputs, + grid_search_outputs=self.grid_search_outputs, + errors=self.errors, + ) + def values(self, name: str, parser=lambda o: o) -> Iterator: """ Get values from outputs with a given name. diff --git a/autofit/aggregator/search_output.py b/autofit/aggregator/search_output.py index 9a8965fbf..43af08b0b 100644 --- a/autofit/aggregator/search_output.py +++ b/autofit/aggregator/search_output.py @@ -4,7 +4,9 @@ import pickle import tempfile import weakref +import zipfile from abc import ABC +from datetime import datetime, timezone from hashlib import md5 from pathlib import Path from shutil import rmtree @@ -110,6 +112,40 @@ def is_complete(self) -> bool: """ return (self.directory / ".completed").exists() + @cached_property + def completed_at(self) -> Optional[str]: + """ + When the search completed (ISO 8601), or ``None`` if it has not. + + Taken from the status record beside the output (``.status.json``) + when it says ``completed``, else from the ``.completed`` member of the zip + beside the output, else from the ``.completed`` file's modification time. The + zip's own modification time is never used: copying or re-zipping resets it. + An output extracted to a temporary directory has neither sibling, so its + ``.completed`` time is the extraction time; index the tree + (``python -m autofit.results index``) to compare such outputs. + """ + directory = Path(self.directory) + try: + with open(f"{directory}.status.json") as f: + status = json.load(f) + if status.get("state") == "completed" and status.get("updated"): + return status["updated"] + except (OSError, ValueError, AttributeError): + pass + try: + with zipfile.ZipFile(f"{directory}.zip") as f: + return datetime(*f.getinfo(".completed").date_time).isoformat() + except (OSError, KeyError, zipfile.BadZipFile): + pass + try: + mtime = (directory / ".completed").stat().st_mtime + except OSError: + return None + return datetime.fromtimestamp(mtime, timezone.utc).isoformat( + timespec="seconds" + ) + @property def parent_identifier(self) -> Optional[str]: """ diff --git a/autofit/config/general.yaml b/autofit/config/general.yaml index 177f93ab7..8d03928eb 100644 --- a/autofit/config/general.yaml +++ b/autofit/config/general.yaml @@ -13,6 +13,8 @@ inversion: check_reconstruction: true # If True, the inversion's reconstruction is checked to ensure the solution of a meshs's mapper is not an invalid solution where the values are all the same. reconstruction_vmax_factor: 0.5 # Plots of an Inversion's reconstruction use the reconstructed data's bright value multiplied by this factor. output: + dataset_identity: true # If True, every fit writes files/dataset_identity.json at start: its object id, the paths of its inputs (from Analysis.dataset_identity) and, with dataset_identity_sha256, their SHA256, so the results index can find duplicate and wrong-input fits. + dataset_identity_sha256: true # If True, dataset_identity.json records the SHA256 of each input file (reads every input once at fit start). If False, only paths and sizes are recorded. force_pickle_overwrite: false # If True pickle files output by a search (e.g. samples.pickle) are recreated when a new model-fit is performed. force_visualize_overwrite: false # If True, visualization images output by a search (e.g. subplots of the fit) are recreated when a new model-fit is performed. info_whitespace_length: 80 # Length of whitespace between the parameter names and values in the model.info / result.info diff --git a/autofit/non_linear/analysis/analysis.py b/autofit/non_linear/analysis/analysis.py index b92747306..0b6fb55ae 100644 --- a/autofit/non_linear/analysis/analysis.py +++ b/autofit/non_linear/analysis/analysis.py @@ -279,6 +279,19 @@ def shared_state_from(self, instance): def save_attributes(self, paths: AbstractPaths): pass + def dataset_identity(self) -> Optional[Dict]: + """ + What this analysis fits, for the fit's ``files/dataset_identity.json`` + (``autofit.non_linear.status.identity``). + + Override to return a dict with any of ``object_id`` (a stable name for the + object, e.g. a catalogue id), ``external_ids`` (a dict of other ids), + ``inputs`` (a dict of name to the path of each input file, which are hashed) + and ``centre`` (a sequence of numbers, e.g. a cutout centre). The default, + ``None``, records only the search's ``unique_tag`` as the ``object_id``. + """ + return None + def save_results(self, paths: AbstractPaths, result: Result): pass diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index 40992ac49..ec4205a2f 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -44,7 +44,11 @@ from autofit.non_linear.search.execution import SearchExecutionMixin, _SearchMeta from autofit.non_linear.search.internal_state import SearchInternalStateMixin from autofit.non_linear.search.updates import SearchUpdatesMixin -from autofit.non_linear.status import status_notify, status_recorded +from autofit.non_linear.status import ( + status_notify, + status_recorded, + write_dataset_identity, +) from autofit.non_linear.search.test_mode_bypass import TestModeBypass, TestModeMixin from autofit.non_linear.test_mode import test_mode_level, skip_fit_output @@ -405,6 +409,7 @@ def start_resume_fit(self, analysis: Analysis, model: AbstractPriorModel) -> Res self.timer.start() status_notify(self, "start") + write_dataset_identity(self, analysis) mode = test_mode_level() if mode >= 2: diff --git a/autofit/non_linear/status/__init__.py b/autofit/non_linear/status/__init__.py index efaddf31b..fa70934ea 100644 --- a/autofit/non_linear/status/__init__.py +++ b/autofit/non_linear/status/__init__.py @@ -15,7 +15,8 @@ ``None``. It is called at each full update (``FitContext.update``); the record adds ``eta_s`` from the fraction's rate. -``states`` is the single vocabulary of run states, failure classes and product names. +``states`` is the single vocabulary of run states, result states, failure classes and +product names. ``identity`` writes ``dataset_identity.json`` (results-library phase 1). """ from autofit.non_linear.status.states import ( COLLECTOR_STATES, @@ -23,6 +24,7 @@ WRITTEN_STATES, FailureClass, Product, + ResultState, RunState, failure_class_of, ) @@ -34,3 +36,7 @@ status_recorded, status_interval_s, ) +from autofit.non_linear.status.identity import ( + dataset_identity_enabled, + write_dataset_identity, +) diff --git a/autofit/non_linear/status/identity.py b/autofit/non_linear/status/identity.py new file mode 100644 index 000000000..6ed8dacf3 --- /dev/null +++ b/autofit/non_linear/status/identity.py @@ -0,0 +1,218 @@ +""" +``dataset_identity.json``: what a fit was run on, written once at fit start into +``/files/``. + +A fit's output folder is named by a hash of its model and search, so two fits of the +same model to different data, or a refit after an input was replaced, are only told +apart by what they were given. This record names the object (``object_id`` plus any +external ids), the input files with their sizes and SHA256 and, where the dataset +exposes one, its centre, with the versions of the libraries the fit ran with. The +results index (``autofit.results``) joins on it, so duplicate fits of one object and +fits of the wrong input become detectable. + +The inputs come from ``Analysis.dataset_identity()``, which returns ``None`` by default; +the record then carries only the ``object_id`` (the search's ``unique_tag``). Datasets +that know their input files (PyAutoArray / PyAutoLens) fill it in. + +``general.output.dataset_identity: false`` turns the record off and +``general.output.dataset_identity_sha256: false`` skips the hashing (paths and sizes +are still recorded). Writing is best effort: a record that cannot be written logs a +warning and never fails the fit. +""" +import hashlib +import json +import logging +import os +import sys +from datetime import datetime, timezone +from pathlib import Path +from typing import Dict, Optional + +from autonerves import conf + +from autofit.non_linear.status.states import Product +from autofit.tools.util import open_atomic + +logger = logging.getLogger(__name__) + +SCHEMA = 1 + +_CHUNK_BYTES = 1 << 20 + + +def _output_setting(name: str, default: bool) -> bool: + try: + value = conf.instance["general"]["output"][name] + except Exception: + return default + return default if value is None else bool(value) + + +def dataset_identity_enabled() -> bool: + """ + Whether fits write ``dataset_identity.json`` (``general.output.dataset_identity``, + default on). + """ + return _output_setting("dataset_identity", True) + + +def dataset_identity_sha256() -> bool: + """ + Whether ``dataset_identity.json`` records the SHA256 of each input + (``general.output.dataset_identity_sha256``, default on). + """ + return _output_setting("dataset_identity_sha256", True) + + +def sha256_of(path) -> str: + """ + The SHA256 hex digest of the file at ``path``, read in 1 MB chunks. + """ + digest = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(_CHUNK_BYTES), b""): + digest.update(chunk) + return digest.hexdigest() + + +_VERSIONED_PACKAGES = ( + "autonerves", + "autofit", + "autoarray", + "autogalaxy", + "autolens", + "numpy", + "jax", +) + + +def library_versions() -> Dict[str, str]: + """ + The ``__version__`` of each PyAuto library (and numpy / jax) already imported by + this process; a library that is not imported is not imported here. + """ + versions = {} + for name in _VERSIONED_PACKAGES: + module = sys.modules.get(name) + version = getattr(module, "__version__", None) + if version is not None: + versions[name] = str(version) + return versions + + +def _input_entry(path, sha256: bool) -> Dict: + path = Path(path) + entry = {"path": str(path.resolve()) if path.exists() else str(path)} + if not path.is_file(): + entry["missing"] = True + return entry + entry["bytes"] = path.stat().st_size + if sha256: + entry["sha256"] = sha256_of(path) + return entry + + +def dataset_identity_document( + identity: Optional[Dict], unique_tag: Optional[str], sha256: bool = True +) -> Dict: + """ + The ``dataset_identity.json`` document (``schema`` 1) for the identity an + ``Analysis`` returned. + + Parameters + ---------- + identity + What ``Analysis.dataset_identity()`` returned: a dict with any of ``object_id``, + ``external_ids`` (a dict), ``inputs`` (a dict of name to file path, or a list of + paths) and ``centre`` (a sequence of numbers), or ``None``. + unique_tag + The search's ``unique_tag``, used as the ``object_id`` when the identity names + none. + sha256 + Whether to hash each input. + """ + identity = dict(identity or {}) + + inputs = identity.get("inputs") or {} + if not isinstance(inputs, dict): + inputs = {Path(path).name: path for path in inputs} + + centre = identity.get("centre") + if centre is not None: + centre = [float(value) for value in centre] + + return { + "schema": SCHEMA, + "object_id": identity.get("object_id") or unique_tag, + "external_ids": dict(identity.get("external_ids") or {}), + "inputs": { + str(name): _input_entry(path, sha256=sha256) + for name, path in inputs.items() + }, + "centre": centre, + "versions": library_versions(), + "written": datetime.now(timezone.utc).isoformat(timespec="seconds"), + } + + +def _differences(old: Dict, new: Dict): + for name, entry in new["inputs"].items(): + previous = old.get("inputs", {}).get(name) + if previous is None: + continue + for key in ("sha256", "bytes"): + if key in entry and key in previous and entry[key] != previous[key]: + yield f"{name} ({key} {previous[key]} -> {entry[key]})" + break + if old.get("object_id") != new["object_id"]: + yield f"object_id ({old.get('object_id')} -> {new['object_id']})" + + +def write_dataset_identity(search, analysis) -> Optional[Path]: + """ + Write ``/files/dataset_identity.json`` for the fit ``search`` is about + to start, unless it is already there. + + A resumed fit keeps the record of its first start; if the inputs it is resumed with + differ (another SHA256, size or ``object_id``) a warning names them, since the + output then mixes two inputs. Returns the path written, or ``None`` when nothing was + written (disabled, no output folder, already present, or an error). + """ + from autofit.non_linear.paths.directory import DirectoryPaths + + paths = getattr(search, "paths", None) + if not isinstance(paths, DirectoryPaths) or not dataset_identity_enabled(): + return None + + try: + hook = getattr(type(analysis), "dataset_identity", None) + identity = analysis.dataset_identity() if hook is not None else None + document = dataset_identity_document( + identity, + unique_tag=getattr(paths, "unique_tag", None), + sha256=dataset_identity_sha256(), + ) + path = Path(paths._files_path) / str(Product.DATASET_IDENTITY) + + if path.exists(): + try: + with open(path) as f: + previous = json.load(f) + except (OSError, ValueError): + previous = None + if previous is not None: + changed = list(_differences(previous, document)) + if changed: + logger.warning( + f"{path}: this fit is resumed with different inputs than it " + f"started with: {', '.join(changed)}. The first record is kept." + ) + return None + + os.makedirs(path.parent, exist_ok=True) + with open_atomic(path) as f: + json.dump(document, f, indent=2) + return path + except Exception as exception: + logger.warning(f"dataset_identity.json not written ({exception}).") + return None diff --git a/autofit/non_linear/status/states.py b/autofit/non_linear/status/states.py index 154638311..76ae2f717 100644 --- a/autofit/non_linear/status/states.py +++ b/autofit/non_linear/status/states.py @@ -76,6 +76,39 @@ def __str__(self): return self.value +class ResultState(str, Enum): + """ + The state of one result on disk, as the results index (``autofit.results``) + classifies it after the fact. Where a ``RunState`` is what a running fit says about + itself, a ``ResultState`` is what its output says once read back: it is assigned + from the status record when one exists and from the output folder or zip otherwise. + """ + + COMPLETED = "completed" + """The output (folder or zip) carries ``.completed`` and reads back cleanly.""" + RUNNING = "running" + """The status record says the fit is running and was written recently.""" + INTERRUPTED_VALID_CKPT = "interrupted_valid_ckpt" + """The fit stopped before completing and left a checkpoint it can resume from.""" + CORRUPT_CKPT = "corrupt_ckpt" + """The fit stopped before completing and its checkpoint cannot be read (or was + quarantined to ``search_internal.failed_/`` with nothing written since).""" + CORRUPT_ZIP = "corrupt_zip" + """The output zip cannot be read, or fails its CRC check.""" + FAILED = "failed" + """The status record says a Python exception ended the fit.""" + SUPERSEDED = "superseded" + """A completed result that a newer completed result of the same key replaces + (``Aggregator.latest_per``).""" + NEVER_STARTED = "never_started" + """An output folder with no checkpoint and no status record, so a rerun starts the + search from scratch; with a declared grid (results-library phase 2), also an + expected result with no output at all.""" + + def __str__(self): + return self.value + + class Product(str, Enum): """ The files a fit's status record names, relative to its ``output_path``. diff --git a/autofit/results/__init__.py b/autofit/results/__init__.py new file mode 100644 index 000000000..dd5612f0c --- /dev/null +++ b/autofit/results/__init__.py @@ -0,0 +1,14 @@ +""" +The results library (results-library epic): find, classify and count thousands of +finished fits without opening each one by hand. + +- ``ResultsIndex``: an incremental index of every result under one or more roots, one + JSON record per result (``ResultRecord``), each classified into a ``ResultState``; +- ``ResultsCache``: a local SQLite cache of an index for queries; +- ``python -m autofit.results {index,status,count}``: the command line. +""" +from autofit.non_linear.status.states import ResultState +from autofit.results.cache import ResultsCache +from autofit.results.classify import classify +from autofit.results.index import DEFAULT_LATEST_KEY, ResultsIndex, find_results +from autofit.results.record import ResultRecord diff --git a/autofit/results/__main__.py b/autofit/results/__main__.py new file mode 100644 index 000000000..f00c5a8fe --- /dev/null +++ b/autofit/results/__main__.py @@ -0,0 +1,155 @@ +""" +``python -m autofit.results``: index, classify and count results from the shell. + + python -m autofit.results index output/ [more_roots/ ...] [--index-dir DIR] + python -m autofit.results status output/ [--index-dir DIR] [--state corrupt_zip] + python -m autofit.results count output/ [--index-dir DIR] [--state completed] + +``index`` brings the index up to date (only new or changed results are opened); +``status`` prints one line per result state, or with ``--state`` the results in that +state; ``count`` prints a number. ``status`` and ``count`` read the existing index and +never open a result; run ``index`` first. +""" +import argparse +import json +import sys +import time + +from autofit.non_linear.status.states import ResultState +from autofit.results.index import ResultsIndex + + +def _index(arguments) -> ResultsIndex: + return ResultsIndex( + arguments.roots, + index_dir=arguments.index_dir, + verify=not getattr(arguments, "no_verify", False), + stale_after_s=getattr(arguments, "stale_after_s", 600.0), + ) + + +def _states(value): + if value is None: + return None + states = [state.strip() for state in value.split(",") if state.strip()] + for state in states: + ResultState(state) + return states + + +def command_index(arguments) -> int: + index = _index(arguments) + start = time.perf_counter() + counts = index.update() + elapsed = time.perf_counter() - start + print( + f"indexed {counts['scanned']} results in {elapsed:.1f} s: " + f"{counts['new']} new, {counts['changed']} changed, " + f"{counts['unchanged']} unchanged, {counts['removed']} removed " + f"(index: {index.index_dir})" + ) + return 0 + + +def _require_index(index: ResultsIndex) -> bool: + if index.manifest() is None: + print( + f"No index at {index.index_dir}; run `python -m autofit.results index` " + f"first.", + file=sys.stderr, + ) + return False + return True + + +def command_status(arguments) -> int: + index = _index(arguments) + if not _require_index(index): + return 1 + records = index.records() + states = _states(arguments.state) + if arguments.json: + if states: + records = [record for record in records if record.state in states] + print(json.dumps([record.to_dict() for record in records], indent=1)) + else: + print(json.dumps(index.counts(records), indent=1)) + return 0 + if states: + for record in records: + if record.state in states: + reason = f" ({record.reason})" if record.reason else "" + print(f"{record.state:24s} {record.output_path}{reason}") + return 0 + manifest = index.manifest() + total = len(records) + print(f"{total} results (index updated {manifest.get('updated')})") + for state, count in index.counts(records).items(): + print(f" {state:24s} {count}") + mismatched = sum(1 for record in records if record.location_mismatch) + if mismatched: + print(f" {'location_mismatch':24s} {mismatched} (declared path differs)") + return 0 + + +def command_count(arguments) -> int: + index = _index(arguments) + if not _require_index(index): + return 1 + states = _states(arguments.state) + records = index.records() + if states: + records = [record for record in records if record.state in states] + print(len(records)) + return 0 + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser( + prog="python -m autofit.results", + description="Index, classify and count PyAutoFit results.", + ) + commands = parser.add_subparsers(dest="command", required=True) + + def add(name, function, help_): + command = commands.add_parser(name, help=help_) + command.add_argument("roots", nargs="+", help="Directories holding results.") + command.add_argument( + "--index-dir", + default=None, + help="Where the index is kept (default /.autofit_index; required " + "with several roots or a read-only tree).", + ) + command.set_defaults(function=function) + return command + + index = add("index", command_index, "Bring the index up to date.") + index.add_argument( + "--no-verify", + action="store_true", + help="Do not CRC-check new or changed zips.", + ) + index.add_argument( + "--stale-after-s", + type=float, + default=600.0, + help="Age after which a 'running' status record is not trusted.", + ) + + for name, function, help_ in ( + ("status", command_status, "Results per state, or the results in a state."), + ("count", command_count, "How many results (in a state)."), + ): + command = add(name, function, help_) + command.add_argument( + "--state", default=None, help="Comma-separated result states." + ) + if name == "status": + command.add_argument("--json", action="store_true") + + arguments = parser.parse_args(argv) + return arguments.function(arguments) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/autofit/results/cache.py b/autofit/results/cache.py new file mode 100644 index 000000000..4d209fd9e --- /dev/null +++ b/autofit/results/cache.py @@ -0,0 +1,124 @@ +""" +``ResultsCache``: a local SQLite cache of a ``ResultsIndex`` for queries. + +The cache is rebuilt from the index's JSON records whenever the index is newer than +it, so it can be deleted at any time. It lives in the user's cache directory +(``$XDG_CACHE_HOME/autofit/results``, default ``~/.cache/autofit/results``), never +beside the results: SQLite is not safe on network filesystems and the records are the +truth. +""" +import hashlib +import json +import os +import sqlite3 +from pathlib import Path +from typing import Dict, List, Optional + +from autofit.results.index import ResultsIndex +from autofit.results.record import ResultRecord + +COLUMNS = ( + "output_path", + "root", + "state", + "reason", + "name", + "unique_tag", + "path_prefix", + "identifier", + "search", + "object_id", + "completed_at", + "location_mismatch", +) + + +def default_cache_dir() -> Path: + base = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache" + return Path(base) / "autofit" / "results" + + +class ResultsCache: + def __init__(self, index: ResultsIndex, cache_dir: Optional[os.PathLike] = None): + self.index = index + cache_dir = Path(cache_dir) if cache_dir is not None else default_cache_dir() + name = hashlib.sha1(str(index.index_dir).encode("utf-8")).hexdigest()[:16] + self.path = cache_dir / f"{name}.sqlite" + + def _stamp(self) -> Optional[str]: + manifest = self.index.manifest() + return None if manifest is None else manifest.get("updated") + + def connect(self) -> sqlite3.Connection: + """ + A connection to the cache, rebuilt first if the index changed since it was + built. The ``results`` table has one row per record (``COLUMNS`` plus the full + record as JSON in ``record``). + """ + stamp = self._stamp() + if self.path.exists(): + connection = sqlite3.connect(self.path) + try: + (built,) = connection.execute( + "SELECT value FROM meta WHERE key = 'index_updated'" + ).fetchone() + if built == stamp: + return connection + except (sqlite3.Error, TypeError): + pass + connection.close() + return self.rebuild(stamp) + + def rebuild(self, stamp: Optional[str] = None) -> sqlite3.Connection: + os.makedirs(self.path.parent, exist_ok=True) + tmp = self.path.with_name(f"{self.path.name}.{os.getpid()}.tmp") + if tmp.exists(): + tmp.unlink() + connection = sqlite3.connect(tmp) + connection.execute( + f"CREATE TABLE results ({', '.join(COLUMNS)}, record TEXT, " + f"PRIMARY KEY (output_path))" + ) + connection.execute("CREATE INDEX results_state ON results (state)") + connection.execute("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)") + connection.executemany( + f"INSERT INTO results VALUES ({', '.join('?' * (len(COLUMNS) + 1))})", + ( + tuple(getattr(record, column) for column in COLUMNS) + + (json.dumps(record.to_dict()),) + for record in self.index.load().values() + ), + ) + connection.execute( + "INSERT INTO meta VALUES ('index_updated', ?)", + (stamp if stamp is not None else self._stamp(),), + ) + connection.commit() + connection.close() + os.replace(tmp, self.path) + return sqlite3.connect(self.path) + + def query(self, where: str = "1", parameters=()) -> List[ResultRecord]: + """ + The records matching an SQL ``where`` clause over ``COLUMNS``, e.g. + ``query("state = ?", ("completed",))``. + """ + connection = self.connect() + try: + rows = connection.execute( + f"SELECT record FROM results WHERE {where} ORDER BY output_path", + parameters, + ).fetchall() + finally: + connection.close() + return [ResultRecord.from_dict(json.loads(row[0])) for row in rows] + + def counts(self) -> Dict[str, int]: + connection = self.connect() + try: + rows = connection.execute( + "SELECT state, COUNT(*) FROM results GROUP BY state" + ).fetchall() + finally: + connection.close() + return dict(rows) diff --git a/autofit/results/classify.py b/autofit/results/classify.py new file mode 100644 index 000000000..b63a70404 --- /dev/null +++ b/autofit/results/classify.py @@ -0,0 +1,364 @@ +""" +Classify one result on disk into a ``ResultState`` and read what the index records about +it, opening nothing but the result's own small files. + +The order of evidence: + +1. a readable zip with a ``.completed`` member (and, with ``verify``, a clean CRC check) + or a folder with a ``.completed`` file is ``completed``; an unreadable zip is + ``corrupt_zip``; +2. otherwise the status record: ``failed`` is ``failed``; ``running`` / ``pending`` / + ``timeout_pending`` written within ``stale_after_s`` is ``running``; +3. otherwise the checkpoint under ``files/search_internal/``: readable is + ``interrupted_valid_ckpt``, unreadable (or quarantined to + ``search_internal.failed_/`` with nothing since) is ``corrupt_ckpt``; +4. otherwise ``never_started`` (a folder with no checkpoint: a rerun starts from + scratch). + +``superseded`` is assigned afterwards, across results (``ResultsIndex``). +""" +import json +import os +import zipfile +import zlib +from datetime import datetime, timezone +from hashlib import md5 +from pathlib import Path, PurePosixPath +from typing import Dict, Iterable, List, Optional + +from autofit.non_linear.status.states import Product, ResultState +from autofit.results.record import ResultRecord + +ZIP_READ_ERRORS = (zipfile.BadZipFile, EOFError, zlib.error, OSError) + +RUNNING_STATES = ("running", "pending", "timeout_pending") + +STATUS_SUMMARY_KEYS = ("state", "attempt", "failure_class", "updated", "started", "job") + + +def _iso_utc(timestamp: float) -> str: + return datetime.fromtimestamp(timestamp, timezone.utc).isoformat(timespec="seconds") + + +def _parse_time(value: Optional[str]) -> Optional[datetime]: + if not value: + return None + try: + parsed = datetime.fromisoformat(value) + except ValueError: + return None + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + return parsed + + +def stat_fingerprint(output_path: Path) -> List: + """ + The (size, mtime) of each file a result's record depends on: the zip, the status + record, the folder's ``.completed`` and its ``files/`` and ``search_internal/`` + folders. A result whose fingerprint is unchanged is not classified again. + """ + output_path = Path(output_path) + fingerprint = [] + for path in ( + Path(f"{output_path}{Product.ZIP}"), + Path(f"{output_path}{Product.STATUS}"), + output_path / str(Product.COMPLETED), + output_path / "files", + output_path / "files" / "search_internal", + ): + try: + stat = os.stat(path) + except OSError: + fingerprint.append(None) + else: + fingerprint.append([stat.st_size, stat.st_mtime_ns]) + return fingerprint + + +class _Contents: + """ + The member names of a result (zip members, or files under the folder) and a way to + read the small ones. + """ + + def __init__(self, names: Iterable[str], read): + self.names = set(names) + self._read = read + + def has(self, name: str) -> bool: + return name in self.names + + def json(self, name: str) -> Optional[Dict]: + if name not in self.names: + return None + try: + return json.loads(self._read(name)) + except Exception: + return None + + def text(self, name: str) -> Optional[str]: + if name not in self.names: + return None + try: + return self._read(name).decode("utf-8") + except Exception: + return None + + +def _folder_contents(directory: Path) -> _Contents: + names = [] + for root, dirs, filenames in os.walk(directory): + relative = Path(root).relative_to(directory) + # Checkpoints are probed separately; their contents are not products. + dirs[:] = [d for d in dirs if not d.startswith("search_internal")] + for filename in filenames: + names.append(str(PurePosixPath(*relative.parts, filename))) + + def read(name): + return (directory / name).read_bytes() + + return _Contents(names, read) + + +def _identifier_of(description: Optional[str]) -> Optional[str]: + """ + The identifier recorded by ``.identifier`` (its md5, as ``SearchOutput.id``). + """ + if not description: + return None + return md5(".".join(description.split("\n")).encode("utf-8")).hexdigest() + + +def _path_of(value) -> Optional[str]: + if isinstance(value, dict) and "path" in value: + return str(value["path"]) + if value is None: + return None + return str(value) + + +def _read_metadata(record: ResultRecord, contents: _Contents, output_path: Path): + search = contents.json("files/search.json") or {} + arguments = search.get("arguments") or {} + paths = (arguments.get("paths") or {}).get("arguments") or {} + + record.name = arguments.get("name") or paths.get("name") + record.unique_tag = arguments.get("unique_tag") or paths.get("unique_tag") + record.path_prefix = _path_of( + arguments.get("path_prefix", paths.get("path_prefix")) + ) + class_path = search.get("class_path") + record.search = class_path.rsplit(".", 1)[-1] if class_path else None + + record.identifier = _identifier_of(contents.text(".identifier")) or ( + output_path.name if len(output_path.name) == 32 else None + ) + + # A result whose declared name, or the last segment of its declared path_prefix + # (usually the object), is not where it sits was copied or moved there: the fit + # it holds belongs elsewhere. Only the last segment is compared because whole + # trees are routinely moved under another root. + parts = output_path.parts + prefix_parts = PurePosixPath(record.path_prefix or "").parts + record.location_mismatch = bool( + (record.name is not None and parts[-2:-1] != (record.name,)) + or (prefix_parts and prefix_parts[-1] not in parts[:-2]) + ) + + names = contents.names + record.files = sorted( + name[len("files/") :] + for name in names + if name.startswith("files/") and not name.startswith("files/search_internal") + ) + record.n_images = sum(1 for name in names if name.startswith("image/")) + record.products = { + "samples": "files/samples.csv" in names, + "samples_summary": "files/samples_summary.json" in names, + "latent": any( + name.startswith("files/latent") or name == "latent.results" + for name in names + ), + "image": record.n_images > 0, + "dataset_identity": f"files/{Product.DATASET_IDENTITY}" in names, + } + + identity = contents.json(f"files/{Product.DATASET_IDENTITY}") + if identity: + record.object_id = identity.get("object_id") + record.inputs = { + name: entry.get("sha256") + for name, entry in (identity.get("inputs") or {}).items() + if isinstance(entry, dict) + } + record.versions = dict(identity.get("versions") or {}) + + +def _probe_search_internal(files_path: Path) -> Optional[ResultState]: + """ + ``interrupted_valid_ckpt`` / ``corrupt_ckpt`` from the checkpoint under + ``files_path``, or ``None`` when there is no checkpoint. + """ + directory = files_path / "search_internal" + entries = ( + [p for p in directory.rglob("*") if p.is_file()] if directory.is_dir() else [] + ) + if entries: + for path in entries: + if path.stat().st_size == 0: + return ResultState.CORRUPT_CKPT + if path.suffix in (".hdf5", ".h5"): + from autofit.non_linear.checkpoint import ( + HDF5_PROBE_ERRORS, + probe_hdf5, + ) + + try: + probe_hdf5(path) + except HDF5_PROBE_ERRORS: + return ResultState.CORRUPT_CKPT + except ImportError: + pass + return ResultState.INTERRUPTED_VALID_CKPT + if files_path.is_dir() and any( + p.name.startswith("search_internal.failed_") for p in files_path.iterdir() + ): + return ResultState.CORRUPT_CKPT + return None + + +def classify( + output_path, + root, + verify: bool = True, + stale_after_s: float = 600.0, + now: Optional[datetime] = None, +) -> ResultRecord: + """ + The ``ResultRecord`` of the result at ``output_path`` (the folder path, without + ``.zip``), found under ``root``. + + Parameters + ---------- + verify + Check every zip member's CRC (``ZipFile.testzip``), which reads the whole zip. + Without it a zip with a ``.completed`` member counts as completed unread. + stale_after_s + A status record saying ``running`` that was last written longer ago than this + is not trusted: the process is assumed gone and the checkpoint decides. + """ + output_path = Path(output_path) + zip_path = Path(f"{output_path}{Product.ZIP}") + status_path = Path(f"{output_path}{Product.STATUS}") + now = now or datetime.now(timezone.utc) + + record = ResultRecord( + output_path=str(output_path), + root=str(root), + state=str(ResultState.NEVER_STARTED), + has_zip=zip_path.is_file(), + has_dir=output_path.is_dir(), + has_status=status_path.is_file(), + stat_key=stat_fingerprint(output_path), + ) + + status = None + if record.has_status: + try: + with open(status_path) as f: + status = json.load(f) + except (OSError, ValueError): + status = None + if status is not None: + record.status = {k: status.get(k) for k in STATUS_SUMMARY_KEYS} + + state = None + contents = None + + if record.has_zip: + record.bytes = zip_path.stat().st_size + try: + with zipfile.ZipFile(zip_path) as f: + names = f.namelist() + small = {} + for name in names: + if name.startswith("files/search_internal"): + continue + info = f.getinfo(name) + if info.file_size <= 1 << 20 and ( + name in (".identifier", ".completed") + or name.endswith(".json") + ): + small[name] = f.read(name) + if ".completed" in names: + if verify and f.testzip() is not None: + raise zipfile.BadZipFile("a member fails its CRC check") + state = ResultState.COMPLETED + record.completed_at = datetime( + *f.getinfo(".completed").date_time + ).isoformat() + record.completed_at_source = "zip_member" + contents = _Contents(names, small.__getitem__) + except ZIP_READ_ERRORS as error: + state = ResultState.CORRUPT_ZIP + record.reason = f"{type(error).__name__}: {error}" + if state is None and contents is not None and not record.has_dir: + state = ResultState.CORRUPT_ZIP + record.reason = "zip has no .completed member" + + if state is None and record.has_dir: + completed = output_path / str(Product.COMPLETED) + if completed.exists(): + state = ResultState.COMPLETED + record.completed_at = _iso_utc(completed.stat().st_mtime) + record.completed_at_source = "completed_file" + contents = _folder_contents(output_path) + elif state == ResultState.CORRUPT_ZIP and record.has_dir: + # The folder beside an unreadable zip may still be whole. + if (output_path / str(Product.COMPLETED)).exists(): + state = ResultState.COMPLETED + record.reason = "zip unreadable; the folder beside it is complete" + record.completed_at = _iso_utc( + (output_path / str(Product.COMPLETED)).stat().st_mtime + ) + record.completed_at_source = "completed_file" + contents = _folder_contents(output_path) + + if state == ResultState.COMPLETED and status and status.get("state") == "completed": + record.completed_at = status.get("updated") or record.completed_at + record.completed_at_source = "status" + + if state is None and status is not None: + if status.get("state") == "failed": + state = ResultState.FAILED + record.reason = status.get("failure_class") + elif status.get("state") in RUNNING_STATES: + updated = _parse_time(status.get("updated")) + if updated is not None and (now - updated).total_seconds() <= stale_after_s: + state = ResultState.RUNNING + else: + record.reason = ( + f"status says {status.get('state')} but was last written " + f"{status.get('updated')}" + ) + + if state is None and record.has_dir: + probed = _probe_search_internal(output_path / "files") + if probed is not None: + state = probed + else: + state = ResultState.NEVER_STARTED + record.reason = record.reason or "output folder with no checkpoint" + + if state is None: + state = ResultState.NEVER_STARTED + record.reason = record.reason or "status record only" + + record.state = str(state) + if contents is not None: + _read_metadata(record, contents, output_path) + record.products["search_internal"] = ( + output_path / "files" / "search_internal" + ).is_dir() + return record diff --git a/autofit/results/index.py b/autofit/results/index.py new file mode 100644 index 000000000..b7c4400d0 --- /dev/null +++ b/autofit/results/index.py @@ -0,0 +1,310 @@ +""" +``ResultsIndex``: an incremental, layout-agnostic index of every result under one or +more root directories. + +The index is a folder of per-result JSON records (``/records/.json``, +``ResultRecord``) plus ``/index.json`` (roots, counts, when it was last +updated). The records are the truth: they are plain files, so they rsync with the +results and any tool can read them. ``ResultsCache`` builds a local SQLite cache from +them for queries; the cache is never the truth and never sits on a network filesystem. + +The index is written only by ``ResultsIndex.update`` (``python -m autofit.results +index``); a fit writes only its status record and ``dataset_identity.json``. + +``update`` walks the roots and fingerprints each result (``stat_fingerprint``); a +result whose fingerprint matches its record is not opened again, so re-indexing a +large tree after a few new results costs a directory walk. Records of results that no +longer exist are removed. + +By default the index lives at ``/.autofit_index``; pass ``index_dir`` to keep it +elsewhere, e.g. when the results tree is read-only. +""" +import json +import logging +import os +from collections import Counter, defaultdict +from datetime import datetime, timezone +from pathlib import Path +from typing import Dict, Iterable, Iterator, List, Optional, Sequence, Tuple, Union + +from autofit.non_linear.status.states import Product, ResultState +from autofit.results.classify import classify, stat_fingerprint +from autofit.results.record import SCHEMA, ResultRecord, record_key +from autofit.tools.util import open_atomic + +logger = logging.getLogger(__name__) + +INDEX_DIRNAME = ".autofit_index" + +DEFAULT_LATEST_KEY = ("path_prefix", "unique_tag", "name") +""" +The key whose results replace one another: one fit of one search (``name``) of one +object (``path_prefix`` / ``unique_tag``). Different identifiers under one key are +reruns of that fit with another model or search setting (sibling hashes). +""" + +_SKIP_DIRS = {"files", "image", INDEX_DIRNAME} + +_STATUS_SUFFIX = str(Product.STATUS) +_ZIP_SUFFIX = str(Product.ZIP) + + +def _is_output_folder(path: Path, filenames: Sequence[str], dirs: Sequence[str]) -> bool: + if "files" in dirs and (path / "files" / "search.json").exists(): + return True + return ".completed" in filenames or "metadata" in filenames + + +def find_results(root: Union[str, os.PathLike]) -> Iterator[Path]: + """ + Every result ``output_path`` under ``root``: a folder holding ``files/search.json`` + (or ``.completed`` / legacy ``metadata``), a ``.zip`` or a + ``.status.json``, whatever the nesting. + """ + seen = set() + for current, dirs, filenames in os.walk(root, topdown=True): + current_path = Path(current) + for filename in filenames: + if filename.endswith(_STATUS_SUFFIX): + stem = filename[: -len(_STATUS_SUFFIX)] + elif filename.endswith(_ZIP_SUFFIX): + stem = filename[: -len(_ZIP_SUFFIX)] + else: + continue + output_path = current_path / stem + if output_path not in seen: + seen.add(output_path) + yield output_path + if current_path != Path(root) and _is_output_folder( + current_path, filenames, dirs + ): + if current_path not in seen: + seen.add(current_path) + yield current_path + # Never descend into a result's own products or checkpoints; nested + # searches (grid search children, ``analyses/``) still are. + dirs[:] = sorted( + d + for d in dirs + if d not in _SKIP_DIRS and not d.startswith("search_internal") + ) + + +def _now() -> str: + # Microseconds: the cache is rebuilt when this stamp changes, and two updates can + # fall within one second. + return datetime.now(timezone.utc).isoformat(timespec="microseconds") + + +class ResultsIndex: + def __init__( + self, + roots: Union[str, os.PathLike, Iterable[Union[str, os.PathLike]]], + index_dir: Optional[Union[str, os.PathLike]] = None, + verify: bool = True, + stale_after_s: float = 600.0, + latest_key: Tuple[str, ...] = DEFAULT_LATEST_KEY, + ): + """ + The index of the results under ``roots``. + + Parameters + ---------- + roots + One or more directories searched recursively for results. + index_dir + Where the records are kept. Defaults to ``/.autofit_index`` (only + allowed with a single root). + verify + Check each new or changed zip's CRC when classifying it. + stale_after_s + How old a ``running`` status record may be before it is not trusted. + latest_key + The record fields whose results replace one another; within a key, every + completed result but the latest is ``superseded``. + """ + if isinstance(roots, (str, os.PathLike)): + roots = [roots] + self.roots = [Path(root).resolve() for root in roots] + if index_dir is None: + if len(self.roots) != 1: + raise ValueError( + "Indexing several roots needs an explicit index_dir." + ) + index_dir = self.roots[0] / INDEX_DIRNAME + self.index_dir = Path(index_dir).resolve() + self.verify = verify + self.stale_after_s = stale_after_s + self.latest_key = tuple(latest_key) + + @property + def records_dir(self) -> Path: + return self.index_dir / "records" + + @property + def manifest_path(self) -> Path: + return self.index_dir / "index.json" + + def _record_path(self, key: str) -> Path: + return self.records_dir / f"{key}.json" + + def load(self) -> Dict[str, ResultRecord]: + """ + Every record in the index, by output path. Unreadable records are skipped (and + rebuilt by the next ``update``). + """ + records = {} + if not self.records_dir.is_dir(): + return records + with os.scandir(self.records_dir) as entries: + for entry in entries: + if not entry.name.endswith(".json"): + continue + try: + with open(entry.path) as f: + record = ResultRecord.from_dict(json.load(f)) + except (OSError, ValueError, TypeError): + continue + if record.schema != SCHEMA: + continue + records[record.output_path] = record + return records + + def records(self) -> List[ResultRecord]: + """ + Every record, sorted by output path. + """ + return sorted(self.load().values(), key=lambda record: record.output_path) + + def _write(self, record: ResultRecord): + with open_atomic(self._record_path(record.key)) as f: + json.dump(record.to_dict(), f, indent=1) + + def update(self) -> Dict[str, int]: + """ + Bring the index up to date with the roots: classify new and changed results, + keep unchanged ones, drop vanished ones and re-mark ``superseded``. + + Returns + ------- + Counts of ``scanned``, ``new``, ``changed``, ``unchanged`` and ``removed`` + results. + """ + os.makedirs(self.records_dir, exist_ok=True) + existing = self.load() + found = {} + counts = Counter() + + for root in self.roots: + for output_path in find_results(root): + if self.index_dir in output_path.parents: + continue + counts["scanned"] += 1 + key = str(output_path) + record = existing.get(key) + if record is not None and record.stat_key == stat_fingerprint( + output_path + ): + # A running record goes stale with time alone, not on disk. + if record.state != str(ResultState.RUNNING): + found[key] = record + counts["unchanged"] += 1 + continue + try: + record_new = classify( + output_path, + root=root, + verify=self.verify, + stale_after_s=self.stale_after_s, + ) + except Exception as exception: + logger.warning(f"Could not index {output_path}: {exception}") + continue + counts["new" if record is None else "changed"] += 1 + found[key] = record_new + self._write(record_new) + + for key, record in existing.items(): + if key not in found: + try: + self._record_path(record.key).unlink() + except FileNotFoundError: + pass + counts["removed"] += 1 + + for record in self._mark_superseded(found.values()): + self._write(record) + + self._write_manifest(found.values()) + + return { + name: counts[name] + for name in ("scanned", "new", "changed", "unchanged", "removed") + } + + def _mark_superseded(self, records: Iterable[ResultRecord]) -> List[ResultRecord]: + """ + Within each ``latest_key`` group, mark every completed result but the latest + ``superseded`` (and restore a superseded result that became the latest). + Returns the records that changed. + """ + groups = defaultdict(list) + for record in records: + if record.state in ( + str(ResultState.COMPLETED), + str(ResultState.SUPERSEDED), + ): + groups[tuple(getattr(record, k) for k in self.latest_key)].append( + record + ) + + changed = [] + for group in groups.values(): + latest = max(group, key=lambda r: (r.completed_at or "", r.output_path)) + for record in group: + state = ( + str(ResultState.COMPLETED) + if record is latest + else str(ResultState.SUPERSEDED) + ) + if record.state != state: + record.state = state + record.reason = ( + None + if record is latest + else f"a later result of the same key: {latest.output_path}" + ) + changed.append(record) + return changed + + def _write_manifest(self, records: Iterable[ResultRecord]): + states = Counter(record.state for record in records) + with open_atomic(self.manifest_path) as f: + json.dump( + { + "schema": SCHEMA, + "roots": [str(root) for root in self.roots], + "updated": _now(), + "latest_key": list(self.latest_key), + "counts": dict(sorted(states.items())), + }, + f, + indent=1, + ) + + def manifest(self) -> Optional[Dict]: + try: + with open(self.manifest_path) as f: + return json.load(f) + except (OSError, ValueError): + return None + + def counts(self, records: Optional[Iterable[ResultRecord]] = None) -> Dict[str, int]: + """ + The number of results in each ``ResultState`` (every state listed, zeros + included). + """ + if records is None: + records = self.load().values() + states = Counter(record.state for record in records) + return {str(state): states.get(str(state), 0) for state in ResultState} diff --git a/autofit/results/record.py b/autofit/results/record.py new file mode 100644 index 000000000..231ed0f53 --- /dev/null +++ b/autofit/results/record.py @@ -0,0 +1,84 @@ +""" +``ResultRecord``: one result as the results index sees it. + +A result is one fit's ``output_path`` (``///``), +which may be on disk as a folder, a ``.zip``, a +``.status.json`` or any combination of them. The record is the index's +unit of truth: it is written as one JSON file per result +(``/records/.json``) and holds everything ``status``, ``count`` and +``latest_per`` need, so none of them opens a result again. +""" +import hashlib +from dataclasses import asdict, dataclass, field +from typing import Dict, List, Optional + +SCHEMA = 1 + + +def record_key(output_path: str) -> str: + """ + The file name (without ``.json``) of the record of the result at ``output_path``. + """ + return hashlib.sha1(str(output_path).encode("utf-8")).hexdigest() + + +@dataclass +class ResultRecord: + output_path: str + """The result's ``output_path`` (absolute, without ``.zip``).""" + root: str + """The root directory the result was found under.""" + state: str + """A ``ResultState`` value.""" + reason: Optional[str] = None + """Why the result has this state, when it is not plainly ``completed``.""" + has_zip: bool = False + has_dir: bool = False + has_status: bool = False + name: Optional[str] = None + """The search's ``name``, from ``files/search.json``.""" + unique_tag: Optional[str] = None + path_prefix: Optional[str] = None + """The ``path_prefix`` the search declared, from ``files/search.json``.""" + location_mismatch: bool = False + """Whether the declared ``path_prefix`` / ``name`` disagree with where the result + sits on disk (e.g. a result copied or moved into another object's folder).""" + identifier: Optional[str] = None + search: Optional[str] = None + """The class name of the search (e.g. ``Nautilus``).""" + completed_at: Optional[str] = None + """When the result completed (ISO 8601), never the zip's modification time.""" + completed_at_source: Optional[str] = None + """``status`` (the status record), ``zip_member`` (the ``.completed`` member's + timestamp, local time as zipped) or ``completed_file`` (its mtime).""" + products: Dict[str, bool] = field(default_factory=dict) + """Which standard products are present (``samples``, ``samples_summary``, + ``latent``, ``image``, ``search_internal``, ``dataset_identity``).""" + files: List[str] = field(default_factory=list) + """The paths under ``files/``, relative to it.""" + n_images: int = 0 + object_id: Optional[str] = None + """From ``dataset_identity.json``.""" + inputs: Dict[str, Optional[str]] = field(default_factory=dict) + """Input name to SHA256 (``None`` when not hashed), from ``dataset_identity.json``.""" + versions: Dict[str, str] = field(default_factory=dict) + status: Optional[Dict] = None + """A summary of the status record: state, attempt, failure class, updated, job.""" + bytes: Optional[int] = None + """The size of the zip, when there is one.""" + stat_key: List = field(default_factory=list) + """The stat fingerprint the record was built from; an unchanged fingerprint means + the result is not opened again.""" + schema: int = SCHEMA + + @property + def key(self) -> str: + return record_key(self.output_path) + + def to_dict(self) -> Dict: + return asdict(self) + + @classmethod + def from_dict(cls, document: Dict) -> "ResultRecord": + known = cls.__dataclass_fields__ + return cls(**{k: v for k, v in document.items() if k in known}) diff --git a/test_autofit/results/__init__.py b/test_autofit/results/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/test_autofit/results/conftest.py b/test_autofit/results/conftest.py new file mode 100644 index 000000000..2e76cd99a --- /dev/null +++ b/test_autofit/results/conftest.py @@ -0,0 +1,8 @@ +import pytest + + +@pytest.fixture(name="results_root") +def make_results_root(tmp_path): + root = tmp_path / "output" + root.mkdir() + return root diff --git a/test_autofit/results/test_identity.py b/test_autofit/results/test_identity.py new file mode 100644 index 000000000..048486763 --- /dev/null +++ b/test_autofit/results/test_identity.py @@ -0,0 +1,146 @@ +""" +``dataset_identity.json`` written by real (cheap) fits, and ``Aggregator.latest_per`` +over their outputs. +""" +import json +import zipfile +from pathlib import Path + +import numpy as np +import pytest + +import autofit as af +from autofit.non_linear.status.identity import ( + dataset_identity_document, + sha256_of, +) +from autofit.aggregator.aggregator import Aggregator +from autofit.results import ResultsIndex +from autonerves import conf + +CONFIG = Path(__file__).parents[1] / "config" + +pytestmark = pytest.mark.filterwarnings("ignore::FutureWarning") + + +@pytest.fixture(name="output", autouse=True) +def make_output(tmp_path): + conf.instance.push(new_path=str(CONFIG), output_path=str(tmp_path / "output")) + return tmp_path / "output" + + +class IdentifiedAnalysis(af.ex.Analysis): + def __init__(self, data_path, **kwargs): + super().__init__(**kwargs) + self.data_path = data_path + + def dataset_identity(self): + return { + "object_id": "lens_42", + "external_ids": {"tile": "102022527"}, + "inputs": {"data": self.data_path}, + "centre": (0.1, -0.2), + } + + +def _analysis(cls=af.ex.Analysis, **kwargs): + return cls(data=np.ones(20), noise_map=np.ones(20) * 0.1, use_jax=False, **kwargs) + + +def _fit(analysis, name="identity_fit", unique_tag=None, total_draws=5): + search = af.Drawer(name=name, unique_tag=unique_tag, total_draws=total_draws) + search.fit(model=af.Model(af.ex.Gaussian), analysis=analysis) + return search + + +def _identity_in_zip(search): + with zipfile.ZipFile(f"{search.paths.output_path}.zip") as f: + return json.loads(f.read("files/dataset_identity.json")) + + +def test_fit_records_its_inputs_with_sha256(tmp_path): + data_path = tmp_path / "data.fits" + data_path.write_bytes(b"pixels" * 100) + + search = _fit(_analysis(IdentifiedAnalysis, data_path=data_path)) + identity = _identity_in_zip(search) + + assert identity["schema"] == 1 + assert identity["object_id"] == "lens_42" + assert identity["external_ids"] == {"tile": "102022527"} + assert identity["centre"] == [0.1, -0.2] + assert identity["inputs"]["data"]["sha256"] == sha256_of(data_path) + assert identity["inputs"]["data"]["bytes"] == 600 + assert "autofit" in identity["versions"] + + +def test_default_identity_is_the_unique_tag(): + search = _fit(_analysis(), unique_tag="dataset_7") + + identity = _identity_in_zip(search) + + assert identity["object_id"] == "dataset_7" + assert identity["inputs"] == {} + + +def test_sha256_switch_and_off_switch(tmp_path, monkeypatch): + data_path = tmp_path / "data.fits" + data_path.write_bytes(b"pixels") + + document = dataset_identity_document( + {"inputs": [data_path]}, unique_tag=None, sha256=False + ) + assert document["inputs"]["data.fits"] == { + "path": str(data_path.resolve()), + "bytes": 6, + } + + output = conf.instance["general"]["output"] + monkeypatch.setitem(output, "dataset_identity", False) + search = _fit(_analysis(), name="no_identity") + with zipfile.ZipFile(f"{search.paths.output_path}.zip") as f: + assert "files/dataset_identity.json" not in f.namelist() + + +def test_missing_input_is_recorded_not_raised(tmp_path): + document = dataset_identity_document( + {"inputs": {"psf": tmp_path / "absent.fits"}}, unique_tag="x" + ) + assert document["inputs"]["psf"]["missing"] is True + + +def test_index_reads_identity_from_a_real_fit(output, tmp_path): + data_path = tmp_path / "data.fits" + data_path.write_bytes(b"pixels") + _fit(_analysis(IdentifiedAnalysis, data_path=data_path)) + + index = ResultsIndex(output) + index.update() + (record,) = index.records() + + assert record.state == "completed" + assert record.object_id == "lens_42" + assert record.inputs == {"data": sha256_of(data_path)} + assert record.products["dataset_identity"] + assert record.completed_at_source == "status" + assert record.status["state"] == "completed" + + +def test_latest_per_keeps_the_latest_sibling(output): + _fit(_analysis(), name="search", unique_tag="dataset_0", total_draws=5) + second = _fit(_analysis(), name="search", unique_tag="dataset_0", total_draws=6) + _fit(_analysis(), name="search", unique_tag="dataset_1", total_draws=5) + second_completed = json.loads( + Path(f"{second.paths.output_path}.status.json").read_text() + )["updated"] + + aggregator = Aggregator.from_directory(output) + assert len(aggregator) == 3 + + latest = aggregator.latest_per() + + assert len(latest) == 2 + kept = {o.unique_tag: o for o in latest} + # From the status record beside each output, not the extraction's file times. + assert kept["dataset_0"].completed_at == second_completed + assert Path(kept["dataset_0"].directory) == Path(second.paths.output_path) diff --git a/test_autofit/results/test_index.py b/test_autofit/results/test_index.py new file mode 100644 index 000000000..4730c657e --- /dev/null +++ b/test_autofit/results/test_index.py @@ -0,0 +1,251 @@ +""" +The results index over synthetic trees: every result state, incremental re-indexing, +superseded siblings, the SQLite cache and the command line. +""" +import json +import zipfile +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest + +from autofit.non_linear.status.states import ResultState +from autofit.results import ResultsCache, ResultsIndex, classify, find_results +from autofit.results.__main__ import main + +from .tree import write_folder, write_status, write_zip + + +def _states(index): + return {Path(r.output_path).parts[-3]: r.state for r in index.records()} + + +def test_every_state_is_classified(results_root): + write_zip(results_root, prefix="zipped") + write_folder(results_root, prefix="folder") + corrupt = write_zip(results_root, prefix="corrupt_zip") + Path(f"{corrupt}.zip").write_bytes(b"not a zip") + write_folder(results_root, prefix="resumable", completed=False, checkpoint="valid") + write_folder(results_root, prefix="bad_ckpt", completed=False, checkpoint="empty") + write_folder( + results_root, prefix="quarantined", completed=False, checkpoint="quarantined" + ) + write_folder(results_root, prefix="fresh", completed=False) + failed = write_folder(results_root, prefix="failed", completed=False) + write_status(failed, "failed", failure_class="bad_input") + running = write_folder(results_root, prefix="running", completed=False) + write_status(running, "running") + stale = write_folder( + results_root, prefix="stale", completed=False, checkpoint="valid" + ) + write_status( + stale, + "running", + updated=(datetime.now(timezone.utc) - timedelta(hours=2)).isoformat(), + ) + + index = ResultsIndex(results_root) + index.update() + + assert _states(index) == { + "zipped": "completed", + "folder": "completed", + "corrupt_zip": "corrupt_zip", + "resumable": "interrupted_valid_ckpt", + "bad_ckpt": "corrupt_ckpt", + "quarantined": "corrupt_ckpt", + "fresh": "never_started", + "failed": "failed", + "running": "running", + "stale": "interrupted_valid_ckpt", + } + records = {Path(r.output_path).parts[-3]: r for r in index.records()} + assert records["failed"].reason == "bad_input" + assert "last written" in records["stale"].reason + assert set(index.counts()) == {str(state) for state in ResultState} + + +def test_record_holds_metadata_products_and_completion_time(results_root): + output_path = write_zip( + results_root, prefix="lens_1", name="vis_lp", date_time=(2026, 9, 28, 0, 47, 52) + ) + + record = classify(output_path, root=results_root) + + assert record.state == "completed" + assert record.name == "vis_lp" + assert record.unique_tag == "lens_1" + assert record.path_prefix == "lens_1" + assert record.search == "Nautilus" + assert record.identifier == output_path.name + assert record.completed_at == "2026-09-28T00:47:52" + assert record.completed_at_source == "zip_member" + assert record.products["samples"] and record.products["image"] + assert not record.products["latent"] + assert "samples_summary.json" in record.files + assert not record.location_mismatch + + +def test_status_record_gives_the_completion_time(results_root): + output_path = write_zip(results_root) + write_status(output_path, "completed", updated="2026-10-02T09:00:00+00:00") + + record = classify(output_path, root=results_root) + + assert record.completed_at == "2026-10-02T09:00:00+00:00" + assert record.completed_at_source == "status" + + +def test_crc_failure_is_a_corrupt_zip(results_root): + output_path = write_zip(results_root) + zip_path = Path(f"{output_path}.zip") + data = bytearray(zip_path.read_bytes()) + offset = data.index(b"a,b") + data[offset] = ord("X") + zip_path.write_bytes(bytes(data)) + + assert classify(output_path, root=results_root).state == "corrupt_zip" + assert ( + classify(output_path, root=results_root, verify=False).state == "completed" + ) + + +def test_result_moved_into_another_objects_folder_is_flagged(results_root): + output_path = write_zip(results_root, prefix="lens_1") + moved = results_root / "lens_2" / "search" / output_path.name + moved.parent.mkdir(parents=True) + Path(f"{output_path}.zip").rename(f"{moved}.zip") + + assert classify(moved, root=results_root).location_mismatch + + +def test_nested_and_custom_layouts_are_found(results_root): + write_zip(results_root / "a" / "b" / "c", prefix="deep") + write_folder(results_root, prefix="flat") + nested = write_folder(results_root, prefix="outer") + write_folder(nested / "analyses", prefix="analysis_0") + + found = sorted(str(p.relative_to(results_root)) for p in find_results(results_root)) + + assert len(found) == 4 + assert all("files" not in Path(p).parts for p in found) + + +def test_reindex_only_opens_new_and_changed_results(results_root, monkeypatch): + for seed in range(30): + write_zip(results_root, prefix=f"dataset_{seed}", seed=seed) + index = ResultsIndex(results_root) + assert index.update()["new"] == 30 + + opened = [] + import autofit.results.index as index_module + + original = index_module.classify + + def counting(output_path, **kwargs): + opened.append(output_path) + return original(output_path, **kwargs) + + monkeypatch.setattr(index_module, "classify", counting) + + for seed in range(30, 40): + write_zip(results_root, prefix=f"dataset_{seed}", seed=seed) + counts = index.update() + + assert counts == { + "scanned": 40, + "new": 10, + "changed": 0, + "unchanged": 30, + "removed": 0, + } + assert len(opened) == 10 + + removed = results_root / "dataset_0" + for path in removed.rglob("*.zip"): + path.unlink() + assert index.update()["removed"] == 1 + assert len(index.records()) == 39 + + +def test_sibling_hashes_older_completed_is_superseded(results_root): + old = write_zip(results_root, seed=1, date_time=(2026, 9, 1, 0, 0, 0)) + new = write_zip(results_root, seed=2, date_time=(2026, 10, 1, 0, 0, 0)) + other = write_zip(results_root, prefix="dataset_1", seed=3) + + index = ResultsIndex(results_root) + index.update() + states = {r.output_path: r.state for r in index.records()} + + assert states[str(old)] == "superseded" + assert states[str(new)] == "completed" + assert states[str(other)] == "completed" + + # The latest disappearing restores the older one. + Path(f"{new}.zip").unlink() + index.update() + assert {r.output_path: r.state for r in index.records()}[str(old)] == "completed" + + +def test_index_dir_keeps_a_read_only_tree_untouched(results_root, tmp_path): + write_zip(results_root) + before = sorted(p for p in results_root.rglob("*")) + + index = ResultsIndex([results_root], index_dir=tmp_path / "index") + index.update() + + assert sorted(p for p in results_root.rglob("*")) == before + assert (tmp_path / "index" / "index.json").exists() + assert len(index.records()) == 1 + + +def test_several_roots_need_an_index_dir(tmp_path): + with pytest.raises(ValueError): + ResultsIndex([tmp_path / "a", tmp_path / "b"]) + + +def test_sqlite_cache_is_rebuilt_from_the_records(results_root, tmp_path): + write_zip(results_root) + corrupt = write_zip(results_root, prefix="dataset_1") + Path(f"{corrupt}.zip").write_bytes(b"junk") + index = ResultsIndex(results_root) + index.update() + + cache = ResultsCache(index, cache_dir=tmp_path / "cache") + + assert cache.counts() == {"completed": 1, "corrupt_zip": 1} + assert [r.output_path for r in cache.query("state = ?", ("corrupt_zip",))] == [ + str(corrupt) + ] + + write_zip(results_root, prefix="dataset_2") + index.update() + assert cache.counts()["completed"] == 2 + + +def test_cli_index_status_count(results_root, tmp_path, capsys): + write_zip(results_root) + corrupt = write_zip(results_root, prefix="dataset_1") + Path(f"{corrupt}.zip").write_bytes(b"junk") + index_dir = str(tmp_path / "index") + + assert main(["status", str(results_root), "--index-dir", index_dir]) == 1 + capsys.readouterr() + + assert main(["index", str(results_root), "--index-dir", index_dir]) == 0 + assert "indexed 2 results" in capsys.readouterr().out + + main(["status", str(results_root), "--index-dir", index_dir]) + out = capsys.readouterr().out + assert "2 results" in out + assert "completed 1" in out + assert "corrupt_zip 1" in out + + main(["status", str(results_root), "--index-dir", index_dir, "--state", "corrupt_zip"]) + assert str(corrupt) in capsys.readouterr().out + + main(["count", str(results_root), "--index-dir", index_dir, "--state", "completed"]) + assert capsys.readouterr().out.strip() == "1" + + main(["status", str(results_root), "--index-dir", index_dir, "--json"]) + assert json.loads(capsys.readouterr().out)["completed"] == 1 diff --git a/test_autofit/results/tree.py b/test_autofit/results/tree.py new file mode 100644 index 000000000..89457499d --- /dev/null +++ b/test_autofit/results/tree.py @@ -0,0 +1,114 @@ +""" +Synthetic results trees for the results index: each helper writes one result in the +on-disk form a real fit leaves (``//`` as a zip, a folder, +a status record or a mix), with only the small files the index reads. +""" +import json +import zipfile +from datetime import datetime, timezone +from hashlib import md5 +from pathlib import Path + + +def _search_json(name, unique_tag, path_prefix): + return json.dumps( + { + "type": "instance", + "class_path": "autofit.non_linear.search.nest.nautilus.search.Nautilus", + "arguments": { + "name": name, + "unique_tag": unique_tag, + "path_prefix": {"type": "path", "path": str(path_prefix)}, + }, + } + ) + + +def _identifier(seed): + return md5(f"Nautilus.{seed}".encode()).hexdigest() + + +def _members(name, unique_tag, path_prefix, seed, completed=True): + members = { + ".identifier": f"Nautilus\n{seed}", + "files/search.json": _search_json(name, unique_tag, path_prefix), + "files/samples_summary.json": "{}", + "files/samples.csv": "a,b\n1,2\n", + "image/fit.png": b"\x89PNG", + } + if completed: + members[".completed"] = "" + return members + + +def write_zip( + root, + prefix="dataset_0", + name="search", + unique_tag=None, + seed=0, + completed=True, + date_time=(2026, 10, 1, 12, 0, 0), +): + """ + A ``remove_files`` result: only ``.zip`` is left. + """ + output_path = Path(root) / prefix / name / _identifier(seed) + output_path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(f"{output_path}.zip", "w") as f: + for member, content in _members( + name, unique_tag or prefix, prefix, seed, completed + ).items(): + f.writestr(zipfile.ZipInfo(member, date_time=date_time), content) + return output_path + + +def write_folder( + root, + prefix="dataset_0", + name="search", + seed=0, + completed=True, + checkpoint=None, +): + """ + An unzipped result folder; ``checkpoint`` is ``None``, ``"valid"``, + ``"empty"`` or ``"quarantined"``. + """ + output_path = Path(root) / prefix / name / _identifier(seed) + for member, content in _members(name, prefix, prefix, seed, completed).items(): + path = output_path / member + path.parent.mkdir(parents=True, exist_ok=True) + if isinstance(content, bytes): + path.write_bytes(content) + else: + path.write_text(content) + internal = output_path / "files" / "search_internal" + if checkpoint == "valid": + internal.mkdir(parents=True) + (internal / "search_internal.dill").write_bytes(b"state") + elif checkpoint == "empty": + internal.mkdir(parents=True) + (internal / "search_internal.dill").write_bytes(b"") + elif checkpoint == "quarantined": + failed = output_path / "files" / "search_internal.failed_20261001T000000Z" + failed.mkdir(parents=True) + (failed / "checkpoint.hdf5").write_bytes(b"x") + return output_path + + +def write_status(output_path, state, updated=None, failure_class=None): + updated = updated or datetime.now(timezone.utc).isoformat(timespec="seconds") + Path(f"{output_path}.status.json").write_text( + json.dumps( + { + "schema": 1, + "state": state, + "attempt": 1, + "failure_class": failure_class, + "updated": updated, + "started": updated, + "job": None, + } + ) + ) From 7cc434cb747c1f126ef71311d975a1d7df3e7eeb Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 30 Oct 2026 09:30:04 +0000 Subject: [PATCH 2/4] fix: an I/O error reading a zip is unreadable, not corrupt (results index) Witness W1 over the DR1 laptop mirror classified a healthy zip as corrupt_zip after a transient ENOMEM over /mnt/c. Only BadZipFile, EOFError and zlib.error mean a damaged archive; an OSError is retried once, then the result is counted as unreadable and keeps its previous record. Refs #1739 Co-Authored-By: Claude Opus 5.5 --- autofit/results/__main__.py | 3 +- autofit/results/classify.py | 77 +++++++++++++++++++++--------- autofit/results/index.py | 21 ++++++-- test_autofit/results/test_index.py | 22 +++++++++ 4 files changed, 96 insertions(+), 27 deletions(-) diff --git a/autofit/results/__main__.py b/autofit/results/__main__.py index f00c5a8fe..7eecd0e32 100644 --- a/autofit/results/__main__.py +++ b/autofit/results/__main__.py @@ -45,7 +45,8 @@ def command_index(arguments) -> int: print( f"indexed {counts['scanned']} results in {elapsed:.1f} s: " f"{counts['new']} new, {counts['changed']} changed, " - f"{counts['unchanged']} unchanged, {counts['removed']} removed " + f"{counts['unchanged']} unchanged, {counts['removed']} removed, " + f"{counts['unreadable']} unreadable (retried next time) " f"(index: {index.index_dir})" ) return 0 diff --git a/autofit/results/classify.py b/autofit/results/classify.py index b63a70404..47dbc178d 100644 --- a/autofit/results/classify.py +++ b/autofit/results/classify.py @@ -29,7 +29,19 @@ from autofit.non_linear.status.states import Product, ResultState from autofit.results.record import ResultRecord -ZIP_READ_ERRORS = (zipfile.BadZipFile, EOFError, zlib.error, OSError) +ZIP_CONTENT_ERRORS = (zipfile.BadZipFile, EOFError, zlib.error) +""" +What a damaged zip raises. An ``OSError`` is not among them: reading a healthy zip +over a network or WSL filesystem can fail transiently (``ENOMEM``, ``EIO``), and such +a result is not corrupt but unreadable this time (``UnreadableResult``). +""" + + +class UnreadableResult(OSError): + """ + A result could not be read because of an I/O error that persisted after a retry; + its state is unknown, not corrupt. + """ RUNNING_STATES = ("running", "pending", "timeout_pending") @@ -228,6 +240,42 @@ def _probe_search_internal(files_path: Path) -> Optional[ResultState]: return None +def _read_zip(zip_path: Path, verify: bool): + """ + The member names, the small JSON / marker members and the ``.completed`` time of + the zip at ``zip_path``; raises one of ``ZIP_CONTENT_ERRORS`` if it is damaged. + """ + with zipfile.ZipFile(zip_path) as f: + names = f.namelist() + small = {} + for name in names: + if name.startswith("files/search_internal"): + continue + if f.getinfo(name).file_size <= 1 << 20 and ( + name in (".identifier", ".completed") or name.endswith(".json") + ): + small[name] = f.read(name) + completed_at = None + if ".completed" in names: + if verify and f.testzip() is not None: + raise zipfile.BadZipFile("a member fails its CRC check") + completed_at = datetime(*f.getinfo(".completed").date_time).isoformat() + return names, small, completed_at + + +def _read_zip_with_retry(zip_path: Path, verify: bool, attempts: int = 2): + for attempt in range(attempts): + try: + return _read_zip(zip_path, verify) + except ZIP_CONTENT_ERRORS: + raise + except OSError as error: + if attempt == attempts - 1: + raise UnreadableResult( + f"{zip_path}: {type(error).__name__}: {error}" + ) from error + + def classify( output_path, root, @@ -279,28 +327,13 @@ def classify( if record.has_zip: record.bytes = zip_path.stat().st_size try: - with zipfile.ZipFile(zip_path) as f: - names = f.namelist() - small = {} - for name in names: - if name.startswith("files/search_internal"): - continue - info = f.getinfo(name) - if info.file_size <= 1 << 20 and ( - name in (".identifier", ".completed") - or name.endswith(".json") - ): - small[name] = f.read(name) - if ".completed" in names: - if verify and f.testzip() is not None: - raise zipfile.BadZipFile("a member fails its CRC check") - state = ResultState.COMPLETED - record.completed_at = datetime( - *f.getinfo(".completed").date_time - ).isoformat() - record.completed_at_source = "zip_member" + names, small, completed_at = _read_zip_with_retry(zip_path, verify) + if completed_at is not None: + state = ResultState.COMPLETED + record.completed_at = completed_at + record.completed_at_source = "zip_member" contents = _Contents(names, small.__getitem__) - except ZIP_READ_ERRORS as error: + except ZIP_CONTENT_ERRORS as error: state = ResultState.CORRUPT_ZIP record.reason = f"{type(error).__name__}: {error}" if state is None and contents is not None and not record.has_dir: diff --git a/autofit/results/index.py b/autofit/results/index.py index b7c4400d0..b96a6e381 100644 --- a/autofit/results/index.py +++ b/autofit/results/index.py @@ -28,7 +28,7 @@ from typing import Dict, Iterable, Iterator, List, Optional, Sequence, Tuple, Union from autofit.non_linear.status.states import Product, ResultState -from autofit.results.classify import classify, stat_fingerprint +from autofit.results.classify import UnreadableResult, classify, stat_fingerprint from autofit.results.record import SCHEMA, ResultRecord, record_key from autofit.tools.util import open_atomic @@ -187,8 +187,10 @@ def update(self) -> Dict[str, int]: Returns ------- - Counts of ``scanned``, ``new``, ``changed``, ``unchanged`` and ``removed`` - results. + Counts of ``scanned``, ``new``, ``changed``, ``unchanged``, ``removed`` and + ``unreadable`` results; an unreadable result (an I/O error, e.g. a transient + network-filesystem failure) keeps its previous record, or gets none, and is + retried by the next ``update``. """ os.makedirs(self.records_dir, exist_ok=True) existing = self.load() @@ -218,7 +220,11 @@ def update(self) -> Dict[str, int]: stale_after_s=self.stale_after_s, ) except Exception as exception: + # Unknown, not corrupt: keep what was known and try next time. logger.warning(f"Could not index {output_path}: {exception}") + counts["unreadable"] += 1 + if record is not None: + found[key] = record continue counts["new" if record is None else "changed"] += 1 found[key] = record_new @@ -239,7 +245,14 @@ def update(self) -> Dict[str, int]: return { name: counts[name] - for name in ("scanned", "new", "changed", "unchanged", "removed") + for name in ( + "scanned", + "new", + "changed", + "unchanged", + "removed", + "unreadable", + ) } def _mark_superseded(self, records: Iterable[ResultRecord]) -> List[ResultRecord]: diff --git a/test_autofit/results/test_index.py b/test_autofit/results/test_index.py index 4730c657e..bf87717b3 100644 --- a/test_autofit/results/test_index.py +++ b/test_autofit/results/test_index.py @@ -158,6 +158,7 @@ def counting(output_path, **kwargs): "changed": 0, "unchanged": 30, "removed": 0, + "unreadable": 0, } assert len(opened) == 10 @@ -249,3 +250,24 @@ def test_cli_index_status_count(results_root, tmp_path, capsys): main(["status", str(results_root), "--index-dir", index_dir, "--json"]) assert json.loads(capsys.readouterr().out)["completed"] == 1 + + +def test_io_error_is_unreadable_not_corrupt(results_root, monkeypatch): + output_path = write_zip(results_root) + index = ResultsIndex(results_root) + index.update() + + import sys + + classify_module = sys.modules["autofit.results.classify"] + + def failing(zip_path, verify): + raise OSError(12, "Cannot allocate memory") + + monkeypatch.setattr(classify_module, "_read_zip", failing) + Path(f"{output_path}.zip").touch() + counts = index.update() + + assert counts["unreadable"] == 1 + # The previous record is kept, not replaced by a corrupt one. + assert [r.state for r in index.records()] == ["completed"] From 1934430f07821d298ac88178e8dd6b4b588c39e2 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 30 Oct 2026 10:05:25 +0000 Subject: [PATCH 3/4] test: dataset_identity.json is part of every fit's archived file set Refs #1739 Co-Authored-By: Claude Opus 5.5 --- test_autofit/non_linear/search/test_conformance_backend.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test_autofit/non_linear/search/test_conformance_backend.py b/test_autofit/non_linear/search/test_conformance_backend.py index 68451adfc..4664d71ef 100644 --- a/test_autofit/non_linear/search/test_conformance_backend.py +++ b/test_autofit/non_linear/search/test_conformance_backend.py @@ -92,6 +92,7 @@ "files/samples.csv", "files/samples_info.json", "files/samples_summary.json", + "files/dataset_identity.json", "files/.start_time", "files/.time", } From b2630e5fcca3235eb4bc31eb884041f4a3e6cb0c Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 30 Oct 2026 11:08:01 +0000 Subject: [PATCH 4/4] refactor: keep abstract_search.py within its 600-line decomposition budget Refs #1739 Co-Authored-By: Claude Opus 5.5 --- autofit/non_linear/search/abstract_search.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/autofit/non_linear/search/abstract_search.py b/autofit/non_linear/search/abstract_search.py index ec4205a2f..6865857fa 100644 --- a/autofit/non_linear/search/abstract_search.py +++ b/autofit/non_linear/search/abstract_search.py @@ -44,11 +44,8 @@ from autofit.non_linear.search.execution import SearchExecutionMixin, _SearchMeta from autofit.non_linear.search.internal_state import SearchInternalStateMixin from autofit.non_linear.search.updates import SearchUpdatesMixin -from autofit.non_linear.status import ( - status_notify, - status_recorded, - write_dataset_identity, -) +from autofit.non_linear.status import status_notify, status_recorded +from autofit.non_linear.status.identity import write_dataset_identity from autofit.non_linear.search.test_mode_bypass import TestModeBypass, TestModeMixin from autofit.non_linear.test_mode import test_mode_level, skip_fit_output