small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
albedo robot-docs kernel.md
45 kB · 723 lines
Markdown
at main

The detached kernel #

A session's Python kernel runs cells in a process separate from the daemon. The daemon opens or reattaches to it through kernel.open. The Python entry point is albedo_kernel.py, which starts albedo_cells.main. Kernel namespace snapshots are described in Python kernel state.

Kernel Python environment #

The kernel project declares the Python version and package requirements. Its lockfile pins their resolution. Outside Nix, run uv sync --locked --project python after pulling changes to the lockfile. Local launches use the absolute interpreter in ALBEDO_KERNEL_PYTHON when set, then the kernel project's .venv/bin/python when present, otherwise python3 on PATH. Packaged launches set the interpreter. The Nix development shell defaults to its built kernel environment. Local launch selection also supplies the interpreter for the kernel's local helpers.

The project owns every package a cell may rely on: dill and Pydantic v2 (pydantic>=2,<3, with its pydantic-core, annotated-types, typing-extensions, and typing-inspection dependencies) are declared in that project and pinned in its lockfile, so agent cells can import pydantic and use BaseModel, validation, and serialisation without installing anything or relying on host site-packages. Do not add a cell dependency anywhere else, and do not vendor it: change the project, re-lock with uv lock --project python, and let both launch paths pick it up. The Nix package builds the same locked set as a virtual environment (Python 3.11 there) and exposes its wheels as testWheels for the offline loopback SSH tests. The Python floor stays at 3.11; the lock also resolves on newer interpreters the project already supports, including 3.15 where the pinned dill source build applies.

SSH staging selects the remote host's Python when it meets the project's minimum. When no explicit interpreter is requested, it checks python3 on PATH, /run/current-system/sw/bin/python3, /nix/var/nix/profiles/default/bin/python3, and on NixOS hosts without python3 on PATH any matching /nix/store/*-python3-3.*/bin/python3. To prepare a new environment, Albedo fetches the latest stable uv release for the target platform and copies it over SSH. If no usable host interpreter is found, NixOS hosts try realizing nixpkgs#python3 with nix or nix-build first (avoiding stub-ld failures on generic Linux builds), and otherwise the remote uv installs Python at the project's minimum major and minor version. Environment preparation runs uv sync --locked for either interpreter, and its startup check requires both dill and pydantic to load from the prepared environment, so a stale or partly installed environment is rebuilt rather than reused. A prepared environment can be reused without checking for a newer uv. See Remote kernels for host requirements. Real-cell coverage for the bundled Pydantic lives in python_test.py locally and in remote_kernels_test.py over SSH; both assert the import resolves inside the kernel interpreter's prefix.

Read retained output #

output.read(id, offset=0, limit=4000) pages retained cell or job output. job.read(offset=0, limit=4000) with an explicit limit uses the same paging rules. Each page is an awaitable string. Pass its next_offset back as offset rather than adding limit. A page can stop short of the byte limit to leave a UTF-8 character intact. An unchanged offset means no further bytes are available yet. If the writer is still running, retry from that offset when more output arrives.

Use a positive limit of at least four bytes to fit any UTF-8 character. A page can read up to 64 KiB and raises if the requested bytes are no longer retained. Pages ignore invalid UTF-8 bytes. Use job.save(path) for the original job output bytes when the completed output is fully retained.

Ownership #

The kernel and its model-facing feature are core harness code under apps/albedo/src/albedo/kernel. Python is not an extension. Every session runs a kernel and composes the harness base: the python tool, the cells, user_shell_output, and session host routes, the /kernel command and its client bindings, and the remote-place context. No extension selection removes them, so every extension may rely on the kernel and its bindings. The kernel tables' transfer declaration is core's too.

The runtime owns the kernel's storage. Before it installs extensions, runtime.start_with_config creates the cell journal tables (cells, cell_traces) and then the link tables. It then records kernels that an earlier daemon left in this home's run directories. A failed reconciliation is reported and does not stop the daemon. runtime.cleaners puts the link cleanup before the extensions' cleanups when a session is deleted. The cell_images data upgrade is described in storage migrations.

