"""A real kernel process with no daemon: the kernel tier between unit and e2e. `OwnerChannel` starts `python/albedo_kernel.py` over stdio and speaks the owner's control frames to it, as the daemon's driver does over its port. A kernel is ready in well under a second, so a test that only needs a cell to run in a real kernel (memory caps, spills, jobs, the cell API, frames the daemon cannot be made to send) starts one here instead of a daemon, a fake provider and a model turn. Use `e2e/` only for what crosses the daemon. """ from __future__ import annotations from collections.abc import Callable, Mapping import json import os import select import struct import subprocess import sys import tempfile import time from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[2] KERNEL = ROOT / "python" / "albedo_kernel.py" sys.path.insert(0, str(ROOT / "test")) import scratch # noqa: E402 # Temporary workspaces and homes go under this run's scratch directory, which # is removed at exit. scratch.claim("harness") MAX_FRAME = 8 * 1024 * 1024 Frame = dict[str, Any] Host = Callable[[str, object], object] class OwnerChannel: """A minimal owner: speak the kernel's control frames over stdio. Frames the owner is not looking for stay buffered, so looking for one kind never discards another (mirrors and job events interleave with replies). `env` adds to the test process's environment, such as ``ALBEDO_KERNEL_MEMORY_BYTES``. """ def __init__(self, modules, env: Mapping[str, str] | None = None): self.workspace = tempfile.mkdtemp(prefix="albedo-owner-") self.process = subprocess.Popen( [sys.executable, "-u", str(KERNEL), json.dumps(modules)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, cwd=self.workspace, env={**os.environ, **(env or {})}, ) self.buffered = [] def close(self): if self.process.poll() is None: self.send({"type": "shutdown"}) self.process.wait(timeout=10) assert self.process.stdin is not None assert self.process.stdout is not None assert self.process.stderr is not None self.process.stdin.close() self.process.stdout.close() self.process.stderr.close() self.buffered.clear() def send(self, message): data = json.dumps(message).encode() assert self.process.stdin is not None self.process.stdin.write(struct.pack(">I", len(data)) + data) self.process.stdin.flush() def recv(self, timeout=30.0): assert self.process.stdout is not None # Local startup is ~70 ms, but a contended VM can delay a process for # much longer; the protocol has no useful progress frame before ready. if not select.select([self.process.stdout], [], [], timeout)[0]: raise AssertionError(f"kernel did not send a frame within {timeout} s") header = self.read_exact(4) size = struct.unpack(">I", header)[0] assert size <= MAX_FRAME, "control frame exceeds the ceiling" return json.loads(self.read_exact(size)) def read_exact(self, size): assert self.process.stdout is not None data = bytearray() while len(data) < size: chunk = self.process.stdout.read(size - len(data)) if not chunk: raise AssertionError("kernel closed the channel during a frame") data.extend(chunk) return bytes(data) def wait_for(self, predicate, timeout=10.0): deadline = time.monotonic() + timeout while time.monotonic() < deadline: for index, frame in enumerate(self.buffered): if predicate(frame): return self.buffered.pop(index) self.buffered.append(self.recv()) raise AssertionError( f"no matching frame; buffered: {[f.get('type') for f in self.buffered]}" ) def recv_reply(self, call_id): return self.wait_for( lambda f: ( f.get("id") == call_id and f["type"] in ("invoked", "introspected") ) ) def invoke(self, call_id, **frame): self.send({"type": "invoke", "id": call_id, **frame}) return self.recv_reply(call_id) class Kernel(OwnerChannel): """A ready kernel that runs cells and answers their host calls. `host(method, args)` answers each host call a cell makes; it returns the reply's value, or raises `HostError` for a failure reply. The default answers every call with None, as a daemon with nothing to add does. """ def __init__( self, modules=("run", "files"), env: Mapping[str, str] | None = None, host: Host | None = None, ): super().__init__(list(modules), env) self.host = host or (lambda method, args: None) self.cells = 0 ready = self.recv() assert ready["type"] == "ready", ready self.pid = ready["pid"] def execute(self, code: str, timeout: float = 30.0, **fields) -> Frame: """Run `code` as one cell and return its done frame.""" self.cells += 1 cell = f"s/c{self.cells}" self.send({"type": "execute", "id": cell, "code": code, **fields}) deadline = time.monotonic() + timeout while time.monotonic() < deadline: frame = self.wait_for( lambda f: ( f["type"] == "call" or (f["type"] == "done" and f["id"] == cell) ), timeout=deadline - time.monotonic(), ) if frame["type"] == "done": return frame self.answer(frame) raise AssertionError(f"cell {cell} did not finish within {timeout} s") def answer(self, call: Frame) -> None: try: value = {"ok": True, "value": self.host(str(call["method"]), call["args"])} except HostError as error: value = {"ok": False, "code": error.code, "message": str(error)} self.send({"type": "reply", "id": call["id"], "value": value}) def observed(self, kind: str) -> list[Frame]: """The buffered frames of `kind`, removed from the buffer.""" kept, taken = [], [] for frame in self.buffered: (taken if frame.get("type") == kind else kept).append(frame) self.buffered = kept return taken class HostError(Exception): def __init__(self, code: str, message: str): super().__init__(message) self.code = code