From 146237e09c4e3744adda99182ba012e144cf0014 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 1 Oct 2026 18:32:32 -0400 Subject: [PATCH] feat(kernel): restore helpers from source, cap saved state, expire idle sessions' state The kernel saved its namespace with dill when installed, else pickle, and its Python has no dill, so functions, classes and imports were lost on every restart. It now records the source of top-level imports, functions and classes (including from a cell that fails after defining them) and re-runs it on restore, re-registering it so the next save keeps it. Saved state is capped at 64 MiB (8 MiB a variable; 256 KiB of definitions) instead of 256 MiB. The restore note names what was re-run from source, what was not, and the largest saved variables. A state file is deleted when its session has been idle past ALBEDO_STATE_EXPIRY_SECONDS (default 14 days), judged from fresh store activity, never for a live kernel or running turn; unknown files older than a day go at startup. Covered by e2e tests through the real daemon. --- agents.md | 2 +- priv/python/albedo_kernel.py | 244 ++++++++++++++++-- robot-docs/kernel-state.md | 29 +++ src/albedo/daemon/albedo_state_expiry.erl | 30 +++ src/albedo/daemon/server.gleam | 106 ++++++++ src/albedo/daemon/session_namespace.gleam | 41 ++- src/albedo/daemon/state_expiry.gleam | 32 +++ .../harness/extensions/python/kernel.gleam | 21 +- test/e2e/kernel_state_test.py | 119 +++++++++ test/e2e/state_expiry_test.py | 131 ++++++++++ 10 files changed, 717 insertions(+), 38 deletions(-) create mode 100644 robot-docs/kernel-state.md create mode 100644 src/albedo/daemon/albedo_state_expiry.erl create mode 100644 src/albedo/daemon/state_expiry.gleam create mode 100644 test/e2e/kernel_state_test.py create mode 100644 test/e2e/state_expiry_test.py diff --git a/agents.md b/agents.md index a2aacc986..bb242748b 100644 --- a/agents.md +++ b/agents.md @@ -72,7 +72,7 @@ An extension bundles plugins: context (system instructions), tool (model tools + ### robot-docs/ -`robot-docs/` is one model-facing doc per subsystem (agents, auth, settings, migrations, cache-ttl, cache-warming, commands, compaction, context, extensions, files, mcp, models, paperclips, provider-requests, proxy, quota, skills, usage-feed, webhooks, workspaces). This file is the map; those are the details. When you change a subsystem's behavior, update its doc in the same change; when you need to understand one, read it there first. +`robot-docs/` is one model-facing doc per subsystem (agents, auth, settings, kernel-state, migrations, cache-ttl, cache-warming, commands, compaction, context, extensions, files, mcp, models, paperclips, provider-requests, proxy, quota, skills, usage-feed, webhooks, workspaces). This file is the map; those are the details. When you change a subsystem's behavior, update its doc in the same change; when you need to understand one, read it there first. ### Other directories diff --git a/priv/python/albedo_kernel.py b/priv/python/albedo_kernel.py index 542027ff5..c502a90c3 100644 --- a/priv/python/albedo_kernel.py +++ b/priv/python/albedo_kernel.py @@ -23,6 +23,7 @@ import reprlib import select import signal import pickle +import types import struct import sys import tempfile @@ -72,6 +73,7 @@ active_capture: Capture | None = None interrupt_capture: Capture | None = None ARCHIVES: collections.OrderedDict[str, Capture] = collections.OrderedDict() NAMESPACE: dict[str, object] = {"__name__": "__main__"} +DEFINITIONS: collections.OrderedDict[str, str] = collections.OrderedDict() CLEANUP: list[albedo_api.Cleanup] = [] HANDLES: list[type[object]] = [asyncio.Task] REPR = reprlib.Repr() @@ -557,9 +559,12 @@ def interrupt(_signal: int, _frame: FrameType | None) -> None: raise KeyboardInterrupt() -def compile_cell(source: str, filename: str) -> tuple[CodeType, CodeType | None]: - """Every part compiles before anything runs; a trailing expression yields the cell value.""" +def compile_cell( + source: str, filename: str +) -> tuple[CodeType, CodeType | None, ast.Module]: + """Compile every part before running; return the unmodified tree for state capture.""" tree = ast.parse(source, filename=filename) + original = ast.Module(body=list(tree.body), type_ignores=tree.type_ignores) last = tree.body[-1] if tree.body else None trailing = None if isinstance(last, ast.Expr): @@ -576,13 +581,125 @@ def compile_cell(source: str, filename: str) -> tuple[CodeType, CodeType | None] if trailing else None ) - return prefix, suffix + return prefix, suffix, original + + +def _target_names(node: ast.AST) -> set[str]: + return { + target.id + for target in ast.walk(node) + if isinstance(target, ast.Name) and isinstance(target.ctx, (ast.Store, ast.Del)) + } + + +def _bound_names(node: ast.AST) -> set[str]: + names = { + item.id + for item in ast.walk(node) + if isinstance(item, ast.Name) and isinstance(item.ctx, (ast.Store, ast.Del)) + } + for item in ast.walk(node): + if isinstance(item, ast.ExceptHandler) and item.name: + names.add(item.name) + elif isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.add(item.name) + return names + + +def _drop_definition(name: str) -> None: + for key in list(DEFINITIONS): + if key == name or key.startswith(name + "#"): + DEFINITIONS.pop(key, None) + + +def _definition_changes( + source: str, tree: ast.Module +) -> list[tuple[set[str], str | None, bool]]: + changes: list[tuple[set[str], str | None, bool]] = [] + for statement in tree.body: + names: set[str] = set() + definition = isinstance( + statement, + ( + ast.FunctionDef, + ast.AsyncFunctionDef, + ast.ClassDef, + ast.Import, + ast.ImportFrom, + ), + ) + if isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.add(statement.name) + elif isinstance(statement, ast.Import): + names.update( + alias.asname or alias.name.split(".")[0] for alias in statement.names + ) + elif isinstance(statement, ast.ImportFrom): + names.update( + alias.asname or alias.name + for alias in statement.names + if alias.name != "*" + ) + else: + names = _bound_names(statement) + if names: + changes.append( + ( + names, + ast.get_source_segment(source, statement) if definition else None, + isinstance(statement, ast.Import), + ) + ) + return changes + + +def capture_definitions( + source: str, tree: ast.Module, upto_line: int | None = None +) -> None: + for statement, (names, segment, is_import) in zip( + tree.body, _definition_changes(source, tree) + ): + if ( + upto_line is not None + and (statement.end_lineno or statement.lineno) >= upto_line + ): + continue + for name in names: + # Plain dotted imports share their root binding and must accumulate. + plain_dotted = ( + is_import + and any( + alias.name.startswith(name + ".") and alias.asname is None + for alias in statement.names + ) + if isinstance(statement, ast.Import) + else False + ) + if not plain_dotted: + _drop_definition(name) + if segment is not None: + key = next(iter(names), "definition") + if ( + is_import + and isinstance(statement, ast.Import) + and any( + "." in alias.name and alias.asname is None + for alias in statement.names + ) + ): + while key in DEFINITIONS: + key += "#2" + elif key in DEFINITIONS: + _drop_definition(key) + # One source segment is replayed once; its imports bind every listed name. + if segment not in DEFINITIONS.values(): + DEFINITIONS[key] = segment async def evaluate(source: str, cell_id: str, durable: bool = False) -> object: started = False try: - prefix, suffix = compile_cell(source, "") + prefix, suffix, tree = compile_cell(source, "") if durable: _ = await host("cells.started", {"id": cell_id}) started = True @@ -594,8 +711,20 @@ async def evaluate(source: str, cell_id: str, durable: bool = False) -> object: if inspect.isawaitable(value) and not isinstance(value, tuple(HANDLES)): value = await cast(Awaitable[object], value) NAMESPACE["_"] = value - return value + capture_definitions(source, tree) + return value except BaseException as error: + filename = "" + line = next( + ( + lineno + for frame, lineno in traceback.walk_tb(error.__traceback__) + if frame.f_code.co_filename == filename + ), + None, + ) + if "tree" in locals() and line is not None: + capture_definitions(source, tree, line) if not hasattr(error, "_albedo_cell_id"): setattr(error, "_albedo_cell_id", cell_id) setattr(error, "_albedo_started", started) @@ -758,9 +887,11 @@ class Cells: # Saved state is the session's own namespace, written by this kernel into the -# daemon's home. Loading it runs pickle: the same trust domain as the transcript. -STATE_MAX = 256 * 1024 * 1024 -STATE_MAX_VALUE = 16 * 1024 * 1024 +# daemon's home. Loading pickle and replaying definitions share the transcript's trust domain. +STATE_MAX = 64 * 1024 * 1024 +STATE_MAX_VALUE = 8 * 1024 * 1024 +DEFINITION_MAX = 256 * 1024 +DEFINITION_MAX_VALUE = 32 * 1024 INJECTED: set[str] = {"__name__", "__builtins__", "_"} @@ -776,38 +907,63 @@ def engine() -> tuple[object, str]: def save_state(path: str) -> dict[str, object]: - """Serialise each name on its own, so one unpicklable object costs only itself.""" + """Serialise values and readable top-level definitions within fixed caps.""" serialiser, kind = cast("Any", engine()) payload: dict[str, bytes] = {} skipped: list[dict[str, str]] = [] total = 0 + largest: list[tuple[str, int]] = [] for name in list(NAMESPACE.keys()): if name.startswith("_") or name in INJECTED: continue - value = NAMESPACE.get( - name, INJECTED - ) # a background thread may delete it mid-walk + value = NAMESPACE.get(name, INJECTED) if value is INJECTED: continue try: blob = cast(bytes, serialiser.dumps(value)) except BaseException as error: - skipped.append( - {"name": name, "reason": f"{type(error).__name__}: {error}"[:200]} - ) + if name not in DEFINITIONS or not isinstance( + value, (types.FunctionType, type, types.ModuleType) + ): + skipped.append( + {"name": name, "reason": f"{type(error).__name__}: {error}"[:200]} + ) continue if len(blob) > STATE_MAX_VALUE: + if name not in DEFINITIONS or not isinstance( + value, (types.FunctionType, type, types.ModuleType) + ): + skipped.append( + { + "name": name, + "reason": f"{len(blob)} bytes exceeds the per-variable cap", + } + ) + elif total + len(blob) > STATE_MAX: + skipped.append({"name": name, "reason": "saved state is full"}) + else: + payload[name] = blob + total += len(blob) + if len(blob) >= 64 * 1024: + largest.append((name, len(blob))) + definitions: list[dict[str, str]] = [] + definition_bytes = 0 + for name, source in DEFINITIONS.items(): + size = len(source.encode("utf-8")) + if size > DEFINITION_MAX_VALUE: skipped.append( { "name": name, - "reason": f"{len(blob)} bytes exceeds the per-variable cap", + "reason": f"definition is {size} bytes; per-definition cap is {DEFINITION_MAX_VALUE}", } ) - elif total + len(blob) > STATE_MAX: - skipped.append({"name": name, "reason": "saved state is full"}) + elif definition_bytes + size > DEFINITION_MAX: + skipped.append( + {"name": name, "reason": "definitions are over the total source cap"} + ) else: - payload[name] = blob - total += len(blob) + definitions.append({"name": name, "source": source}) + definition_bytes += size try: os.makedirs(os.path.dirname(path) or ".", exist_ok=True) handle, temporary = tempfile.mkstemp( @@ -815,31 +971,38 @@ def save_state(path: str) -> dict[str, object]: ) try: with os.fdopen(handle, "wb") as file: - pickle.dump({"cwd": os.getcwd(), "names": payload}, file) - os.replace(temporary, path) # a crash leaves the previous state intact + pickle.dump( + {"cwd": os.getcwd(), "names": payload, "definitions": definitions}, + file, + ) + os.replace(temporary, path) except BaseException: os.unlink(temporary) raise except OSError as error: return {"error": f"could not write saved state: {error}"} + largest.sort(key=lambda item: item[1], reverse=True) return { - "saved": sorted(payload), + "saved": sorted(set(payload) | {item["name"] for item in definitions}), + "defs": [item["name"] for item in definitions], "skipped": skipped, + "largest": [{"name": name, "bytes": size} for name, size in largest[:5]], "bytes": total, "engine": kind, } def load_state(path: str) -> dict[str, object]: - """Revive every name that survives; a name that fails is reported, not fatal.""" + """Restore pickled values, then replay definitions in their saved order.""" try: with open(path, "rb") as file: saved = cast(dict[str, object], pickle.load(file)) except FileNotFoundError: - return {"restored": [], "failed": [], "error": "no saved state"} + return {"restored": [], "defs": [], "failed": [], "error": "no saved state"} except BaseException as error: return { "restored": [], + "defs": [], "failed": [], "error": f"unreadable saved state: {type(error).__name__}", } @@ -855,10 +1018,39 @@ def load_state(path: str) -> dict[str, object]: ) else: restored.append(name) + defs: list[str] = [] + for item in cast(list[object], saved.get("definitions", [])): + if ( + not isinstance(item, dict) + or not isinstance(item.get("name"), str) + or not isinstance(item.get("source"), str) + ): + continue + name, source = item["name"], item["source"] + try: + exec(compile(source, "", "exec"), NAMESPACE) + except BaseException as error: + failed.append( + {"name": name, "reason": f"{type(error).__name__}: {error}"[:200]} + ) + else: + if source not in DEFINITIONS.values(): + key = name + while key in DEFINITIONS: + key += "#2" + DEFINITIONS[key] = source + if name not in restored: + restored.append(name) + defs.append(name) directory = saved.get("cwd") if isinstance(directory, str) and os.path.isdir(directory): os.chdir(directory) - return {"restored": sorted(restored), "failed": failed, "engine": kind} + return { + "restored": sorted(set(restored)), + "defs": defs, + "failed": failed, + "engine": kind, + } def swap_sink(capture: Capture | None) -> Capture | None: diff --git a/robot-docs/kernel-state.md b/robot-docs/kernel-state.md new file mode 100644 index 000000000..f6f07320c --- /dev/null +++ b/robot-docs/kernel-state.md @@ -0,0 +1,29 @@ +# python kernel state + +The Python kernel snapshots the session namespace into the session-owned state file. Plain values are serialized with dill when installed, otherwise pickle; each value is independent, so one unserializable value does not prevent other values from being saved. Loading runs in the same daemon-home/session trust domain as pickle and is not a security boundary. + +## definitions from source + +After a successful cell, the kernel records source for direct, top-level imports, functions, async functions, and classes. Decorators are included. Definitions nested inside `if`, `try`, `with`, or other compound statements are not captured. A later top-level assignment, delete, loop target, or with target removes a recorded name, so rebinding a function name to a value is not resurrected on restore. The latest definition wins. + +On restore, pickled values load first, then definitions run in recorded order. Successfully restored definitions are registered again and saved on the next release. Definition source is authoritative when a name has both forms. A failing definition is reported and does not prevent later definitions. Definition replay has the same trust as pickle loading: it executes in the daemon home for this session. + +## caps and reply contract + +Pickled state is capped at 64 MiB total and 8 MiB per variable. Definition source is capped at 256 KiB total and 32 KiB per definition; over-cap entries appear in `skipped`. The snapshot/restore reply has a `state` object with existing `saved`, `restored`, `skipped`, `failed`, `engine`, and `error` fields. It may also contain: + +- `defs`: names saved or restored by definition replay; these also occur in `saved`/`restored`. +- `largest`: up to five saved variables, biggest first, as `{"name": str, "bytes": int}`, only entries at least 64 KiB. + +Old state files without `definitions` continue to load. Older readers ignore the additive key. + +## expiry + +A session's state file is deleted when the session has been idle longer than `ALBEDO_STATE_EXPIRY_SECONDS` (default 1209600, 14 days; range 1 to 31536000). Idle time is the session's last assistant reply, read fresh from the store at each sweep, not from the registry's cached copy. A session with no assistant reply yet is never expired. A session that later returns finds no saved state and gets the ordinary "kernel was reset" notice. + +The sweep runs once shortly after startup and then every `min(1 day, retention)` seconds, in its own process, never in a request or in the registry. A filesystem or store error ends that sweep quietly. It logs one line, `python state expiry: reclaimed N files (B bytes)`, when it deleted something. + +Never deleted: the state of a session that holds a live kernel or is running a turn (a failed or timed-out status check counts as protected), and the state of any session the store knows about that is still inside its retention. + +A state file that belongs to no session the store knows about is an orphan, and is deleted once it is more than a day old by modification time. Startup removes old orphans before sessions open. + diff --git a/src/albedo/daemon/albedo_state_expiry.erl b/src/albedo/daemon/albedo_state_expiry.erl new file mode 100644 index 000000000..beb28db7a --- /dev/null +++ b/src/albedo/daemon/albedo_state_expiry.erl @@ -0,0 +1,30 @@ +-module(albedo_state_expiry). +-export([reclaim/4]). +-include_lib("kernel/include/file.hrl"). + +reclaim(Home, Expired, Protected, Known) -> + Dir = filename:join(Home, <<"kernels">>), + Now = erlang:system_time(second), + Names = case file:list_dir(Dir) of {ok, Ns} -> Ns; _ -> [] end, + lists:foldl(fun(Name, Acc) -> reclaim_one(Dir, Name, Expired, Protected, Known, Now, Acc) end, + {0, 0}, Names). + +reclaim_one(Dir, Name0, Expired, Protected, Known, Now, {Count, Bytes}) -> + Name = unicode:characters_to_binary(Name0), + case filename:extension(Name) of + <<".state">> -> + Id = filename:rootname(Name, <<".state">>), + Path = filename:join(Dir, Name), + case file:read_file_info(Path, [{time, posix}]) of + {ok, #file_info{type = regular, size = Size, mtime = Mtime}} -> + OldOrphan = not lists:member(Id, Expired) andalso + not lists:member(Id, Known) andalso Now - Mtime >= 86400, + Target = (lists:member(Id, Expired) andalso not lists:member(Id, Protected)) orelse OldOrphan, + case Target andalso file:delete(Path) of + ok -> {Count + 1, Bytes + Size}; + _ -> {Count, Bytes} + end; + _ -> {Count, Bytes} + end; + _ -> {Count, Bytes} + end. diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index b57ab08d8..3d92a4ac2 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -14,6 +14,7 @@ import albedo/daemon/requests import albedo/daemon/session import albedo/daemon/session_provider import albedo/daemon/settings +import albedo/daemon/state_expiry import albedo/daemon/store import albedo/daemon/usage import albedo/harness/cache_ttl @@ -55,6 +56,7 @@ pub type Config { token: String, idle_ms: Int, budget_kb: Int, + state_expiry_seconds: Int, /// How often schedules fire and letters left undelivered are retried. tick_ms: Int, ) @@ -131,6 +133,7 @@ type State { /// Mail arrived while a dispatcher ran; read the inbox again after it. mail_waiting: Bool, stage: Stage, + last_state_expiry: Int, ) } @@ -480,7 +483,23 @@ fn serve(state: State, message: Message) -> actor.Next(State, a) { // must not make API calls wait behind filesystem or database work. let workers = workers(state) let config = state.config + let now = usage.now() / 1000 + let should_expire = + now - state.last_state_expiry + >= state_expiry.sweep_seconds(config.state_expiry_seconds) let _ = process.spawn_unlinked(fn() { reap(workers, config) }) + let state = case should_expire { + True -> { + let infos = dict.values(state.sessions) + let ledger = runtime.ledger(state.host) + let _ = + process.spawn_unlinked(fn() { + expire_states(config, ledger, infos, now) + }) + State(..state, last_state_expiry: now) + } + False -> state + } let _ = process.send_after(state.self, sweep_interval(state.config), Sweep) actor.continue(state) @@ -663,6 +682,8 @@ fn start_registry( } #(info.id, #(info, worker)) }) + let _ = + reclaim_states(config.home, [], [], list.map(saved, fn(info) { info.id })) case stage { Open -> { let _ = process.send_after(self, sweep_interval(config), Sweep) @@ -684,6 +705,7 @@ fn start_registry( None, False, stage, + 0, )) |> actor.returning(self) |> actor.selecting( @@ -900,6 +922,89 @@ fn reap(workers: List(session.Session), config: Config) -> Nil { }) } +fn expire_states( + config: Config, + ledger: store.Store, + cached: List(#(conversation.Info, Option(session.Session))), + now: Int, +) -> Nil { + let statuses = + cached + |> list.filter_map(fn(entry) { + case entry.1 { + None -> Error(Nil) + Some(worker) -> { + let report = session.report(worker) + Ok(#(entry.0.id, #(report.kernel != None, report.running))) + } + } + }) + case conversation.list(ledger) { + Error(_) -> Nil + Ok(infos) -> { + let protected = + infos + |> list.filter_map(fn(info) { + case list.key_find(statuses, info.id) { + Ok(#(live, running)) if live || running -> Ok(info.id) + _ -> Error(Nil) + } + }) + let candidates = + list.map(infos, fn(info) { + let running = case list.key_find(statuses, info.id) { + Ok(#(live, active)) -> live || active + Error(_) -> False + } + state_expiry.Candidate( + info.id, + info.last_assistant_at, + running, + info.stage != conversation.Idle, + ) + }) + let expired = + state_expiry.expired(candidates, now, config.state_expiry_seconds) + let _ = + reclaim_states( + config.home, + expired, + protected, + list.map(infos, fn(info) { info.id }), + ) + Nil + } + } +} + +fn reclaim_states( + home: String, + expired: List(String), + protected: List(String), + known: List(String), +) -> Nil { + let #(count, bytes) = reclaim_native(home, expired, protected, known) + case count > 0 { + True -> + io.println( + "python state expiry: reclaimed " + <> int.to_string(count) + <> " files (" + <> int.to_string(bytes) + <> " bytes)", + ) + False -> Nil + } +} + +@external(erlang, "albedo_state_expiry", "reclaim") +fn reclaim_native( + home: String, + expired: List(String), + protected: List(String), + known: List(String), +) -> #(Int, Int) + @external(erlang, "albedo_daemon", "rss") fn rss(pids: List(Int)) -> List(#(Int, Int)) @@ -2502,6 +2607,7 @@ pub fn main() -> Nil { token, setting("ALBEDO_IDLE_SECONDS", 31 * 60, 1, 604_800) * 1000, setting("ALBEDO_KERNEL_BUDGET_MB", 2048, 64, 1_048_576) * 1024, + setting("ALBEDO_STATE_EXPIRY_SECONDS", 1_209_600, 1, 31_536_000), setting("ALBEDO_SCHEDULE_TICK_MS", 15_000, 50, 60_000), ) let assert True = string.byte_size(token) >= 32 && home != "" diff --git a/src/albedo/daemon/session_namespace.gleam b/src/albedo/daemon/session_namespace.gleam index c52f2c99d..ca9c516b5 100644 --- a/src/albedo/daemon/session_namespace.gleam +++ b/src/albedo/daemon/session_namespace.gleam @@ -49,26 +49,47 @@ pub fn save_state_within( } } -fn names(saved: python.Saved) -> String { - string.join(list.take(saved.names, 40), ", ") +fn names(values: List(String)) -> String { + string.join(list.take(values, 40), ", ") +} + +fn human_size(bytes: Int) -> String { + case bytes { + bytes if bytes >= 1024 * 1024 -> int.to_string(bytes / 1_048_576) <> " MB" + bytes -> int.to_string(bytes / 1024) <> " KB" + } +} + +fn largest(saved: python.Saved) -> String { + saved.largest + |> list.map(fn(entry) { entry.0 <> " (" <> human_size(entry.1) <> ")" }) + |> names } fn restored_notice(saved: python.Saved) -> String { "The python kernel restarted. These variables were restored from disk: " - <> names(saved) + <> names(saved.names) + <> case saved.defs { + [] -> "" + defs -> + ". Functions, classes, and imports re-run from source: " <> names(defs) + } <> case saved.missed { - [] -> "." + [] -> "" missed -> - ". These were not: " + ". These were not restored: " <> string.join( list.map(list.take(missed, 20), fn(entry) { entry.0 <> " (" <> entry.1 <> ")" }), ", ", ) - <> "." } - <> " Imports and definitions from earlier cells are gone unless named here." + <> case saved.largest { + [] -> "" + _ -> ". Largest saved variables: " <> largest(saved) + } + <> ". Other imports and definitions from earlier cells are gone." } pub fn restored_text(saved: python.Saved) -> String { @@ -87,7 +108,7 @@ pub fn released_text( ) -> String { let prefix = "python kernel released: " <> reason <> "; " case saved { - Ok(python.Saved([_, ..] as names, missed, engine)) -> + Ok(python.Saved([_, ..] as names, missed, engine, _defs, _largest)) -> prefix <> int.to_string(list.length(names)) <> " variables saved to disk" @@ -96,7 +117,7 @@ pub fn released_text( _, "pickle" -> ", " <> int.to_string(list.length(missed)) - <> " skipped (install dill to also save functions and classes)" + <> " skipped (source definitions are restored when available)" _, _ -> ", " <> int.to_string(list.length(missed)) <> " skipped" } _ -> prefix <> "variables are gone, the transcript is intact" @@ -147,7 +168,7 @@ pub fn adopt( None -> Error(python.Invalid("session has no state file")) } case revived { - Ok(python.Saved([_, ..], _, _) as saved) -> + Ok(python.Saved([_, ..], _, _, _, _) as saved) -> adopted(state, kernel, restored_notice(saved), restored_text(saved)) _ -> adopted(state, kernel, lost_notice, lost_text) } diff --git a/src/albedo/daemon/state_expiry.gleam b/src/albedo/daemon/state_expiry.gleam new file mode 100644 index 000000000..f1452f72a --- /dev/null +++ b/src/albedo/daemon/state_expiry.gleam @@ -0,0 +1,32 @@ +//// Pure policy for deciding which saved session states are safe to expire. + +import gleam/list +import gleam/option.{type Option, Some} + +pub type Candidate { + Candidate(id: String, last_activity: Option(Int), live: Bool, running: Bool) +} + +/// Returns idle, non-running sessions past the retention period. +pub fn expired( + candidates: List(Candidate), + now: Int, + retention: Int, +) -> List(String) { + candidates + |> list.filter(fn(candidate) { + case candidate.last_activity, candidate.live, candidate.running { + Some(last), False, False -> now - last >= retention + _, _, _ -> False + } + }) + |> list.map(fn(candidate) { candidate.id }) +} + +/// Checks at most daily in production, but follows short test retentions. +pub fn sweep_seconds(retention: Int) -> Int { + case retention < 86_400 { + True -> retention + False -> 86_400 + } +} diff --git a/src/albedo/harness/extensions/python/kernel.gleam b/src/albedo/harness/extensions/python/kernel.gleam index b04797f2d..27d2154d4 100644 --- a/src/albedo/harness/extensions/python/kernel.gleam +++ b/src/albedo/harness/extensions/python/kernel.gleam @@ -123,7 +123,13 @@ fn execute_native( /// Names carried across a kernel's life: saved or restored, and those that could not be. pub type Saved { - Saved(names: List(String), missed: List(#(String, String)), engine: String) + Saved( + names: List(String), + missed: List(#(String, String)), + engine: String, + defs: List(String), + largest: List(#(String, Int)), + ) } /// Write the namespace to path. The kernel must be idle; a busy kernel answers Busy. @@ -171,11 +177,22 @@ fn saved_decoder() -> decode.Decoder(Result(Saved, Error)) { } let names = decode.list(decode.string) let entries = decode.list(entry) + let largest_entry = { + use name <- decode.field("name", decode.string) + use bytes <- decode.field("bytes", decode.int) + decode.success(#(name, bytes)) + } use saved <- decode.optional_field("saved", [], names) use restored <- decode.optional_field("restored", [], names) use skipped <- decode.optional_field("skipped", [], entries) use failed <- decode.optional_field("failed", [], entries) use engine <- decode.optional_field("engine", "", decode.string) + use defs <- decode.optional_field("defs", [], names) + use largest <- decode.optional_field( + "largest", + [], + decode.list(largest_entry), + ) use failure <- decode.optional_field("error", "", decode.string) decode.success(case failure { "" -> @@ -183,6 +200,8 @@ fn saved_decoder() -> decode.Decoder(Result(Saved, Error)) { list.append(saved, restored), list.append(skipped, failed), engine, + defs, + largest, )) message -> Error(Invalid(message)) }) diff --git a/test/e2e/kernel_state_test.py b/test/e2e/kernel_state_test.py new file mode 100644 index 000000000..2fa3884a4 --- /dev/null +++ b/test/e2e/kernel_state_test.py @@ -0,0 +1,119 @@ +"""A restarted kernel gets back its helpers, not only its variables. + +Saved state is written when an idle kernel is released and read when the next +turn opens a new one, so these scenarios run through the real daemon: the +restore path lives in the kernel and the notice in the daemon. +""" + +import os +import pickle +import time +import unittest + +from harness import Albedo, Provider, exclusive, python, text + +IDLE_SECONDS = 1 +BIG_DEFINITION = "def big():\n return '" + "x" * 40000 + "'\n" + +DEFINE = ( + "import json\n" + "import os.path\n" + "import xml.dom\n" + "def helper(x):\n return x * 2\n" + "class Box:\n def __init__(self, v):\n self.v = v\n" + "answer = 7\n" + "def rebound():\n return 1\n" + "if answer:\n rebound = 5\n" + BIG_DEFINITION + "blob = bytes(9 * 1024 * 1024)\n" +) +FAIL = "def survivor():\n return 'alive'\nraise RuntimeError('boom')" +RECALL = ( + "print('RESULT', helper(21), Box(3).v, json.dumps([1]), answer, rebound,\n" + " survivor(), os.path.basename('a/b'), xml.dom.__name__,\n" + " 'big' in globals(), 'blob' in globals())" +) +LEGACY = "print('LEGACY', legacy)" + + +def latest_user(request): + return [item["content"] for item in request["input"] if item.get("role") == "user"][ + -1 + ] + + +def wait_until(condition, seconds, message): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if condition(): + return + time.sleep(0.1) + raise AssertionError(message) + + +@exclusive +class KernelStateTests(unittest.TestCase): + def setUp(self): + cells = {"define": DEFINE, "fail": FAIL, "recall": RECALL, "legacy": LEGACY} + + def script(request): + if request["input"][-1].get("role") == "user": + prompt = latest_user(request).split("")[0] + if prompt in cells: + return python(cells[prompt]) + return text("ok") + + self.provider = Provider(script) + self.addCleanup(self.provider.close) + self.app = Albedo( + self.provider, + protocol="responses", + prepare=lambda app: app.env.update(ALBEDO_IDLE_SECONDS=str(IDLE_SECONDS)), + ) + self.app.__enter__() + self.addCleanup(self.app.__exit__, None, None, None) + + def state(self, session): + return self.app.home / "kernels" / f"{session}.state" + + def turn(self, session, prompt): + self.app.prompt(session, prompt).close() + self.app.idle(session) + + def saved_after(self, session, since): + """The idle kernel was released again: its state file is newer than `since`.""" + wait_until( + lambda: ( + self.state(session).exists() + and self.state(session).stat().st_mtime_ns > since + ), + 15, + "the idle kernel was not saved", + ) + + def outputs(self): + return "".join( + item.get("output", "") + for item in self.provider.requests[-1]["request"]["input"] + ) + + def test_helpers_classes_imports_and_failed_cells_survive_a_restart(self): + session = self.app.session() + self.turn(session, "define") + self.saved_after(session, 0) + saved = self.state(session).stat().st_mtime_ns + self.turn(session, "fail") + self.saved_after(session, saved) + self.turn(session, "recall") + output = self.outputs() + self.assertIn("RESULT 42 3 [1] 7 5 alive b xml.dom False False", output) + notice = latest_user(self.provider.requests[-2]["request"]) + self.assertIn("re-run from source", notice) + self.assertIn("helper", notice) + + def test_a_state_file_in_the_old_format_still_restores_its_variables(self): + session = self.app.session() + self.turn(session, "define") + self.saved_after(session, 0) + legacy = {"cwd": os.getcwd(), "names": {"legacy": pickle.dumps(5)}} + self.state(session).write_bytes(pickle.dumps(legacy)) + self.turn(session, "legacy") + self.assertIn("LEGACY 5", self.outputs()) diff --git a/test/e2e/state_expiry_test.py b/test/e2e/state_expiry_test.py new file mode 100644 index 000000000..a3b135dd5 --- /dev/null +++ b/test/e2e/state_expiry_test.py @@ -0,0 +1,131 @@ +"""Saved Python state expires with its idle session, and only then. + +Expiry deletes files the daemon cannot recreate, so the bugs worth catching are +the ones that delete too much (a live kernel's file) or nothing at all (a type +mismatch once made the sweep a no-op), and only the real daemon exercises both. +""" + +import os +import time +import unittest + +from harness import Albedo, Provider, exclusive, python, text + +IDLE_SECONDS = 1 +EXPIRY_SECONDS = 3 +LOST = ( + "The python kernel got reset and all variables are lost" +) + + +def latest_user(request): + return [item["content"] for item in request["input"] if item.get("role") == "user"][ + -1 + ] + + +def wait_until(condition, seconds, message): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if condition(): + return + time.sleep(0.1) + raise AssertionError(message) + + +@exclusive +class StateExpiryTests(unittest.TestCase): + def setUp(self): + def script(request): + if request["input"][-1].get("role") == "user": + prompt = latest_user(request) + if prompt.startswith("remember"): + return python("answer = 7") + if prompt.startswith("pin"): + return python("job = run('sleep', '25')\nanswer = 8") + return text("ok") + + self.provider = Provider(script) + self.addCleanup(self.provider.close) + self.app = Albedo( + self.provider, + protocol="responses", + prepare=lambda app: app.env.update( + ALBEDO_IDLE_SECONDS=str(IDLE_SECONDS), + ALBEDO_STATE_EXPIRY_SECONDS=str(EXPIRY_SECONDS), + ), + ) + self.app.__enter__() + self.addCleanup(self.app.__exit__, None, None, None) + + def state(self, session): + return self.app.home / "kernels" / f"{session}.state" + + def turn(self, session, prompt): + self.app.prompt(session, prompt).close() + self.app.idle(session) + return latest_user(self.provider.requests[-1]["request"]) + + def test_an_idle_session_loses_its_state_and_a_live_kernel_keeps_it(self): + idle, live = self.app.session(), self.app.session() + for session in (idle, live): + self.turn(session, "remember this") + wait_until( + lambda: self.state(idle).exists() and self.state(live).exists(), + 15, + "idle kernels were never saved", + ) + # a background job pins this session's kernel, so it is not idle + self.turn(live, "pin this") + wait_until( + lambda: not self.state(idle).exists(), 30, "an idle session kept its state" + ) + self.assertTrue(self.state(live).exists(), "a live kernel lost its state") + self.assertEqual(self.turn(idle, "recall it"), "recall it" + LOST) + + def test_old_orphan_state_goes_at_startup_and_a_young_one_stays(self): + kernels = self.app.home / "kernels" + kernels.mkdir(exist_ok=True) + old, young = kernels / "orphan-old.state", kernels / "orphan-young.state" + for path in (old, young): + path.write_bytes(b"x") + two_days_ago = time.time() - 2 * 86400 + os.utime(old, (two_days_ago, two_days_ago)) + self.app.restart() + self.assertFalse(old.exists(), "an old orphan survived startup") + self.assertTrue(young.exists(), "a young orphan was deleted") + + +@exclusive +class StateRetentionTests(unittest.TestCase): + def setUp(self): + self.provider = Provider( + lambda request: ( + python("answer = 7") + if request["input"][-1].get("role") == "user" + else text("ok") + ) + ) + self.addCleanup(self.provider.close) + self.app = Albedo( + self.provider, + protocol="responses", + prepare=lambda app: app.env.update( + ALBEDO_IDLE_SECONDS=str(IDLE_SECONDS), + ALBEDO_STATE_EXPIRY_SECONDS=str(10 * 86400), + ), + ) + self.app.__enter__() + self.addCleanup(self.app.__exit__, None, None, None) + + def test_a_session_inside_its_retention_keeps_an_old_file(self): + session = self.app.session() + self.app.prompt(session, "remember this").close() + self.app.idle(session) + state = self.app.home / "kernels" / f"{session}.state" + wait_until(state.exists, 15, "the idle kernel was never saved") + two_days_ago = time.time() - 2 * 86400 + os.utime(state, (two_days_ago, two_days_ago)) + self.app.restart() + time.sleep(3) # the first periodic sweep runs within a second of startup + self.assertTrue(state.exists(), "a session inside its retention lost its state") -- knotmirror 0.0.1