"""The API a cell reaches for, in a real kernel with no daemon. Jobs a cell starts (text(), wait_for(), awaiting them), the names a model expects in scope, refusals that point at the right tool, and the injected tools a cell must not shadow. A defect here gives a model a wrong answer or an exception it cannot act on. All of it is the kernel's own; the e2e versions ran each case through a daemon, a fake provider and a model turn. """ from pathlib import Path from typing import cast import unittest from kernel_owner_support import HostError, Kernel class CellApiTest(unittest.TestCase): def setUp(self) -> None: self.kernel = Kernel(["run", "files"]) self.addCleanup(self.kernel.close) def execute(self, code: str) -> str: done = self.kernel.execute(code) self.assertEqual(done["status"], "ok", done) return done["output"] def test_text_returns_plain_output_and_raises_with_the_last_lines(self): program = ( "import sys; print('\\x1b[32mgreen\\x1b[0m'); " "print('10%\\r100%'); sys.exit(int(sys.argv[1]))" ) output = self.execute( f"program = {program!r}\n" "print(repr(await run(sys.executable, '-c', program, '0').text()))\n" "try:\n" " await run(sys.executable, '-c', program, '3').text()\n" "except RuntimeError as error:\n" " print(type(error).__name__, repr(str(error).splitlines()[0]))\n" " print(repr(error.output))\n" "print(repr(await run(sys.executable, '-c', program, '3').text(check=False)))\n" # `await` takes the slice with it; the slice applies to the text. "print(repr(await run(sys.executable, '-c', program, '0').text()[-5:]))\n" "job = run(sys.executable, '-c', program, '3')\n" "print(repr(await parallel(job.text(check=False)[:5])))" ) lines = output.splitlines() self.assertEqual(lines[0], repr("green\n100%\n")) self.assertEqual(lines[1].split()[0], "JobFailed") self.assertIn("exited 3", lines[1]) self.assertEqual(lines[2], repr("green\n100%\n")) self.assertEqual(lines[3], repr("green\n100%\n")) self.assertEqual(lines[4], repr("100%\n")) self.assertEqual(lines[5], repr(["green"])) def test_wait_for_returns_the_line_and_leaves_the_job_running(self): server = ( "import sys, time; print('starting', flush=True); time.sleep(0.4); " "print('ready on 4321', flush=True); time.sleep(60)" ) output = self.execute( "import re\n" f"server = run(sys.executable, '-c', {server!r})\n" "print(repr(await server.wait_for('ready', timeout=20)))\n" "print(repr(await server.wait_for(re.compile(r'on \\d+'), timeout=1)))\n" "print(server.exit_code)\n" "try:\n" " await server.wait_for('never', timeout=0.5)\n" "except TimeoutError as error:\n" " print('timeout', 'still running' in str(error))\n" "await server.stop()\n" "quick = run(sys.executable, '-c', 'print(1)')\n" "try:\n" " await quick.wait_for('ready', timeout=20)\n" "except RuntimeError as error:\n" " print(type(error).__name__, 'without printing' in str(error))" ) self.assertEqual( output.splitlines(), [ repr("ready on 4321"), repr("ready on 4321"), "None", "timeout True", "JobFailed True", ], ) def test_cells_get_the_api_a_model_reaches_for(self): output = self.execute( "job = run('echo', 'hello')\n" "await job\n" "assert (await job.tail()).strip() == 'hello'\n" "assert (await job.head(lines=1)).strip() == 'hello'\n" "assert output.read(job.id, 0, 3) == 'hel'\n" "try:\n" " output.read(job.id, limit=10**7)\n" "except ValueError as error:\n" " assert 'offset=' in str(error), error\n" "else:\n" " raise AssertionError('over-cap limit shortened silently')\n" "from albedo import files as imported\n" "assert imported is files\n" "assert re.fullmatch('a+', 'aa') and Path('.').is_dir()\n" "assert hashlib.md5(b'').hexdigest() and json.dumps(os.sep)\n" "try:\n" " run('true', timeout=120000)\n" "except ValueError as error:\n" " assert 'seconds' in str(error) and 'milliseconds' in str(error), error\n" "try:\n" " time.sleep(2)\n" "except PermissionError as error:\n" " assert 'run()' in str(error) and 'asyncio.sleep' in str(error), error\n" "time.sleep(0.01)\n" "await asyncio.sleep(0.01)\n" "print('api shapes ok')" ) self.assertEqual(output.strip(), "api shapes ok") def test_parallel_awaits_handles_that_do_not_hash(self): # A remote reference compares by value and is unhashable, so # asyncio.gather's own dict of arguments refused it outright. output = self.execute( "class Ref:\n" " __hash__ = None\n" " def __init__(self, value):\n" " self.value = value\n" " async def _wait(self):\n" " return self.value\n" " def __await__(self):\n" " return self._wait().__await__()\n" "print(await parallel(Ref(1), [Ref(2), Ref(3)]))" ) self.assertEqual(output.strip(), "[1, 2, 3]") def test_chdir_moves_run_and_files(self): workspace = Path(self.kernel.workspace) (workspace / "sub").mkdir() (workspace / "sub" / "note.txt").write_text("inside\n") output = self.execute( "os.chdir('sub')\n" "print(await run(sys.executable, '-c', 'import os; print(os.getcwd())').text())\n" "print(files.read('note.txt'))" ) self.assertIn(str((workspace / "sub").resolve()), output) self.assertIn("inside", output) def test_shadowing_injected_tools_is_refused_while_locals_and_stdlib_recovery_work( self, ): (Path(self.kernel.workspace) / "note.txt").write_text("recovered\n") for bad in ( "ran_before = True\nfiles = 1", "del files", "end_turn = 1", "del end_turn", "no_reply = 1", "del no_reply", "def overwrite():\n global output\n output = 1", ): failed = self.kernel.execute(bad) self.assertEqual(failed["status"], "error", failed) self.assertIn("kernel tool", failed["output"]) output = self.execute( "assert 'ran_before' not in globals()\n" "try:\n" " globals()['files'] = 1\n" "except PermissionError as err:\n" " assert 'kernel tool' in str(err)\n" "else:\n" " raise AssertionError('runtime globals() overwrite was not refused')\n" "from albedo import end_turn, files, no_reply\n" "def local_scope(files):\n" " return [output for output in (files,)]\n" "assert local_scope('ok') == ['ok']\n" "json = 'shadowed'\n" "assert json == 'shadowed'\n" "del json\n" "assert json.dumps(1) == '1'\n" "import builtins\nassert not hasattr(builtins, 'files')\n" "print(files.read('note.txt'))" ) self.assertIn("recovered", output) def test_a_cell_reports_how_long_it_ran(self): slept = self.kernel.execute("import asyncio\nawait asyncio.sleep(0.3)") self.assertGreaterEqual(slept["duration"], 0.3) self.assertLess(slept["duration"], 5) class BackgroundCellTest(unittest.TestCase): """Cancelling cells, including a backgrounded one and the cell itself.""" def setUp(self) -> None: # The daemon answers cells.list from its journal: here, the cell that # asks is the one started cell. self.kernel = Kernel( env={"ALBEDO_CELL_BACKGROUND_SECONDS": "0.5"}, host=lambda method, args: ( [{"id": f"s/c{self.kernel.cells}", "status": "started"}] if method == "cells.list" else None ), ) self.addCleanup(self.kernel.close) def test_a_cell_that_cancels_itself_leaves_the_kernel_running(self): cancelled = self.kernel.execute( "own = next(c['id'] for c in await cells.list() if c['status'] == 'started')\n" "print(await cells.cancel(own))" ) self.assertEqual(cancelled["status"], "interrupted", cancelled) alive = self.kernel.execute("print('alive')") self.assertEqual(alive["output"].strip(), "alive") def test_a_cancel_names_the_jobs_the_cell_leaves_running(self): started = self.kernel.execute( "held = run('sleep', '30')\nimport asyncio\nawait asyncio.Event().wait()" ) self.assertEqual(started["status"], "backgrounded", started) output = self.kernel.execute(f"print(await cells.cancel({started['id']!r}))")[ "output" ] self.assertIn("started jobs that the cancel leaves running", output) self.assertIn("(sleep 30)", output) self.assertEqual(output.strip().splitlines()[-1], "True") def test_a_backgrounded_cell_is_interrupted_at_its_original_deadline(self): # Backgrounding returns the turn early but keeps the cell's own # deadline, whether the cell awaits or blocks the kernel's loop. cells = { "awaits": "import asyncio\nawait asyncio.Event().wait()", "blocks": "import threading\nthreading.Event().wait(30)", } for kind, code in cells.items(): with self.subTest(kind): cell = f"s/{kind}" self.kernel.send( {"type": "execute", "id": cell, "code": code, "timeout_ms": 1800} ) outcomes = [ self.kernel.wait_for( lambda f: f["type"] == "done" and f["id"] == cell )["status"] for _ in range(2) ] self.assertEqual(outcomes, ["backgrounded", "interrupted"]) wake = self.kernel.wait_for( lambda f: f["type"] == "call" and f["method"] == "cells.completed" ) self.kernel.answer(wake) self.assertIn(f"{cell}: status=interrupted", wake["args"]["text"]) def test_stopping_a_backgrounded_cell_promotes_the_job_it_leaves(self): # The owner stops a backgrounded cell as a job (the jobs view's stop): # the cell is interrupted, and the job it started keeps running as # a job of its own rather than a child of a cell that is gone. started = self.kernel.execute( "# wait with child job\n" "held = run('sleep', '30')\nimport asyncio\nawait asyncio.Event().wait()" ) self.assertEqual(started["status"], "backgrounded", started) cell = started["id"] self.kernel.send({"type": "job_stop", "id": cell}) stopped = self.kernel.wait_for( lambda f: f["type"] == "job_stop" and f["id"] == cell ) self.assertTrue(stopped["ok"], stopped) ended = self.kernel.wait_for(lambda f: f["type"] == "done" and f["id"] == cell) self.assertEqual(ended["status"], "interrupted", ended) self.kernel.send({"type": "job_list", "id": "list"}) listing = self.kernel.wait_for( lambda f: f["type"] == "job_list" and f["id"] == "list" ) running = [job for job in listing["jobs"] if job["state"] == "running"] self.assertEqual( [(job["kind"], job["command"], job["parent_id"]) for job in running], [("command", "sleep 30", None)], listing, ) class UnjournaledResultTest(unittest.TestCase): def test_a_result_the_journal_refuses_is_announced_as_not_journaled(self): # A durable cell's result goes to the journal (cells.finish) before # its wake. When the journal refuses it, the wake says so, and the # cell's output keeps the result and why it is unconfirmed. calls: list[tuple[str, object]] = [] def host(method, args): calls.append((method, args)) if method == "cells.finish": raise HostError("failed", "journal write refused") return None kernel = Kernel(env={"ALBEDO_CELL_BACKGROUND_SECONDS": "0.5"}, host=host) self.addCleanup(kernel.close) started = kernel.execute( "import asyncio\ngate = asyncio.Event()\nawait gate.wait()\n" "print('after detach')\n{'answer': 42}", durable=True, ) self.assertEqual(started["status"], "backgrounded", started) cell = started["id"] kernel.execute("gate.set()") while not any(method == "cells.completed" for method, _ in calls): kernel.answer(kernel.wait_for(lambda f: f["type"] == "call")) [wake] = [args for method, args in calls if method == "cells.completed"] self.assertIn( f"{cell}: status=ok, result not journaled", cast(dict, wake)["text"] ) shown = kernel.execute(f"print(output.read({cell!r}))")["output"] self.assertIn("could not be journaled: journal write refused", shown) self.assertIn("{'answer': 42}", shown) self.assertEqual(shown.count("after detach"), 1, shown) if __name__ == "__main__": unittest.main()