From ea9d3d95437ed18ef9b7be2e0123846db67407ff Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Fri, 20 Nov 2026 10:00:27 -0500 Subject: [PATCH] test(kernel): move background cell rules out of the daemon suite cell_background_test ran twelve daemon scenarios, each a fake model turn around one rule. Most rules are the kernel's or the jobs reader's own, so they move to the cheapest tier that sees them: - the kernel tier (kernel_cell_api_test): a backgrounded cell, awaiting or blocking the loop, is interrupted at its original deadline and announced so; stopping it as a job leaves its child running as a top job; a durable result the journal refuses is announced as not journaled and keeps the result and the warning in its output. - a property over the saved job book (jobs_source_test): a job page's cell source is bounded to 16,384 characters, never cut inside one. The daemon keeps two scenarios: one session whose first cell wakes it once and is listed with its nested job, whose second is read before the turn ends and whose third is cancelled, neither waking it; and the cell that survives idle reaping and a restart. About 33 s becomes 12 s. --- .../test/albedo/kernel/jobs_source_test.gleam | 87 +++++++ e2e/cell_background_test.py | 231 +++++------------- test/harness/kernel_cell_api_test.py | 92 ++++++- 3 files changed, 238 insertions(+), 172 deletions(-) create mode 100644 apps/albedo/test/albedo/kernel/jobs_source_test.gleam diff --git a/apps/albedo/test/albedo/kernel/jobs_source_test.gleam b/apps/albedo/test/albedo/kernel/jobs_source_test.gleam new file mode 100644 index 000000000..680593abc --- /dev/null +++ b/apps/albedo/test/albedo/kernel/jobs_source_test.gleam @@ -0,0 +1,87 @@ +//// A job page shows the source of the cell it ran, bounded so a long cell +//// cannot swell every page that reads it. The bound is in characters +//// (Unicode scalars), so a multibyte source is never cut inside one. Read +//// here from a released kernel's saved job book, through the same +//// `kernel_jobs` capability the job routes use. + +import albedo/kernel/jobs +import albedo_bytes/scalars +import albedo_file +import albedo_property +import albedo_sdk/kernel as sdk_kernel +import gleam/json +import gleam/option.{None, Some} +import gleam/string +import qcheck + +@external(erlang, "albedo_runtime_test_support", "temporary_workspace") +fn temporary_workspace() -> String + +@external(erlang, "albedo_runtime_test_support", "cleanup_workspace") +fn cleanup_workspace(path: String) -> Nil + +/// A saved book holding one finished cell job with `source`. +fn saved_book(home: String, source: String) -> Nil { + let job = + json.object([ + #("id", json.string("cell-1")), + #("command", json.string("a long cell")), + #("state", json.string("exited")), + #("exit_code", json.int(0)), + #("timed_out", json.bool(False)), + #("service", json.bool(False)), + #("kind", json.string("cell")), + #("started_at", json.int(1)), + #("ended_at", json.int(2)), + #("bytes", json.int(0)), + #("spill", json.null()), + #("spilled", json.int(0)), + #("tail", json.null()), + #("source", json.string(source)), + ]) + let path = home <> "/kernels/s.state.jobs.json" + albedo_file.ensure_parent(path) + let assert Ok(Nil) = + albedo_file.write_private(path, << + json.to_string(json.object([#("jobs", json.preprocessed_array([job]))])):utf8, + >>) + Nil +} + +pub fn a_job_page_bounds_its_cell_source_in_characters_test() -> Nil { + let home = temporary_workspace() + let read = jobs.capability(home).read + let chunk = + qcheck.from_generators(qcheck.return("x"), [ + qcheck.return("é"), + qcheck.return("€"), + qcheck.return("🙂"), + ]) + let length = + qcheck.from_generators( + qcheck.bounded_int( + sdk_kernel.max_job_source - 3, + sdk_kernel.max_job_source + 3, + ), + [qcheck.bounded_int(0, 40_000)], + ) + use <- cleaned(home) + use #(chunks, count) <- albedo_property.run( + 40, + qcheck.tuple2(qcheck.fixed_length_list_from(chunk, 4), length), + ) + let source = + string.repeat(string.concat(chunks), count / 4 + 1) + |> scalars.take(count) + saved_book(home, source) + let assert Ok(page) = read("s", None, "cell-1", None, 65_536) + let expected = scalars.take(source, sdk_kernel.max_job_source) + assert page.source == Some(expected) + assert string.starts_with(source, expected) + Nil +} + +fn cleaned(home: String, body: fn() -> Nil) -> Nil { + body() + cleanup_workspace(home) +} diff --git a/e2e/cell_background_test.py b/e2e/cell_background_test.py index 56ba3da25..888688ffe 100644 --- a/e2e/cell_background_test.py +++ b/e2e/cell_background_test.py @@ -1,7 +1,6 @@ """Long cells detach without losing output, deadlines, or completion wakes.""" import json -import sqlite3 import time import unittest @@ -14,7 +13,6 @@ from harness import ( latest_user, Provider, python, - Reply, text, ) @@ -33,12 +31,9 @@ class CellBackgroundTests(unittest.TestCase): def setUp(self): self.results = [] self.read_before_idle = False - self.deadline = False - self.synchronous = False self.with_job = False self.stop_job_on_release = False self.cell_title = "" - self.cell_padding = "" self.cell_code = None self.cell_id = None @@ -73,15 +68,7 @@ class CellBackgroundTests(unittest.TestCase): code = "held = run('sleep', '30')\n" + code if self.cell_title: code = f"# {self.cell_title}\n" + code - if self.cell_padding: - code = code + f"\n# {self.cell_padding}" - if self.synchronous: - code = "import threading\nprint('before detach')\nthreading.Event().wait(10)\nprint('after detach')" self.cell_code = code - if self.deadline: - return Reply( - "python", tool_arguments={"code": code, "timeout_ms": 1800} - ) return python(code) if "release cell" in user: code = "print('other cell output')\ncell_gate.set()" @@ -127,11 +114,18 @@ class CellBackgroundTests(unittest.TestCase): self.assertIn("wake automatically", result["output"]) return session - def test_cell_wakes_once_and_keeps_its_capture_separate(self): + def test_a_background_cell_wakes_once_unless_read_or_cancelled(self): + # The first cell starts a job, wakes its session once when it ends, + # and is listed with that job nested under it meanwhile. + self.with_job = True + self.stop_job_on_release = True + self.cell_title = "watch CI pipelines" session = self.start() + first = self.cell_id self.prompt(session, "inspect cell") self.assertIn("'status': 'started'", self.results[-1]["output"]) self.assertIn("before detach", self.results[-1]["output"]) + child = self.check_listed_while_running(session, first) self.prompt(session, "release cell") self.assertEqual(self.results[-1]["output"].strip(), "other cell output") wait_for(lambda: self.wakes()) @@ -151,206 +145,101 @@ class CellBackgroundTests(unittest.TestCase): part["text"] for part in notes[0]["content"] if part["kind"] == "text" ) self.assertTrue(shown.startswith("cell finished (status=ok"), shown) - # the transcript names the code, the model's notice the cell id - self.assertTrue(shown.endswith("import asyncio"), shown) + # The transcript names the code's first line, the model's notice the + # cell id. + self.assertTrue(shown.endswith("held = run('sleep', '30')"), shown) self.assertFalse(has_note(shown), shown) - self.assertIn(self.cell_id, latest_user(self.wakes()[0]["request"])) + self.assertIn(first, latest_user(self.wakes()[0]["request"])) self.prompt(session, "inspect cell") self.assertIn("'status': 'ok'", self.results[-1]["output"]) self.assertIn("after detach", self.results[-1]["output"]) self.assertIn("{'answer': 42}", self.results[-1]["output"]) self.assertNotIn("other cell output", self.results[-1]["output"]) - time.sleep(2.5) - self.assertEqual(len(self.wakes()), 1) - - def test_a_result_the_journal_refuses_is_announced_as_not_journaled(self): - session = self.start() - refuse = ( - "CREATE TRIGGER refuse_cell_finish BEFORE UPDATE ON cells " - f"WHEN NEW.id = '{self.cell_id}' AND NEW.status = 'finished' " - "BEGIN SELECT RAISE(ABORT, 'journal write refused'); END" - ) - with sqlite3.connect(self.app.home / "albedo.sqlite", timeout=10) as db: - db.execute(refuse) - - def allow(): - with sqlite3.connect(self.app.home / "albedo.sqlite", timeout=10) as db: - db.execute("DROP TRIGGER IF EXISTS refuse_cell_finish") + self.check_listed_after(session, first, child) - self.addCleanup(allow) - self.prompt(session, "release cell") - wait_for(lambda: self.wakes()) - self.app.idle(session) - wake = latest_user(self.wakes()[0]["request"]) - self.assertIn(f"{self.cell_id}: status=ok, result not journaled", wake) - self.prompt(session, "inspect cell") - shown = self.results[-1]["output"] - self.assertIn("'status': 'started'", shown) - self.assertIn("journal write refused", shown) - self.assertIn("{'answer': 42}", shown) - self.assertEqual(shown.count("after detach"), 1, shown) - - def test_reading_finished_output_suppresses_the_wake(self): + # A second cell whose finished output is read before the turn ends + # owes no wake. + self.with_job = self.stop_job_on_release = False self.read_before_idle = True - session = self.start() - self.prompt(session, "release cell") - self.assertIn("after detach", self.results[1]["output"]) - time.sleep(2.5) - self.assertEqual(self.wakes(), []) - - def test_original_deadline_interrupts_the_background_cell(self): - self.deadline = True - session = self.start() - wait_for(lambda: self.wakes()) - self.app.idle(session) - self.assertIn("status=interrupted", latest_user(self.wakes()[0]["request"])) - self.prompt(session, "inspect cell") - self.assertIn("'status': 'interrupted'", self.results[-1]["output"]) - - def test_background_cell_survives_idle_reaping_and_daemon_restart(self): - session = self.start() - time.sleep(4) - self.app.restart() + self.prompt(session, "start cell") + self.assertEqual(self.results[-1]["status"], "backgrounded") self.prompt(session, "release cell") - wait_for(lambda: self.wakes()) - self.app.idle(session) - self.assertEqual(len(self.wakes()), 1) - self.assertIn("status=ok", latest_user(self.wakes()[0]["request"])) + self.assertIn("after detach", self.results[-1]["output"]) + self.read_before_idle = False - def test_cancelled_background_cell_does_not_wake(self): - session = self.start() + # A third, cancelled, owes none either. + self.prompt(session, "start cell") + self.assertEqual(self.results[-1]["status"], "backgrounded") self.prompt(session, "cancel cell") - self.assertEqual(self.results[1]["output"].strip(), "True") - time.sleep(2.5) + self.assertEqual(self.results[-1]["output"].strip(), "True") self.prompt(session, "inspect cell") self.assertIn("'status': 'interrupted'", self.results[-1]["output"]) - self.assertEqual(self.wakes(), []) - - def test_synchronous_cell_returns_early_and_keeps_its_deadline(self): - self.synchronous = True - self.deadline = True - session = self.start() - wait_for(lambda: self.wakes()) - self.app.idle(session) + time.sleep(2.5) self.assertEqual(len(self.wakes()), 1) - self.assertIn("status=interrupted", latest_user(self.wakes()[0]["request"])) - def test_background_cell_appears_in_jobs_and_nests_its_runs(self): - self.with_job = True - self.stop_job_on_release = True - self.cell_title = "watch CI pipelines" - session = self.start() + def check_listed_while_running(self, session, cell): kernel = json.loads(self.app.api(f"/sessions/{session}?tail=0").read())[ "kernel" ] self.assertEqual(kernel["live_job_count"], 1, kernel) running = {job["id"]: job for job in kernel["running_jobs"]} - self.assertIn(self.cell_id, running) - self.assertEqual(running[self.cell_id]["kind"], "cell") - self.assertEqual(running[self.cell_id]["command"], "watch CI pipelines") - self.assertIsNone(running[self.cell_id]["parent_id"]) - children = [j for j in running.values() if j["parent_id"] == self.cell_id] + self.assertEqual(running[cell]["kind"], "cell") + self.assertEqual(running[cell]["command"], "watch CI pipelines") + self.assertIsNone(running[cell]["parent_id"]) + children = [j for j in running.values() if j["parent_id"] == cell] self.assertEqual(len(children), 1, running) - self.assertEqual(children[0]["kind"], "command") - self.assertEqual(children[0]["command"], "sleep 30") - + child = children[0] + self.assertEqual((child["kind"], child["command"]), ("command", "sleep 30")) jobs_page = json.loads( self.app.api(f"/extensions/run/sessions/{session}/jobs").read() ) - self.assertEqual(jobs_page["live_job_count"], 1) self.assertEqual(jobs_page["page"]["summary"], "1 background job running") - self.assertEqual( - [row["id"] for row in jobs_page["page"]["rows"]], - [self.cell_id, children[0]["id"]], - ) - self.assertTrue(jobs_page["page"]["rows"][1]["text"].startswith(" └ ")) - + rows = jobs_page["page"]["rows"] + self.assertEqual([row["id"] for row in rows], [cell, child["id"]]) + self.assertTrue(rows[1]["text"].startswith(" └ ")) recent = json.loads( self.app.api(f"/extensions/run/sessions/{session}/jobs/recent").read() )["items"] by_id = {item["id"]: item for item in recent} - self.assertEqual(by_id[self.cell_id]["kind"], "cell") - self.assertEqual(by_id[self.cell_id]["state"], "running") - self.assertNotIn("source", by_id[self.cell_id]) - self.assertEqual(by_id[children[0]["id"]]["parent_id"], self.cell_id) - - # reading output through /jobs/{id}/output must not suppress the wake - page = json.loads( - self.app.api( - f"/extensions/run/sessions/{session}/jobs/{self.cell_id}/output" - ).read() + self.assertEqual( + (by_id[cell]["kind"], by_id[cell]["state"]), ("cell", "running") ) + self.assertNotIn("source", by_id[cell]) + self.assertEqual(by_id[child["id"]]["parent_id"], cell) + # Reading output through the jobs route does not suppress the wake. + page = self.output_page(session, cell) self.assertIn("before detach", page["text"]) self.assertEqual(page["job"]["kind"], "cell") self.assertEqual(page["source"], self.cell_code) + self.assertIsNone(self.output_page(session, child["id"])["source"]) + return child - child_page = json.loads( - self.app.api( - f"/extensions/run/sessions/{session}/jobs/{children[0]['id']}/output" - ).read() - ) - self.assertIsNone(child_page["source"]) - - self.prompt(session, "release cell") - wait_for(lambda: self.wakes()) - self.app.idle(session) - + def check_listed_after(self, session, cell, child): after = json.loads(self.app.api(f"/sessions/{session}?tail=0").read())["kernel"] - self.assertEqual(after["live_job_count"], 0) - self.assertEqual(after["running_jobs"], []) + self.assertEqual((after["live_job_count"], after["running_jobs"]), (0, [])) finished = { item["id"]: item for item in json.loads( self.app.api(f"/extensions/run/sessions/{session}/jobs/recent").read() )["items"] } - self.assertEqual(finished[self.cell_id]["state"], "exited") - self.assertEqual(finished[self.cell_id]["exit_code"], 0) - self.assertEqual(finished[children[0]["id"]]["parent_id"], self.cell_id) - finished_page = json.loads( - self.app.api( - f"/extensions/run/sessions/{session}/jobs/{self.cell_id}/output" - ).read() + self.assertEqual( + (finished[cell]["state"], finished[cell]["exit_code"]), ("exited", 0) ) - self.assertEqual(finished_page["source"], self.cell_code) + self.assertEqual(finished[child["id"]]["parent_id"], cell) + self.assertEqual(self.output_page(session, cell)["source"], self.cell_code) - def test_background_cell_source_on_output_page_is_bounded(self): - self.cell_title = "long quiet cell" - self.cell_padding = "x" * 20_000 - session = self.start() - page = json.loads( - self.app.api( - f"/extensions/run/sessions/{session}/jobs/{self.cell_id}/output" - ).read() + def output_page(self, session, job): + return json.loads( + self.app.api(f"/extensions/run/sessions/{session}/jobs/{job}/output").read() ) - assert self.cell_code is not None - self.assertEqual(page["source"], self.cell_code[:16_384]) - self.assertEqual(len(page["source"]), 16_384) - def test_stopping_a_background_cell_promotes_its_surviving_child(self): - self.with_job = True - self.cell_title = "wait with child job" + def test_background_cell_survives_idle_reaping_and_daemon_restart(self): session = self.start() - with self.app.api( - f"/extensions/run/sessions/{session}/jobs/{self.cell_id}/stop", - method="POST", - ) as resp: - self.assertEqual(json.load(resp), {"stopped": self.cell_id}) - - def child_promoted(): - k = json.loads(self.app.api(f"/sessions/{session}?tail=0").read())["kernel"] - jobs = k["running_jobs"] - if ( - k["live_job_count"] == 1 - and len(jobs) == 1 - and jobs[0]["kind"] == "command" - and jobs[0]["parent_id"] is None - ): - return jobs[0] - return None - - child = wait_for(child_promoted, timeout=15) - self.assertEqual(child["command"], "sleep 30") - self.prompt(session, "inspect cell") - self.assertIn("'status': 'interrupted'", self.results[-1]["output"]) - self.assertEqual(self.wakes(), []) + time.sleep(4) + self.app.restart() + self.prompt(session, "release cell") + wait_for(lambda: self.wakes()) + self.app.idle(session) + self.assertEqual(len(self.wakes()), 1) + self.assertIn("status=ok", latest_user(self.wakes()[0]["request"])) diff --git a/test/harness/kernel_cell_api_test.py b/test/harness/kernel_cell_api_test.py index e2fd8688f..57014b1d8 100644 --- a/test/harness/kernel_cell_api_test.py +++ b/test/harness/kernel_cell_api_test.py @@ -8,9 +8,10 @@ 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 Kernel +from kernel_owner_support import HostError, Kernel class CellApiTest(unittest.TestCase): @@ -223,6 +224,95 @@ class BackgroundCellTest(unittest.TestCase): 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() -- knotmirror 0.0.1