Source code for qdpy.bundles

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Portable run manifests and checkpoint-aware observation of a search.

"""Save, verify, and move complete QDpy run directories."""

from contextlib import contextmanager, ExitStack
from dataclasses import dataclass
from errno import EACCES, EAGAIN
from hashlib import file_digest, sha256
import json
import os
from pathlib import Path, PurePosixPath
from secrets import randbits
from shutil import copyfile
from typing import Callable
from uuid import uuid4

from .base import _atomic_output_path
from .results import _evaluator_info, _json_bytes, _json_value, _write, read_run_manifest

__all__ = ["RunBundle", "RunBundleOptions", "open_run_bundle"]

_WORK = ".run-state"


## @brief Configure portable recording and optional restart for the simple runner.
[docs] @dataclass(frozen=True) class RunBundleOptions: """Select search artifacts and restart behavior for ``qdpy.simple.run``. ``history_every`` counts completed batches. Set it to None to omit history. ``lineage`` records ancestry, fitness, and descriptors for supported emitters. ``checkpoint_every`` enables exact restart with the native checkpoint driver, in units of batches. ``stop_after`` is an optional cumulative evaluation boundary. ``stop_requested`` is polled at complete batches. Reconstruct the same optimiser and bundle settings to resume. Set ``trusted=True`` only when you trust the checkpoint's source. """ history_every: int | None = 10 lineage: bool = False checkpoint_every: int | None = None resume: bool = False trusted: bool = False stop_after: int | None = None stop_requested: Callable[[], bool] | None = None
## @brief Verified paths to the portable artifacts of one published run boundary.
[docs] @dataclass(frozen=True) class RunBundle: """Hold the manifest and local artifact paths without loading a checkpoint.""" manifest_path: Path manifest: dict archive_path: Path | None history_paths: tuple[Path, ...] lineage_path: Path | None checkpoint_path: Path | None best_lineage_id: int | None
def _sha256_file(path): with path.open("rb") as stream: return file_digest(stream, "sha256").hexdigest() def _artifact_path(directory, entry, verify): if not isinstance(entry, dict) or not isinstance(entry.get("file"), str): raise ValueError("Invalid run bundle artifact entry.") name = entry["file"] relative = PurePosixPath(name) if not relative.parts or relative.is_absolute() or ".." in relative.parts or "\\" in name or ":" in name: raise ValueError(f"Artifact path must be relative to the run directory: {name!r}.") path = directory.joinpath(*relative.parts) if not path.resolve().is_relative_to(directory.resolve()): raise ValueError(f"Artifact path leaves the run directory: {name!r}.") if not path.is_file(): raise ValueError(f"Run bundle artifact is missing: {name!r}.") if verify and _sha256_file(path) != entry.get("sha256"): raise ValueError(f"Artifact SHA-256 does not match: {name!r}.") return path ## @brief Verify a relocated run directory without executing Python serialization.
[docs] def open_run_bundle(path, *, verify=True): """Open a directory or its ``run.json`` and verify every published artifact. All paths are relative to the manifest. The history is returned in capture order, independently of other files in the directory. The checkpoint is never deserialized here. Use ``verify=False`` to inspect paths without reading each artifact's contents. """ path = Path(path) if path.is_dir(): path /= "run.json" path = path.absolute() manifest = read_run_manifest(path) bundle = manifest.get("bundle") if not isinstance(bundle, dict) or bundle.get("version") != 1: raise ValueError("This manifest does not describe a supported QDpy run bundle.") artifacts = bundle.get("artifacts") if not isinstance(artifacts, dict) or not isinstance(artifacts.get("history"), list): raise ValueError("Invalid run bundle artifact list.") archive = manifest.get("archive") if not isinstance(archive, dict): raise ValueError("Invalid run bundle archive entry.") def optional(entry): return None if entry is None else _artifact_path(path.parent, entry, verify) return RunBundle(path, manifest, optional(archive if "file" in archive else None), tuple(_artifact_path(path.parent, frame, verify) for frame in artifacts["history"]), optional(artifacts.get("lineage")), optional(artifacts.get("checkpoint")), bundle.get("best_lineage_id"))
def _claim_writer(stream): if os.name == "nt": import msvcrt stream.seek(0) msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) else: import fcntl fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) @contextmanager def _reserve_bundle(directory, *, resume): directory = Path(directory) manifest = directory / "run.json" if not resume and (manifest.exists() or manifest.is_symlink()): raise FileExistsError(f"Run manifest already exists at {manifest}.") working = directory / _WORK working.mkdir(parents=True, exist_ok=True) with (working / "writer.lock").open("a+b") as stream: try: _claim_writer(stream) except OSError as error: if error.errno not in (EACCES, EAGAIN): raise raise FileExistsError(f"A writer is already active for {directory}.") from error if (directory / ".run.json.lock").exists(): raise FileExistsError(f"A writer is already active for {directory}.") if not resume and (manifest.exists() or manifest.is_symlink()): raise FileExistsError(f"Run manifest already exists at {manifest}.") yield manifest class _BundleWriter: def __init__(self, manifest, options, algorithm, evaluate, seed, configuration, execution): self.manifest = manifest self.directory = manifest.parent self.working = self.directory / _WORK self.history = self.directory / "history" self.checkpoint = self.working / "checkpoint.pkl" self.lineage_path = self.working / "lineage.jsonl" self.options = options self.total = algorithm.budget self.execution = execution self.frames = [] self._iteration = 0 self._last = None self.recorder = None self._identity_path = self.working / "identity.json" self._published_count = None identity = _json_value({ "version": 1, "algorithm": type(algorithm).__name__, "evaluator": _evaluator_info(evaluate), "history_every": options.history_every, "lineage": options.lineage, "checkpoint_every": options.checkpoint_every, "execution": execution, }) if options.resume: if not self._identity_path.is_file(): raise ValueError("No working run bundle metadata to resume.") saved = json.loads(self._identity_path.read_text(encoding="utf-8")) self.seed = saved["seed"] if seed is None else seed self.run_id = saved["id"] if manifest.exists(): previous = read_run_manifest(manifest) if previous.get("bundle", {}).get("id") != self.run_id: raise ValueError("The working state belongs to a different run bundle.") self._published_count = previous["evaluation"]["attempted"] else: if self._identity_path.exists(): raise FileExistsError(f"A bundle already owns {self.directory}.") if options.history_every is not None and self.history.exists() and any(self.history.iterdir()): raise FileExistsError(f"Archive history directory must be empty: {self.history}.") self.seed = randbits(32) if seed is None else seed self.run_id = uuid4().hex self.configuration = dict(configuration or {}) | {"seed": self.seed} identity["configuration"] = _json_value(self.configuration) identity.update(seed=self.seed, id=self.run_id) if options.resume: if identity != saved: raise ValueError("Run bundle settings, seed, or evaluator differ from the saved run.") self._identity = identity def _capture(self, algorithm): from ._archive_data import _named_data from ._archive_history import _archive_payloads, _write_archive_frame payload = _archive_payloads(_named_data(algorithm.container)) state = algorithm.nb_evaluations, sha256(_json_bytes(payload)).hexdigest() if self._last == state: return path = _write_archive_frame(self.history, len(self.frames), self._iteration, state[0], payload) self.frames.append(_sha256_file(path)) self._last = state def _history_entries(self): return [{"file": f"history/frame-{number:06d}.json", "sha256": digest} for number, digest in enumerate(self.frames)] def _restore_history(self, state): from ._archive_history import _FRAME, _numbered_paths self.frames = list(state["frames"]) self._iteration = state["iteration"] self._last = state["last"] for entry in self._history_entries(): _artifact_path(self.directory, entry, True) for path in _numbered_paths(self.history, _FRAME): if int(_FRAME.fullmatch(path.name)[1]) >= len(self.frames): # These frames are beyond the last saved batch and were not published. path.unlink() @contextmanager def record(self, algorithm, state=None): from .lineage import LineageRecorder with ExitStack() as stack: if self.options.lineage: checkpointed = self.options.checkpoint_every is not None self.recorder = LineageRecorder(self.lineage_path, record_measurements=True) self.recorder._attach(algorithm, checkpointed=checkpointed, state=None if state is None else state["lineage"]) stack.callback(self.recorder.close) if self.options.history_every is not None: self.history.mkdir(exist_ok=True) if state is None: self._capture(algorithm) else: self._restore_history(state) def at_iteration(search, _elapsed): self._iteration += 1 if self._iteration % self.options.history_every == 0: self._capture(search) def at_finish(search, _elapsed): if self.options.checkpoint_every is None or search.nb_evaluations == self.total: self._capture(search) for event, callback in (("iteration", at_iteration), ("finished_optimisation", at_finish)): algorithm.add_callback(event, callback) stack.callback(algorithm._callbacks.get(event).remove, callback) if state is None: _write(self._identity_path, _json_bytes(self._identity)) yield def check_resume(self, state, evaluations): if not isinstance(state, dict) or state.get("id") != self.run_id: raise ValueError("The checkpoint belongs to a different run bundle.") if self._published_count is not None and evaluations < self._published_count: raise ValueError("The working checkpoint predates the published run boundary.") def boundary(self): return {"id": self.run_id, "frames": tuple(self.frames), "iteration": self._iteration, "last": self._last, "lineage": None if self.recorder is None else self.recorder._boundary()} def _publish(self, path): digest = _sha256_file(path) name = f"{path.stem}-{digest}{path.suffix}" entry = {"file": name, "sha256": digest} destination = self.directory / name if not destination.exists(): with _atomic_output_path(destination) as pending: copyfile(path, pending) else: _artifact_path(self.directory, entry, True) return entry def describe(self, best, attempted, *, resumed_from): artifacts = {"history": self._history_entries(), "lineage": None, "checkpoint": None} if self.recorder is not None: artifacts["lineage"] = self._publish(self.lineage_path) if self.options.checkpoint_every is not None: artifacts["checkpoint"] = self._publish(self.checkpoint) return {"version": 1, "id": self.run_id, "status": "complete" if attempted >= self.total else "paused", "history_every": self.options.history_every, "checkpoint_every": self.options.checkpoint_every, "resumed_from": resumed_from, "artifacts": artifacts, "best_lineage_id": None if self.recorder is None else self.recorder.id_for(best)}