"""Bounded, atomic snapshots of the kernel-owned namespace and definitions.""" from __future__ import annotations import importlib import io import os # Every resting kernel checkpoints its namespace, so every kernel needs pickle. # Imported here, it loads in the zygote and forked kernels share its pages; # imported at the first save, each kernel paid ~200 KB of private memory. import pickle import sys import tempfile import types from collections.abc import Callable from typing import Any, BinaryIO, Literal, Protocol, cast # Saved state is the session's own namespace, written by this kernel into the # daemon's home. Loading pickle and replaying definitions share the transcript's trust domain. STATE_MAX = 64 * 1024 * 1024 STATE_MAX_VALUE = 8 * 1024 * 1024 DEFINITION_MAX = 256 * 1024 DEFINITION_MAX_VALUE = 32 * 1024 # What the kernel started with; entries a cell adds (a sys.path.insert before # an import) are saved so replayed imports find their modules again. START_PATH = list(sys.path) class _WriteSink(Protocol): def write(self, data: bytes, /) -> int: ... class _Serialiser(Protocol): def dump(self, value: object, file: _WriteSink, /) -> None: ... def load(self, file: BinaryIO, /) -> object: ... def loads(self, data: bytes, /) -> object: ... def engine() -> tuple[_Serialiser, Literal["dill", "pickle"]]: """Use optional dill for legacy snapshots and richer values when installed.""" try: import dill dill.settings["recurse"] = True return cast(_Serialiser, dill), "dill" except ImportError: return pickle, "pickle" class TooLarge(Exception): """The value's serialisation passed the per-variable cap.""" class _Bounded: """A write sink that stops a serialiser once it has produced more than `limit` bytes, so an oversized value costs the cap, not its full size.""" def __init__(self, limit: int) -> None: self.limit = limit self.chunks: list[bytes] = [] self.size = 0 def write(self, data: bytes) -> int: self.size += len(data) if self.size > self.limit: raise TooLarge self.chunks.append(bytes(data)) return len(data) def getvalue(self) -> bytes: return b"".join(self.chunks) def dumps_within( serialiser: _Serialiser, value: object, limit: int, shared: dict[int, str] | None = None, ) -> bytes: """`serialiser.dumps(value)`, or TooLarge once it passes `limit` bytes. `shared` names the namespace's classes and functions by id. Each value is saved on its own, so a reference from one to another (an instance to its class, a function to a helper) is saved as that name, and `loads_shared` binds it to the restored object: otherwise each value would carry its own copy, and an instance would no longer be an instance of its class's name. """ sink = _Bounded(limit) if not shared: serialiser.dump(value, sink) return sink.getvalue() # dill's Pickler, or pickle's: a subclass hooks persistent_id either way. base: Any = getattr(serialiser, "Pickler") root = id(value) class Referring(base): def persistent_id(self, obj: object) -> object: name = shared.get(id(obj)) if id(obj) != root else None return None if name is None else ("albedo-name", name) Referring(sink).dump(value) return sink.getvalue() class MissingName(Exception): """A saved value refers to a namespace name not restored yet.""" def loads_shared( serialiser: _Serialiser, data: bytes, namespace: dict[str, object] ) -> object: """`serialiser.loads(data)`, binding names `dumps_within` saved by reference to what `namespace` holds; MissingName when one is not there.""" base: Any = getattr(serialiser, "Unpickler") class Resolving(base): def persistent_load(self, pid: object) -> object: if isinstance(pid, tuple) and len(pid) == 2 and pid[0] == "albedo-name": if pid[1] in namespace: return namespace[pid[1]] raise MissingName(pid[1]) raise pickle.UnpicklingError(f"unknown persistent id {pid!r}") return Resolving(io.BytesIO(data)).load() # A restore that could not preserve its input may still be followed by an # automatic checkpoint. Retry the copy before replacing that same path. _PENDING_ORIGINALS: dict[str, str] = {} def preserve_original(path: str, file: BinaryIO, archive: str) -> str: """Publish the opened snapshot by content hash before a partial restore.""" import hashlib key = os.path.abspath(path) archive = os.path.abspath(archive) _PENDING_ORIGINALS[key] = archive os.makedirs(archive, mode=0o700, exist_ok=True) digest = hashlib.sha256() fd, temporary = tempfile.mkstemp(dir=archive, prefix=".copy-") try: with os.fdopen(fd, "wb") as out: while chunk := file.read(256 * 1024): digest.update(chunk) out.write(chunk) os.replace(temporary, os.path.join(archive, digest.hexdigest() + ".state")) finally: if os.path.exists(temporary): os.unlink(temporary) del _PENDING_ORIGINALS[key] return digest.hexdigest() def save_state( path: str, namespace: dict[str, object], definitions: dict[str, str], injected: set[str], kernel: object = None, ) -> dict[str, object]: """Serialise values and readable top-level definitions within fixed caps. `kernel` is the kernel's own state (retained output, the job book), saved as it is and handed back to load_state's `restore_kernel`.""" serialiser, kind = engine() payload: dict[str, bytes] = {} modules: dict[str, str] = {} skipped: list[dict[str, str]] = [] total = 0 largest: list[tuple[str, int]] = [] shared = { id(value): name for name, value in list(namespace.items()) if not name.startswith("_") and name not in injected and isinstance(value, (types.FunctionType, type)) } for name in list(namespace.keys()): if name.startswith("_") or name in injected: continue value = namespace.get(name, injected) if value is injected: continue if isinstance(value, types.ModuleType): # A module cannot be pickled; its import name is enough to bind it again. modules[name] = value.__name__ continue replayed = name in definitions and isinstance(value, (types.FunctionType, type)) if replayed and kind == "pickle": continue try: blob = dumps_within(serialiser, value, STATE_MAX_VALUE, shared) except BaseException as error: reason = ( f"over the {STATE_MAX_VALUE}-byte per-variable cap" if isinstance(error, TooLarge) else f"{type(error).__name__}: {error}"[:200] ) if not replayed: skipped.append({"name": name, "reason": reason}) continue if total + len(blob) > STATE_MAX: skipped.append({"name": name, "reason": "saved state is full"}) else: payload[name] = blob total += len(blob) if len(blob) >= 64 * 1024: largest.append((name, len(blob))) saved_definitions: list[dict[str, str]] = [] definition_bytes = 0 for name, source in definitions.items(): size = len(source.encode("utf-8")) if size > DEFINITION_MAX_VALUE: skipped.append( { "name": name, "reason": f"definition is {size} bytes; per-definition cap is {DEFINITION_MAX_VALUE}", } ) elif definition_bytes + size > DEFINITION_MAX: skipped.append( {"name": name, "reason": "definitions are over the total source cap"} ) else: saved_definitions.append({"name": name, "source": source}) definition_bytes += size try: cwd = os.getcwd() except FileNotFoundError: # The workspace was removed under the kernel; a restore keeps its own. cwd = None directory = os.path.dirname(path) or "." try: if archive := _PENDING_ORIGINALS.get(os.path.abspath(path)): with open(path, "rb") as original: preserve_original(path, original, archive) os.makedirs(directory, exist_ok=True) handle, temporary = tempfile.mkstemp( dir=directory, prefix=os.path.basename(path) + "." ) try: with os.fdopen(handle, "wb") as file: pickle.dump( { # Keep this first so restore can select a decoder before loading plugin state. "writer_python": sys.implementation.cache_tag, "cwd": cwd, "path": [ entry for entry in sys.path if isinstance(entry, str) and entry not in START_PATH ], "modules": modules, "names": payload, "definitions": saved_definitions, "kernel": kernel, "skipped": skipped, }, file, ) os.replace(temporary, path) except BaseException: os.unlink(temporary) raise except OSError as error: return {"error": f"could not write saved state: {error}"} largest.sort(key=lambda item: item[1], reverse=True) return { "saved": sorted( set(payload) | set(modules) | {item["name"] for item in saved_definitions} ), "defs": [item["name"] for item in saved_definitions], "skipped": skipped, "largest": [{"name": name, "bytes": size} for name, size in largest[:5]], "bytes": total, "engine": kind, } def snapshot_writer(file: BinaryIO) -> str | None: """Read the writer's first dict key without executing the snapshot.""" import pickletools prefix = file.read(128) file.seek(0) # save_state uses the default binary pickle protocol. Only its leading # dictionary/key/value instructions can identify a compatible writer. operations = ( (op.name, arg) for op, arg, _ in pickletools.genops(prefix) if op.name not in {"PROTO", "FRAME", "MEMOIZE", "MARK"} ) try: if next(operations) != ("EMPTY_DICT", None): return None if next(operations) != ("SHORT_BINUNICODE", "writer_python"): return None opcode, tag = next(operations) except (StopIteration, ValueError): return None return tag if opcode == "SHORT_BINUNICODE" and isinstance(tag, str) else None class IncompatibleValue(pickle.UnpicklingError): """A foreign or unknown writer used an interpreter-specific encoding.""" def _portable_type(name: str) -> type: # dill records some builtin data constructors through its _load_type # reducer. Resolve these here without calling that open-ended resolver. if name == "complex": return complex if name == "bytearray": return bytearray raise IncompatibleValue(f"unsupported serialized type {name}") class _PortableUnpickler(pickle.Unpickler): def find_class(self, module: str, name: str) -> object: if module == "builtins" and name in {"complex", "bytearray"}: return _portable_type(name) if (module, name) == ("dill._dill", "_load_type"): return _portable_type raise IncompatibleValue(f"requires {module}.{name}") def persistent_load(self, pid: object) -> object: # A class or function saved by name: interpreter-specific, as they are. raise IncompatibleValue(f"refers to {pid!r}") def _load_portable(file: BinaryIO) -> object: import pickletools # EXT opcodes can fetch previously cached globals without find_class. for opcode, _, _ in pickletools.genops(file): if opcode.name in {"EXT1", "EXT2", "EXT4"}: raise IncompatibleValue("requires a registered pickle extension") file.seek(0) return _PortableUnpickler(file).load() def load_state( path: str, namespace: dict[str, object], definitions: dict[str, str], restore_kernel: Callable[[object], list[str]] | None = None, archive: str | None = None, ) -> dict[str, object]: """Restore the added sys.path entries and modules, the kernel's own state, then pickled values (which may refer to it), then replay definitions in their saved order.""" original = None try: with open(path, "rb") as file: writer = snapshot_writer(file) compatible = writer is not None and writer == sys.implementation.cache_tag if compatible: saved = cast(dict[str, object], pickle.load(file)) else: original = preserve_original(path, file, archive or path + ".originals") file.seek(0) saved = cast(dict[str, object], _load_portable(file)) except FileNotFoundError: return {"restored": [], "defs": [], "failed": [], "error": "no saved state"} except BaseException as error: return { "restored": [], "defs": [], "failed": [], "error": f"unreadable saved state: {type(error).__name__}: {error}"[:300], } serialiser, kind = engine() restored: list[str] = [] failed: list[dict[str, str]] = [] for entry in reversed(cast(list[object], saved.get("path", []))): if isinstance(entry, str) and entry not in sys.path: sys.path.insert(0, entry) for name, module in cast(dict[str, str], saved.get("modules", {})).items(): try: namespace[name] = importlib.import_module(module) except BaseException as error: failed.append( {"name": name, "reason": f"{type(error).__name__}: {error}"[:200]} ) else: restored.append(name) # Retained output and job book channels that did not come back; absent # when the state predates saving them. output_lost: list[str] | None = None if restore_kernel is not None and saved.get("kernel") is not None: try: output_lost = restore_kernel(saved["kernel"]) except BaseException as error: output_lost = [f" {type(error).__name__}: {error}"[:200]] incompatible: dict[str, str] = {} deferred: list[tuple[str, bytes]] = [] # The values loaded, by name. values: dict[str, object] = {} waiting = list(cast(dict[str, bytes], saved.get("names", {})).items()) while waiting: # A value naming another saved value loads after it. progress, missing = False, [] for name, blob in waiting: try: if compatible: namespace[name] = loads_shared(serialiser, blob, namespace) else: namespace[name] = _load_portable(io.BytesIO(blob)) except MissingName: missing.append((name, blob)) continue except IncompatibleValue as error: incompatible[name] = f"snapshot writer {writer or 'unknown'}: {error}"[ :200 ] except AttributeError as error: if compatible: deferred.append((name, blob)) else: failed.append({"name": name, "reason": str(error)[:200]}) except BaseException as error: failed.append( {"name": name, "reason": f"{type(error).__name__}: {error}"[:200]} ) else: restored.append(name) values[name] = namespace[name] progress = True waiting = missing if not progress: # What they name never loaded; replayed definitions may supply it. deferred.extend(missing) break # A single captured import may bind more names than its definition key. # A pre-existing binding is not evidence that replay recovered a value. before_replay = { name: namespace[name] for name in incompatible if name in namespace } defs: list[str] = [] for item in cast(list[object], saved.get("definitions", [])): if ( not isinstance(item, dict) or not isinstance(item.get("name"), str) or not isinstance(item.get("source"), str) ): continue name, source = item["name"], item["source"] try: exec(compile(source, "", "exec"), namespace) except BaseException as error: failed.append( {"name": name, "reason": f"{type(error).__name__}: {error}"[:200]} ) else: if source not in definitions.values(): key = name while key in definitions: key += "#2" definitions[key] = source if name not in restored: restored.append(name) defs.append(name) # Replay rebinds a class's name to a new class; the instances restored # above belong to the loaded one. A replayed function keeps the replay: # its globals are the live namespace, not the copy saved with it. namespace.update( {name: value for name, value in values.items() if isinstance(value, type)} ) for name, blob in deferred: try: namespace[name] = loads_shared(serialiser, blob, namespace) except BaseException as error: failed.append( {"name": name, "reason": f"{type(error).__name__}: {error}"[:200]} ) else: restored.append(name) for name, reason in incompatible.items(): if name in namespace and ( name not in before_replay or namespace[name] is not before_replay[name] ): restored.append(name) else: failed.append({"name": name, "reason": reason}) directory = saved.get("cwd") if isinstance(directory, str) and os.path.isdir(directory): os.chdir(directory) result: dict[str, object] = { "restored": sorted(set(restored)), "defs": defs, "failed": failed, # What the save could not keep is as lost as what fails to load. "skipped": saved.get("skipped", []), "engine": kind, } if original is not None: result["original_sha256"] = original if output_lost is not None: result["output_lost"] = output_lost return result