Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215"""A kernel that cannot run Python is diagnosed, held to its deadline, and replaced.
The verdicts and what each one leads to are checked on a test clock inapps/albedo/test/albedo/kernel/driver_model_test.gleam: a kernel spinning innative code backgrounded for its waiter and held to its deadline, and oneasleep with nothing bounding it ended at the idle limit. This keeps the onejourney only a real process shows: a kernel holding the GIL asleep in C,probed, reported, ended at its deadline, and replaced with its variables.
Native code can hold the interpreter so that nothing the daemon sends getsthrough: no interrupt, no deadline timer, no background notice. The port ownerprobes the kernel's link while it has work and reads the process when the probegoes unanswered. A verdict informs, since a C call that blocks for a whilelooks like one that never returns: a waiting turn is answered as backgroundedwith the diagnosis so the model can tell the user, and the owner enforces thedeadline the kernel's own timer cannot, ending the kernel with a result and awake that say why; the next cell restores the variables last saved. A kernelthat answers its probes, however busy, is left alone. A kernel found busy aftera daemon restart because it is asleep in native code, which nothing bounds, isended after the idle limit instead of being waited for forever."""
import astfrom contextlib import suppressimport jsonimport osimport signalimport unittest
import harnessfrom harness import ( Albedo, Provider, Reply, alive, exclusive_class, has_note, latest_user, text,)
# Finish setup before timing the native sleep. Imports and job startup can# otherwise occupy the probe window or outlast the background notice timer.ASLEEP_SETUP = ( "import asyncio, ctypes, os, pathlib\n" "_native_sleep = ctypes.PyDLL(None).sleep\n" "hold = run('sleep', '120')\n" "while hold.process is None:\n" " await asyncio.sleep(0.01)\n" "pathlib.Path({marker!r}).write_text(f'{{os.getpid()}} {{hold.process.pid}}')")
PROBE = "import os\n(globals().get('survivor'), os.getpid())"
def end(*pids): for pid in pids: with suppress(OSError): os.kill(pid, signal.SIGKILL)
def pids(marker): harness.wait_until(marker.exists, 30, "the wedging cell never started") return [int(word) for word in marker.read_text().split()]
class Wedges(unittest.TestCase): def boot(self, prepare=None): self.cells = [] self.turn = []
def script(request): last = request["input"][-1] if last.get("role") == "user" and "cells finished" in latest_user(request): return text("completion received") if last.get("role") == "user" and self.cells: code, timeout_ms = self.cells.pop(0) return Reply( "python", tool_arguments={"code": code, "timeout_ms": timeout_ms} ) return text("ok")
def environment(app): # Probes every 250 ms, so a verdict takes about a second; the # background threshold is the kernel's own, in wall time. app.env.update( ALBEDO_TEST_TIME_SCALE="20", ALBEDO_CELL_BACKGROUND_SECONDS="0.5", ALBEDO_IDLE_SECONDS="600", ) if prepare is not None: prepare(app)
self.provider = Provider(script) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, protocol="responses", prepare=environment) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.session = self.app.session() self.log_offset = self.log_size()
def log_size(self): log = self.app.home / "daemon.log" return log.stat().st_size if log.exists() else 0
def log(self): """The daemon log written since this test began.""" log = self.app.home / "daemon.log" return log.read_bytes()[self.log_offset :].decode(errors="replace")
def cell(self, code, timeout_ms=60_000, settle=30): """Run one cell through a turn: its result, and every daemon note the model saw during the turn, whether it rode on the prompt or came as a message of its own.""" self.cells.append((code, timeout_ms)) start = len(self.provider.requests) self.app.prompt(self.session, "run it").close() self.app.idle(self.session, timeout=settle) results = [ json.loads(part["value"]) for entry in self.app.history(self.session)["items"] if entry["kind"] == "tool_result" and entry["tool"]["name"] == "python" for part in entry["content"] if part["kind"] == "json" and part["field"] == "result" ] self.turn = self.provider.requests[start:] return results[-1], self.notes()
def notes(self): return "".join( str(item.get("content", "")) for record in self.turn for item in record["request"]["input"] if item.get("role") == "user" and has_note(str(item.get("content", ""))) )
def wakes(self): return [ latest_user(record["request"]) for record in self.provider.requests if "cells finished" in latest_user(record["request"]) ]
def assert_ended(self, *pids): harness.wait_until( lambda: not any(alive(pid) for pid in pids), 15, "the wedged kernel or its job outlived its replacement", )
def saved(self): state = self.app.home / "kernels" / f"{self.session}.state" harness.wait_until(state.exists, 30, "the resting kernel was never saved") return state
@exclusive_classclass KernelWedgeTests(Wedges): def setUp(self): self.boot()
def test_a_kernel_asleep_in_native_code_is_reported_then_replaced_at_its_deadline_with_its_saved_variables( self, ): first, _ = self.cell("import os\nsurvivor = 41\nos.getpid()") self.assertEqual(first["status"], "ok", first) self.saved() # the resting release wrote the namespace to disk marker = self.app.workspace / "asleep" setup, _ = self.cell(ASLEEP_SETUP.format(marker=str(marker))) self.assertIn(setup["status"], ("ok", "backgrounded"), setup) kernel, job = pids(marker) self.addCleanup(end, kernel, job) if setup["status"] == "backgrounded": harness.wait_until(self.wakes, 20, "fixture setup never finished") self.assertIn("status=ok", self.wakes()[-1]) self.app.idle(self.session) wakes_before = len(self.wakes())
# No imports or process startup in the measured cell. libc holds the # GIL, so neither the deadline timer nor an interrupt can reach it. # The deadline outlasts the verdict; on the test clock it is 3 s away. result, _ = self.cell("_native_sleep(600)", timeout_ms=60_000)
# Asleep in libc with the GIL: told to the model, not ended on that. self.assertEqual(result["status"], "backgrounded", result) self.assertIn("using no CPU", result["output"]) self.assertIn("deadline (60 s)", result["output"]) self.assertIn("kernel_unresponsive", self.log()) self.assertIn("asleep", self.log()) self.assertNotIn("kernel_wedged", self.log()) # At the deadline the owner interrupts, and ends what will not stop. harness.wait_until( lambda: len(self.wakes()) > wakes_before, 20, "the deadline never woke the session", ) wake = self.wakes()[-1] self.assertIn("status=interrupted", wake) self.assertIn("ran past its deadline of 60 s", wake) self.assertIn("using no CPU", wake) self.assert_ended(kernel, job) self.assertIn("{deadline,", self.log()) self.app.idle(self.session)
# The replacement restores the save, whole, so the restore itself is # silent: what the model was told is in the result and the wake. The # job handle made after the save is not in it. after, _ = self.cell( "import os\n(globals().get('survivor'), 'hold' in globals(), os.getpid())" ) survivor, held, pid = ast.literal_eval(after["value"]) self.assertEqual(survivor, 41, "the replacement did not restore the save") self.assertFalse(held) self.assertNotEqual(pid, kernel)