"""A kernel's memory cap, spills and paged values, in a real kernel with no daemon. The cap is the kernel's own: it samples its footprint, interrupts the cell past the cap, moves large bindings to disk behind handles that page, and sets an allocation limit that refuses one huge allocation. Spills keep a cell's whole output in a file past the preview. A defect here kills the kernel with the user's namespace, or leaves it past its cap. None of it involves the daemon, so each case runs in its own kernel process (well under a second to start) instead of through a model turn. What does involve the daemon (a kernel restarted when a stuck thread holds memory, a bloated kernel recycled when its session rests, and where spills land under ALBEDO_HOME) stays in e2e/cell_limits_test.py. """ import sys import unittest from kernel_owner_support import Kernel 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__)' ) # 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 to the cap a MiB at a time, then holds that memory while copying and # deleting. The kernel baseline takes it above the sampled cap, but bounded # growth leaves room below the allocation fuse even if sampling is delayed. # `del` runs Namespace.__delitem__, where CPython can misreport an interrupt # as a NameError. The slice copy gives the sampler time to signal before del. DELETE_HOG = """ held = [] copy = bytearray(4 << 20) source = bytes(4 << 20) x = 0 while True: if len(held) < 96: held.append(bytearray(1 << 20)) for _ in range(20): copy[:] = source del x x = 0 """ # Leaves the kernel's address space just under its allocation limit, as # fan-out workers retrying at the limit can, in private mappings it never # touches, so the sampled footprint stays under the cap. The workers' small # stack size leaves no cached thread stack to reuse: a thread started now needs # a new mapping, and it does not fit. AT_LIMIT = """ import mmap, resource, threading threading.stack_size(256 * 1024) soft = resource.getrlimit(resource.RLIMIT_DATA)[0] assert soft != resource.RLIM_INFINITY, "the kernel set no allocation limit" def room(): status = open("/proc/self/status").read().split("VmData:")[1] return soft - int(status.split()[0]) * 1024 held = [] for size, leave in ((1 << 20, 1 << 20), (1 << 12, 64 * 1024)): while room() - size >= leave: held.append(mmap.mmap(-1, size, flags=mmap.MAP_PRIVATE)) print("room", room()) """ 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") """ class KernelMemoryTest(unittest.TestCase): def kernel(self) -> Kernel: kernel = Kernel(env={"ALBEDO_KERNEL_MEMORY_BYTES": str(CAP)}) self.addCleanup(kernel.close) return kernel def cell(self, kernel: Kernel, code: str, status: str | None = "ok") -> dict: done = kernel.execute(code) if status is not None: self.assertEqual(done["status"], status, done) return done def pid(self, kernel: Kernel, code: str, before: str = "") -> tuple[int, str]: """The pid a cell printed, and its output; `before` is what an earlier cell said, shown when this one printed none.""" out = self.cell(kernel, code, None)["output"] self.assertIn("pid ", out, f"{out}\nbefore it: {before}") return int(out.split("pid ", 1)[1].split()[0]), out def test_output_past_the_preview_is_spilled_whole(self): kernel = self.kernel() result = self.cell( kernel, f"for i in range({LINES}):\n" " print(f'line {i:05d} ' + 'x' * 60)\n" "print('the last line')", ) 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] spill = note.split(" in ", 1)[1].split(":")[0] with open(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( kernel, f"print(files.read({spill!r}, start_line={LINES - 1}))" ) 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): kernel = self.kernel() spilled = self.cell(kernel, "print('p' * 2097152 + 'A€🙂Z', end='')") result = self.cell( kernel, f"id = {spilled['id']!r}\n" "assert output.read(id, offset=1048576-2, limit=10) == 'p' * 10\n" "first = output.read(id, offset=2097152, limit=5)\n" "assert first == 'A€' and first.next_offset == 2097156\n" "second = output.read(id, offset=first.next_offset, limit=5)\n" "assert second == '🙂Z' and second.next_offset == 2097161\n" "assert output.read(id, offset=second.next_offset, limit=5) == ''\n" "print('cell spill pages verified')", ) self.assertIn("cell spill pages verified", result["output"]) def test_a_cell_past_the_memory_cap_is_interrupted_and_the_namespace_kept(self): kernel = self.kernel() hog = self.cell(kernel, HOG, "interrupted") 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(kernel, "import gc\ndel chunks\ngc.collect()\nprint('freed')") self.assertEqual(freed["output"].strip(), "freed") # The memory really went: the next hog is stopped at the cap again. again = self.cell(kernel, HOG, "interrupted") 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, ): kernel = self.kernel() before, _ = self.pid(kernel, REMEMBER) hog = self.cell(kernel, THREAD_HOG, "interrupted") self.assertIn("kernel memory passed its cap", hog["output"]) after, out = self.pid(kernel, RECALL, hog["output"]) self.assertIn("still here stopped", out, hog["output"]) self.assertEqual(before, after, out) def test_a_cell_stopped_while_it_deletes_a_name_is_interrupted(self): hog = self.cell(self.kernel(), DELETE_HOG, "interrupted") self.assertIn("kernel memory passed its cap", hog["output"]) @unittest.skipUnless(sys.platform == "linux", "RLIMIT_DATA counts mappings") def test_a_kernel_left_at_its_allocation_limit_runs_the_next_cell(self): # The next cell's timers must not need a thread that cannot start. kernel = self.kernel() self.cell(kernel, AT_LIMIT) after = self.cell(kernel, ALIVE) self.assertEqual(after["output"].strip(), "alive 1024") 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. kernel = self.kernel() failed = self.cell(kernel, ALLOCATE, "error") self.assertIn("MemoryError", failed["output"]) alive = self.cell(kernel, 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(self.kernel(), BIG_READ) 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): kernel = self.kernel() result = self.cell(kernel, CHILDREN) self.assertEqual(result["output"].count("child 402653184"), 2, result["output"]) again = self.cell(kernel, ALLOCATE, "error") self.assertIn("MemoryError", again["output"]) def test_large_values_move_to_disk_behind_handles_that_page(self): kernel = self.kernel() built = self.cell(kernel, BIG_TEXT, None) self.assertIn("moved to disk", built["output"], built) self.assertIn("text (", built["output"]) self.assertIn("name.read(offset, limit)", built["output"]) out = self.cell(kernel, PAGE_TEXT)["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): kernel = self.kernel() built = self.cell(kernel, ODD_SIZE, None) # The sampler may land after the text is built and before the cell # ends; 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(kernel, ODD_AFTER) 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): kernel = self.kernel() grown = self.cell(kernel, GROW_ROWS, "interrupted") self.assertIn("kernel memory passed its cap", grown["output"]) self.assertIn("rows (", grown["output"]) self.assertIn("moved to disk", grown["output"]) paged = self.cell(kernel, PAGE_ROWS) 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 test_the_kernel_reports_itself_bloated_only_while_over_its_cap(self): # The daemon recycles a bloated kernel when its session rests, and # keeps a healthy one resident; this is the kernel's half. kernel = self.kernel() self.cell(kernel, ALIVE) self.assertFalse(any(f["bloated"] for f in kernel.observed("cells"))) self.cell(kernel, BLOAT, None) self.assertTrue(kernel.observed("cells")[-1]["bloated"]) ALIVE = "print('alive', len(bytearray(1024)))" # Untouched zero pages: the sampled footprint never sees them. ALLOCATE = f"x = bytearray({4 * CAP})" if __name__ == "__main__": unittest.main()