The modules in that directory divide the work as follows:

  • kernel opens, executes, upgrades, and snapshots kernels, and reports their jobs and liveness.
  • kernel/link keeps kernel records, the outbox, the host-call ledger, and staged kernels.
  • kernel/journal is the cell journal: saved sources, outcomes, and traces.
  • kernel/cell_storage owns the journal reads for storage accounting, deletion, and transfer image references. Transfer checks for the cell table once per export.
  • kernel/result_view renders a stored cell result for a model request.
  • kernel/tool names the cell tool. Core matches calls against tool.name for binding rewrites, progress, repetition, and the composed instructions. Do not spell the name as a literal in core.
  • kernel/base assembles the harness base that composition.compose puts ahead of every selection. Its owner name stays python for client command ids and saved selections.
  • kernel/python_tool is the python tool: its schema, its instructions, a call's journaled execution, and the recovery of an interrupted call. When it offers a repair for a cell that started, it suggests compiling the replacement with check=True first. This does not save or execute a cell. Check relevant external state as well as the trace before replaying, since traces can omit effects. Cell source that shows token-stream corruption is elided from replay before a model sees it again: sdk/python_repair owns the verdict and the note, the loop applies it (loop.replay_repair) to the history it projects and the calls it sends back, and replay.rewrite_tool_input rewrites the calls of every protocol, Bedrock Converse blocks included, leaving every other item the same term.
  • kernel/cells serves the cells and session host routes.
  • kernel/kernel_command declares /kernel and its client bindings.
  • kernel/place tells the model where a remote session's kernel runs. Remote kernels reach their host through core's ssh, which answers with the SDK's sdk/hosts values; extensions reach hosts only through the hosts capability.
  • kernel/transfer declares the kernel tables for session transfer. transfer/transfer.adapters lists it after the core adapter. Its owner name python and its table versions are on the wire, so peers of any version stage its segments; do not rename them.
  • kernel/jobs and kernel/resources serve job observation and recorded process ownership to the run and agents extensions, through the kernel_jobs and kernel_resources capabilities they build. The types those carry are in sdk/kernel.
  • kernel/cell_codec encodes the stored form of a cell's outcome and trace. It reads every shape earlier daemons wrote.
  • kernel/job_window pages a released kernel's saved job output for the run routes.
  • kernel/driver is the process that owns one kernel: its connection, sequencing, job ownership, probes, and cleanup.
  • kernel/frame reads each frame the kernel sends into a typed kind once, in the driver's read_wire, and names the asks the driver sends. Match on Kind, not on the frame's type text. kernel/cell_status is how a cell ended, with its wire spelling. The journal stores its constructor atoms, so do not rename them.
  • kernel/supervision runs checked process stops, recorded stops, and run-directory discovery.
  • kernel/spare owns spare custodians and the zygote.
  • kernel/launch picks a spare, the zygote, or a cold start, and holds the cold launcher and the socket relay.
  • kernel/native binds the ports, local sockets, and OTP calls those owners share.
  • kernel/recovery, kernel/termination, and kernel/wedge hold policy that the driver calls.
  • kernel/wire decodes and frames the link's messages.
  • kernel/process_probe reads a local kernel's process state and CPU time.
  • kernel/python_tree finds the Python tree a kernel starts from and saves the trees that booted.
  • kernel/environment builds the environment of every program the daemon starts for a kernel or a model tool, and reads the kernel's grace.
  • kernel/signal_helper keeps one shared signal helper process running while stops keep coming.

Do not move kernel runtime code back into an extension, and do not add kernel housekeeping as extension plugins.

