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

Python kernel state #

A kernel snapshot carries serializable namespace values and selected kernel state into a replacement. It is separate from the conversation projection described in compaction. kernel.snapshot and kernel.restore take a path and timeout and return a Saved report. A busy kernel answers Busy. A missing state file returns an Invalid error.

Saved namespace #

save_state excludes the values of names beginning with _ and injected names. It records module import names, serializes other values with dill when available or pickle otherwise, and stores captured definition source separately. Each value is serialized on its own, so a reference from one value to a class or function bound to another top-level name is saved as that name. Restore loads values in the order those references need and binds each to the restored object. An instance therefore stays an instance of its class's name, and a replayed class definition does not replace the loaded class. The kernel project includes dill so its locked environment can restore values saved by older kernels that had dill installed. On Python 3.15 and newer, the project pins an upstream dill revision because 0.4.1 cannot save closures on 3.15. Before returning to a released version, verify that a fresh kernel on the same Python minor can restore and call a closure that captures a local value. New snapshots include the writer’s CPython cache tag (for example, cpython-311) in writer_python. Older snapshots omit this field. The snapshot also records the working directory and added sys.path entries. It writes a temporary file and replaces the destination. Definition source is saved whatever its name, so a private helper that a saved function calls comes back with it.

The serialized values have a 64 MiB total limit and an 8 MiB per-value limit. Definition source has a 256 KiB total limit and a 32 KiB per-definition limit. The report lists saved names, skipped names and reasons, the engine, definitions, and up to five large values. These limits apply to the listed components, not a promise about the total file size.

Restore and trust #

load_state restores path entries, kernel state, and definition source eagerly. For a matching writer, namespace values stay in the snapshot until their names are used. Saved modules import on first use. The outer pickle is scanned into file offsets without retaining value bytes. The open snapshot descriptor keeps those offsets valid after a checkpoint replaces the path. The restored report lists available names, and lazy lists names not loaded yet. If the indexed reader fails, restore retries the ordinary pickle reader and keeps its value bytes pending in memory. The kernel log records that fallback. If the saved working directory still exists, restore changes to it.

Before a cell runs, the kernel scans its compiled code and nested code objects for names read or deleted. It loads those pending names first. A cell that mentions globals, locals, vars, or dir loads every pending name. A namespace lookup also loads a missing pending name, including reads by older functions, eval or exec, threads, and __main__. Loading is serialized by a reentrant lock, so concurrent readers get one object. Namespace membership, length, iteration, and key views include pending names without loading them. Values and items load their values.

A binding written by a cell replaces its pending entry. CPython global stores and deletes bypass dict-subclass methods, so code scanning also loads pending targets of STORE_GLOBAL and DELETE_GLOBAL. This scan runs for cells and their nested code, replayed definitions, and functions or classes loaded from disk. After each cell and before a checkpoint, any live binding wins over pending bytes. There is no profile or trace hook. A dynamically compiled string that declares a global and deletes it before any read is not covered by that scan.

Named references load their dependencies first. Definition replay keeps saved classes pending rather than replacing them with fresh classes. Their replayed source supplies a fallback if the serialized class cannot load. Functions with captured source use the replayed function and its live globals. Captured module imports retain their source without importing eagerly when every bound name is a pending module. Decorators and default arguments can load names they use during replay.

A first-use failure raises RestoreError with the name and reason. That pending entry is removed, so later reads do not retry it. The next snapshot lists the failure in skipped. Restore still reports definition failures and prior skips. An untouched value is copied into the next snapshot in bounded chunks, without unpickling or re-pickling it. Serializer reads of a pending function global use the same named-reference encoding as other shared values, rather than loading the global while saving. If the streaming writer fails, save reads pending slices into bytes and retries the ordinary pickle writer. Neither fallback unpickles pending namespace values. The kernel log records the save fallback. These paths preserve state if CPython's private pickle internals change, but use more memory than the indexed and streaming paths.

After a checkpoint replaces the path, still-pending slices retain the old snapshot's inode through their descriptor. That disk allocation remains until the last pending slice is loaded or discarded, or the kernel exits. The slices are not reindexed against each new snapshot.

That descriptor is the kernel's own, not work it holds. The kernel names it in the resources its release check ignores, so a restored kernel with unread values can still be released.

