diff --git a/python/albedo_state.py b/python/albedo_state.py index ce02d1204..07d5f608b 100644 --- a/python/albedo_state.py +++ b/python/albedo_state.py @@ -14,7 +14,7 @@ import sys import tempfile import types from collections.abc import Callable -from typing import BinaryIO, Literal, Protocol, cast +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. @@ -72,13 +72,59 @@ class _Bounded: return b"".join(self.chunks) -def dumps_within(serialiser: _Serialiser, value: object, limit: int) -> bytes: - """`serialiser.dumps(value)`, or TooLarge once it passes `limit` bytes.""" +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) - serialiser.dump(value, sink) + 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] = {} @@ -123,6 +169,13 @@ def save_state( 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 @@ -137,7 +190,7 @@ def save_state( if replayed and kind == "pickle": continue try: - blob = dumps_within(serialiser, value, STATE_MAX_VALUE) + blob = dumps_within(serialiser, value, STATE_MAX_VALUE, shared) except BaseException as error: reason = ( f"over the {STATE_MAX_VALUE}-byte per-variable cap" @@ -271,6 +324,10 @@ class _PortableUnpickler(pickle.Unpickler): 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 @@ -338,25 +395,43 @@ def load_state( output_lost = [f" {type(error).__name__}: {error}"[:200]] incompatible: dict[str, str] = {} deferred: list[tuple[str, bytes]] = [] - for name, blob in cast(dict[str, bytes], saved.get("names", {})).items(): - try: - if compatible: - namespace[name] = serialiser.loads(blob) - else: - namespace[name] = _load_portable(io.BytesIO(blob)) - except IncompatibleValue as error: - incompatible[name] = f"snapshot writer {writer or 'unknown'}: {error}"[:200] - except AttributeError as error: - if compatible: - deferred.append((name, blob)) + # 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: - 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) + 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 = { @@ -386,9 +461,15 @@ def load_state( 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] = serialiser.loads(blob) + namespace[name] = loads_shared(serialiser, blob, namespace) except BaseException as error: failed.append( {"name": name, "reason": f"{type(error).__name__}: {error}"[:200]} diff --git a/robot-docs/kernel-state.md b/robot-docs/kernel-state.md index 53a288452..879b05bd9 100644 --- a/robot-docs/kernel-state.md +++ b/robot-docs/kernel-state.md @@ -12,16 +12,20 @@ take a path and timeout and return a `Saved` report. A busy kernel answers [`save_state`](../python/albedo_state.py) excludes names beginning with `_` and injected names. It records module import names, serializes other values with `dill` when available or `pickle` otherwise, and stores captured definition -source separately. The [kernel project](../python/pyproject.toml) includes -`dill` so its locked environment can restore values saved by older kernels that -had `dill` installed. On Python 3.15 and newer, the project pins an upstream -dill revision because 0.4.1 cannot save closures on 3.15. Before returning to a -released version, verify that a fresh kernel on the same Python minor can -restore and call a closure that captures a local value. New snapshots include -the writer’s CPython cache tag (for example, `cpython-311`) in `writer_python`. -Older snapshots omit this field. The snapshot also records the working directory -and added `sys.path` entries. It writes a temporary file and replaces the -destination. +source separately. Each value is serialized on its own, so a reference from one +value to a class or function bound to another top-level name is saved as that +name. Restore loads values in the order those references need and binds each to +the restored object. An instance therefore stays an instance of its class's +name, and a replayed class definition does not replace the loaded class. The +[kernel project](../python/pyproject.toml) includes `dill` so its locked +environment can restore values saved by older kernels that had `dill` installed. +On Python 3.15 and newer, the project pins an upstream dill revision because +0.4.1 cannot save closures on 3.15. Before returning to a released version, +verify that a fresh kernel on the same Python minor can restore and call a +closure that captures a local value. New snapshots include the writer’s CPython +cache tag (for example, `cpython-311`) in `writer_python`. Older snapshots omit +this field. The snapshot also records the working directory and added `sys.path` +entries. It writes a temporary file and replaces the destination. The serialized values have a 64 MiB total limit and an 8 MiB per-value limit. Definition source has a 256 KiB total limit and a 32 KiB per-definition limit. diff --git a/test/harness/kernel_snapshot_test.py b/test/harness/kernel_snapshot_test.py new file mode 100644 index 000000000..bd6fd8c89 --- /dev/null +++ b/test/harness/kernel_snapshot_test.py @@ -0,0 +1,49 @@ +"""A restored kernel's classes are the classes its restored values belong to. + +Each saved value is pickled on its own, so a reference from one to another +(an instance to its class, a function to a helper class) was saved as a +copy: after a restore, `isinstance(boxed, Box)` was False. Restoring needs a +real kernel's snapshot and restore frames, with no daemon. +""" + +import os +import tempfile +import unittest + +from kernel_owner_support import Kernel + + +class RestoredIdentityTest(unittest.TestCase): + def restored(self, code: str, check: str) -> str: + path = os.path.join(tempfile.mkdtemp(), "session.state") + saved = Kernel() + try: + self.assertEqual(saved.execute(code)["status"], "ok") + saved.send({"type": "snapshot", "id": "snap", "path": path}) + saved.wait_for(lambda f: f.get("id") == "snap") + finally: + saved.close() + restored = Kernel() + try: + restored.send({"type": "restore", "id": "restore", "path": path}) + restored.wait_for(lambda f: f.get("id") == "restore") + done = restored.execute(check) + finally: + restored.close() + self.assertEqual(done["status"], "ok", done) + return done["output"].strip() + + def test_a_restored_instance_is_still_an_instance_of_its_class(self) -> None: + # Replaying Box's definition after its instances were restored bound + # the name to a new class, so isinstance(boxed, Box) was False. + self.assertEqual( + self.restored( + "class Box:\n pass\nboxed = Box()", + "print(isinstance(boxed, Box), type(boxed) is Box)", + ), + "True True", + ) + + +if __name__ == "__main__": + unittest.main()