albedo_cells.main imports the plugin modules with the kernel's own directory first on sys.path, then replaces that entry with the workspace. A submodule loaded on first use, as the browser package loads its own, can import a top-level albedo_* module only if startup already loaded it. Put a helper that only such code needs under albedo_plugins, which resolves through the package rather than sys.path, as proxy and ws are. Do not put the kernel's directory back on sys.path to fix a missing module: a workspace file would then shadow it. kernel_lazy_imports_test.py imports every plugin module, then each plugin package's submodules after that switch.

The shared WebSocket client counts data fragments toward the message size limit. Close, ping, and pong frames have a separate 125-byte payload limit. The HTTP upgrade can read header lines up to at least 64 KiB, even when the message limit is smaller.

Execution and results #

kernel.execute and execute_saved send code and a deadline to the kernel. Code is limited to 1 MiB and the timeout to 1 through 3,600,000 milliseconds. An outcome has an ID, status, text output, value, truncation flag, images, image errors, and an optional duration. Its images hold what show_media (or its alias show_image) attached, pictures and audio and video clips alike. Status is ok, error, interrupted, or backgrounded.

The interface also reports Unavailable, Busy, Lost, Invalid, and Detached errors. Detached means a cell exceeded its deadline while the kernel was unreachable. The cell continues there and its result is journaled when the kernel returns. A caller must not assume that retrying a detached cell has no side effects.

Memory cap #

albedo_memory reads ALBEDO_KERNEL_MEMORY_BYTES, which defaults to 256 MiB. On Linux, its preferred measurement sums RssAnon, RssShmem, and VmSwap from /proc/self/status. This counts resident anonymous and shared memory plus private anonymous swap. It excludes swapped shared memory and resident regular-file mappings. When the split counters are missing or unreadable, it falls back to the resident set in /proc/self/statm. Darwin uses ri_phys_footprint through libproc. The Linux status-field definitions describe which mappings each counter includes.

guard_memory samples while cells run, at 100 ms intervals. It interrupts cells that pass their threshold and tries to stop their worker threads. Sampling can overshoot the cap. A cell that starts above it gets 8 MiB of cleanup slack so it can release retained objects. albedo_spill.relieve can move large namespace values to disk and replace them with Paged handles when memory remains high.

albedo_memory.enforce also sets a soft allocation limit above the starting allocation size plus the cap and a platform margin, when supported. It uses RLIMIT_DATA on Linux and RLIMIT_AS on Darwin. This backstop and the sampled measurement cover different memory; neither is a sandbox. The kernel installs that limit after its plugins have loaded, so the starting size is the loaded kernel's: imports a plugin or the first frame brings in grow the address space, and a limit measured before them leaves a cell no room for its own allocations on top.

Thread interruption is best-effort. A thread blocked in a C call receives the exception only when that call returns, and a thread can catch BaseException. Under allocation pressure, thread startup can fail before reporting that it started, leaving Thread.start() waiting. Start workers before beginning a deliberately allocation-heavy workload. The kernel itself starts no thread per cell: each cell's deadline and background timers are alarms on the two threads albedo_alarms starts with the kernel, so a cell that leaves the process at its limit cannot stop the next cell from starting. Deadlines have their own thread: a background alarm writes to the daemon and can block while an attached daemon is not reading, and no deadline may wait behind that write.

stop_threads can leave a worker to the guard after one second if the process is back under its cap. If workers remain after five seconds and keep the process over its cap, the foreground cell requests a kernel restart. Replacement restores the last saved variables, subject to the saved-state limits. Check side effects before rerunning a cell; current objects and background jobs need not survive replacement.

Process jobs #

Use run(program, *args, cwd=..., env=...) for external programs. It starts a job immediately and returns a handle. Pass arguments separately and use cwd for the working directory. For captured text, await run("git", "status").text() waits for completion and checks the exit status.

The shell translator suggests run() calls for simple shell commands. It falls back to general run() guidance when a pipeline has a missing command or when nested shell commands or multiple directory changes would make it lose the working directory.

