"""Python's seams: what must stay true when python becomes an ordinary component. The model's `python` tool is today a privileged extension: the kernel it drives is booted, reloaded, swapped and reaped by the runtime itself, other extensions reach the kernel as `python_modules` that load into it, and the cell journal is a table the daemon owns. The components refactor makes python one component beside the rest. This file guards what a user or the model sees across that move, and nothing about how it is wired: - an extension's bindings are in the model's namespace exactly while it is enabled, live, with other bindings and the user's variables untouched; - a binding reference captured before its extension was disabled cannot reach the extension afterwards; - a reload that changes no module keeps the kernel, its variables and its running job; one that changes the module set never kills a job, is refused or deferred while one runs, keeps the saved choice, and applies once the job ends; values that cannot be carried across are reported; - a plugin module that fails while the kernel boots leaves the session a working kernel and says why; - a module two extensions serve (mcp, editor-mcp) is one binding that outlives either extension; - a remote kernel boots the session's modules; - a call that names a binding runs as its cell and hooks judge that cell; any other unknown tool name is refused with the documented answer; - the cell journal (output, images, file-change traces) survives a daemon restart, shows in history, counts in the storage report and is deleted with its session. Neighbours already pin the rest: kernel_*_test.py (detach, swap, wedges, spares), cell_*_test.py, job_wake_test.py, traces_test.py, remote_kernels_test.py. E2E is the only place these show: they span the runtime, the kernel and the HTTP selection API at once. """ import base64 from contextlib import closing import json import os from pathlib import Path import secrets import sqlite3 import struct import unittest import urllib.error import urllib.parse import zlib import harness from harness import ( LOOPBACK_REMOTE, Albedo, Provider, Reply, exclusive, python, text, ) from kernel_support import ModelCells, editable_daemon # Bindings the default session carries, by the extension that owns them. PAPERCLIP_BINDINGS = ["resolve_vent", "vent", "vents"] OTHER_BINDINGS = ["artifacts", "files", "mail", "memory", "run", "work"] def png(rgb): """A 1x1 PNG of that colour, so one test's image is nobody else's row.""" def chunk(kind, data): body = kind + data return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) header = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0) pixel = zlib.compress(b"\x00" + bytes(rgb)) return ( b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", pixel) + chunk(b"IEND", b"") ) def bound(*names): """A cell that prints the sorted subset of `names` bound in the namespace.""" return ( "_present = []\n" f"for _name in {list(names)!r}:\n" " try:\n eval(_name)\n except NameError:\n continue\n" " _present.append(_name)\n" "print(json.dumps(sorted(_present)))" ) class KernelCase(ModelCells, unittest.TestCase): """A session whose model runs the cells (or whole replies) a test queues.""" prepare = None app: Albedo def setUp(self): self.cells = [] self.replies = [] def script(request): if request["input"][-1].get("role") == "user": if self.replies: return self.replies.pop(0) if self.cells: return python(self.cells.pop(0)) return text("ok") self.provider = Provider(script) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, protocol="responses", prepare=self.prepare) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.session = self.app.session() def get(self, path): with self.app.api(path) as response: return json.load(response) def select(self, **extensions): """Save the session's extension choice; applying it is `reload`.""" route = f"/sessions/{self.session}?view=configuration" with self.app.api(route) as response: response.read() etag = response.headers["ETag"] with self.app.api( route, {"selection": {"extensions": extensions}}, method="PATCH", headers={"If-Match": etag}, ) as response: return json.load(response) def reload(self): """Apply the saved choice; the reload's own report.""" route = f"/sessions/{self.session}/reload" with self.app.api(route, {"target": "session"}) as response: return json.load(response)["session"] def chosen(self): snapshot = self.get(f"/sessions/{self.session}?tail=0") return snapshot["selection"]["effective"]["extensions"] def kernel(self): return self.get(f"/sessions/{self.session}?tail=0")["kernel"] def output(self, code): """What a cell printed, which must have run.""" result, _ = self.cell(code) self.assertEqual(result["status"], "ok", result) return result["output"] def names(self, *wanted): return json.loads(self.output(bound(*wanted))) def last_output(self): """What the latest request carries as the result of the model's last call.""" items = self.provider.requests[-1]["request"]["input"] return next( item["output"] for item in reversed(items) if item.get("type") == "function_call_output" ) def held_job(self): """The cell code that starts a job running until the gate opens, so the test decides when it ends rather than a sleep a slow machine outlasts.""" gate = self.app.workspace / "job-gate" os.mkfifo(gate) self.addCleanup(harness.release_fifo, gate) program = f"open({str(gate)!r}, 'rb').read(1); print('JOB-DONE')" return gate, f"import sys\njob = run(sys.executable, '-c', {program!r})" def end_job(self, gate): harness.wait_until( lambda: harness.release_fifo(gate), 10, "the held job never opened its gate" ) harness.wait_until( lambda: self.kernel()["live_job_count"] == 0, 20, "the job never ended" ) self.app.idle(self.session) class BindingsFollowSelectionTests(KernelCase): def test_disabling_an_extension_removes_only_its_bindings(self): wanted = PAPERCLIP_BINDINGS + OTHER_BINDINGS self.output("import os\nmark = 7\ndef twice(x):\n return x * 2\n") self.assertEqual(self.names(*wanted), sorted(wanted)) self.select(paperclips=False) self.assertEqual(self.reload()["state"], "applied") self.assertEqual(self.names(*wanted), sorted(OTHER_BINDINGS)) # What the user made is still theirs. self.assertEqual(self.output("print(mark, twice(21))").strip(), "7 42") def test_enabling_an_extension_adds_its_bindings_to_a_live_session(self): self.output("mark = 7") self.assertEqual(self.names("view_diff", "work"), ["work"]) self.select(view=True) self.assertEqual(self.reload()["state"], "applied") self.assertEqual(self.names("view_diff", "work"), ["view_diff", "work"]) self.assertEqual(self.output("print(mark)").strip(), "7") self.select(view=False) self.assertEqual(self.reload()["state"], "applied") self.assertEqual(self.names("view_diff", "work"), ["work"]) self.assertEqual(self.output("print(mark)").strip(), "7") def test_a_binding_captured_before_a_disable_cannot_reach_its_extension(self): ledger = "/extensions/work/items?" + urllib.parse.urlencode( {"workspace": str(self.app.workspace)} ) self.output( "create = work.create\n" "item = await create('written while enabled')\nprint(item.title)" ) self.select(work=False) self.assertEqual(self.reload()["state"], "applied") outcome = self.output( "try:\n" " await create('written after the disable')\n" "except BaseException as error:\n" " print('REFUSED')\n" "else:\n" " print('REACHED')" ) self.assertEqual(outcome.strip(), "REFUSED") ledger_text = json.dumps(self.get(ledger)) self.assertIn("written while enabled", ledger_text) self.assertNotIn("written after the disable", ledger_text) def test_values_a_swap_cannot_carry_are_reported_not_silently_lost(self): self.output( "import threading\nkept = [1, 2, 3]\ngen = (i for i in range(3))\n" "lock = threading.Lock()" ) self.select(artifacts=False) report = self.reload() self.assertEqual(report["state"], "applied", report) # The first cell after the swap is the one whose request carries its note. result, prompt = self.cell( "print(json.dumps([kept, [n for n in ('gen', 'lock') if n in globals()]]))" ) kept, survivors = json.loads(result["output"]) self.assertEqual(kept, [1, 2, 3]) # Whatever the swap could not keep is named, to the user and the model. warned = " ".join(warning["detail"] for warning in report["warnings"]) for name in {"gen", "lock"} - set(survivors): self.assertIn(name, warned, report) self.assertIn(name, prompt) class ReloadKeepsOrReplacesTests(KernelCase): def test_a_reload_that_changes_no_module_keeps_the_kernel_and_its_job(self): gate, job = self.held_job() first = self.output(f"import os\nmark = 7\n{job}\nprint(os.getpid())") instance = self.kernel()["instance_id"] late = self.app.workspace / ".albedo/skills/late/SKILL.md" late.parent.mkdir(parents=True) late.write_text("---\nname: late\ndescription: added after boot\n---\nbody\n") self.assertEqual(self.reload()["state"], "applied") # The reload did its work: the new skill is a command now. probe = self.output( "import os\nnames = [c['name'] for c in await commands.catalog()]\n" "print(os.getpid(), mark, '/late' in names)" ) self.assertEqual(probe.split(), [first.strip(), "7", "True"]) after = self.kernel() self.assertEqual(after["instance_id"], instance) self.assertEqual(after["live_job_count"], 1, after) self.end_job(gate) self.assertIn("JOB-DONE", self.output("print(await job.read())")) def test_a_module_change_never_kills_a_job_and_waits_for_it(self): wanted = PAPERCLIP_BINDINGS gate, job = self.held_job() self.output(f"mark = 7\n{job}") self.select(paperclips=False) held = self.reload() # While the job runs the swap is not made, and nothing is lost. if held["state"] != "applied": self.assertEqual(self.names(*wanted), sorted(wanted)) self.assertEqual(self.kernel()["live_job_count"], 1, held) self.assertFalse(self.chosen()["paperclips"], "the saved choice is kept") self.end_job(gate) self.assertIn("JOB-DONE", self.output("print(await job.read())")) # The choice applies once the job is over. self.assertEqual(self.reload()["state"], "applied") self.assertEqual(self.names(*wanted), []) self.assertEqual(self.output("print(mark)").strip(), "7") def test_the_modules_two_extensions_share_survive_either_leaving(self): # mcp and editor-mcp both serve the `mcp` module: one binding, however many serve it. self.output("mark = 7") self.assertEqual(self.names("mcp"), []) self.select(**{"mcp": True}) report = self.reload() self.assertEqual((report["state"], report["warnings"]), ("applied", [])) self.assertEqual(self.names("mcp"), ["mcp"]) self.select(**{"editor-mcp": False}) self.assertEqual(self.reload()["state"], "applied") self.assertEqual(self.names("mcp"), ["mcp"]) self.assertEqual(self.output("print(mark)").strip(), "7") self.select(mcp=False) self.assertEqual(self.reload()["state"], "applied") self.assertEqual(self.names("mcp"), []) self.assertEqual(self.output("print(mark)").strip(), "7") def test_a_remote_kernel_boots_the_sessions_modules(self): names = ( LOOPBACK_REMOTE + "print(json.dumps(sorted((await rem.tools())['names'])))" ) remote = json.loads(self.output(names)) for binding in PAPERCLIP_BINDINGS + OTHER_BINDINGS: self.assertIn(binding, remote) self.select(paperclips=False) self.assertEqual(self.reload()["state"], "applied") remote = json.loads(self.output(names)) self.assertEqual([n for n in PAPERCLIP_BINDINGS if n in remote], []) for binding in OTHER_BINDINGS: self.assertIn(binding, remote) class BindingCallsTests(KernelCase): def refusal(self, name): self.replies.append(Reply("python", "", tool_name=name, tool_arguments={})) self.app.prompt(self.session, f"call {name}").close() self.app.idle(self.session) return self.last_output() def test_a_name_that_is_neither_tool_nor_binding_is_refused_with_the_documented_answer( self, ): answer = {"error": "no such tool"} for name in ("not-a-binding", "too.many.dotted.names"): with self.subTest(name=name): self.assertEqual(json.loads(self.refusal(name)), answer) # The refusal costs the call, not the session. self.assertEqual(self.output("print('still here')").strip(), "still here") def test_a_binding_called_by_name_gets_its_arguments_as_keywords_and_is_awaited( self, ): ledger = "/extensions/work/items?" + urllib.parse.urlencode( {"workspace": str(self.app.workspace)} ) self.replies.append( Reply( "python", "", tool_name="work.create", tool_arguments={"title": "by name"}, ) ) self.app.prompt(self.session, "call work.create").close() self.app.idle(self.session) output = self.last_output() self.assertEqual(harness.cell_result(output)["status"], "ok", output) self.assertIn("by name", json.dumps(self.get(ledger))) # exclusive: hooks.json and the hooks extension are global @exclusive class BindingCallsAreJudgedAsCellsTests(KernelCase): def setUp(self): super().setUp() with self.app.api("/settings?group=extensions") as response: validator = response.getheader("ETag") response.read() self.app.api( "/settings?group=extensions", {"defaults": {"hooks": True}}, method="PATCH", headers={"If-Match": validator}, ).close() gate = self.app.workspace / "gate.sh" gate.write_text( "cat > payload.json\ngrep -q forbidden payload.json && exit 2\nexit 0\n" ) hook = {"type": "command", "command": f"sh {gate}", "timeout": 5} hooks = {"PreToolUse": [{"matcher": "^python$", "hooks": [hook]}]} (self.app.home / "hooks.json").write_text(json.dumps({"hooks": hooks})) self.session = self.app.session() def write_by_name(self, content): arguments = {"path": "effect", "content": content} self.replies.append( Reply("python", "", tool_name="files.write", tool_arguments=arguments) ) self.app.prompt(self.session, "write by name").close() self.app.idle(self.session) return self.last_output() def test_hooks_judge_the_cell_a_binding_call_runs_as(self): refused = self.write_by_name("forbidden") self.assertIn("blocked by a hook", refused) self.assertFalse((self.app.workspace / "effect").exists()) # The hook was asked about the python call, whose code names the binding. asked = json.loads((self.app.workspace / "payload.json").read_text()) self.assertEqual(asked["tool_name"], "python") self.assertIn("files.write", json.dumps(asked["tool_input"])) # The same call the hook lets through runs. self.write_by_name("allowed") self.assertEqual((self.app.workspace / "effect").read_text(), "allowed") # exclusive: boots an editable python bundle @exclusive class PluginFailureAtBootTests(KernelCase): bundle: Path def prepare(self, app): launcher, self.bundle = editable_daemon(app.root) app.env["ALBEDO_DAEMON"] = str(launcher) def fresh(self, code): """A cell in a new session, so its kernel is a fresh boot.""" self.session = self.app.session() return self.cell(code) def test_one_plugin_module_failing_to_load_leaves_a_working_kernel_that_says_why( self, ): good = self.app.home / "kernel-bundles" / "good" first, prompt = self.fresh(bound("vent", "work")) self.assertEqual(json.loads(first["output"]), ["vent", "work"]) self.assertNotIn("started cleanly", prompt) harness.wait_until(good.exists, 10, "the tree that booted was never saved") # Break the one module that defines the `vent` binding. (broken,) = [ path for path in self.bundle.rglob("*.py") if "def vent(" in path.read_text() ] original = broken.read_text() broken.write_text(original + '\nraise TypeError("plugin broke on purpose")\n') fallen, prompt = self.fresh(bound("vent", "work")) # The session still has a kernel with every binding, and the model is # told which code runs and what failed. self.assertEqual(json.loads(fallen["output"]), ["vent", "work"]) self.assertIn("started cleanly", prompt) self.assertIn("plugin broke on purpose", prompt) broken.write_text(original) fixed, prompt = self.fresh(bound("vent", "work")) self.assertEqual(json.loads(fixed["output"]), ["vent", "work"]) self.assertNotIn("started cleanly", prompt) class CellJournalTests(KernelCase): def database(self): path = self.app.home / "albedo.sqlite" return closing(sqlite3.connect(f"file:{path}?mode=ro", uri=True)) def shown_cell(self, image): """Run a cell that prints, shows an image and writes a file; its history entry.""" data = base64.b64encode(image).decode() result, _ = self.cell( "import base64\n" "open('made.txt', 'w').write('hello\\n')\n" f"show_image(base64.b64decode('{data}'))\nprint('LINE-OUT')\n1 + 1" ) self.assertEqual(result["status"], "ok", result) return result["cell_id"], self.last_result() def last_result(self): items = self.app.history(self.session)["items"] return [item for item in items if item["kind"] == "tool_result"][-1] def image_bytes(self, entry): (image,) = [part for part in entry["content"] if part["kind"] == "image"] with self.app.api(image["image"]["reference"]["url"]) as response: return response.read() @exclusive def test_cells_images_and_traces_survive_a_daemon_restart(self): image = png(secrets.token_bytes(3)) cell_id, before = self.shown_cell(image) kinds = {part["kind"] for part in before["content"]} self.assertEqual(kinds, {"json", "image", "trace"}) self.assertEqual(self.image_bytes(before), image) self.app.restart() after = self.last_result() self.assertEqual(after, before) self.assertEqual(self.image_bytes(after), image) # The model can still ask the journal about the cell. info = self.output(f"print(json.dumps(await cells.info({cell_id!r})))") self.assertEqual(json.loads(info)["status"], "ok", info) trace = self.output(f"print(json.dumps(await cells.trace({cell_id!r})))") self.assertIn("made.txt", trace) def test_deleting_a_session_deletes_its_cells_traces_and_images(self): image = png(secrets.token_bytes(3)) cell_id, _ = self.shown_cell(image) with self.database() as db: self.assertEqual( db.execute( "SELECT count(*) FROM cells WHERE session=?", (self.session,) ).fetchone()[0], 1, ) self.assertEqual( db.execute( "SELECT count(*) FROM cell_traces WHERE id=?", (cell_id,) ).fetchone()[0], 1, ) self.assertEqual( db.execute( "SELECT count(*) FROM images WHERE data=?", (image,) ).fetchone()[0], 1, ) self.assertEqual(self.app.delete_tree(self.session)["state"], "complete") with self.database() as db: self.assertEqual( db.execute( "SELECT count(*) FROM cells WHERE session=?", (self.session,) ).fetchone()[0], 0, ) self.assertEqual( db.execute( "SELECT count(*) FROM cell_traces WHERE id=?", (cell_id,) ).fetchone()[0], 0, ) self.assertEqual( db.execute( "SELECT count(*) FROM images WHERE data=?", (image,) ).fetchone()[0], 0, ) # exclusive: the report lists every session of its daemon @exclusive def test_the_storage_report_counts_what_a_cell_journals(self): def stored(): report = json.loads(self.app.cli("storage", "--json")) (row,) = [r for r in report["db"]["sessions"] if r["id"] == self.session] return row["bytes"] self.output("pass") before = stored() # A written file leaves a bounded diff of several KiB in the journal. self.output("import os\nopen('big.txt', 'w').write(os.urandom(6000).hex())") self.assertGreater(stored() - before, 10_000) if __name__ == "__main__": unittest.main()