# 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`](../src/albedo/harness/extensions/python/kernel.gleam). The Python entry point is [`albedo_kernel.py`](../priv/python/albedo_kernel.py), which starts [`albedo_cells.main`](../priv/python/albedo_cells.py). Kernel namespace snapshots are described in [Python kernel state](kernel-state.md). ## Execution and results [`kernel.execute` and `execute_saved`](../src/albedo/harness/extensions/python/kernel.gleam) 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`](../priv/python/albedo_memory.py) 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](https://docs.kernel.org/filesystems/proc.html) describe which mappings each counter includes. [`guard_memory`](../priv/python/albedo_cells.py) 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`](../priv/python/albedo_spill.py) 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. [`stop_threads`](../priv/python/albedo_cells.py) 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](kernel-state.md). Check side effects before rerunning a cell; current objects and background jobs need not survive replacement. ## Process jobs Use [`run(program, *args, cwd=..., env=...)`](../priv/python/albedo_plugins/run.py) 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](../priv/python/albedo_plugins/run.py) and [albedo_capture.py](../priv/python/albedo_capture.py). The public [`python/jobs`](../src/albedo/harness/extensions/python/jobs.gleam) 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. [`python/resources`](../src/albedo/harness/extensions/python/resources.gleam) 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`](../src/albedo/harness/extensions/python/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`](../src/albedo/harness/extensions/python/kernel.gleam) 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`](../src/albedo/harness/extensions/python/kernel.gleam) 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](kernel-state.md). [`runtime/kernels.gleam`](../src/albedo/harness/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`](../src/albedo/harness/extensions/python/kernel.gleam). ## Native lifecycle boundaries [`launch.gleam`](../src/albedo/harness/extensions/python/launch.gleam) selects reserved-spare adoption, current-tree zygote use, and cold fallback. [`albedo_python_spare.erl`](../src/albedo/harness/extensions/python/albedo_python_spare.erl) owns spare custodians and zygote mechanisms. [`albedo_python_launch.erl`](../src/albedo/harness/extensions/python/albedo_python_launch.erl) owns cold launcher ports and local socket relays. The existing driver in [`albedo_python.erl`](../src/albedo/harness/extensions/python/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`](../src/albedo/harness/extensions/python/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`](../src/albedo/harness/extensions/python/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](runtime.md#admission-and-worker-lifetime). 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](../src/albedo/harness/runtime/kernels.gleam) handles opens that use a spare. [albedo_spare.py](../priv/python/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](contributing.md#preserve-extension-lifecycle-boundaries). ## Related pages - [All topics](README.md) - [Change guidance](contributing.md) - [Python kernel state](kernel-state.md) - [Files extension](files.md) - [Image generation](imagegen.md)