Bind a job before awaiting it when later calls need its handle. Start independent jobs before waiting for their results. Read bounded previews with job.tail or use the output-read interface for larger results. Do not treat a preview as complete output. The job and capture implementations are in run.py and albedo_capture.py.

Attach run(...).pipe(...) in one expression to stream from the start. This holds for rem.run too. A method called on a pending remote reference in the same step travels in that call's invoke frame as its then list. The remote kernel makes the chained calls right after the call they follow, with no await between them, so the pipe is attached before the job's output is read. A pipe sent in its own frame could arrive after the job had already written 1 MiB. A later pipe can replay only the output still in memory, at most 1 MiB. This limit is separate from disk retention. If the complete output is retained, use saved_path = await job.save(path) after the job finishes. Pass the filename to a program on the same host. To stream it into another job, start with run("cat", "--", saved_path).pipe(...) locally or rem.run on the remote host.

Piping jobs with run(...).pipe(...) or stdin=job leaves await job, job.exit_code, and await job.text(check=True) scoped to the last stage. Use await job.stage_outcomes() on the final handle to wait for every stage and get a list from the first producer to the last reader. Each entry contains id, command, exit_code (None if unavailable), and timed_out. The summary reports nonzero exits and timeouts without raising for them, and cancelling the wait does not stop the pipeline. It also works for rem.run with a live remote kernel. Kernel release does not preserve stage history, so restored job handles cannot report it. A pipeline passed as one shell command to degraded rem.shell is opaque and has no per-stage report.

The live output reader can page across a retained prefix and the recent tail when they touch or overlap. A request that crosses a gap between them fails because part of the page is unavailable.

kernel/jobs owns live and saved job observations, and its capability is the kernel_jobs record the run extension's service reads them through. A failed live read falls back to the saved book only when it is unavailable and the kernel is dead. Missing output or a rejected request does not trigger that fallback. kernel/resources provides recorded kernel-process attribution to the agents extension as the kernel_resources capability.

Cells that outlast the foreground timeout (status=backgrounded) also appear in the job observation (running_jobs, /jobs, and /jobs/recent) with kind: "cell" and their title comment or first line, expose their live output and bounded source (source, up to 16,384 characters) through the job-output route without withdrawing their completion notice, and can be stopped through the job-stop route. Live run jobs started inside a still-running backgrounded cell carry parent_id naming that cell and promote to top-level if they outlive it. live_job_count counts top-level items.

Unresponsive kernels #

While a kernel has work, the driver sends it a {"ping": n} every 5 seconds. Work means a cell someone waits for, cells the kernel reported live, backgrounded cells, or a hello still owed after a daemon restart. The link's reader thread answers with {"pong": n} whenever it can take the GIL. After three unanswered pings, wedge.classify judges the process from two samples that process_probe reads:

  • asleep: under a twentieth of the window on the CPU.
  • spinning: more CPU than that.
  • stopped: stopped by a signal, or a zombie.
  • gone: the process no longer exists.
  • unresponsive: a remote kernel, or a process that could not be read.

A verdict goes to the log once. It ends nothing by itself, because native code holding the GIL can still return. A cell's deadline ends the kernel. A kernel with no waited-for or backgrounded cell that is asleep or stopped is ended after the idle limit, ALBEDO_IDLE_SECONDS clamped to between 1 second and a week, 600 seconds by default. A waited-for cell past the background threshold, ALBEDO_CELL_BACKGROUND_SECONDS with a default of 60, is answered as backgrounded with the verdict in its output.

A backgrounded cell's deadline is kept by the driver too, because the kernel's own timer thread cannot run while native code holds the GIL. Ten seconds past the deadline the driver interrupts the cell. A cell the driver answered as backgrounded itself gets no such grace. If the cell still runs two seconds after the interrupt, the driver ends the kernel and its jobs. The next cell starts a fresh kernel and restores the variables last saved to disk.

Session layer #

