"""A cell's output past the preview is spilled whole to a file, and a cell that pushes the kernel past its memory cap is interrupted while the namespace lives on.""" import os import unittest from harness import ( Albedo, alive, cell_result, exclusive_class, latest_user, Provider, python, text, wait_until, ) LINES = 3000 # ~200 KiB, past the 64 KiB preview and the ascii shortcut # Grows by 8 MiB every 50 ms until the cap stops it; the chunks stay in the # namespace, so the kernel is still past the cap when the next cell starts. HOG = ( "import time\n" "chunks = []\n" "while True:\n" " chunks.append(bytearray(8 * 1024 * 1024))\n" " time.sleep(0.05)\n" ) CAP = 96 * 1024 * 1024 # A file twice the cap, sparse so it costs nothing, read whole and in chunks. BIG_READ = f""" import os, tempfile path = os.path.join(tempfile.mkdtemp(), "big.log") with open(path, "wb") as f: f.truncate({2 * CAP}) for read in (lambda: open(path).read(), lambda: open(path, "rb").read(), lambda: open(path).readlines()): try: read() except MemoryError as error: print("refused:", error) with open(path, "rb") as f: print("chunk", len(f.read(1 << 20))) small = os.path.join(os.path.dirname(path), "small.txt") with open(small, "w") as f: f.write("hello") print("small", open(small).read()) """ # A job and a library subprocess a cell starts are not the kernel: the limit is not theirs. CHILDREN = f""" import pathlib, sys pathlib.Path("_lib_spawn.py").write_text( "import subprocess, sys\\n" "def spawn(code): return subprocess.run([sys.executable, '-c', code], capture_output=True, text=True).stdout.strip()\\n" ) import _lib_spawn code = "x = bytearray({4 * CAP}); x[::4096] = bytes(len(x[::4096])); print('child', len(x))" print(_lib_spawn.spawn(code)) job = await run(sys.executable, "-c", code) print(job.tail().strip()) """ # 110 MB of text past the cap in one statement; the kernel moves it to disk. BIG_TEXT = 'text = "0123456789\\n" * 10_000_000\nprint("built")\n' PAGE_TEXT = """ import pickle print("type", type(text).__name__, len(text)) print("read", repr(text.read(0, 11)), repr(text.read(55, 11))) print("head", repr(text.head(lines=2))) print("tail", repr(text.tail(lines=1))) print("iter", repr(next(iter(text)))) try: text.load() except MemoryError as error: print("load refused:", "memory cap" in str(error)) again = pickle.loads(pickle.dumps(text)) print("pickled", again.path == text.path, again.read(0, 4)) """ # A list of lines that grows until the sampled guard stops the cell; the # partial list is already bound, so it is moved too. GROW_ROWS = ( "import time\n" "rows = []\n" "while True:\n" ' rows.extend("row %d" % i for i in range(len(rows), len(rows) + 200_000))\n' " time.sleep(0.05)\n" ) PAGE_ROWS = """ print("type", type(rows).__name__, len(rows) > 0) print("head", repr(rows.head(lines=2))) print("iter", next(iter(rows)), sum(1 for _ in zip(range(5), rows))) print("load refused:", rows.size > 96 * 1024 * 1024 and "refused" or "small") """ # 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 os print("pid", os.getpid()) keep = [] chain = None try: 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 binding whose size probe raises (an h5py dataset after its file closes) beside # a value past the cap: the text still moves and the kernel lives on. # Record its pid before allocating, since the guard can interrupt the allocation. ODD_SIZE = ( """ import os print("pid", os.getpid()) class Closed: @property def nbytes(self): raise RuntimeError("dataset closed") closed = Closed() """ + BIG_TEXT ) ODD_AFTER = ( 'import os\nprint("pid", os.getpid(), type(closed).__name__, type(text).__name__)' ) PID = 'import os\nprint("pid", os.getpid(), "keep" in globals())' # Eight worker threads grow memory while the cell awaits them, as a cell that # fans HTTP calls out over a thread pool does, and retry whatever fails, so # they sit at the allocation limit. Cancelling the cell's await does not stop # them; they must be stopped too or the kernel starves and is lost. Small # stacks leave allocation headroom for the heap to cross the sampled cap. # They grow only once the pool has started all eight: a thread started at the # allocation limit can die before it reports that it started, and # Thread.start() then waits for it forever, past any stop. THREAD_HOG = """ import asyncio, concurrent.futures, threading, time threading.stack_size(256 * 1024) held, grown, started, aborted = [], [0], threading.Event(), threading.Event() def grow(_): started.wait() if aborted.is_set(): return deadline = time.monotonic() + 30 while time.monotonic() < deadline: try: held.append(bytearray(16 * 1024 * 1024)) held[-1][::4096] = bytes(len(held[-1][::4096])) grown[0] += 1 except Exception: pass time.sleep(0.01) def fan_out(): with concurrent.futures.ThreadPoolExecutor(8) as pool: try: results = pool.map(grow, range(8)) # submits all eight first except BaseException: aborted.set() raise finally: started.set() list(results) await asyncio.to_thread(fan_out) """ # Grows past the cap a MiB at a time while most of its time goes to a slice # copy, which checks for no signal, so the interrupt lands in the `del` right # after it. `del` runs the namespace's own __delitem__, and CPython reports # anything raised there as a NameError. DELETE_HOG = """ held = [] copy = bytearray(4 << 20) source = bytes(4 << 20) x = 0 while True: held.append(bytearray(1 << 20)) for _ in range(20): copy[:] = source del x x = 0 """ # 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, while leaving room below # the allocation limit for imports and the worker stack. STUCK_THREAD = f""" import asyncio, mmap, os, threading, time print("pid", os.getpid()) gate = threading.Lock() gate.acquire() def hold(chunk): gate.acquire() chunk = mmap.mmap(-1, {CAP}, flags=mmap.MAP_PRIVATE) # counts once touched, below threading.Thread(target=hold, args=(chunk,), daemon=True).start() time.sleep(0.2) chunk[::4096] = b"\\1" * len(chunk[::4096]) del chunk await asyncio.sleep(60) """ REMEMBER = 'import os\nkept = "still here"\nprint("pid", os.getpid())' # The workers are stopped: what they grew no longer changes. RECALL = """ import os, time before = grown[0] time.sleep(0.5) print("pid", os.getpid(), kept, "stopped" if grown[0] == before else "growing") """ # exclusive: the memory cap is daemon environment @exclusive_class class 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 user.startswith(""): # A fresh kernel's notice comes after the prompt that picks the cell. self.notes.append(user) user = next( message["content"] for message in reversed(request["messages"]) if message.get("role") == "user" and not message["content"].startswith("") ) if "large spill" in user: return python("print('p' * 2097152 + 'the end', end='')") if "page spill" in user: return python( f"id = {self.large_cell!r}\n" "assert output.read(id, offset=1048576-2, limit=10) == 'p' * 10\n" "assert output.read(id, offset=2097152, limit=65536) == 'the end'\n" "assert output.read(id, offset=2097159, limit=65536) == ''\n" "print('cell spill pages verified')" ) if "read the spill" in user: return python( f"print(files.read({self.spill!r}, start_line={LINES - 1}))" ) if "spill" in user: return python( f"for i in range({LINES}):\n" " print(f'line {i:05d} ' + 'x' * 60)\n" "print('the last line')" ) if "hog" in user: return python(HOG) if "allocate" in user: # Untouched zero pages: the sampled footprint never sees them. return python(f"x = bytearray({4 * CAP})") if "bigread" in user: return python(BIG_READ) if "children" in user: return python(CHILDREN) if "bigtext" in user: return python(BIG_TEXT) if "pagetext" in user: return python(PAGE_TEXT) if "growrows" in user: return python(GROW_ROWS) if "pagerows" in user: return python(PAGE_ROWS) if "bloatkernel" in user: return python(BLOAT) if "oddsize" in user: return python(ODD_SIZE) if "oddafter" in user: return python(ODD_AFTER) if "namedrop" in user: return python(DELETE_HOG) if "fanout" in user: return python(THREAD_HOG) if "stuckthread" in user: return python(STUCK_THREAD) if "remember" in user: return python(REMEMBER) if "recall" in user: return python(RECALL) if "pidnow" in user: return python(PID) if "alive" in user: return python("print('alive', len(bytearray(1024)))") if "free" in user: return python("import gc\ndel chunks\ngc.collect()\nprint('freed')") 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 test_output_past_the_preview_is_spilled_whole(self): result = self.cell("spill") self.assertEqual(result["status"], "ok") self.assertTrue(result["truncated"]) self.assertIn("line 00000", result["output"]) self.assertNotIn("the last line", result["output"].split("[output was")[0]) note = result["output"].rsplit("[output was", 1)[1] self.spill = note.split(" in ", 1)[1].split(":")[0] self.assertEqual( os.path.dirname(self.spill), str(self.app.home / "output"), self.spill ) with open(self.spill, "rb") as spilled: content = spilled.read() self.assertTrue(content.startswith(b"line 00000 xxx"), content[:40]) self.assertTrue(content.endswith(b"the last line\n"), content[-40:]) self.assertTrue( note.startswith(f" {len(content)} bytes; all of it is in"), note ) read = self.cell("read the spill") self.assertIn(f"line {LINES - 1:05d}", read["output"]) self.assertIn("the last line", read["output"]) def test_cell_output_pages_its_spill_past_the_memory_prefix(self): spilled = self.cell("large spill") self.assertEqual(spilled["status"], "ok", spilled) self.large_cell = spilled["cell_id"] result = self.cell("page spill") self.assertEqual(result["status"], "ok", result) self.assertIn("cell spill pages verified", result["output"]) def test_a_cell_past_the_memory_cap_is_interrupted_and_the_namespace_kept(self): hog = self.cell("hog") self.assertEqual(hog["status"], "interrupted", hog) self.assertIn("kernel memory passed its cap", hog["output"]) self.assertIn("cap 96 MiB", hog["output"]) # Over the cap already, a cell that frees memory still runs. freed = self.cell("free") self.assertEqual(freed["status"], "ok", freed) self.assertEqual(freed["output"].strip(), "freed") # The memory really went: the next hog is stopped at the cap again. again = self.cell("hog") self.assertEqual(again["status"], "interrupted", again) self.assertIn("kernel memory passed its cap", again["output"]) def test_a_cell_whose_threads_pass_the_cap_is_interrupted_and_the_namespace_kept( self, ): before, _ = self.pid("remember") hog = self.cell("fanout") self.assertEqual(hog["status"], "interrupted", hog) self.assertIn("kernel memory passed its cap", hog["output"]) after, out = self.pid("recall", hog["output"]) self.assertIn("still here stopped", out, hog["output"]) # Darwin's allocator may keep the freed pages: the kernel is then # recycled when its session rests, and the namespace comes back. if "stays above the cap" not in hog["output"]: self.assertEqual(before, after, out) def test_a_cell_stopped_while_it_deletes_a_name_is_interrupted(self): hog = self.cell("namedrop") self.assertEqual(hog["status"], "interrupted", hog) self.assertIn("kernel memory passed its cap", hog["output"]) 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_one_allocation_past_the_cap_raises_and_the_kernel_keeps_answering(self): # A single allocation sails past the 100 ms sample; the limit stops it. failed = self.cell("allocate") self.assertEqual(failed["status"], "error", failed) self.assertIn("MemoryError", failed["output"]) alive = self.cell("alive") self.assertEqual(alive["status"], "ok", alive) self.assertEqual(alive["output"].strip(), "alive 1024") def test_reading_a_file_past_the_cap_whole_is_refused_with_a_way_out(self): result = self.cell("bigread") self.assertEqual(result["status"], "ok", result) refusals = [ line for line in result["output"].splitlines() if line.startswith("refused:") ] self.assertEqual(len(refusals), 3, result["output"]) for line in refusals: self.assertIn("files.read", line) self.assertIn("192 MiB", line) self.assertIn("chunk 1048576", result["output"]) self.assertIn("small hello", result["output"]) def test_children_a_cell_starts_are_not_limited_like_the_kernel(self): result = self.cell("children") self.assertEqual(result["status"], "ok", result) self.assertEqual(result["output"].count("child 402653184"), 2, result["output"]) again = self.cell("allocate") self.assertEqual(again["status"], "error", again) self.assertIn("MemoryError", again["output"]) def test_large_values_move_to_disk_behind_handles_that_page(self): built = self.cell("bigtext") self.assertIn("moved to disk", built["output"], built) self.assertIn("text (", built["output"]) self.assertIn("name.read(offset, limit)", built["output"]) paged = self.cell("pagetext") self.assertEqual(paged["status"], "ok", paged) out = paged["output"] self.assertIn("type Paged 110000000", out) self.assertIn("read '0123456789\\n' '0123456789\\n'", out) self.assertIn("head '0123456789\\n0123456789\\n'", out) self.assertIn("tail '0123456789\\n'", out) self.assertIn("iter '0123456789\\n'", out) self.assertIn("load refused: True", out) self.assertIn("pickled True 0123", out) def test_a_value_whose_size_probe_raises_stays_while_others_move_to_disk(self): built = self.cell("oddsize") # The sampler may land after the text is built and before the cell ends # (a loaded host stretches that window); the cap then interrupts the # cell, and the move to disk is the same. self.assertIn(built["status"], ("ok", "interrupted"), built) self.assertNotIn("were not moved", built["output"]) self.assertIn("text (", built["output"]) self.assertIn("moved to disk", built["output"]) before = int(built["output"].split("pid ", 1)[1].split()[0]) after, out = self.pid("oddafter") # Where the allocator keeps freed pages (Darwin) the process stays over # the cap and is recycled when its session rests; the namespace comes back. if "stays above the cap" not in built["output"]: self.assertEqual(before, after) self.assertIn("Closed Paged", out) def test_a_cell_stopped_by_the_cap_has_its_partial_list_moved_to_disk(self): grown = self.cell("growrows") self.assertEqual(grown["status"], "interrupted", grown) self.assertIn("kernel memory passed its cap", grown["output"]) self.assertIn("rows (", grown["output"]) self.assertIn("moved to disk", grown["output"]) paged = self.cell("pagerows") self.assertEqual(paged["status"], "ok", paged) self.assertIn("type Paged True", paged["output"]) self.assertIn("head 'row 0\\nrow 1\\n'", paged["output"]) self.assertIn("iter row 0 5", paged["output"]) def pid(self, prompt, before=""): """The pid a cell printed, and its output; `before` is what an earlier cell said, shown when this one printed none.""" out = self.cell(prompt)["output"] self.assertIn("pid ", out, f"{prompt}: {out}\nbefore it: {before}") return int(out.split("pid ", 1)[1].split()[0]), out def test_a_kernel_still_over_the_cap_is_recycled_when_its_session_rests(self): 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 def test_a_kernel_under_the_cap_stays_resident_without_spares(self): first, _ = self.pid("pidnow") second, _ = self.pid("pidnow") self.assertEqual(first, second)