When the saved writer matches the running interpreter, restore can load functions serialized by that interpreter. Across CPython minors, the same bytecode can decode as different instructions. A function can appear to restore successfully and then crash the kernel on its first call.

For a different or unknown writer, restore eagerly reads portable data and recompiles captured definitions from source with the running interpreter. A lambda with only a serialized code object cannot be recovered this way. Restore reports its name so the session can recreate it from the original cell. If the outer snapshot itself requires an unsupported constructor, restore reports an error. This path creates no lazy entries. Its next checkpoint writes the current writer tag, so later restores can be lazy without mixing interpreter-specific blobs.

Before reading a different or unknown writer’s state, the kernel copies the original bytes into the session’s <session>.state.originals/ directory. The SHA-256 of the contents names the copy. Later checkpoints can replace the active snapshot while the original remains available. Local session transfers carry these copies alongside the active state. A live kernel upgrade saves into the old run directory. On SSH, the daemon fetches the original from that host and verifies its SHA-256 before it retires the old kernel.

Loading uses pickle and executes saved definition source. A state file therefore belongs to the session's trust domain and must not be treated as safe untrusted input. A successful restore does not imply every name survived. The Saved report also includes output_lost when the saved kernel state reports lost output or job-book channels. See restore_kernel.

The job book preserves the cell that started each retained job. A job restored from an older snapshot without that field appears without a parent.

Unchanged snapshots #

snapshot reuses its previous report without writing when the path and kernel change counter match and the file's modification time and size still match. This is an optimization, not a content integrity check. The kernel refuses a snapshot while cells are active or queued. A successful matching-writer restore also seeds this unchanged check, so a snapshot before any work reuses the original file. A portable restore does not seed it, because its next snapshot must write the current interpreter's encoding.

Idle resting sessions also checkpoint their kernel namespace in the background checkpoint_idle_ms (2 s) after a turn settles (CheckpointKernel in session.gleam), reusing the unchanged snapshot check above. While a checkpoint is in flight (checkpointing), new turns, AcquireKernel, and releases park behind it so the driver never rejects a cell with Busy. Note that this writes the state file on every settled rest whose namespace changed, and if a later turn crashes mid-cell before settling, a restarted kernel restores from that previous rest's checkpoint rather than the unsettled cells.

Because nearly every kernel saves, its first checkpoint is part of its steady-state memory. albedo_state.py imports pickle at module load. Before freezing its heap, albedo_zygote.main also calls engine to load the selected serializer, including optional dill. Forks can then share those imported objects. Keep serializer imports before the freeze rather than making each fork pay for them at its first save. engine still selects the serializer on each save and load, preserving the pickle fallback when dill is unavailable.

State expiry #

state_expiry.expired selects sessions whose last assistant activity has passed retention, with no observed live kernel or running session. A missing activity timestamp does not qualify. server.main configures retention through ALBEDO_STATE_EXPIRY_SECONDS.

maintenance.expire protects captured owners whose status observation failed. An uncertain observation must not authorize deletion. Loaded sessions delete their own expired state through session.expire_state. Keep that decision inside the session actor, where kernel boots start. The actor rechecks for a kernel or work that uses one because the sweep's earlier report can become stale.

The state file reclaimer handles expired unloaded sessions and a separate orphan policy. Orphans are state files for IDs absent from the known-session list, with a file modification time at least one day old. This policy is distinct from session activity retention. Successful state-file deletion also removes its jobs sidecar and originals directory. A live swap can create an originals directory before the first ordinary checkpoint. The sweep applies the same expiry rules to that directory using its own modification time when the state file is absent.

Saved pastes and uploads #

Long pastes and uploaded chat files live under $ALBEDO_HOME/pastes/<session>/. maintenance.prune_pastes runs during the same expiry sweep and uses the same ALBEDO_STATE_EXPIRY_SECONDS retention. pastes.prune deletes each regular file whose modification time is older than the retention, then removes empty session folders.

This policy uses file age, not session activity. An active conversation does not keep an old upload. A transcript can still name a file that has been deleted, so retained history does not mean the bytes are available. Deleting a session does not itself delete these files. They remain until the age-based sweep removes them.