link.gleam stores a session's kernel record, unacknowledged frames, and host-call ledger. Reattachment resends pending frames. The ledger distinguishes a fresh call, an answered call, and a call started by an earlier daemon whose effects are unknown. The latter is not evidence that the call had no effect.

The kernel drops a daemon frame whose sequence number it has already seen, so a restarted daemon must number on from the last frame the kernel could have received. The record keeps that number for every frame sent, including the reply to cells.started, which is not saved because the kernel resends that call and the host answers it again. Do not send a sequenced frame without recording its number. A restarted daemon that numbered its next cell's execute below it would have that cell dropped as a repeat and left running.

A record an older daemon wrote can still lag: it did not count those replies. The kernel's hello says what it has seen, so the driver writes no sequenced frame until the kernel greets. A frame numbered meanwhile, such as a cell sent while an attach could not reach a remote kernel, waits in the outbox, and the reply to cells.started is saved there too. At the hello, if a lagging record numbered any of those frames at or below what the kernel has seen, the driver renumbers them all, in order, past it with Link.renumber, then sends every frame the kernel has not seen. The renumber commits the frames, reply claims, and last sent sequence together. A failed renumber rolls back those changes and leaves the frames available for the next attach. Writing such a frame before the hello could have the kernel drop it, or take it once under its first number and again under its new one. The shutdown request is the exception: nothing follows it, so it goes out at once.

The driver marks a connection linked after it reads the outbox and sends the pending frames in order. If renumbering or the read fails, the driver closes the connection and retries under the existing local attempt limit or remote grace deadline. Once the outbox is readable, the next hello replays frames above the kernel's acknowledgment. A hello from an incompatible protocol takes the stale-kernel path and discards the old frames.

The daemon reads frames with OTP's json, which refuses NaN, the infinities, and the escape of a lone surrogate, and it abandons a kernel whose frame it cannot read. albedo_link therefore refuses NaN and the infinities in any frame. It refuses a lone surrogate in a host call, whose arguments name what the call acts on, so the call fails in the cell. Text another frame only shows, such as a file-change trace naming a path decoded with surrogateescape, crosses with each lone surrogate as U+FFFD. A remote call's result is a value, so albedo_values carries a non-finite float and a string holding lone surrogates as markers. The caller reads them back exactly. A plain dict whose keys a JSON object cannot hold, or whose key set reads as a marker, crosses as its key and value pairs. That holds for results and for the arguments a remote call sends.

A remote call's reply is one frame of at most 8 MiB. Its value may take up to 7 MiB as encoded JSON, and the rest holds the envelope and a job's mirrored state. A larger value is refused with RemoteValueError. JSON escapes a control byte to six bytes, so a job's whole read, at most 1 MiB, stays under the ceiling and reads the same remotely as locally.

The outbox retains at most 2,048 frames and 67,108,864 bytes per kernel. Past either limit it drops the oldest frames. A dropped frame can be the reply to a host call. When the kernel sends that call again, the ledger reads it as answered with its reply dropped, and the driver fails the call with an unknown outcome. It neither runs the call twice nor leaves the cell waiting for a reply that will not come.

A host call's reply nests at most 512 levels of arrays and objects, counting the reply's own {"ok", ...} object. wire.reply in wire.gleam owns that limit as max_reply_depth. The daemon splices the host's reply text into the reply frame unparsed, but the kernel's json.loads recurses once per level and fails near 1,000. albedo_link.read_frame refuses such a frame as invalid and the session detaches. The daemon would then resend the unacknowledged reply on every reattach, so the call would never end. Before it sends a reply, the daemon therefore scans the reply's bracket depth outside strings. A deeper reply goes out as a failed reply with code too_deep, so the kernel's call raises and the link stays up. The limit leaves room for the frame's own levels and the reader's stack. It is far above the 32 levels that albedo_values encodes for a value crossing a kernel connection. That separate limit governs values a kernel encodes, not the plain JSON a host replies with. The reply is the only daemon frame that carries host data unparsed. Other frames are built from typed fields, so their depth is fixed.

