"""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, Iterator, KeysView 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) # 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: if isinstance(obj, _SavingName): return ("albedo-name", obj.name) name = (shared or {}).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": try: return namespace[pid[1]] except KeyError: raise MissingName(pid[1]) from None 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() class _Backing: def __init__(self, file: BinaryIO) -> None: self.fd = os.dup(file.fileno()) def fileno(self) -> int: return self.fd def __del__(self) -> None: os.close(self.fd) class _Slice: """One serialized value in an opened snapshot, retained across replacement.""" def __init__(self, file: _Backing, offset: int, size: int) -> None: self.file, self.offset, self.size = file, offset, size def read(self) -> bytes: data = os.pread(self.file.fileno(), self.size, self.offset) if len(data) != self.size: raise EOFError("saved value was truncated") return data # These pure-Python codecs change only the handling of bytes in `names`. # The file remains an ordinary pickle, readable by older kernels. _IndexBase: Any = getattr(pickle, "_Unpickler", object) _StreamBase: Any = getattr(pickle, "_Pickler", object) class _IndexedUnpickler(_IndexBase): dispatch: Any = getattr(_IndexBase, "dispatch", {}).copy() def __init__(self, file: BinaryIO) -> None: self.file = os.fdopen(os.dup(file.fileno()), "rb") self.file.seek(file.tell()) self.backing = _Backing(self.file) try: super().__init__(self.file) except BaseException: self.file.close() raise self.names: object = None def load(self) -> object: try: return super().load() finally: self.file.close() def load_empty_dictionary(self) -> None: is_names = len(self.metastack) == 1 and self.stack[-1:] == ["names"] super().load_empty_dictionary() if is_names: self.names = self.stack[-1] def _bytes(self, width: int) -> None: size = int.from_bytes(self.read(width), "little") container = self.metastack[-1][-1] if self.metastack else None if len(self.stack) >= 2 and self.stack[-2] is self.names: container = self.names if container is not self.names or self.names is None: self.append(self.read(size)) return frame = self._unframer.current_frame if frame is not None and frame.tell() < len(frame.getbuffer()): offset = self.file.tell() - len(frame.getbuffer()) + frame.tell() if frame.tell() + size > len(frame.getbuffer()): raise pickle.UnpicklingError("saved value crosses a pickle frame") frame.seek(size, 1) else: offset = self.file.tell() self.file.seek(size, 1) self.append(_Slice(self.backing, offset, size)) def load_short_binbytes(self) -> None: self._bytes(1) def load_binbytes(self) -> None: self._bytes(4) def load_binbytes8(self) -> None: self._bytes(8) dispatch[pickle.EMPTY_DICT[0]] = load_empty_dictionary dispatch[pickle.SHORT_BINBYTES[0]] = load_short_binbytes dispatch[pickle.BINBYTES[0]] = load_binbytes dispatch[pickle.BINBYTES8[0]] = load_binbytes8 class _StreamingPickler(_StreamBase): dispatch: Any = getattr(_StreamBase, "dispatch", {}).copy() def save_slice(self, value: _Slice) -> None: self.framer.commit_frame(force=True) self.framer.file_write(pickle.BINBYTES + value.size.to_bytes(4, "little")) offset, remaining = value.offset, value.size while remaining: chunk = os.pread(value.file.fileno(), min(256 * 1024, remaining), offset) if not chunk: raise EOFError("saved value was truncated") self.framer.file_write(chunk) offset += len(chunk) remaining -= len(chunk) self.memoize(value) dispatch[_Slice] = save_slice class _SavingName: """A pending global read by dill while saving, encoded as an albedo-name reference.""" def __init__(self, name: str) -> None: self.name = name class RestoreError(RuntimeError): """A saved name could not be loaded at its first use.""" class LazyNamespace(dict[str, object]): """A namespace whose missing names can still live in a snapshot.""" def __init__(self, initial: dict[str, object] | None = None) -> None: super().__init__(initial or {}) self.pending: dict[str, _Slice | bytes | str] = {} self.failures: dict[str, str] = {} self.replayed: dict[str, object] = {} self.loading: set[str] = set() self.lock: Any = None self.saving: Any = None self.serialiser: _Serialiser | None = None self._prepared: Any = None self._global_codes: Any = None def descriptors(self) -> set[int]: """Descriptors of the snapshots unread values are still read from.""" return { entry.file.fileno() for entry in list(self.pending.values()) if isinstance(entry, _Slice) } def __missing__(self, name: str) -> object: if self.lock is None: raise KeyError(name) with self.lock: if dict.__contains__(self, name): return dict.__getitem__(self, name) if name not in self.pending: raise KeyError(name) if ( self.saving is not None and getattr(self.saving, "active", False) and not self.loading and sys._getframe(1).f_globals.get("__name__") in {"dill.detect", "dill._dill"} ): return _SavingName(name) if name in self.loading: if name in self.replayed: return self.replayed[name] raise RestoreError( f"could not restore {name!r}: cyclic saved reference" ) self.loading.add(name) entry = self.pending[name] try: if isinstance(entry, str): value = importlib.import_module(entry) else: blob = entry.read() if isinstance(entry, _Slice) else entry assert self.serialiser is not None value = loads_shared(self.serialiser, blob, self) except BaseException as error: if name in self.replayed: value = self.replayed[name] else: reason = f"{type(error).__name__}: {error}"[:200] self.failures[name] = reason raise RestoreError( f"could not restore {name!r}: {reason}" ) from error finally: self.loading.remove(name) self.pending.pop(name, None) if not dict.__contains__(self, name): dict.__setitem__(self, name, value) self.replayed.pop(name, None) self.prepare_globals(value) return dict.__getitem__(self, name) def __setitem__(self, name: str, value: object, /) -> None: if self.lock is None: super().__setitem__(name, value) return with self.lock: self.pending.pop(name, None) self.failures.pop(name, None) self.replayed.pop(name, None) super().__setitem__(name, value) self.prepare_globals(value) def __delitem__(self, name: str, /) -> None: if self.lock is None: super().__delitem__(name) return with self.lock: if name in self.pending: self[name] super().__delitem__(name) self.failures.pop(name, None) self.replayed.pop(name, None) def __contains__(self, name: object) -> bool: return dict.__contains__(self, name) or name in self.pending def keys(self) -> Any: return KeysView(self) def __iter__(self) -> Iterator[str]: return iter(dict.fromkeys(dict.keys(self)) | dict.fromkeys(self.pending)) def __len__(self) -> int: return dict.__len__(self) + len(self.pending.keys() - dict.keys(self)) def items(self): self.materialise() return dict.items(self) def values(self): self.materialise() return dict.values(self) def copy(self) -> dict[str, object]: self.materialise() return dict.copy(self) def __repr__(self) -> str: self.materialise() return dict.__repr__(self) def get(self, key: object, default: object = None) -> object: try: return self[cast(str, key)] except KeyError: return default def materialise(self) -> None: for name in list(self.pending): self[name] def prepare(self, code: types.CodeType) -> None: if not self.pending: return import dis prepared = self._prepared.get(code) if prepared is None: names: set[str] = set() reflect = False todo = [code] while todo: current = todo.pop() for instruction in dis.get_instructions(current): if instruction.opname.startswith( ("LOAD_", "DELETE_") ) and instruction.opname not in {"LOAD_CONST", "LOAD_SMALL_INT"}: name = instruction.argval if isinstance(name, str): names.add(name) reflect |= bool( set(current.co_names) & {"globals", "locals", "vars", "dir"} ) todo.extend( c for c in current.co_consts if isinstance(c, types.CodeType) ) prepared = names, reflect self._prepared[code] = prepared names, reflect = prepared self.prepare_global_code(code) for name in list(self.pending) if reflect else names & self.pending.keys(): self[name] def prepare_global_code(self, code: types.CodeType) -> None: if not self.pending or code in self._global_codes: return import dis self._global_codes.add(code) for instruction in dis.get_instructions(code): if instruction.opname in {"STORE_GLOBAL", "DELETE_GLOBAL"}: if instruction.argval in self.pending: self[instruction.argval] for constant in code.co_consts: if isinstance(constant, types.CodeType): self.prepare_global_code(constant) def prepare_globals(self, value: object) -> None: if not self.pending: return if isinstance(value, types.FunctionType): self.prepare_global_code(value.__code__) elif isinstance(value, type): for member in vars(value).values(): if isinstance(member, (staticmethod, classmethod)): member = member.__func__ if isinstance(member, types.FunctionType): self.prepare_global_code(member.__code__) elif isinstance(member, property): for method in (member.fget, member.fset, member.fdel): if method is not None: self.prepare_global_code(method.__code__) def reconcile(self) -> None: # CPython STORE_GLOBAL writes directly into the dict, bypassing __setitem__. for name in self.pending.keys() & dict.keys(self): self.pending.pop(name, None) def _codec_fallback( log: Callable[[str], None] | None, operation: str, error: BaseException ) -> None: if log is not None: try: log( f"kernel state {operation} fell back to standard pickle: {type(error).__name__}: {error}"[ :400 ] ) except Exception: pass def save_state( path: str, namespace: dict[str, object], definitions: dict[str, str], injected: set[str], kernel: object = None, log: Callable[[str], None] | None = 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 | _Slice] = {} modules: dict[str, str] = {} skipped: list[dict[str, str]] = [] if isinstance(namespace, LazyNamespace): namespace.reconcile() skipped.extend({"name": n, "reason": r} for n, r in namespace.failures.items()) for name, entry in namespace.pending.items(): if name.startswith("_") or name in injected: continue if isinstance(entry, str): modules[name] = entry else: payload[name] = entry total = sum(v.size if isinstance(v, _Slice) else len(v) for v in payload.values()) largest: list[tuple[str, int]] = [] largest.extend( (n, v.size if isinstance(v, _Slice) else len(v)) for n, v in payload.items() if (v.size if isinstance(v, _Slice) else len(v)) >= 64 * 1024 ) shared = { id(value): name for name, value in list(dict.items(namespace)) if not name.startswith("_") and name not in injected and isinstance(value, (types.FunctionType, type)) } for name in list(dict.keys(namespace)): if name.startswith("_") or name in injected: continue value = dict.get(namespace, 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: if isinstance(namespace, LazyNamespace) and namespace.saving is not None: namespace.saving.active = True try: blob = dumps_within(serialiser, value, STATE_MAX_VALUE, shared) finally: if ( isinstance(namespace, LazyNamespace) and namespace.saving is not None ): namespace.saving.active = False 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: snapshot = { # 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, } try: _StreamingPickler(file).dump(snapshot) except BaseException as error: _codec_fallback(log, "streamed save", error) snapshot["names"] = { name: value.read() if isinstance(value, _Slice) else value for name, value in payload.items() } file.seek(0) file.truncate() pickle.dump(snapshot, 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, log: Callable[[str], None] | None = None, ) -> dict[str, object]: """Restore kernel state and definitions, deferring matching-writer values until use.""" 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: if isinstance(namespace, LazyNamespace): try: saved = cast(dict[str, object], _IndexedUnpickler(file).load()) except BaseException as error: _codec_fallback(log, "indexed restore", error) file.seek(0) saved = cast(dict[str, object], pickle.load(file)) else: 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 ( {} if isinstance(namespace, LazyNamespace) and compatible else 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]] if isinstance(namespace, LazyNamespace) and compatible: return _restore_lazy( saved, namespace, definitions, serialiser, kind, original, output_lost, ) 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 def _restore_lazy( saved: dict[str, object], namespace: LazyNamespace, definitions: dict[str, str], serialiser: _Serialiser, kind: str, original: str | None, output_lost: list[str] | None, ) -> dict[str, object]: import ast import threading import weakref namespace.lock = threading.RLock() namespace.saving = threading.local() namespace.serialiser = serialiser namespace._prepared = weakref.WeakKeyDictionary() namespace._global_codes = weakref.WeakSet() namespace.pending.clear() namespace.failures.clear() namespace.replayed.clear() namespace.pending.update(cast(dict[str, _Slice | bytes], saved.get("names", {}))) namespace.pending.update(cast(dict[str, str], saved.get("modules", {}))) available = set(namespace.pending) failed: list[dict[str, str]] = [] defs: list[str] = [] for item in cast(list[dict[str, str]], 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"] pending_class = None loaded_classes = {n: v for n, v in dict.items(namespace) if isinstance(v, type)} try: tree = ast.parse(source) statement = tree.body[0] if len(tree.body) == 1 else None if isinstance(statement, (ast.Import, ast.ImportFrom)): bound = { alias.asname or ( alias.name.split(".")[0] if isinstance(statement, ast.Import) else alias.name ) for alias in statement.names } defer_import = all( isinstance(namespace.pending.get(n), str) for n in bound ) else: defer_import = False if isinstance(statement, ast.ClassDef): pending_class = namespace.pending.pop(statement.name, None) if not defer_import: code = compile(tree, "", "exec") namespace.prepare_global_code(code) exec(code, namespace) if pending_class is not None and isinstance(statement, ast.ClassDef): namespace.replayed[statement.name] = namespace[statement.name] dict.__delitem__(namespace, statement.name) namespace.pending[statement.name] = pending_class dict.update(namespace, loaded_classes) except BaseException as error: failed.append( {"name": name, "reason": f"{type(error).__name__}: {error}"[:200]} ) if pending_class is not None: namespace.pending[name] = pending_class else: if source not in definitions.values(): key = name while key in definitions: key += "#2" definitions[key] = source available.add(name) defs.append(name) namespace.reconcile() directory = saved.get("cwd") if isinstance(directory, str) and os.path.isdir(directory): os.chdir(directory) result: dict[str, object] = { "restored": sorted(available - namespace.failures.keys()), "lazy": sorted(namespace.pending), "defs": defs, "failed": failed + [{"name": n, "reason": r} for n, r in namespace.failures.items()], "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