File size: 13,635 Bytes
31441cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""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