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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""What the daemon does with a kernel's memory: restart one whose stuckthreads hold memory past the cap, recycle one still over its cap when itssession rests, and keep spills under its home.
The cap, spills and paged values themselves are the kernel's own and arechecked in a kernel with no daemon (test/harness/kernel_memory_test.py).These need the driver that replaces a kernel and the session that rests it."""
import osimport unittest
from harness import ( Albedo, alive, cell_result, exclusive_class, is_note, latest_user, prompt_text, Provider, python, text, wait_until,)
CAP = 96 * 1024 * 1024
# A chain of rows grows until the cap stops the cell and is dropped; the few# rows `keep` holds pin every allocator arena, so the process stays above the# cap with nothing left to move to disk.BLOAT = """import osprint("pid", os.getpid())keep = []chain = Nonetry: for i in range(3_000_000): row = "row %d" % i chain = (row, chain) if i % 500 == 0: keep.append(row)finally: chain = None"""
# A worker blocked in a C call (a lock nobody releases) holds memory past the# cap: the stop raised into it never lands, so the kernel must restart rather# than stay past its cap. It blocks before the memory is touched, so no# interrupt can reach it first; the namespace holds none of it. The memory is# a private anonymous mapping, not a bytearray: bytearray(n) zero-fills, so the# cap could interrupt the cell before any thread held it, and a shared mapping# swapped out would no longer count. Allocate only the cap itself: the# existing kernel footprint takes it over the cap. Start the worker before# allocating, as the kernel documentation directs for allocation-heavy work:# after the mapping, the room below the allocation limit no longer fits a# new thread stack (the first frame's imports alone can take it).STUCK_THREAD = f"""import asyncio, mmap, os, threading, timeprint("pid", os.getpid())gate = threading.Lock()gate.acquire()held = []def hold(box): gate.acquire()threading.Thread(target=hold, args=(held,), daemon=True).start()chunk = mmap.mmap(-1, {CAP}, flags=mmap.MAP_PRIVATE) # counts once touched, belowheld.append(chunk)time.sleep(0.2)chunk[::4096] = b"\\1" * len(chunk[::4096])del chunkawait asyncio.sleep(60)"""
PID = 'import os\nprint("pid", os.getpid(), "keep" in globals())'SPILL = "for i in range(3000):\n print(f'line {i:05d} ' + 'x' * 60)\n"
# exclusive: the memory cap is daemon environment@exclusive_classclass CellLimitsTests(unittest.TestCase): def setUp(self): self.results = [] self.notes = []
def script(request): last = request["messages"][-1] if last.get("role") == "tool": self.results.append(cell_result(last["content"])) return text("noted") user = latest_user(request) if is_note(last): # A fresh kernel's notice comes after the prompt that picks the cell. self.notes.append(user) user = prompt_text(request) if "spill" in user: return python(SPILL) if "bloatkernel" in user: return python(BLOAT) if "stuckthread" in user: return python(STUCK_THREAD) if "pidnow" in user: return python(PID) return text("done")
def prepare(app): app.env["ALBEDO_KERNEL_MEMORY_BYTES"] = str(CAP) # No spares: the pool is never healthy, so only a bloated kernel is released. app.env["ALBEDO_KERNEL_SPARES"] = "0"
self.provider = Provider(script) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, prepare=prepare) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) self.session = self.app.session()
def cell(self, prompt): self.app.prompt(self.session, prompt).close() self.app.idle(self.session) result = self.results[-1] # A kernel that died answers with an error and no output. self.assertIn("output", result, result) return result
def pid(self, prompt): out = self.cell(prompt)["output"] self.assertIn("pid ", out, f"{prompt}: {out}") return int(out.split("pid ", 1)[1].split()[0]), out
def test_a_cell_whose_threads_cannot_be_stopped_restarts_the_kernel(self): stuck = self.cell("stuckthread") self.assertEqual(stuck["status"], "interrupted", stuck) self.assertIn("kernel is restarting", stuck["output"]) before = int(stuck["output"].split("pid ", 1)[1].split()[0]) fresh = self.cell("pidnow") self.assertEqual(fresh["status"], "ok", fresh) after = int(fresh["output"].split("pid ", 1)[1].split()[0]) self.assertNotEqual(before, after) self.assertFalse(alive(before)) self.assertIn("python kernel got reset", " ".join(self.notes))
def test_a_kernel_still_over_the_cap_is_recycled_when_its_session_rests(self): # A detached kernel spills beside its run directory, under the # daemon's home: never a shared /tmp another user could own. spill = self.cell("spill")["output"].rsplit("[output was", 1)[1] path = spill.split(" in ", 1)[1].split(":")[0] self.assertEqual(os.path.dirname(path), str(self.app.home / "output"), path) before, _ = self.pid("bloatkernel") wait_until(lambda: not alive(before), 20, "the bloated kernel was not released") after, out = self.pid("pidnow") self.assertNotEqual(before, after) self.assertIn("True", out) # the namespace came back in the new process