"""Recoverable, single-writer checkpoints for local disks and Drive/FUSE mounts. ``save_checkpoint(root, payload, keep_last=2)`` returns a unique snapshot directory. Payload must be a dict with an integer ``step`` in 0..999999999999. Everything in it is forwarded to torch.save: include model/optimizer/scheduler state_dicts, Python and torch CPU/CUDA RNG states, counters and the data cursor yourself. Only tensors and weights_only-compatible basic containers/scalars are supported; encode NumPy RNG state as basic values/tensors rather than pickled NumPy objects. Pause training while saving so the payload cannot change during serialization. ``load_latest(root)`` returns ``(payload, info)`` or None. Tensors load onto CPU; the caller restores training objects and RNGs. info is JSON-loggable and contains path, step, manifest, and skipped [{path, reason}] recovery diagnostics. Rejected snapshots also produce logger warnings, including when none can be recovered. ``list_valid(root)`` returns fully verified directory Paths, newest first. Each step_{step:012d}_{uuid_hex} directory contains checkpoint.pt, manifest.json, and READY. Files are flushed/fsynced as .partial files before os.replace; READY is written LAST and binds the manifest's SHA-256. The manifest binds the fixed payload filename, size, digest, step, creation time and directory UUID. Recovery scans directories, never a latest pointer, and verifies bytes AND weights-only deserialization. Neither hardlinks, locks nor atomic directory operations are needed. A process kill may leave partial files; these are ignored and preserved. File fsync cannot guarantee a cloud provider has finished remote replication. SINGLE WRITER REQUIRED: MUST NOT run two notebooks against the same RunDir. Stop the old runtime before resuming in a new one. Readers should run between saves; this is not a protocol for concurrent hostile filesystem mutation. Symlinks/reparse points, including in root ancestors, are rejected. Retention runs only after the new snapshot verifies. keep_last must be >= 2. The newest keep_last valid snapshots and the newly saved snapshot are protected (an out-of-order save can therefore temporarily exceed the limit). Only the three known files of older complete, owned, verified snapshots are removed; unknown files and incomplete/corrupt snapshots are never recursively deleted. SHA-256 detects corruption, not malicious replacement/authenticity. No remote code, unrestricted pickle fallback, or torch safe-global additions are used. """ import hashlib import json import logging import os from pathlib import Path import re import stat import time import uuid __all__ = ["save_checkpoint", "load_latest", "list_valid"] _LOG = logging.getLogger(__name__) _FORMAT = "pear15.cloud_checkpoint.v1" _DIRECTORY = re.compile(r"step_([0-9]{12})_([0-9a-f]{32})\Z") _DIGEST = re.compile(r"[0-9a-f]{64}\Z") _FILES = ("READY", "manifest.json", "checkpoint.pt") _FIELDS = {"format", "file", "sha256", "bytes", "step", "created_ns", "id"} _CHUNK = 1024 * 1024 def _import_torch(): import torch return torch def _linked(status): # Junctions and other Windows reparse points must not escape the RunDir. return stat.S_ISLNK(status.st_mode) or bool( getattr(status, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400) ) def _directory(path): status = path.lstat() if _linked(status) or not stat.S_ISDIR(status.st_mode): raise ValueError(f"not a plain directory (symlinks forbidden): {path}") def _root(root, create=False): # abspath deliberately does not resolve away symlinks before checking them. path = Path(os.path.abspath(os.fspath(root))) for parent in reversed((path, *path.parents)): try: _directory(parent) except FileNotFoundError: continue if create: path.mkdir(parents=True, exist_ok=True) _directory(path) return path def _open_regular(path): before = path.lstat() if _linked(before) or not stat.S_ISREG(before.st_mode): raise ValueError(f"not a plain file (symlinks forbidden): {path}") flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) descriptor = os.open(path, flags) try: after = os.fstat(descriptor) if not stat.S_ISREG(after.st_mode) or (before.st_dev, before.st_ino) != (after.st_dev, after.st_ino): raise ValueError(f"file changed while opening: {path}") handle = os.fdopen(descriptor, "rb") except BaseException: os.close(descriptor) raise return handle def _small_file(path, limit): with _open_regular(path) as handle: content = handle.read(limit + 1) if len(content) > limit: raise ValueError(f"oversized metadata: {path.name}") return content def _json_object(pairs): result = {} for key, value in pairs: if key in result: raise ValueError(f"duplicate manifest field: {key}") result[key] = value return result def _ready_bytes(manifest_bytes): return (_FORMAT + "\n" + hashlib.sha256(manifest_bytes).hexdigest() + "\n").encode("ascii") def _header(path): _directory(path) match = _DIRECTORY.fullmatch(path.name) if match is None: raise ValueError("not an owned checkpoint directory") raw = _small_file(path / "manifest.json", 16384) if _small_file(path / "READY", 256) != _ready_bytes(raw): raise ValueError("incomplete or mismatched READY marker") manifest = json.loads(raw, object_pairs_hook=_json_object) if not isinstance(manifest, dict) or set(manifest) != _FIELDS: raise ValueError("invalid manifest fields") if manifest["format"] != _FORMAT or manifest["file"] != "checkpoint.pt": raise ValueError("unsupported format or unsafe manifest file path") if type(manifest["step"]) is not int or manifest["step"] != int(match[1]): raise ValueError("manifest step does not match directory") if manifest["id"] != match[2]: raise ValueError("manifest id does not match directory") if type(manifest["created_ns"]) is not int or manifest["created_ns"] < 0: raise ValueError("invalid creation metadata") if type(manifest["bytes"]) is not int or manifest["bytes"] <= 0: raise ValueError("invalid payload byte count") if not isinstance(manifest["sha256"], str) or not _DIGEST.fullmatch(manifest["sha256"]): raise ValueError("invalid SHA-256 digest") return {"path": str(path), "step": manifest["step"], "manifest": manifest} def _reject(skipped, path, error): entry = {"path": str(path), "reason": f"{type(error).__name__}: {error}"} skipped.append(entry) _LOG.warning("Skipping checkpoint %s: %s", entry["path"], entry["reason"]) def _headers(root, skipped): root = _root(root) try: children = sorted(root.iterdir(), key=lambda path: path.name) except FileNotFoundError: return [] records = [] for path in children: if not _DIRECTORY.fullmatch(path.name): continue try: records.append(_header(path)) except Exception as exc: _reject(skipped, path, exc) # A UUID name is the final deterministic tie-breaker for equal timestamps. records.sort(key=lambda item: (item["step"], item["manifest"]["created_ns"], item["path"]), reverse=True) return records def _digest_file(handle): digest, size = hashlib.sha256(), 0 while True: chunk = handle.read(_CHUNK) if not chunk: return digest.hexdigest(), size digest.update(chunk) size += len(chunk) def _load_record(torch, record): path, manifest = Path(record["path"]), record["manifest"] _directory(path) with _open_regular(path / "checkpoint.pt") as handle: if os.fstat(handle.fileno()).st_size != manifest["bytes"]: raise ValueError("payload size mismatch") digest, size = _digest_file(handle) if size != manifest["bytes"] or digest != manifest["sha256"]: raise ValueError("payload SHA-256/size mismatch") handle.seek(0) payload = torch.load(handle, map_location="cpu", weights_only=True) if not isinstance(payload, dict) or type(payload.get("step")) is not int or payload["step"] != record["step"]: raise ValueError("payload step does not match manifest") return payload def load_latest(root): """Return (unchanged payload, JSON-loggable info), falling back on corruption.""" skipped = [] records = _headers(root, skipped) if not records: return None torch = _import_torch() # Missing/broken torch is an environment error, not corruption. for record in records: try: payload = _load_record(torch, record) except Exception as exc: _reject(skipped, record["path"], exc) continue return payload, {**record, "skipped": skipped} return None def _valid_records(records, torch, skipped): valid = [] for record in records: try: # Do not retain model/optimizer tensors from multiple snapshots in RAM. payload = _load_record(torch, record) del payload except Exception as exc: _reject(skipped, record["path"], exc) else: valid.append(record) return valid, skipped def list_valid(root): """Fully verify snapshots and return Paths ordered by step, creation, then UUID.""" # Empty/missing roots do not require PyTorch to be installed. skipped = [] records = _headers(root, skipped) if not records: return [] records, _ = _valid_records(records, _import_torch(), skipped) return [Path(record["path"]) for record in records] def _flush(handle): handle.flush() os.fsync(handle.fileno()) def _write_file(path, content): partial = path.with_name(path.name + ".partial") with partial.open("xb") as handle: handle.write(content) _flush(handle) os.replace(partial, path) def _invalidate(path): try: marker = path / "READY" status = marker.lstat() if not _linked(status) and stat.S_ISREG(status.st_mode): marker.unlink() except FileNotFoundError: pass except OSError as exc: _LOG.warning("Could not remove failed checkpoint marker %s: %s", path, exc) def _prune(records, keep_last, new_path): protected = {record["path"] for record in records[:keep_last]} | {str(new_path)} for record in records: if record["path"] in protected: continue path = Path(record["path"]) try: # Recheck ownership/completeness immediately before touching known files. if _header(path) != record: continue for name in _FILES: with _open_regular(path / name): pass # Invalidate first. An interrupted cleanup can never look complete. for name in _FILES: (path / name).unlink() if not any(path.iterdir()): path.rmdir() except (OSError, ValueError) as exc: _LOG.warning("Could not prune checkpoint %s: %s", path, exc) def save_checkpoint(root, payload, keep_last=2): """Publish and verify a unique snapshot, then conservatively retain >=2 copies. Serialization/I/O/verification failures propagate; failed snapshots have no READY marker and previous snapshots are untouched. Partial debris is retained for diagnosis. Exceptions after commit during retention may leave extra copies. """ if not isinstance(payload, dict) or type(payload.get("step")) is not int or not 0 <= payload["step"] < 10**12: raise ValueError("payload must be a dict with integer step in 0..999999999999") if type(keep_last) is not int or keep_last < 2: raise ValueError("keep_last must be an integer >= 2") torch = _import_torch() root = _root(root, create=True) identifier = uuid.uuid4().hex path = root / f"step_{payload['step']:012d}_{identifier}" path.mkdir() # Exclusive unique name, not an atomic directory publication. try: partial = path / "checkpoint.pt.partial" with partial.open("xb") as handle: torch.save(payload, handle) _flush(handle) os.replace(partial, path / "checkpoint.pt") with _open_regular(path / "checkpoint.pt") as handle: digest, size = _digest_file(handle) manifest = {"format": _FORMAT, "file": "checkpoint.pt", "sha256": digest, "bytes": size, "step": payload["step"], "created_ns": time.time_ns(), "id": identifier} raw = json.dumps(manifest, sort_keys=True, allow_nan=False).encode("utf-8") _write_file(path / "manifest.json", raw) _write_file(path / "READY", _ready_bytes(raw)) # Verify deserialization as well as on-mount checksums before any retention. skipped = [] records, skipped = _valid_records(_headers(root, skipped), torch, skipped) if not any(record["path"] == str(path) for record in records): reason = next((item["reason"] for item in skipped if item["path"] == str(path)), "snapshot disappeared") raise ValueError(f"new checkpoint failed verification: {reason}") except BaseException: _invalidate(path) # Includes KeyboardInterrupt and ENOSPC, even after marker publication. raise _prune(records, keep_last, path) return path