A frame is at most 8 MiB, which a cell's base64 pictures fit. A clip that show_media attaches crosses in raw blob frames instead, each part at most 4 MiB, sent just before the frame that names it: a result, the cells.finish call that journals one, or a claim's done. Such a frame is a binary packet, a zero byte and the envelope's length ahead of the envelope and the bytes. The result lists the clip among its images as {"clip": digest}, with the fps a video asks for (frame rates). kernel/blobs holds the parts in the driver, at most 64 MiB of them, and puts the clip's base64 in its place when the result arrives. The kernel keeps the clips it sent last, at most 64 MiB, under clips in its run directory, and sends a kept clip's parts again ahead of a claim's done, a result it replays for a resent execute, and a cells.finish it sends again. A daemon restart that lost parts the kernel had seen acknowledged therefore costs a finished cell nothing. A clip whose parts did not all arrive becomes an image error the model reads. That happens when newer clips pushed it out of what the kernel keeps, or when the outbox dropped its parts while detached and the result arrives replayed rather than claimed. The bridge copies the packets unread, and the hello, snapshot and shutdown messages are unchanged. The database record also identifies the daemon home that owns the kernel, so a daemon using a copied database does not claim another daemon's processes.

Daemon-held cell media #

Some host routes already have the bytes on the daemon. They use host.Context.stage_media under the CellMedia capability to save them for an unfinished cell in that session. The kernel receives only a receipt and media metadata to check its cell's limits. Its result names the receipt in images. The driver resolves it for that cell beside the ordinary image and clip entries, before the result goes through media validation and provider fitting.

cell_media bounds pending bytes per session and checks the cell on every stage and read. The journal clears pending bytes when it commits the final result. Unclaimed receipts expire after two hours and stay on the source daemon during a session move. Finished cell media moves with the result. A missing or expired receipt costs that attachment, not the rest of the cell output. See Discord media.

Checked messages #

albedo_protocol.py owns the dictionary shape of every frame at the kernel and remote boundaries. Its TypedDict classes are the contract producers and consumers use, and parse_incoming (kernel requests) and parse_remote (remote replies and events) validate an untrusted frame against that contract with strict standard-library checks on type before it reaches an event loop: numbers are not booleans, booleans are not integers, and strings are never coerced. Unknown fields are kept, because frames such as done and job views carry payloads their types only partly describe. Three relationships need a check beside the shape. An invoke target names exactly one handle or pending call. Each call in an invoke frame's then list follows the frame's own call or an earlier chained call. An invoked result carries its error when it failed and a value or handle when it succeeded. Validation imports no third-party package, so importing the module and validating a kernel's first frame in the kernel, spare, and zygote bootstraps do not pay for Pydantic's import or schema build. Pydantic stays bundled in the kernel environment for cells that import it, not for this wire. Do not route wire validation through Pydantic again without measuring the kernel anonymous-memory budgets in performance budgets. Validation errors name fields only, so an error string never echoes cell source or a token from the frame it refused. The host-only helpers that reattach to a kernel (the bridge, signal, gather, and relay helpers) import only the standard library, so they still run on a host's bare python3 when no prepared environment or recorded launch survives; a current kernel itself always runs from the managed environment. Strict validation now also checks execute.snapshots as a boolean; it was declared but unchecked, so any truthy value used to enable trace snapshots. Behaviour is covered by protocol_test.py, which E2E cannot reach because it only ever sends valid frames.

Opening and replacing kernels #

open_inner reconciles the session's staged record and tries to reattach before starting a fresh kernel. The kernel link creates fresh identities and looks up staged records by session. Boot can open a store before its staging table exists. Daemon startup recovery reads all staged records. For a recorded remote kernel, the SSH helper reads the bundle and interpreter that the starting bridge saved in the run directory. For older records without those paths, it looks for an already uploaded helper and an existing prepared interpreter or the host's Python 3.11 or newer. Remote turn admission lets the recorded kernel reconnect even if a probe cannot prepare a new environment.

