"""A restored kernel gets back what its namespace held, as the same objects. When the daemon releases an idle kernel it sends `snapshot`, and the next kernel for the session gets `restore`. A defect loses a helper, a class, an import, or a decorated definition the model relies on, or brings back a different one. The daemon only carries the path, so this replays generated programs (rebinding names, definitions in failed cells, values past the per-value cap, private names) in one kernel, snapshots it, restores a fresh kernel, and compares every name's fingerprint between the two. The cross-interpreter upgrade stays in e2e/kernel_state_test.py. Each saved value is pickled on its own, which once made a restored instance's class a different object from its class's name (RestoredIdentityTest). """ from __future__ import annotations import os from pathlib import Path import sys import tempfile import unittest HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE.parent)) import hypothesis_profiles # noqa: E402 from hypothesis import given, settings, strategies as st # noqa: E402 from kernel_owner_support import Kernel # noqa: E402 NAMES = ["a", "b", "c", "_d"] # Statements whose source the kernel records as a definition. DEFINED = {"function", "class", "decorated", "failed"} # Helpers the generated statements use; restored like any other name. SETUP = """ def add(amount): def decorate(fn): return lambda: fn() + amount return decorate def mark(cls): cls.k += 100 return cls class Box: def __init__(self, v): self.v = v def fingerprint(x): import types if isinstance(x, types.ModuleType): return ("module", x.__name__) if isinstance(x, type): return ("class", x.k, x().get()) if isinstance(x, Box): return ("box", x.v) if isinstance(x, (bytes, bytearray)): return ("bytes", len(x)) if callable(x): try: return ("call", x(1)) except TypeError: return ("call", x()) return ("value", repr(x)) """ PROBE = ( "for _name in {names!r}:\n" " try:\n" " print(_name, fingerprint(globals()[_name]))\n" " except KeyError:\n" " print(_name, 'missing')\n" ) literals = st.recursive( st.integers(-5, 5) | st.text("xyé", max_size=3) | st.none(), lambda inner: ( st.lists(inner, max_size=3) | st.dictionaries(st.text("kl", max_size=2), inner, max_size=2) ), max_leaves=5, ) @st.composite def statements(draw: st.DrawFn) -> tuple[str, str, str]: """One cell: its source, the name it binds, and its kind.""" name = draw(st.sampled_from(NAMES)) k = draw(st.integers(0, 9)) kind = draw( st.sampled_from( [ "value", "function", "class", "instance", "lambda", "decorated", "import", "big", "failed", "long", ] ) ) source = { "value": f"{name} = {draw(literals)!r}", "function": f"def {name}(v):\n return v + {k}", "class": ( f"@mark\nclass {name}:\n k = {k}\n" f" def get(self):\n return self.k + 1" ), "instance": f"{name} = Box({k})", "lambda": f"{name} = lambda v: v * {k}", "decorated": f"@add({k})\n@add(1)\ndef {name}():\n return {k}", "import": f"import {draw(st.sampled_from(['json', 'os.path', 'xml.dom']))} as {name}", "big": f"{name} = bytes(9 * 1024 * 1024)", # The definition before the raise still runs. "failed": f"def {name}():\n return {k}\nraise RuntimeError('boom')", # Source past the per-definition cap: the value still comes back. "long": f"def {name}(v):\n return v + len('{'x' * 40000}')", }[kind] return source, name, kind def probe(kernel: Kernel) -> dict[str, str]: done = kernel.execute(PROBE.format(names=NAMES)) assert done["status"] == "ok", done return dict(line.split(" ", 1) for line in done["output"].splitlines()) class SnapshotRoundTripTest(unittest.TestCase): @settings(max_examples=hypothesis_profiles.cases(10)) @given(st.lists(statements(), min_size=1, max_size=6)) def test_a_restored_kernel_holds_what_the_saved_one_held(self, program): path = os.path.join(tempfile.mkdtemp(), "session.state") saved = Kernel() try: self.assertEqual(saved.execute(SETUP)["status"], "ok") # The kind of each name's last binding. last: dict[str, str] = {} for source, name, kind in program: saved.execute(source) last[name] = kind before = probe(saved) saved.send({"type": "snapshot", "id": "snap", "path": path}) state = saved.wait_for(lambda f: f.get("id") == "snap")["state"] finally: saved.close() restored = Kernel() try: restored.send({"type": "restore", "id": "restore", "path": path}) report = restored.wait_for(lambda f: f.get("id") == "restore")["state"] after = probe(restored) finally: restored.close() self.assertEqual(report["failed"], [], report) skipped = {item["name"] for item in state["skipped"]} for name in NAMES: kind = last.get(name) if kind == "big": self.assertIn(name, skipped, (program, state)) self.assertEqual(after[name], "missing", (program, name)) elif name.startswith("_") and kind not in DEFINED: # A private name's value is never saved. self.assertEqual(after[name], "missing", (program, name)) else: # Definition source is replayed whatever its name, so a # private helper a saved function calls comes back too. self.assertEqual(after[name], before[name], (program, name)) 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()