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.
Ownership #
The kernel runtime is core harness code under
src/albedo/harness/kernel. Every session runs
a kernel, whichever extensions it enables. The
python extension
holds only the model-facing feature: the python tool, the cells and
user_shell_output host routes, the /kernel command and its client bindings,
the remote-place context, and the transfer declaration for the kernel tables.
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:
kernelopens, executes, upgrades, and snapshots kernels, and reports their jobs and liveness.kernel/linkkeeps kernel records, the outbox, the host-call ledger, and staged kernels.kernel/journalis the cell journal: saved sources, outcomes, and traces.kernel/cell_storageholds the SQL that daemon accounting and deletion run on the journal.kernel/result_viewrenders a stored cell result for a model request.kernel/toolnames the cell tool. Core matches calls againsttool.namefor binding rewrites, progress, repetition, and the composed instructions. Do not spell the name as a literal in core.kernel/jobsandkernel/resourcesserve job observation and recorded process ownership to the run and agents extensions.kernel/launch,kernel/recovery, andkernel/terminationhold policy that the native driver calls.
The native modules (albedo_python.erl and its helpers) live beside their Gleam
owners in the same directory. Do not move kernel runtime code back into an
extension, and do not add kernel housekeeping as extension plugins.
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. 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.
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.
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.
The public kernel/jobs API owns
live and saved job observations. 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.
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
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.
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 outbox retains at most 2,048 frames and 67,108,864 bytes per kernel. Past either limit it drops the oldest frames. 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.
Opening and replacing kernels #
open_inner reconciles staged records and
tries to reattach before starting a fresh kernel. 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.
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.
Native lifecycle boundaries #
launch.gleam selects
reserved-spare adoption, current-tree zygote use, and cold fallback.
albedo_python_spare.erl
owns spare custodians and zygote mechanisms.
albedo_python_launch.erl
owns cold launcher ports and local socket relays. The existing driver in
albedo_python.erl retains
protocol state, acknowledgments, job ownership, and checked cleanup. These
module boundaries do not introduce additional processes or a second pool.
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.
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. Native signal
helpers check process identities and groups and perform the termination ladder.
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 existing 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.