The driver compares the reattached kernel's build with the daemon's Python tree. Replacing an older build prepares the new remote environment before starting the replacement. If preparation fails, the existing kernel stays available with its namespace and jobs.

For a local fresh boot, if the current Python tree fails to start, it can try the last tree that booted successfully, after recorded cleanup of the failed launch succeeds. A remote kernel uses a staged bundle and does not have that local fallback. Opening with a spare also requires spare cleanup to succeed.

python_tree owns the saved trees under kernel-bundles in the home. Each fresh local kernel that starts cleanly from the daemon's tree saves a copy, and saving prunes all but the newest four besides the one just saved. A kernel booting from a saved copy first claims it with a file under kernel-bundles/claims. The claim lasts until the daemon has confirmed the kernel and its jobs gone and removes the run directory (supervision.remove_run_dir). The kernel's own exit does not release it, because run jobs use the copy's shims and can outlive the kernel. A kernel whose cleanup is never confirmed keeps its copy. Pruning spares every claimed copy. Claims and pruning hold the same lock, so a boot either claims a copy before pruning reads the claims or finds it gone and fails. Do not delete or hand out saved trees anywhere else: a fallen-back kernel still imports plugin modules and runs job shims from its copy after startup.

upgrade snapshots the old namespace, starts a replacement, and restores state before retiring the old kernel and its jobs. The returned Carried information records what survived and what did not. A snapshot is not a guarantee that every Python object or running job can be carried. See Python kernel state.

runtime/kernels.gleam owns runtime operations for opening, staging, upgrading, stopping, and reconciling kernels. The Python interface exposes job inspection, interruption, stopping, and liveness operations in kernel.gleam.

Lifecycle owners #

launch.gleam selects reserved-spare adoption, current-tree zygote use, and cold fallback. It also decides whether the zygote runs, reads a spare's readiness line, and holds the cold launcher and the socket relay. spare.gleam owns spare custodians and the zygote. The driver owns protocol state, acknowledgments, job ownership, and checked cleanup. These owners do not introduce a second pool.

The driver is one Gleam process per kernel, addressed by its pid. Callers send it a typed Request on the subject driver.requests names. Its own timers, host-call workers, and the launcher send it a Tick on the subject driver.ticks names. Cell, stop, backstop, and reattach timers carry the identity of the request or connection they belong to, and the driver ignores a tick whose identity is no longer current. Probe and acknowledgement ticks are coalesced with a flag, so at most one is pending at a time. The relay speaks as a bridge port would, so the driver selects one connection's messages the same way for either. The driver keeps its last observation in a protected ETS table, which observation, job_count, live_work, os_pid, and bloated read without waiting on it.

The driver calls Gleam policy for each decision and encoding: wire.gleam for link messages, wedge.gleam and process_probe.gleam for liveness verdicts, and recovery.gleam and termination.gleam below. native.gleam holds the typed bindings for ports, local gen_tcp sockets in active mode, logging, and process labels. Put new policy in a Gleam policy module, and keep the bindings in native.gleam thin.

The test supports under apps/albedo/test/albedo/kernel build a driver state with driver.detached, run it with driver.serve, and call handle_frame, host_reply, and record_lost directly. The driver reads time, arms its timers, and samples its kernel's process through the state's Clock (driver.real_clock in the daemon). driver.step handles one Message the way the loop does and returns Continue(state) or Halt, so a test can deliver each request, frame, and tick itself. The loop also calls arm_probe before it waits. A test that stands in as the kernel's relay, with conn: Some(Relay(self)), receives the frames the driver writes as launch.Command messages. driver_model_test replays generated cell lifecycles this way against a model. The e2e probes under e2e read the driver's mailbox for its Stop and Rebind requests. Update them with the request shapes.

