QDpy
Loading...
Searching...
No Matches
bundles.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Save, verify, and move complete QDpy run directories."""
6
7from contextlib import contextmanager, ExitStack
8from dataclasses import dataclass
9from errno import EACCES, EAGAIN
10from hashlib import file_digest, sha256
11import json
12import os
13from pathlib import Path, PurePosixPath
14from secrets import randbits
15from shutil import copyfile
16from typing import Callable
17from uuid import uuid4
18
19from .base import _atomic_output_path
20from .results import _evaluator_info, _json_bytes, _json_value, _write, read_run_manifest
21
22__all__ = ["RunBundle", "RunBundleOptions", "open_run_bundle"]
23
24_WORK = ".run-state"
25
26
27
28@dataclass(frozen=True)
30 """Select search artifacts and restart behavior for ``qdpy.simple.run``.
31
32 ``history_every`` counts completed batches. Set it to None to omit
33 history. ``lineage`` records ancestry, fitness, and descriptors for
34 supported emitters. ``checkpoint_every`` enables exact restart with
35 the native checkpoint driver, in units of batches.
36
37 ``stop_after`` is an optional cumulative evaluation boundary.
38 ``stop_requested`` is polled at complete batches. Reconstruct the
39 same optimiser and bundle settings to resume. Set ``trusted=True``
40 only when you trust the checkpoint's source.
41 """
42
43 history_every: int | None = 10
44 lineage: bool = False
45 checkpoint_every: int | None = None
46 resume: bool = False
47 trusted: bool = False
48 stop_after: int | None = None
49 stop_requested: Callable[[], bool] | None = None
50
51
52
53@dataclass(frozen=True)
55 """Hold the manifest and local artifact paths without loading a checkpoint."""
56
57 manifest_path: Path
58 manifest: dict
59 archive_path: Path | None
60 history_paths: tuple[Path, ...]
61 lineage_path: Path | None
62 checkpoint_path: Path | None
63 best_lineage_id: int | None
64
65
66def _sha256_file(path):
67 with path.open("rb") as stream:
68 return file_digest(stream, "sha256").hexdigest()
69
70
71def _artifact_path(directory, entry, verify):
72 if not isinstance(entry, dict) or not isinstance(entry.get("file"), str):
73 raise ValueError("Invalid run bundle artifact entry.")
74 name = entry["file"]
75 relative = PurePosixPath(name)
76 if not relative.parts or relative.is_absolute() or ".." in relative.parts or "\\" in name or ":" in name:
77 raise ValueError(f"Artifact path must be relative to the run directory: {name!r}.")
78 path = directory.joinpath(*relative.parts)
79 if not path.resolve().is_relative_to(directory.resolve()):
80 raise ValueError(f"Artifact path leaves the run directory: {name!r}.")
81 if not path.is_file():
82 raise ValueError(f"Run bundle artifact is missing: {name!r}.")
83 if verify and _sha256_file(path) != entry.get("sha256"):
84 raise ValueError(f"Artifact SHA-256 does not match: {name!r}.")
85 return path
86
87
88
89def open_run_bundle(path, *, verify=True):
90 """Open a directory or its ``run.json`` and verify every published artifact.
91
92 All paths are relative to the manifest. The history is returned in
93 capture order, independently of other files in the directory. The
94 checkpoint is never deserialized here. Use ``verify=False`` to inspect
95 paths without reading each artifact's contents.
96 """
97 path = Path(path)
98 if path.is_dir():
99 path /= "run.json"
100 path = path.absolute()
101 manifest = read_run_manifest(path)
102 bundle = manifest.get("bundle")
103 if not isinstance(bundle, dict) or bundle.get("version") != 1:
104 raise ValueError("This manifest does not describe a supported QDpy run bundle.")
105 artifacts = bundle.get("artifacts")
106 if not isinstance(artifacts, dict) or not isinstance(artifacts.get("history"), list):
107 raise ValueError("Invalid run bundle artifact list.")
108 archive = manifest.get("archive")
109 if not isinstance(archive, dict):
110 raise ValueError("Invalid run bundle archive entry.")
111
112 def optional(entry):
113 return None if entry is None else _artifact_path(path.parent, entry, verify)
114
115 return RunBundle(path, manifest, optional(archive if "file" in archive else None),
116 tuple(_artifact_path(path.parent, frame, verify) for frame in artifacts["history"]),
117 optional(artifacts.get("lineage")), optional(artifacts.get("checkpoint")),
118 bundle.get("best_lineage_id"))
119
120
121def _claim_writer(stream):
122 if os.name == "nt":
123 import msvcrt
124
125 stream.seek(0)
126 msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
127 else:
128 import fcntl
129
130 fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
131
132
133@contextmanager
134def _reserve_bundle(directory, *, resume):
135 directory = Path(directory)
136 manifest = directory / "run.json"
137 if not resume and (manifest.exists() or manifest.is_symlink()):
138 raise FileExistsError(f"Run manifest already exists at {manifest}.")
139 working = directory / _WORK
140 working.mkdir(parents=True, exist_ok=True)
141 with (working / "writer.lock").open("a+b") as stream:
142 try:
143 _claim_writer(stream)
144 except OSError as error:
145 if error.errno not in (EACCES, EAGAIN):
146 raise
147 raise FileExistsError(f"A writer is already active for {directory}.") from error
148 if (directory / ".run.json.lock").exists():
149 raise FileExistsError(f"A writer is already active for {directory}.")
150 if not resume and (manifest.exists() or manifest.is_symlink()):
151 raise FileExistsError(f"Run manifest already exists at {manifest}.")
152 yield manifest
153
154
156 def __init__(self, manifest, options, algorithm, evaluate, seed, configuration, execution):
157 self.manifest = manifest
158 self.directory = manifest.parent
159 self.working = self.directory / _WORK
160 self.history = self.directory / "history"
161 self.checkpoint = self.working / "checkpoint.pkl"
162 self.lineage_path = self.working / "lineage.jsonl"
163 self.options = options
164 self.total = algorithm.budget
165 self.execution = execution
166 self.frames = []
167 self._iteration = 0
168 self._last = None
169 self.recorder = None
170 self._identity_path = self.working / "identity.json"
171 self._published_count = None
172 identity = _json_value({
173 "version": 1, "algorithm": type(algorithm).__name__, "evaluator": _evaluator_info(evaluate),
174 "history_every": options.history_every, "lineage": options.lineage,
175 "checkpoint_every": options.checkpoint_every, "execution": execution,
176 })
177 if options.resume:
178 if not self._identity_path.is_file():
179 raise ValueError("No working run bundle metadata to resume.")
180 saved = json.loads(self._identity_path.read_text(encoding="utf-8"))
181 self.seed = saved["seed"] if seed is None else seed
182 self.run_id = saved["id"]
183 if manifest.exists():
184 previous = read_run_manifest(manifest)
185 if previous.get("bundle", {}).get("id") != self.run_id:
186 raise ValueError("The working state belongs to a different run bundle.")
187 self._published_count = previous["evaluation"]["attempted"]
188 else:
189 if self._identity_path.exists():
190 raise FileExistsError(f"A bundle already owns {self.directory}.")
191 if options.history_every is not None and self.history.exists() and any(self.history.iterdir()):
192 raise FileExistsError(f"Archive history directory must be empty: {self.history}.")
193 self.seed = randbits(32) if seed is None else seed
194 self.run_id = uuid4().hex
195 self.configuration = dict(configuration or {}) | {"seed": self.seed}
196 identity["configuration"] = _json_value(self.configuration)
197 identity.update(seed=self.seed, id=self.run_id)
198 if options.resume:
199 if identity != saved:
200 raise ValueError("Run bundle settings, seed, or evaluator differ from the saved run.")
201 self._identity = identity
202
203 def _capture(self, algorithm):
204 from ._archive_data import _named_data
205 from ._archive_history import _archive_payloads, _write_archive_frame
206
207 payload = _archive_payloads(_named_data(algorithm.container))
208 state = algorithm.nb_evaluations, sha256(_json_bytes(payload)).hexdigest()
209 if self._last == state:
210 return
211 path = _write_archive_frame(self.history, len(self.frames), self._iteration, state[0], payload)
212 self.frames.append(_sha256_file(path))
213 self._last = state
214
215 def _history_entries(self):
216 return [{"file": f"history/frame-{number:06d}.json", "sha256": digest}
217 for number, digest in enumerate(self.frames)]
218
219 def _restore_history(self, state):
220 from ._archive_history import _FRAME, _numbered_paths
221
222 self.frames = list(state["frames"])
223 self._iteration = state["iteration"]
224 self._last = state["last"]
225 for entry in self._history_entries():
226 _artifact_path(self.directory, entry, True)
227 for path in _numbered_paths(self.history, _FRAME):
228 if int(_FRAME.fullmatch(path.name)[1]) >= len(self.frames):
229 # These frames are beyond the last saved batch and were not published.
230 path.unlink()
231
232 @contextmanager
233 def record(self, algorithm, state=None):
234 from .lineage import LineageRecorder
235
236 with ExitStack() as stack:
237 if self.options.lineage:
238 checkpointed = self.options.checkpoint_every is not None
239 self.recorder = LineageRecorder(self.lineage_path, record_measurements=True)
240 self.recorder._attach(algorithm, checkpointed=checkpointed,
241 state=None if state is None else state["lineage"])
242 stack.callback(self.recorder.close)
243 if self.options.history_every is not None:
244 self.history.mkdir(exist_ok=True)
245 if state is None:
246 self._capture(algorithm)
247 else:
248 self._restore_history(state)
249
250 def at_iteration(search, _elapsed):
251 self._iteration += 1
252 if self._iteration % self.options.history_every == 0:
253 self._capture(search)
254
255 def at_finish(search, _elapsed):
256 if self.options.checkpoint_every is None or search.nb_evaluations == self.total:
257 self._capture(search)
258
259 for event, callback in (("iteration", at_iteration), ("finished_optimisation", at_finish)):
260 algorithm.add_callback(event, callback)
261 stack.callback(algorithm._callbacks.get(event).remove, callback)
262 if state is None:
263 _write(self._identity_path, _json_bytes(self._identity))
264 yield
265
266 def check_resume(self, state, evaluations):
267 if not isinstance(state, dict) or state.get("id") != self.run_id:
268 raise ValueError("The checkpoint belongs to a different run bundle.")
269 if self._published_count is not None and evaluations < self._published_count:
270 raise ValueError("The working checkpoint predates the published run boundary.")
271
272 def boundary(self):
273 return {"id": self.run_id, "frames": tuple(self.frames), "iteration": self._iteration, "last": self._last,
274 "lineage": None if self.recorder is None else self.recorder._boundary()}
275
276 def _publish(self, path):
277 digest = _sha256_file(path)
278 name = f"{path.stem}-{digest}{path.suffix}"
279 entry = {"file": name, "sha256": digest}
280 destination = self.directory / name
281 if not destination.exists():
282 with _atomic_output_path(destination) as pending:
283 copyfile(path, pending)
284 else:
285 _artifact_path(self.directory, entry, True)
286 return entry
287
288 def describe(self, best, attempted, *, resumed_from):
289 artifacts = {"history": self._history_entries(), "lineage": None, "checkpoint": None}
290 if self.recorder is not None:
291 artifacts["lineage"] = self._publish(self.lineage_path)
292 if self.options.checkpoint_every is not None:
293 artifacts["checkpoint"] = self._publish(self.checkpoint)
294 return {"version": 1, "id": self.run_id, "status": "complete" if attempted >= self.total else "paused",
295 "history_every": self.options.history_every, "checkpoint_every": self.options.checkpoint_every,
296 "resumed_from": resumed_from,
297 "artifacts": artifacts, "best_lineage_id": None if self.recorder is None else self.recorder.id_for(best)}
Configure portable recording and optional restart for the simple runner.
Definition bundles.py:29
Verified paths to the portable artifacts of one published run boundary.
Definition bundles.py:54
_capture(self, algorithm)
Definition bundles.py:203
_restore_history(self, state)
Definition bundles.py:219