kernel_owner_support.py starts a real kernel process over stdio with no daemon and speaks the owner frames to it. Kernel.execute runs a cell, answers its host calls, and returns the done frame. Test kernel-side behavior there, such as memory caps, spills, paged values, jobs, and the cell API, as kernel_memory_test.py does. Keep an end-to-end scenario only for what crosses the daemon: replacement, release, reattach, and where a detached kernel writes under ALBEDO_HOME.

A launcher reaching EOF permits a socket connection attempt. Protocol readiness and runtime publication happen afterward. Request cancellation withdraws its waiter while runtime reconciliation retains responsibility for the launch. A late ready kernel is retired. The cold launcher still waits for EOF before its relay handles owner-death messages, so monitor installation does not guarantee cleanup of a launcher permanently blocked before EOF.

recovery.gleam owns attachment decisions, retry backoff, remote grace, and retry-token checks. The driver retains timers and connection identities. A broken transport alone does not prove kernel death. Local process evidence distinguishes a busy kernel from a stopped or absent process. Repeated connection failures do not extend an already established remote grace deadline. Replay and host-call uncertainty stay with the driver and session link. It also bounds the cell claims a turn's opening waits on after a crash. Every claim shares the deadline that open_claims set. A claim answered after that deadline journals the ended cell it carries, unless the cell was backgrounded.

termination.gleam interprets checked process-group results. Each requested label needs exactly one confirmation, and every reported group must be gone before cleanup succeeds. The driver keeps collecting late job ownership during shutdown. A shutdown request goes to the kernel even when the session link cannot record it. When the owner dies, its store can no longer record frames, and the kernel still needs the request to run its plugin cleanup callbacks before the driver signals what remains. Cleanup that started after the owner died still reports kernel ownership cleanup was not confirmed, because only the owner can forget the kernel's record. albedo_signal.py checks process identities and groups and performs the termination ladder. A local stop sends its request to the helper that signal_helper.gleam keeps running. That helper exits after a minute without requests, and is killed when a request outlives its wait with nothing else in flight. When no helper can start, supervision.gleam runs a one-shot helper. A remote kernel's helper runs on its host over ssh. A malformed verdict or diagnostic from the helper counts as an unconfirmed target. Incomplete confirmation or failed record forgetting retains cleanup ownership for another stop. Runtime failed-stop fencing and cleanup credits remain with the runtime owner.

A spare handle retains its checked process identity and cleanup callback after custodian death. A handle-local completion marker distinguishes acknowledged adoption or cleanup from disappearance. Failed adoption cleanup keeps the custodian available for stop, and a dead custodian's handle can retry checked cleanup. An uncertain direct zygote fork cannot trigger cold fallback. Before adoption, that fork reports its identity to the driver for startup cleanup and records it through the session link.

Fresh spare kernels #

The runtime kernel owner handles opens that use a spare. albedo_spare.py implements the Python spare path. Keep adoption and cleanup in those owners rather than adding another pool in daemon handlers. See extension lifecycle guidance.

A spare imports some plugin modules before adoption, so the adopting session only calls their setup. The runtime computes that list once at startup with selection.preload_modules: the modules that the harness base and the built-in default extensions declare in static plugins, plus hook. It passes the list to albedo_spare.py and albedo_zygote.py as a JSON argument. Do not keep a module list in Python. A module outside the list loads at adoption, before the workspace enters sys.path, like a cold kernel's modules. Users' default changes are left out, so every spare and the one zygote import the same list for the daemon's life.

The list does not cover every shipped module. A zygote exits after a minute without forks, and from then on each kernel it forked keeps the modules it imported as private memory. Every plugin module together cost about 3.1 MB of USS over the bare spare, against 1.1 MB for the default list. Most of the difference is colab, which pulls in http.client and urllib.request through proxy. Importing a module can also have effects: cua registers itself as cua in sys.modules, which would shadow a workspace module of that name in sessions that never enabled it. python_modules_test.gleam checks that every declared and preloaded name is a shipped module.