diff --git a/.agents/skills/gleam-design/SKILL.md b/.agents/skills/gleam-design/SKILL.md index e63d0259b..6e474b4ef 100644 --- a/.agents/skills/gleam-design/SKILL.md +++ b/.agents/skills/gleam-design/SKILL.md @@ -117,7 +117,8 @@ A function-valued field can still do IO. ## 5. Design the process protocol, not just its messages Keep private runtime state separate from the handle or startup data returned to -callers. Hide message constructors behind ordinary functions unless callers +callers. Bind individual fields before constructing a callback that crosses a +process or ETS boundary; referencing `state.field` inside it captures `state`. Hide message constructors behind ordinary functions unless callers legitimately need the protocol for integration. Send operations that protect whole invariants. Prefer `Reserve(amount, reply)` diff --git a/.agents/skills/gleam-design/references/state-and-concurrency.md b/.agents/skills/gleam-design/references/state-and-concurrency.md index e391609df..f8d6ddc9e 100644 --- a/.agents/skills/gleam-design/references/state-and-concurrency.md +++ b/.agents/skills/gleam-design/references/state-and-concurrency.md @@ -105,6 +105,8 @@ Do not mistake an effect description for an asynchronous execution primitive. Lu ## Account for cost and target +Bind the fields a callback needs before building a closure stored in ETS or sent to another process. `fn() { send(state.self, state.changed) }` captures all of `state`, not just two fields. In albedo's 50-session probe, binding the subject and message first removed 10.7 MiB from the watcher table and about 49 MiB of process heaps; each notification had copied the oversized callback out of ETS. + Prefer compact work inputs and results over sending an entire evolving graph on every event. Ordinary BEAM message data is copied, with important exceptions for reference-counted binaries and literals on the same node; ETS object operations also involve copying. Preserve semantics first, then measure fan-out, copying, retained snapshots, and mailbox sizes. [E01-E02] Use `persistent_term` only after establishing that updates are rare and accepting its update costs. It is optimized for reads; replacing complex values can induce VM-wide garbage-collection work. It is not a default store for changing sessions or per-token state. [E03] diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index 9d2a1e9f8..2fc8d7496 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -45,6 +45,12 @@ holds the bound intake port (`publish` at boot, `clear` when the intake stops, `port` for readers). An integer copies nothing, and the one erase happens only when the intake gives up. +Callbacks stored in ETS must capture compact arguments, not their owner's +state record. `session_namespace.watch_kernel` binds the destination subject +and message before creating its callback; capturing `state` there copies the +loaded kernel and session state into the watcher table and into every kernel +process that reads the callback. + ## mutable provider caches `albedo_accounts` keeps transient account limits in `albedo_account_limits` ETS, diff --git a/src/albedo/daemon/session_namespace.gleam b/src/albedo/daemon/session_namespace.gleam index 08917e08f..1d2caecca 100644 --- a/src/albedo/daemon/session_namespace.gleam +++ b/src/albedo/daemon/session_namespace.gleam @@ -56,9 +56,9 @@ pub fn watch_kernel( case state.kernel { None -> state Some(kernel) -> { - python.watch(kernel.kernel, fn() { - process.send(state.self, state.kernel_changed) - }) + let owner = state.self + let changed = state.kernel_changed + python.watch(kernel.kernel, fn() { process.send(owner, changed) }) state } } diff --git a/test/e2e/session_status_test.py b/test/e2e/session_status_test.py index 5b49337c9..5c6bd0cf4 100644 --- a/test/e2e/session_status_test.py +++ b/test/e2e/session_status_test.py @@ -103,6 +103,25 @@ class SessionStatusPushTests(unittest.TestCase): json.load(changed)["resource"]["value"]["status"], "active" ) + @exclusive + def test_kernel_notifications_do_not_retain_session_state(self): + def prepare(app): + app.daemon.env["ALBEDO_INSPECT"] = "1" + + with Albedo(self.provider, prepare=prepare) as app: + session = app.session() + app.prompt(session, "warm kernel").close() + app.idle(session) + sizes = json.loads( + Inspection(app).evaluate( + "io:put_chars(Call(erlang, apply, [fun() -> " + "json:encode([erts_debug:flat_size(F) || {_, F} <- " + "ets:tab2list(albedo_kernel_watch)]) end, []]))" + ) + ) + self.assertTrue(sizes) + self.assertLess(max(sizes), 256) + def test_stream_pushes_job_lifecycle_and_sidebar_changes(self): with Albedo(self.provider) as app: session = app.session() -- knotmirror 0.0.1 From 82f246490862f84b8ba1307ec654f5cd1ffc13cd Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:23:10 -0400 Subject: [PATCH 02/72] Keep density mail recipient alive across reaping measurements --- test/manual/agent_density.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/manual/agent_density.py b/test/manual/agent_density.py index 202ee4525..0bf4c3f66 100644 --- a/test/manual/agent_density.py +++ b/test/manual/agent_density.py @@ -171,7 +171,7 @@ def main(): Albedo(provider, protocol="responses", prepare=prepare) as app, ): recipient = app.session() - turn_prompt = "recipient warmup" + turn_prompt = "cell:recipient" app.prompt(recipient, turn_prompt).close() app.idle(recipient) baseline = sum(process_bytes(item["pid"]) for item in processes(app)) -- knotmirror 0.0.1 From 22ee015ac8dba10b6b28e6008ed8905999803f32 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:23:34 -0400 Subject: [PATCH 03/72] Hibernate quiet Python kernel owners after frame bursts --- robot-docs/kernel.md | 4 ++++ src/albedo/harness/extensions/python/albedo_python.erl | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 761ba8180..b77474b6c 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -163,6 +163,10 @@ changed nothing wakes nobody. The session then re-observes and publishes a `kernel` stream event only when the facts differ ([sessions](sessions.md#live-status-without-a-poll)). A dropped kernel handle is forgotten with `albedo_python:unwatch/1`. +The port owner hibernates after 100 ms without a message, compacting its live +state and dropping garbage from frame decoding and host calls. The next message +wakes it immediately; cells, jobs, deadlines, and reattach timers stay live. + The Erlang port owner truncates commands through `text_scalars.take`, which scans only the retained prefix and copies it. Do not convert the entire command to a codepoint list to take a bounded preview; see [runtime](runtime.md#unicode-scalar-limits). diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index f38edfeae..31a950dde 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -22,6 +22,7 @@ -export([stale/1, mark_stale/2]). -export([observation/1, stop_recorded/2, stop_jobs/1, job_list/1, job_read/4]). -export([watch/2, unwatch/1]). +-export([loop/1]). %% hibernate continuation -define(PROTOCOL, 1). %% Bridge, kernel and plugins, end to end. A kernel that exits fails at once @@ -618,6 +619,9 @@ loop(S = #{port := Port, active := Active}) -> end end; _ -> loop(S) + after albedo_clock:delay(100) -> + %% Drop frame decoding and host-call garbage after a quiet burst. + erlang:hibernate(?MODULE, loop, [S]) end. %% The bridge went away. Status 3 says the kernel is gone too; anything else -- knotmirror 0.0.1 From c4e9d031dde6607ca10f293764f14a5ef7df9774 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:26:58 -0400 Subject: [PATCH 04/72] Discard late actor replies through monitored aliases --- .../references/state-and-concurrency.md | 2 ++ robot-docs/runtime.md | 6 ++++++ src/albedo/actor_call.gleam | 10 ++++++--- src/albedo/albedo_actor_call.erl | 17 +++++++++++++++ test/actor_call_test.gleam | 21 +++++++++++++++++++ test/albedo_actor_call_test_support.erl | 6 +++++- 6 files changed, 58 insertions(+), 4 deletions(-) create mode 100644 src/albedo/albedo_actor_call.erl diff --git a/.agents/skills/gleam-design/references/state-and-concurrency.md b/.agents/skills/gleam-design/references/state-and-concurrency.md index f8d6ddc9e..aa34d988f 100644 --- a/.agents/skills/gleam-design/references/state-and-concurrency.md +++ b/.agents/skills/gleam-design/references/state-and-concurrency.md @@ -95,6 +95,8 @@ Track work identity and completion explicitly. Include a run or request ID, and Separate three errors: domain rejection, dependency failure, and process/transport failure. A reply type such as `Result(Value, DomainError)` does not make `process.call` return a timeout as `Error`: the inspected API returns the reply directly and can panic on transport failure. Check the installed version before selecting a wrapper. [S12] +Use a reply alias for finite calls when the caller survives a timeout. Gleam Erlang 1.3.0's `process.call` uses an ordinary subject, so removing its monitor does not reject late replies. Albedo's 1,000-timeout probe retained 1,000 mailbox entries and 62.5 MiB of reply binaries before alias retirement, and none afterwards. Retire the alias in a native `after` bracket and flush replies already delivered before retirement; test reply/death ordering too. + A timeout means the caller stopped waiting, not necessarily that the operation stopped. Cancellation also needs a real protocol. Where duplicate external effects matter, use operation IDs and an idempotency or reconciliation strategy at the authority. Do not retry a write merely because decoding its result failed: Pog explicitly performs the query before decoding returned rows. [S19] Give every queue a policy: bounded admission, rejection, batching, coalescing, pull-based demand, or a justified upper bound. Checking `Busy` only after processing a message does not bound the mailbox of already queued requests. Track active workers, queue growth, work age, and rejected/coalesced work as appropriate. No blanket queue-size threshold is supplied here. diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index 2fc8d7496..acc68852a 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -162,6 +162,12 @@ Reader connections use private SQLite caches with a 128 KiB suggested page-cache ## finite actor calls +`actor_call.try_call` uses a monitored process alias for its reply subject. +The native `albedo_actor_call.with_reply` bracket retires the alias and drains +already-delivered replies when the call returns or raises. A late reply is +then dropped before entering the caller's mailbox. The request itself is not +cancelled; domain operations must still handle an unconfirmed result. + `albedo/actor_call.gleam` owns monitored calls that return `TimedOut` or `CalleeDown` and remove their monitor on every outcome. Reuse `try_call` for finite waits instead of copying subject lookup, reply selection, and monitor diff --git a/src/albedo/actor_call.gleam b/src/albedo/actor_call.gleam index f332e76ec..08eccca6e 100644 --- a/src/albedo/actor_call.gleam +++ b/src/albedo/actor_call.gleam @@ -21,15 +21,13 @@ pub fn try_call( case process.subject_owner(subject) { Error(_) -> Error(CalleeDown) Ok(callee) -> { - let reply = process.new_subject() - let monitor = process.monitor(callee) + use reply, monitor <- with_reply(callee) process.send(subject, make_request(reply)) let answer = process.new_selector() |> process.select_map(reply, Ok) |> process.select_specific_monitor(monitor, fn(_) { Error(CalleeDown) }) |> process.selector_receive(timeout) - process.demonitor_process(monitor) case answer { Ok(outcome) -> outcome Error(_) -> Error(TimedOut) @@ -37,3 +35,9 @@ pub fn try_call( } } } + +@external(erlang, "albedo_actor_call", "with_reply") +fn with_reply( + callee: process.Pid, + run: fn(Subject(reply), process.Monitor) -> result, +) -> result diff --git a/src/albedo/albedo_actor_call.erl b/src/albedo/albedo_actor_call.erl new file mode 100644 index 000000000..df57789c7 --- /dev/null +++ b/src/albedo/albedo_actor_call.erl @@ -0,0 +1,17 @@ +-module(albedo_actor_call). +-export([with_reply/2]). + +%% The monitor doubles as a reply address. Retiring it drops later replies; +%% anything delivered before retirement must also leave the caller's mailbox. +with_reply(Callee, Run) -> + Alias = erlang:monitor(process, Callee, [{alias, demonitor}]), + try Run({subject, Alias, Alias}, Alias) + after + erlang:demonitor(Alias, [flush]), + flush(Alias) + end. + +flush(Alias) -> + receive {Alias, _} -> flush(Alias) + after 0 -> ok + end. diff --git a/test/actor_call_test.gleam b/test/actor_call_test.gleam index b39c3823a..6d9714199 100644 --- a/test/actor_call_test.gleam +++ b/test/actor_call_test.gleam @@ -95,5 +95,26 @@ pub fn finite_calls_remove_monitors_and_down_messages_test() -> Nil { monitor_state() |> should.equal(before) } +pub fn a_late_reply_cannot_accumulate_after_a_timeout_test() -> Nil { + let held = process.new_subject() + let subject = + server(fn(message) { + case message { + Ping(reply) -> process.send(held, reply) + Die -> Nil + } + actor.continue(Nil) + }) + let before = mailbox_size() + actor_call.try_call(subject, 20, Ping) + |> should.equal(Error(actor_call.TimedOut)) + let assert Ok(reply) = process.receive(held, 2000) + process.send(reply, "late") + mailbox_size() |> should.equal(before) +} + +@external(erlang, "albedo_actor_call_test_support", "mailbox_size") +fn mailbox_size() -> Int + @external(erlang, "albedo_actor_call_test_support", "monitor_state") fn monitor_state() -> #(Int, Int) diff --git a/test/albedo_actor_call_test_support.erl b/test/albedo_actor_call_test_support.erl index 015efc7c9..2fdd94a80 100644 --- a/test/albedo_actor_call_test_support.erl +++ b/test/albedo_actor_call_test_support.erl @@ -1,8 +1,12 @@ -module(albedo_actor_call_test_support). --export([monitor_state/0]). +-export([monitor_state/0, mailbox_size/0]). monitor_state() -> {monitors, Monitors} = process_info(self(), monitors), {messages, Messages} = process_info(self(), messages), Downs = [Ref || {'DOWN', Ref, process, _, _} <- Messages], {length(Monitors), length(Downs)}. + +mailbox_size() -> + {message_queue_len, Size} = process_info(self(), message_queue_len), + Size. -- knotmirror 0.0.1 From a3967aa6ef07a0bc588cb74d944e3651bdd74cf7 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:27:54 -0400 Subject: [PATCH 05/72] Hibernate quiet local kernel socket relays --- robot-docs/kernel.md | 2 ++ src/albedo/harness/extensions/python/albedo_python.erl | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index b77474b6c..b4d448d1e 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -166,6 +166,8 @@ is forgotten with `albedo_python:unwatch/1`. The port owner hibernates after 100 ms without a message, compacting its live state and dropping garbage from frame decoding and host calls. The next message wakes it immediately; cells, jobs, deadlines, and reattach timers stay live. +The local socket relay uses the same quiet-period hibernation, retaining only +its owner monitor and socket rather than its last forwarded frame's heap. The Erlang port owner truncates commands through `text_scalars.take`, which scans only the retained prefix and copies it. Do not convert the entire command diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 31a950dde..a8a2ebb9e 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -22,7 +22,7 @@ -export([stale/1, mark_stale/2]). -export([observation/1, stop_recorded/2, stop_jobs/1, job_list/1, job_read/4]). -export([watch/2, unwatch/1]). --export([loop/1]). %% hibernate continuation +-export([loop/1, relay_loop/3]). %% hibernate continuations -define(PROTOCOL, 1). %% Bridge, kernel and plugins, end to end. A kernel that exits fails at once @@ -168,6 +168,8 @@ relay_loop(Owner, Watch, Connection) -> {tcp_error, Connection, _} -> Owner ! {self(), {exit_status, 0}}; {Owner, close} -> gen_tcp:close(Connection); {'DOWN', Watch, process, Owner, _} -> gen_tcp:close(Connection) + after albedo_clock:delay(100) -> + erlang:hibernate(?MODULE, relay_loop, [Owner, Watch, Connection]) end. %% The launcher's exit status; it gets the token as its one line of stdin. -- knotmirror 0.0.1 From b1be5549ab8adc6de2445d6def5e9d389172ce94 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:46:09 -0400 Subject: [PATCH 06/72] Hibernate quiet session actors after a coalesced timer --- .../references/state-and-concurrency.md | 2 ++ robot-docs/runtime.md | 9 +++++ src/albedo/daemon/albedo_session.erl | 25 ++++++++++++- src/albedo/daemon/session.gleam | 22 ++++++++++-- test/e2e/session_status_test.py | 35 +++++++++++++++++++ 5 files changed, 90 insertions(+), 3 deletions(-) diff --git a/.agents/skills/gleam-design/references/state-and-concurrency.md b/.agents/skills/gleam-design/references/state-and-concurrency.md index aa34d988f..44958545d 100644 --- a/.agents/skills/gleam-design/references/state-and-concurrency.md +++ b/.agents/skills/gleam-design/references/state-and-concurrency.md @@ -111,6 +111,8 @@ Bind the fields a callback needs before building a closure stored in ETS or sent Prefer compact work inputs and results over sending an entire evolving graph on every event. Ordinary BEAM message data is copied, with important exceptions for reference-counted binaries and literals on the same node; ETS object operations also involve copying. Preserve semantics first, then measure fan-out, copying, retained snapshots, and mailbox sizes. [E01-E02] +Compact quiet port owners and forwarding relays after frame bursts, not only on process exit. Albedo's 50-agent probe reclaimed 0.36–0.58 MiB per kernel owner and 0.22–0.41 MiB per socket relay with 100 ms quiet hibernation. The quiet interval determines when to reclaim garbage; a message wakes the process immediately. + Use `persistent_term` only after establishing that updates are rare and accepting its update costs. It is optimized for reads; replacing complex values can induce VM-wide garbage-collection work. It is not a default store for changing sessions or per-token state. [E03] Put changing rate-limit marks and TTL results in lifetime-owned ETS, not compound persistent terms. In albedo's OTP 29 probe with 8,000 parked processes, 200 account-limit updates took 4.66 ms with persistent-term map replacement and 0.49 ms with ETS. ETS added about 28 ns per lookup. Use a separate entry per independently updated key; replacing a whole shared map also loses concurrent updates. Keep expired-entry cleanup and owner lifetime explicit. diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index acc68852a..d2edc6f3d 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -160,6 +160,15 @@ Store and reader initialisers allow 60 seconds for disk I/O and dirty-I/O schedu Reader connections use private SQLite caches with a 128 KiB suggested page-cache limit each (512 KiB across four readers), rather than four default-sized caches. Schema and connection allocations are additional; this is not a total memory cap. Reader connections belong to the store lifetime and close before the writer. A failed connection owner fails the store rather than leaving a live handle with reduced capacity. Private in-memory databases retain one connection and serialize snapshots with writes. Their snapshots still enforce read-only access. +## quiet session actors + +Each session coalesces activity into one 100 ms timer. The first quiet tick +clears the burst's dirty mark; another tick without activity calls OTP 28+'s +stack-preserving `erlang:hibernate/0`. This compacts the actor's live heap and +keeps its Gleam OTP receive loop and system-message handling intact. Any message +wakes it immediately; the timer never delays handling a message. Existing +`Collect` messages still perform a major collection when a handler drops state. + ## finite actor calls `actor_call.try_call` uses a monitored process alias for its reply subject. diff --git a/src/albedo/daemon/albedo_session.erl b/src/albedo/daemon/albedo_session.erl index 5d3506ddf..ae37ed98c 100644 --- a/src/albedo/daemon/albedo_session.erl +++ b/src/albedo/daemon/albedo_session.erl @@ -1,5 +1,5 @@ -module(albedo_session). --export([kill/1, discard/1, collect/0, collect_over/1, decode_submission/1, new_generation/0]). +-export([kill/1, discard/1, collect/0, collect_over/1, activity/2, quiet/2, decode_submission/1, new_generation/0]). kill(Pid) -> exit(Pid,kill), nil. %% Monotonic: idle time must not move when the wall clock does. discard(Path) -> file:delete(Path), nil. @@ -12,6 +12,29 @@ collect_over(Words) -> _ -> nil end. +%% One timer follows a burst; messages only mark it dirty, never add timers. +activity(Subject, Message) -> + put(albedo_session_dirty, true), + case get(albedo_session_collecting) of + true -> nil; + _ -> + put(albedo_session_collecting, true), + later(Subject, Message) + end. + +quiet(Subject, Message) -> + case erase(albedo_session_dirty) of + true -> later(Subject, Message); + _ -> + erase(albedo_session_collecting), + erlang:hibernate(), + nil + end. + +later({subject, Pid, Tag}, Message) -> + albedo_clock:send_after(100, Pid, {Tag, Message}), + nil. + decode_submission(Payload) -> binary_to_term(Payload, [safe]). new_generation() -> diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index ef4c4be86..385666b12 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -324,6 +324,7 @@ pub type Message { /// actor never collects on its own, so without this the dropped history and /// the binaries it references stay resident until the next message. Collect + CollectQuiet Close(Subject(Nil)) /// Stop the actor if nothing runs, waits, watches, or holds a live job or a /// running child, whose report will wake it. True when it stopped. @@ -509,7 +510,13 @@ pub fn start( ), ) }) - |> actor.on_message(handle) + |> actor.on_message(fn(state, message) { + case message { + CollectQuiet -> Nil + _ -> activity(state.self, CollectQuiet) + } + handle(state, message) + }) |> actor.start |> result.map(fn(p) { process.unlink(p.pid) @@ -2253,6 +2260,10 @@ fn handle( collect() actor.continue(state) } + CollectQuiet -> { + quiet(state.self, CollectQuiet) + actor.continue(state) + } ClaimDeletion(request, token, deadline, reply) -> { let claimed = case !request.subtree && { busy(state) || state.booting != None } @@ -2663,6 +2674,12 @@ fn label(kind: String, id: String) -> Nil @external(erlang, "albedo_session", "collect") fn collect() -> Nil +@external(erlang, "albedo_session", "activity") +fn activity(subject: Subject(Message), message: Message) -> Nil + +@external(erlang, "albedo_session", "quiet") +fn quiet(subject: Subject(Message), message: Message) -> Nil + @external(erlang, "albedo_wakes", "register") fn wakes_register( session: String, @@ -4290,7 +4307,8 @@ fn finish_workspace( /// Whether a message only observes session state and must not settle a move. fn read_only(message: Message) -> Bool { case message { - ReadCapture(_) + CollectQuiet + | ReadCapture(_) | CaptureIn(_, _) | Released(_, _, _) | Deleted(_, _) diff --git a/test/e2e/session_status_test.py b/test/e2e/session_status_test.py index 5c6bd0cf4..6850f6347 100644 --- a/test/e2e/session_status_test.py +++ b/test/e2e/session_status_test.py @@ -103,6 +103,41 @@ class SessionStatusPushTests(unittest.TestCase): json.load(changed)["resource"]["value"]["status"], "active" ) + @exclusive + def test_quiet_session_hibernates_and_handles_the_next_turn(self): + def prepare(app): + app.daemon.env["ALBEDO_INSPECT"] = "1" + + with Albedo(self.provider, prepare=prepare) as app: + session = app.session() + app.prompt(session, "first turn").close() + app.idle(session) + probe = Inspection(app) + expression = ( + "io:put_chars(Call(erlang, apply, [fun() -> " + "{some, {subject, Pid, _}} = 'albedo@daemon@session':live(" + + "<<" + + json.dumps(session) + + ">>" + + "), {current_function, {_, F, _}} = process_info(Pid, current_function), " + "json:encode(atom_to_binary(F)) end, []]))" + ) + deadline = time.monotonic() + 10 + while True: + current = json.loads(probe.evaluate(expression)) + # hibernate/0 keeps the caller's frame, so the actor waits in quiet. + if current == "quiet": + break + if time.monotonic() >= deadline: + self.fail(f"quiet session did not hibernate: {current}") + time.sleep(0.05) + app.prompt(session, "second turn").close() + app.idle(session) + self.assertEqual(len(self.provider.requests), 2) + self.assertIn( + "second turn", latest_user(self.provider.requests[-1]["request"]) + ) + @exclusive def test_kernel_notifications_do_not_retain_session_state(self): def prepare(app): -- knotmirror 0.0.1 From ed492a767a90820cd12534e5d9aac4cb343d500e Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:50:12 -0400 Subject: [PATCH 07/72] Serve registry host and live session lookups from ETS --- .../references/state-and-concurrency.md | 2 ++ robot-docs/runtime.md | 8 +++++ src/albedo/daemon/albedo_registry_host.erl | 18 ++++++++++ src/albedo/daemon/registry.gleam | 35 +++++++++++++++++-- 4 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 src/albedo/daemon/albedo_registry_host.erl diff --git a/.agents/skills/gleam-design/references/state-and-concurrency.md b/.agents/skills/gleam-design/references/state-and-concurrency.md index 44958545d..eea654d9e 100644 --- a/.agents/skills/gleam-design/references/state-and-concurrency.md +++ b/.agents/skills/gleam-design/references/state-and-concurrency.md @@ -113,6 +113,8 @@ Prefer compact work inputs and results over sending an entire evolving graph on Compact quiet port owners and forwarding relays after frame bursts, not only on process exit. Albedo's 50-agent probe reclaimed 0.36–0.58 MiB per kernel owner and 0.22–0.41 MiB per socket relay with 100 ms quiet hibernation. The quiet interval determines when to reclaim garbage; a message wakes the process immediately. +Read-mostly facts that every request asks an actor for belong in a table the actor publishes while it is open and withdraws before it closes, with the actor as fallback. Albedo's registry host and live-session lookups went from 19.3 ms median (8,000 concurrent callers queued on one actor) to under 1 µs. Withdraw first on shutdown so readers fall back to the actor's refusal instead of reading a closing owner. + Use `persistent_term` only after establishing that updates are rare and accepting its update costs. It is optimized for reads; replacing complex values can induce VM-wide garbage-collection work. It is not a default store for changing sessions or per-token state. [E03] Put changing rate-limit marks and TTL results in lifetime-owned ETS, not compound persistent terms. In albedo's OTP 29 probe with 8,000 parked processes, 200 account-limit updates took 4.66 ms with persistent-term map replacement and 0.49 ms with ETS. ETS added about 28 ns per lookup. Use a separate entry per independently updated key; replacing a whole shared map also loses concurrent updates. Keep expired-entry cleanup and owner lifetime explicit. diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index d2edc6f3d..1a1f736a7 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -201,6 +201,14 @@ window), widening is the fix. ## registry host lookup +While the registry is open it publishes its runtime host in `albedo_registry_host` +(a `albedo_registry` table), and `registry.host` reads it without a call; a +session already running is likewise answered from `albedo_sessions` by +`registry.lookup`. Shutdown withdraws the host first, so every later read falls +back to the actor and gets its closed-daemon error. Only a session that must +start goes through the actor. With 8,000 concurrent clients the host+lookup pair +took 19.3 ms median through the actor and under 1 µs read directly. + `daemon/registry.host` owns the five-second runtime-host lookup. Callers retain `Result(Runtime, String)` and map failures at the HTTP boundary. Reuse this function rather than sending `Host` with a local copy of its timeout. Timer-driven operation and creation-receipt pruning runs on the single scheduling worker, not on the registry, so pruning behind a writer does not block host and loaded-session lookups. Session activation still registers its live owner on the writer, serialized with deletion claims, and can delay registry requests while that writer is busy. Page diff --git a/src/albedo/daemon/albedo_registry_host.erl b/src/albedo/daemon/albedo_registry_host.erl new file mode 100644 index 000000000..8f190aa86 --- /dev/null +++ b/src/albedo/daemon/albedo_registry_host.erl @@ -0,0 +1,18 @@ +%% The runtime host the session registry serves, readable without a call to the +%% registry actor. It is published while the registry is open and withdrawn when +%% it begins to close, so a reader that finds nothing asks the actor, which +%% refuses. +-module(albedo_registry_host). +-export([publish/2, withdraw/1, find/1]). + +-define(TABLE, albedo_registry_host). + +publish(Registry, Host) -> albedo_registry:register(?TABLE, Registry, Host). + +withdraw(Registry) -> albedo_registry:forget(?TABLE, Registry). + +find(Registry) -> + case albedo_registry:lookup(?TABLE, Registry) of + {ok, Host} -> {ok, Host}; + undefined -> {error, nil} + end. diff --git a/src/albedo/daemon/registry.gleam b/src/albedo/daemon/registry.gleam index bb8202288..0b55b37fc 100644 --- a/src/albedo/daemon/registry.gleam +++ b/src/albedo/daemon/registry.gleam @@ -393,6 +393,7 @@ fn serve(state: State, message: Message) -> actor.Next(State, a) { // caller queued behind the drain gets an answer, not a dead callee. let workers = workers(state) let host = state.host + withdraw_host(process.self()) process.spawn_unlinked(fn() { drain_within(deadline_ms, fn(step) { case stop_kernels { @@ -549,6 +550,10 @@ pub fn start( True -> Open False -> Orphaned } + case stage { + Open -> publish_host(process.self(), host) + _ -> Nil + } use saved <- result.try(case stage { Open -> conversation.list(ledger) _ -> Ok([]) @@ -1522,17 +1527,43 @@ fn call( |> result.flatten } +/// The host is read from a table the open registry publishes; a closing or +/// absent registry has withdrawn it, and the actor then answers with its error. pub fn host(registry: Subject(Message)) -> Result(runtime.Runtime, String) { - call(registry, Host) + case published_host(registry) { + Ok(host) -> Ok(host) + Error(_) -> call(registry, Host) + } } +/// A session already running is answered from the live table, without the +/// registry actor; only a session that must start goes through it. pub fn lookup( registry: Subject(Message), id: String, ) -> Result(session.Session, String) { - call(registry, Lookup(id, _)) + case published_host(registry), session.live(id) { + Ok(_), Some(worker) -> Ok(worker) + _, _ -> call(registry, Lookup(id, _)) + } } +fn published_host(registry: Subject(Message)) -> Result(runtime.Runtime, Nil) { + case process.subject_owner(registry) { + Ok(pid) -> find_host(pid) + Error(_) -> Error(Nil) + } +} + +@external(erlang, "albedo_registry_host", "publish") +fn publish_host(registry: process.Pid, host: runtime.Runtime) -> Nil + +@external(erlang, "albedo_registry_host", "withdraw") +fn withdraw_host(registry: process.Pid) -> Nil + +@external(erlang, "albedo_registry_host", "find") +fn find_host(registry: process.Pid) -> Result(runtime.Runtime, Nil) + pub fn existing( registry: Subject(Message), id: String, -- knotmirror 0.0.1 From 844d1ec44ee2052e277234f06cff1f635589d817 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:53:32 -0400 Subject: [PATCH 08/72] Name stalls with a bounded, rate-limited system monitor --- .../references/state-and-concurrency.md | 2 + robot-docs/runtime.md | 10 +++ src/albedo/daemon/albedo_stalls.erl | 78 +++++++++++++++++++ src/albedo/daemon/server.gleam | 4 + test/daemon/albedo_stalls_test.erl | 55 +++++++++++++ 5 files changed, 149 insertions(+) create mode 100644 src/albedo/daemon/albedo_stalls.erl create mode 100644 test/daemon/albedo_stalls_test.erl diff --git a/.agents/skills/gleam-design/references/state-and-concurrency.md b/.agents/skills/gleam-design/references/state-and-concurrency.md index eea654d9e..ca24f31c8 100644 --- a/.agents/skills/gleam-design/references/state-and-concurrency.md +++ b/.agents/skills/gleam-design/references/state-and-concurrency.md @@ -115,6 +115,8 @@ Compact quiet port owners and forwarding relays after frame bursts, not only on Read-mostly facts that every request asks an actor for belong in a table the actor publishes while it is open and withdraws before it closes, with the actor as fallback. Albedo's registry host and live-session lookups went from 19.3 ms median (8,000 concurrent callers queued on one actor) to under 1 µs. Withdraw first on shutdown so readers fall back to the actor's refusal instead of reading a closing owner. +Give long-lived processes a `proc_lib` label so a VM-wide monitor can name them: a stall line that says `{albedo_session, Id}` is actionable, one that says `gleam@otp@actor` is not. A system monitor must be rate-limited and bounded, because the events it reports arrive exactly when the VM is struggling. + Use `persistent_term` only after establishing that updates are rare and accepting its update costs. It is optimized for reads; replacing complex values can induce VM-wide garbage-collection work. It is not a default store for changing sessions or per-token state. [E03] Put changing rate-limit marks and TTL results in lifetime-owned ETS, not compound persistent terms. In albedo's OTP 29 probe with 8,000 parked processes, 200 account-limit updates took 4.66 ms with persistent-term map replacement and 0.49 ms with ETS. ETS added about 28 ns per lookup. Use a separate entry per independently updated key; replacing a whole shared map also loses concurrent updates. Keep expired-entry cleanup and owner lifetime explicit. diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index 1a1f736a7..75050e95a 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -160,6 +160,16 @@ Store and reader initialisers allow 60 seconds for disk I/O and dirty-I/O schedu Reader connections use private SQLite caches with a 128 KiB suggested page-cache limit each (512 KiB across four readers), rather than four default-sized caches. Schema and connection allocations are additional; this is not a total memory cap. Reader connections belong to the store lifetime and close before the writer. A failed connection owner fails the store rather than leaving a live handle with reduced capacity. Private in-memory databases retain one connection and serialize snapshots with writes. Their snapshots still enforce read-only access. +## stall monitor + +`daemon/albedo_stalls.erl` holds the VM's one `erlang:system_monitor`. It logs +`long_gc` and `long_schedule` over 250 ms, a heap past 4 Mwords (32 MiB), and a +busy port, each naming the process by its `proc_lib` label (else registered name +or initial call). At most ten lines go out per ten-second window, followed by +how many were left out, and a burst past a hundred queued events is counted and +dropped, so a storm cannot grow its mailbox. Nothing else may call +`system_monitor`: a second caller silently replaces this one. + ## quiet session actors Each session coalesces activity into one 100 ms timer. The first quiet tick diff --git a/src/albedo/daemon/albedo_stalls.erl b/src/albedo/daemon/albedo_stalls.erl new file mode 100644 index 000000000..9092b04f4 --- /dev/null +++ b/src/albedo/daemon/albedo_stalls.erl @@ -0,0 +1,78 @@ +%% Names the process behind a stall. The VM allows one system monitor; this one +%% reports long garbage collections, long schedules, very large heaps and busy +%% ports, at most Max lines per window, then says how many it left out. Its mailbox +%% is bounded: a burst is counted and dropped, never queued without limit. +-module(albedo_stalls). +-export([start/0, start/1]). + +-define(WINDOW_MS, 10000). +-define(MAX_LINES, 10). +-define(MAX_QUEUE, 100). + +start() -> start(#{}). + +%% Options: long_gc and long_schedule in ms, large_heap in words, report/1 for +%% each line, and name (the registered name, `undefined` for none). +start(Options) -> + Name = maps:get(name, Options, ?MODULE), + case Name =/= undefined andalso whereis(Name) of + Pid when is_pid(Pid) -> Pid; + _ -> + Pid = spawn(fun() -> init(Options) end), + Name =:= undefined orelse register(Name, Pid), + Pid + end. + +init(Options) -> + erlang:system_monitor(self(), [ + {long_gc, maps:get(long_gc, Options, 250)}, + {long_schedule, maps:get(long_schedule, Options, 250)}, + {large_heap, maps:get(large_heap, Options, 4 * 1024 * 1024)}, + busy_port]), + Report = maps:get(report, Options, fun log/1), + loop(Report, erlang:monotonic_time(millisecond), 0, 0). + +loop(Report, Since, Lines, Dropped) -> + receive + {monitor, Pid, Kind, Info} -> + Now = erlang:monotonic_time(millisecond), + {Since1, Lines1, Dropped1} = window(Report, Now, Since, Lines, Dropped), + Overloaded = element(2, process_info(self(), message_queue_len)) > ?MAX_QUEUE, + case Lines1 < ?MAX_LINES andalso not Overloaded of + true -> + Report(describe(Pid, Kind, Info)), + loop(Report, Since1, Lines1 + 1, Dropped1); + false -> + loop(Report, Since1, Lines1, Dropped1 + 1) + end + end. + +%% A new window reports what the last one left out. +window(Report, Now, Since, _Lines, Dropped) when Now - Since >= ?WINDOW_MS -> + Dropped > 0 andalso Report(io_lib:format("stall: ~b more events left out", [Dropped])), + {Now, 0, 0}; +window(_, _, Since, Lines, Dropped) -> {Since, Lines, Dropped}. + +describe(Pid, Kind, Info) when is_pid(Pid) -> + io_lib:format("stall: ~s ~s in ~s", [Kind, summary(Kind, Info), name(Pid)]); +describe(Port, Kind, Info) -> + io_lib:format("stall: ~s ~s on ~p", [Kind, summary(Kind, Info), Port]). + +summary(long_gc, Info) -> io_lib:format("~b ms", [proplists:get_value(timeout, Info, 0)]); +summary(long_schedule, Info) when is_list(Info) -> io_lib:format("~b ms", [proplists:get_value(timeout, Info, 0)]); +summary(large_heap, Info) -> io_lib:format("~b words", [proplists:get_value(heap_size, Info, 0)]); +summary(_, _) -> "". + +%% The label a process gave itself, else its registered name or initial call. +name(Pid) -> + case proc_lib:get_label(Pid) of + undefined -> + case process_info(Pid, [registered_name, initial_call]) of + [{registered_name, N}, _] when N =/= [] -> io_lib:format("~p", [N]); + [_, {initial_call, MFA}] -> io_lib:format("~p", [MFA]); + undefined -> "an exited process" + end; + Label -> io_lib:format("~0p", [Label]) + end. + +log(Line) -> logger:warning("~s", [Line]). diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index 64992fdc5..c1f5008eb 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -722,6 +722,7 @@ pub fn main() -> Nil { } // Before readiness, so a client that sees the daemon can already inspect it. inspect(home) + watch_stalls() let assert Ok(_) = ready(home, port, webhook_port, token) // After readiness, so loading every reachable module never delays a client. preload_code() @@ -791,6 +792,9 @@ fn ready( @external(erlang, "albedo_inspect", "start") fn inspect(home: String) -> Nil +@external(erlang, "albedo_stalls", "start") +fn watch_stalls() -> process.Pid + @external(erlang, "albedo_code", "start") fn preload_code() -> Nil diff --git a/test/daemon/albedo_stalls_test.erl b/test/daemon/albedo_stalls_test.erl new file mode 100644 index 000000000..9b6decb8c --- /dev/null +++ b/test/daemon/albedo_stalls_test.erl @@ -0,0 +1,55 @@ +%% The VM's one system monitor cannot be driven through the HTTP API: this +%% proves a stall names its labelled process and a burst stays bounded. +-module(albedo_stalls_test). +-include_lib("eunit/include/eunit.hrl"). + +names_the_process_with_a_large_heap_test() -> + Previous = erlang:system_monitor(), + Parent = self(), + Monitor = albedo_stalls:start(#{name => undefined, large_heap => 100000, + report => fun(Line) -> Parent ! {stall, lists:flatten(Line)} end}), + try + spawn(fun() -> + proc_lib:set_label({albedo_session, <<"stalled-fixture">>}), + Big = lists:seq(1, 2000000), + erlang:garbage_collect(), + _ = length(Big) + end), + Line = await(<<"stalled-fixture">>), + ?assertMatch({_, _}, binary:match(list_to_binary(Line), <<"large_heap">>)) + after + exit(Monitor, kill), + restore(Previous) + end. + +a_burst_is_limited_to_the_window_budget_test() -> + Previous = erlang:system_monitor(), + Parent = self(), + Monitor = albedo_stalls:start(#{name => undefined, large_heap => 10000, + report => fun(Line) -> Parent ! {stall, lists:flatten(Line)} end}), + try + [spawn(fun() -> _ = length(lists:seq(1, 200000)), erlang:garbage_collect() end) + || _ <- lists:seq(1, 60)], + timer:sleep(1500), + ?assert(count() =< 10) + after + exit(Monitor, kill), + restore(Previous) + end. + +%% Other tests' processes are heard too; skip lines that name someone else. +await(Needle) -> + receive + {stall, Line} -> + case binary:match(list_to_binary(Line), Needle) of + nomatch -> await(Needle); + _ -> Line + end + after 10000 -> error(no_stall_reported) + end. + +count() -> count(0). +count(N) -> receive {stall, _} -> count(N + 1) after 0 -> N end. + +restore(undefined) -> erlang:system_monitor(undefined); +restore({Pid, Options}) -> erlang:system_monitor(Pid, Options). -- knotmirror 0.0.1 From 56c5638ced455d8abc9bf45d6fa879c32bebaa9d Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:56:03 -0400 Subject: [PATCH 09/72] ci: run the gates on the density branch too --- .tangled/workflows/nix.yml | 2 +- .tangled/workflows/test.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.tangled/workflows/nix.yml b/.tangled/workflows/nix.yml index f913af9bf..b84632efa 100644 --- a/.tangled/workflows/nix.yml +++ b/.tangled/workflows/nix.yml @@ -2,7 +2,7 @@ # never does: it runs from the checkout, not the packaged daemon and CLI. when: - event: ["push", "pull_request"] - branch: ["main"] + branch: ["main", "density"] - event: ["manual"] engine: microvm diff --git a/.tangled/workflows/test.yml b/.tangled/workflows/test.yml index c8010cf6c..d5de859aa 100644 --- a/.tangled/workflows/test.yml +++ b/.tangled/workflows/test.yml @@ -2,7 +2,7 @@ # the local ./test.sh runs only the e2e areas a change touches. when: - event: ["push", "pull_request"] - branch: ["main"] + branch: ["main", "density"] - event: ["manual"] engine: microvm -- knotmirror 0.0.1 From 126dea95cd6e4be01c4b2cc3d7d098bbd75b35e2 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:31:37 -0400 Subject: [PATCH 10/72] Define single-use fresh kernel spare lifecycle API --- .../extensions/python/albedo_python.erl | 6 +++ .../harness/extensions/python/kernel.gleam | 41 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index a8a2ebb9e..06af99a94 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -23,6 +23,12 @@ -export([observation/1, stop_recorded/2, stop_jobs/1, job_list/1, job_read/4]). -export([watch/2, unwatch/1]). -export([loop/1, relay_loop/3]). %% hibernate continuations +-export([start_spare/1, stop_spare/1, spare_current/1]). + +start_spare(_) -> {error, {unavailable, <<"fresh spare startup is not installed">>}}. +stop_spare(_) -> {ok, nil}. +spare_current(_) -> false. + -define(PROTOCOL, 1). %% Bridge, kernel and plugins, end to end. A kernel that exits fails at once diff --git a/src/albedo/harness/extensions/python/kernel.gleam b/src/albedo/harness/extensions/python/kernel.gleam index fb2f88219..46a8fd409 100644 --- a/src/albedo/harness/extensions/python/kernel.gleam +++ b/src/albedo/harness/extensions/python/kernel.gleam @@ -21,6 +21,17 @@ import gleam/string pub type Kernel +pub type Spare + +@external(erlang, "albedo_python", "start_spare") +pub fn start_spare(owner: process.Pid) -> Result(Spare, Error) + +@external(erlang, "albedo_python", "stop_spare") +pub fn stop_spare(spare: Spare) -> Result(Nil, String) + +@external(erlang, "albedo_python", "spare_current") +pub fn spare_current(spare: Spare) -> Bool + pub type Observation { Observation( instance_id: String, @@ -500,6 +511,36 @@ pub fn open( cwd: String, host: fn(String, Dynamic) -> String, modules: List(String), +) -> Result(#(Kernel, Opened), Error) { + open_with_spare(store, session, cwd, host, modules, None) +} + +/// Open the session's kernel, consuming the supplied spare on every outcome. +pub fn open_with_spare( + store: store.Store, + session: String, + cwd: String, + host: fn(String, Dynamic) -> String, + modules: List(String), + spare: Option(Spare), +) -> Result(#(Kernel, Opened), Error) { + let opened = open_inner(store, session, cwd, host, modules) + case spare { + Some(spare) -> { + let _ = stop_spare(spare) + Nil + } + None -> Nil + } + opened +} + +fn open_inner( + store: store.Store, + session: String, + cwd: String, + host: fn(String, Dynamic) -> String, + modules: List(String), ) -> Result(#(Kernel, Opened), Error) { use _ <- result.try( reconcile_stages(store, session) |> result.map_error(Unavailable), -- knotmirror 0.0.1 From cccd43429737f59fa8882daaeeea176fbc9ba707 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:45:26 -0400 Subject: [PATCH 11/72] Adopt single-use preimported Python kernel spares --- priv/python/albedo_bridge.py | 50 +++++++ priv/python/albedo_spare.py | 62 +++++++++ robot-docs/kernel.md | 19 +++ .../extensions/python/albedo_python.erl | 126 ++++++++++++++++-- .../harness/extensions/python/kernel.gleam | 48 +++++-- test/e2e/albedo_kernel_spare_probe.erl | 38 ++++++ test/e2e/kernel_spare_test.py | 23 ++++ test/manual/agent_density.py | 11 +- 8 files changed, 356 insertions(+), 21 deletions(-) create mode 100644 priv/python/albedo_spare.py create mode 100644 test/e2e/albedo_kernel_spare_probe.erl create mode 100644 test/e2e/kernel_spare_test.py diff --git a/priv/python/albedo_bridge.py b/priv/python/albedo_bridge.py index ead2474fa..8c66f474a 100644 --- a/priv/python/albedo_bridge.py +++ b/priv/python/albedo_bridge.py @@ -30,6 +30,7 @@ from __future__ import annotations import contextlib import errno +import json import os import socket import subprocess @@ -141,7 +142,56 @@ def framed() -> list[str]: return [sys.argv[0], *argv] +def spare() -> None: + """Keep a detached fresh interpreter until one adoption or owner EOF.""" + script = os.path.join(os.path.dirname(KERNEL), "albedo_spare.py") + child = subprocess.Popen( + [sys.executable, "-u", script, os.environ.get("ALBEDO_HOME", "")], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=sys.stderr, + start_new_session=True, + close_fds=True, + ) + adopted = False + try: + assert child.stdout is not None and child.stdin is not None + ready = child.stdout.readline(65536) + if not ready or not isinstance(json.loads(ready).get("ready"), str): + raise RuntimeError("spare exited before imports completed") + sys.stdout.buffer.write(ready) + sys.stdout.buffer.flush() + line = sys.stdin.buffer.readline(1024 * 1024 + 1) + if not line: + return + spec = json.loads(line) + os.makedirs(spec["run_dir"], mode=0o700, exist_ok=True) + spec["environment"] = dict(os.environ) + child.stdin.write((json.dumps(spec) + "\n").encode()) + child.stdin.close() + deadline = time.monotonic() + START_TIMEOUT + while time.monotonic() < deadline: + connection = connect(spec["run_dir"]) + if connection is not None: + connection.close() + adopted = True + print(json.dumps({"adopted": True}), flush=True) + return + if child.poll() is not None: + raise RuntimeError("spare exited during adoption") + time.sleep(0.001) + raise RuntimeError("spare adoption timed out") + finally: + if not adopted: + with contextlib.suppress(ProcessLookupError): + child.kill() + child.wait() + + def main(argv: list[str]) -> None: + if argv[1:2] == ["spare"]: + spare() + return if argv[1:] == ["--frame"]: argv = framed() mode, run_dir = argv[1], argv[2] diff --git a/priv/python/albedo_spare.py b/priv/python/albedo_spare.py new file mode 100644 index 000000000..0486348aa --- /dev/null +++ b/priv/python/albedo_spare.py @@ -0,0 +1,62 @@ +"""A fresh interpreter waiting for one kernel identity, never reused.""" + +from __future__ import annotations + +import importlib +import io +import json +import os +import sys + +import albedo_bundle +import albedo_cells +import albedo_proc + +# Import trusted packaged modules only; setup needs the adopting session's host. +PREIMPORT = ( + "run work mail agents paperclips artifacts files memory commands remote browser web_search skills hook" +).split() + + +def main() -> None: + for name in PREIMPORT: + importlib.import_module("albedo_plugins." + name) + bundle = albedo_bundle.digest() + print( + json.dumps( + { + "ready": bundle, + "pid": os.getpid(), + "pgid": os.getpgrp(), + "leader": albedo_proc.leader_token(os.getpid()), + } + ), + flush=True, + ) + line = sys.stdin.buffer.readline(1024 * 1024 + 1) + if len(line) > 1024 * 1024 or not line.endswith(b"\n"): + raise ValueError("invalid spare adoption frame") + spec = json.loads(line) + if bundle != albedo_bundle.digest(): + raise ValueError("spare bundle changed before adoption") + if not isinstance(spec, dict) or not all( + isinstance(spec.get(key), str) for key in ("cwd", "run_dir", "modules", "token") + ): + raise ValueError("invalid spare adoption identity") + environment = spec.get("environment") + if not isinstance(environment, dict) or not all( + isinstance(key, str) and isinstance(value, str) + for key, value in environment.items() + ): + raise ValueError("invalid spare adoption environment") + os.chdir(spec["cwd"]) + os.environ.clear() + os.environ.update(environment) + # The ordinary detached handshake still reads the secret from stdin. + sys.stdin = io.TextIOWrapper(io.BytesIO((spec["token"] + "\n").encode())) + sys.argv = [sys.argv[0], "--run", spec["run_dir"], spec["modules"]] + albedo_cells.main() + + +if __name__ == "__main__": + main() diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index b4d448d1e..dc7ab9b25 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -382,6 +382,25 @@ a kernel run with plain `albedo_kernel.py ` (no `--run`) keeps the old raw stdio protocol and dies with its pipe: the remote plugin's targets use that. +## fresh spares + +`albedo_spare.py` imports the kernel and packaged default plugins without calling +plugin setup or starting kernel threads. A monitored bridge keeps its detached +process waiting on one private stdin adoption frame. Adoption installs the +session's cwd, sanitized launcher environment, module list, run directory, and +token, then starts the ordinary kernel. A spare is consumed once; it never sees +a second agent. Namespace restore still uses the existing state file. + +The native custodian monitors the runtime owner. Stopping an unused spare checks +its process group is gone; an adopted kernel becomes the ordinary link's owned +process and survives daemon detachment as before. A source-bundle change rejects +adoption, cleans the spare, and falls back to a cold launch. `spare_current` only +checks custodian liveness; the adoption checks the source digest again. + +`python.live_work` reads only the last published count of cells and local/remote +jobs, without messaging a blocked owner. Unknown is an error, not zero. A session +with a live job or cell must retain its kernel. + ## handshake the daemon writes `{"attach": {"kernel", "token", "ack", "grace"}}` first. the diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 06af99a94..14c0ca17b 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -23,11 +23,8 @@ -export([observation/1, stop_recorded/2, stop_jobs/1, job_list/1, job_read/4]). -export([watch/2, unwatch/1]). -export([loop/1, relay_loop/3]). %% hibernate continuations --export([start_spare/1, stop_spare/1, spare_current/1]). +-export([start_spare/1, stop_spare/1, spare_current/1, live_work/1]). -start_spare(_) -> {error, {unavailable, <<"fresh spare startup is not installed">>}}. -stop_spare(_) -> {ok, nil}. -spare_current(_) -> false. -define(PROTOCOL, 1). @@ -56,8 +53,115 @@ spare_current(_) -> false. -define(REMOTE_REATTACH_MAX_MS, 30000). -define(GRACE_MARGIN_S, 60). %% past a remote kernel's grace before it is given up +%% A custodian owns the launcher until a detached spare is adopted or stopped. +start_spare(Owner) -> + Parent = self(), Ref = make_ref(), + {Pid, Mon} = spawn_monitor(fun() -> spare_start(Owner, Parent, Ref) end), + receive + {Ref, Result} -> demonitor(Mon, [flush]), Result; + {'DOWN', Mon, process, Pid, Reason} -> {error, {unavailable, detail(Reason)}} + after ?STARTUP_TIMEOUT -> + Pid ! stop, + demonitor(Mon, [flush]), + {error, {unavailable, <<"spare startup timed out">>}} + end. + +spare_current({spare, Pid}) -> is_process_alive(Pid). + +stop_spare({spare, Pid}) -> + case spare_request(Pid, stop) of + {error, lost} -> {ok, nil}; + Result -> Result + end. + +spare_request(Pid, Request) -> + Alias = alias(), Mon = monitor(process, Pid), + Pid ! {spare_call, Alias, Mon, Request}, + Result = receive + {Mon, Reply} -> Reply; + {'DOWN', Mon, process, Pid, _} -> {error, lost} + after ?STARTUP_TIMEOUT + ?HELPER_WAIT -> {error, <<"spare did not answer">>} + end, + unalias(Alias), demonitor(Mon, [flush]), Result. + +spare_start(Owner, Parent, Ref) -> + process_flag(trap_exit, true), + Watch = monitor(process, Owner), + case paths() of + {error, Reason} -> Parent ! {Ref, {error, Reason}}; + {ok, {Python, Bridge}} -> + Port = open_port({spawn_executable, binary_to_list(Python)}, + [binary, {line, 1048576}, use_stdio, exit_status, hide, + {args, ["-u", binary_to_list(Bridge), "spare", os:getenv("ALBEDO_HOME", "")]}, {env, clean_environment()}]), + receive + {Port, {data, {eol, Data}}} -> + Ready = try json:decode(Data) catch _:_ -> #{} end, + case Ready of + #{<<"ready">> := Bundle, <<"pid">> := Pid} when is_binary(Bundle), is_integer(Pid), Pid > 1 -> + albedo_inspect:label(<<"albedo_spare">>, integer_to_binary(Pid)), + Parent ! {Ref, {ok, {spare, self()}}}, + spare_wait(Port, Watch, target_of(Ready)); + _ -> port_close(Port), Parent ! {Ref, {error, {unavailable, <<"invalid spare readiness">>}}} + end; + {Port, {exit_status, Status}} -> Parent ! {Ref, {error, {unavailable, detail(Status)}}}; + {'DOWN', Watch, process, Owner, _} -> port_close(Port) + after ?STARTUP_TIMEOUT -> + port_close(Port), Parent ! {Ref, {error, {unavailable, <<"spare imports timed out">>}}} + end + end. + +spare_wait(Port, Watch, Target) -> + receive + {spare_call, From, Ref, stop} -> + case spare_cleanup(Port, Target) of + {ok, nil} -> From ! {Ref, {ok, nil}}; + Error -> From ! {Ref, Error}, spare_wait(Port, Watch, Target) + end; + {spare_call, From, Ref, {adopt, Spec}} -> + port_command(Port, [json:encode(Spec), $\n]), + spare_adopting(Port, Watch, Target, From, Ref, false); + stop -> spare_cleanup(Port, Target); + {'DOWN', Watch, process, _, _} -> spare_cleanup(Port, Target); + {Port, {exit_status, _}} -> spare_cleanup(Port, Target); + {'EXIT', Port, _} -> spare_cleanup(Port, Target) + end. + +spare_adopting(Port, Watch, Target, From, Ref, Adopted) -> + receive + {Port, {data, {eol, Data}}} -> + Confirmed = try json:decode(Data) =:= #{<<"adopted">> => true} catch _:_ -> false end, + spare_adopting(Port, Watch, Target, From, Ref, Confirmed); + {Port, {exit_status, 0}} when Adopted -> From ! {Ref, {ok, nil}}; + {Port, {exit_status, _}} -> + case spare_cleanup(Port, Target) of + {ok, nil} -> From ! {Ref, {error, lost}}; + Error -> From ! {Ref, Error} + end; + {'DOWN', Watch, process, _, _} -> + spare_cleanup(Port, Target), From ! {Ref, {error, <<"spare owner stopped">>}} + after ?STARTUP_TIMEOUT -> + spare_cleanup(Port, Target), From ! {Ref, {error, <<"spare adoption timed out">>}} + end. + +spare_cleanup(Port, Target) -> + catch port_close(Port), + verdict(supervise(#{remote => none}, [target_spec(<<"spare">>, Target)], ?TERM_MS, ?KILL_MS)). + +warm_launch(S, Launch) -> + case maps:get(spare, S, none) of + none -> launch(Launch); + {some, {spare, Pid}} -> + Spec = #{cwd => maps:get(cwd, S), run_dir => maps:get(run_dir, S), + modules => maps:get(modules, S), token => maps:get(token, S)}, + case spare_request(Pid, {adopt, Spec}) of + {ok, nil} -> 0; + {error, lost} -> launch(Launch); + {error, _} -> ?GONE + end + end. + %% Boot is the Gleam kernel.Boot record; Link is kernel.Link. -start({boot, Owner, Python, Bridge, Cwd, Host, Modules, Link, RunDir, Kernel, Token, Grace, OutSeq, Owned, Fresh, Remote}) -> +start({boot, Owner, Python, Bridge, Cwd, Host, Modules, Link, RunDir, Kernel, Token, Grace, OutSeq, Owned, Fresh, Remote, Spare}) -> Parent = self(), Ref = make_ref(), {Pid, Mon} = spawn_monitor(fun() -> albedo_inspect:label(<<"albedo_kernel">>, Kernel), @@ -70,7 +174,7 @@ start({boot, Owner, Python, Bridge, Cwd, Host, Modules, Link, RunDir, Kernel, To put(albedo_kernel_observation_table, ObservationTable), S = #{port => none, host => Host, link => Link, owner => Owner, active => none, events => [], groups => Groups, external => 0, awaited_external => 0, external_jobs => [], cells => 0, target => Target, - python => Python, bridge => Bridge, cwd => Cwd, remote => Remote, + python => Python, bridge => Bridge, cwd => Cwd, remote => Remote, spare => Spare, modules => Modules, run_dir => RunDir, kernel => Kernel, token => Token, observation_table => ObservationTable, grace => Grace, in => 0, acked => 0, kack => 0, out => OutSeq, @@ -133,9 +237,10 @@ open_relay(S = #{python := Python, bridge := Bridge, run_dir := RunDir}, Mode) - end, Socket = <>, Kernel = maps:get(kernel, S), + Warm = maps:with([spare, cwd, run_dir, modules, token], S), Relay = spawn(fun() -> albedo_inspect:label(<<"albedo_relay">>, Kernel), - relay(Owner, Launch, Socket) + relay(Owner, Launch, Socket, Warm) end), {ok, handshake(S#{bundle => bundle_digest(filename:dirname(Bridge))}, Relay, [])}. @@ -149,9 +254,9 @@ handshake(S, Port, First) -> %% {self(), {data, Frame}} and {self(), {exit_status, Status}} go out, %% {Owner, {command, Frame}} and {Owner, close} come in. Starting a kernel %% runs the bridge script's launch mode first, which exits once it listens. -relay(Owner, Launch, Socket) -> +relay(Owner, Launch, Socket, Warm) -> Watch = monitor(process, Owner), - Status = case Launch of none -> 0; _ -> launch(Launch) end, + Status = case Launch of none -> 0; _ -> warm_launch(Warm, Launch) end, Connected = Status =:= 0 andalso gen_tcp:connect({local, Socket}, 0, [local, binary, {packet, 4}, {active, true}]), case Connected of @@ -329,6 +434,9 @@ execute(Pid, Id, Data, Timeout) -> call(Pid, {execute, Id, Data, Timeout}). %% Background jobs whose groups are still owned: local job groups plus the %% remote jobs the remote plugin reported through "jobs" frames, plus running %% cells. A released kernel would end them, so the idle sweep keeps it alive. +live_work(Pid) -> + cached_call(Pid, job_count, fun() -> {error, nil} end). + job_count(Pid) -> case cached_call(Pid, job_count, fun() -> call(Pid, job_count) end) of {ok, Count} when is_integer(Count), Count >= 0 -> Count; diff --git a/src/albedo/harness/extensions/python/kernel.gleam b/src/albedo/harness/extensions/python/kernel.gleam index 46a8fd409..3fb3c23b9 100644 --- a/src/albedo/harness/extensions/python/kernel.gleam +++ b/src/albedo/harness/extensions/python/kernel.gleam @@ -23,6 +23,10 @@ pub type Kernel pub type Spare +/// Last published live cells and jobs; unknown never means idle. +@external(erlang, "albedo_python", "live_work") +pub fn live_work(kernel: Kernel) -> Result(Int, Nil) + @external(erlang, "albedo_python", "start_spare") pub fn start_spare(owner: process.Pid) -> Result(Spare, Error) @@ -124,6 +128,7 @@ type Boot { owned: String, fresh: Bool, remote: Option(Remote), + spare: Option(Spare), ) } @@ -524,15 +529,15 @@ pub fn open_with_spare( modules: List(String), spare: Option(Spare), ) -> Result(#(Kernel, Opened), Error) { - let opened = open_inner(store, session, cwd, host, modules) - case spare { - Some(spare) -> { - let _ = stop_spare(spare) - Nil - } - None -> Nil + let opened = open_inner(store, session, cwd, host, modules, spare) + let cleanup = case spare { + Some(spare) -> stop_spare(spare) + None -> Ok(Nil) + } + case cleanup { + Ok(_) -> opened + Error(reason) -> Error(Unavailable("spare cleanup failed: " <> reason)) } - opened } fn open_inner( @@ -541,11 +546,18 @@ fn open_inner( cwd: String, host: fn(String, Dynamic) -> String, modules: List(String), + spare: Option(Spare), ) -> Result(#(Kernel, Opened), Error) { use _ <- result.try( reconcile_stages(store, session) |> result.map_error(Unavailable), ) - use #(modules, runs, boot) <- result.try(booter(store, cwd, host, modules)) + use #(modules, runs, boot) <- result.try(booter_with_spare( + store, + cwd, + host, + modules, + spare, + )) case reattach(store, session, cwd, modules, boot) { Ok(kernel) -> Ok(#(kernel, Attached)) Error(Nil) -> { @@ -660,6 +672,23 @@ fn booter( fn(link.Record, Bool) -> Result(Kernel, Error), ), Error, +) { + booter_with_spare(store, cwd, host, modules, None) +} + +fn booter_with_spare( + store: store.Store, + cwd: String, + host: fn(String, Dynamic) -> String, + modules: List(String), + spare: Option(Spare), +) -> Result( + #( + String, + Result(String, Error), + fn(link.Record, Bool) -> Result(Kernel, Error), + ), + Error, ) { use #(python, bridge) <- result.try(paths()) use #(path, runs, reach) <- result.try(place(cwd)) @@ -683,6 +712,7 @@ fn booter( owned: record.owned, fresh: fresh, remote: remote, + spare: spare, )) }), ) diff --git a/test/e2e/albedo_kernel_spare_probe.erl b/test/e2e/albedo_kernel_spare_probe.erl new file mode 100644 index 000000000..8abcab558 --- /dev/null +++ b/test/e2e/albedo_kernel_spare_probe.erl @@ -0,0 +1,38 @@ +%% Exercise fresh-spare adoption through the real kernel/link stack. +-module(albedo_kernel_spare_probe). +-export([run_json/2]). + +run_json(Id, Cwd) -> + [Name] = [N || N <- registered(), lists:prefix("albedo_registry", atom_to_list(N))], + {ok, Runtime} = 'albedo@daemon@registry':host('gleam@erlang@process':named_subject(Name)), + Ledger = 'albedo@harness@runtime':ledger(Runtime), + Owner = 'albedo@daemon@store':owner(Ledger), + Host = fun(_, _) -> <<"{\"ok\":true,\"value\":null}">> end, + {ok, Spare} = albedo_python:start_spare(Owner), + true = albedo_python:spare_current(Spare), + Start = erlang:monotonic_time(microsecond), + {ok, {Kernel, _}} = 'albedo@harness@extensions@python@kernel':open_with_spare( + Ledger, Id, Cwd, Host, [<<"run">>], {some, Spare}), + AdoptUs = erlang:monotonic_time(microsecond) - Start, + false = albedo_python:spare_current(Spare), + {ok, nil} = albedo_python:stop_spare(Spare), + try + Defined = execute(Kernel, <<"define">>, <<"import fractions\nanswer=7\nrows=[1,2,3]\ndef helper(x):\n return fractions.Fraction(x,answer)\nprint('defined')">>), + Path = <>, + {ok, _} = 'albedo@harness@extensions@python@kernel':snapshot(Kernel, Path, 5000), + {ok, nil} = albedo_python:stop(Kernel), + {ok, Spare2} = albedo_python:start_spare(Owner), + {ok, {Restored, _}} = 'albedo@harness@extensions@python@kernel':open_with_spare( + Ledger, Id, Cwd, Host, [<<"run">>], {some, Spare2}), + try + {ok, _} = 'albedo@harness@extensions@python@kernel':restore(Restored, Path, 5000), + Recalled = execute(Restored, <<"recall">>, <<"assert helper(21)==3 and rows==[1,2,3]\nprint('SPARE_OK')">>), + {ok, Idle} = albedo_python:live_work(Restored), + json:encode(#{defined => Defined, recalled => Recalled, live_work => Idle, adopt_us => AdoptUs}) + after albedo_python:stop(Restored) end + after albedo_python:stop(Kernel) end. + +execute(Kernel, Id, Code) -> + Data = iolist_to_binary(json:encode(#{type => <<"execute">>, id => Id, code => Code})), + {ok, Reply} = albedo_python:execute(Kernel, Id, Data, 5000), + json:decode(Reply). diff --git a/test/e2e/kernel_spare_test.py b/test/e2e/kernel_spare_test.py new file mode 100644 index 000000000..1d69cd406 --- /dev/null +++ b/test/e2e/kernel_spare_test.py @@ -0,0 +1,23 @@ +"""Fresh spare adoption restores a namespace through the daemon's real link stack.""" + +from pathlib import Path +import unittest + +from harness import Albedo, exclusive +from inspect_support import Inspection + + +@exclusive +class KernelSpareTests(unittest.TestCase): + def test_spare_is_single_use_and_restores_definitions(self): + with Albedo(prepare=lambda app: app.env.update(ALBEDO_INSPECT="1")) as app: + session = app.session() + probe = Inspection( + app, Path(__file__).with_name("albedo_kernel_spare_probe.erl") + ) + result = probe.call_json( + "run_json", f'[<<"{session}">>, <<"{app.workspace}">>]' + ) + self.assertEqual(result["recalled"]["status"], "ok", result) + self.assertIn("SPARE_OK", result["recalled"]["output"]) + self.assertEqual(result["live_work"], 0) diff --git a/test/manual/agent_density.py b/test/manual/agent_density.py index 0bf4c3f66..1ac122442 100644 --- a/test/manual/agent_density.py +++ b/test/manual/agent_density.py @@ -56,13 +56,18 @@ def processes(app): result = [{"pid": app.connection["pid"], "kind": "daemon"}] for line in listing.splitlines(): pid, command = line.strip().split(None, 1) - if str(app.home) + "/run/" in command and any( - name in command for name in ("albedo_kernel.py", "albedo_bridge.py") + if str(app.home) in command and any( + name in command + for name in ("albedo_kernel.py", "albedo_bridge.py", "albedo_spare.py") ): result.append( { "pid": int(pid), - "kind": "kernel" if "albedo_kernel.py" in command else "bridge", + "kind": "spare" + if "albedo_spare.py" in command + else "kernel" + if "albedo_kernel.py" in command + else "bridge", } ) return result -- knotmirror 0.0.1 From caf8b34087de94348f48089fc1a098ec91d5f14b Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:47:59 -0400 Subject: [PATCH 12/72] Preserve spare cleanup result shape before cold fallback --- .../extensions/python/albedo_python.erl | 5 +++- test/e2e/albedo_kernel_spare_probe.erl | 24 +++++++++++++++-- test/e2e/kernel_spare_test.py | 27 ++++++++++++++++++- 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 14c0ca17b..9fa81d8f8 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -145,7 +145,10 @@ spare_adopting(Port, Watch, Target, From, Ref, Adopted) -> spare_cleanup(Port, Target) -> catch port_close(Port), - verdict(supervise(#{remote => none}, [target_spec(<<"spare">>, Target)], ?TERM_MS, ?KILL_MS)). + case verdict(supervise(#{remote => none}, [target_spec(<<"spare">>, Target)], ?TERM_MS, ?KILL_MS)) of + ok -> {ok, nil}; + Error -> Error + end. warm_launch(S, Launch) -> case maps:get(spare, S, none) of diff --git a/test/e2e/albedo_kernel_spare_probe.erl b/test/e2e/albedo_kernel_spare_probe.erl index 8abcab558..174b21ab5 100644 --- a/test/e2e/albedo_kernel_spare_probe.erl +++ b/test/e2e/albedo_kernel_spare_probe.erl @@ -1,8 +1,8 @@ %% Exercise fresh-spare adoption through the real kernel/link stack. -module(albedo_kernel_spare_probe). --export([run_json/2]). +-export([run_json/3, stop_json/0]). -run_json(Id, Cwd) -> +run_json(Id, Cwd, ChangedBundle) -> [Name] = [N || N <- registered(), lists:prefix("albedo_registry", atom_to_list(N))], {ok, Runtime} = 'albedo@daemon@registry':host('gleam@erlang@process':named_subject(Name)), Ledger = 'albedo@harness@runtime':ledger(Runtime), @@ -10,6 +10,10 @@ run_json(Id, Cwd) -> Host = fun(_, _) -> <<"{\"ok\":true,\"value\":null}">> end, {ok, Spare} = albedo_python:start_spare(Owner), true = albedo_python:spare_current(Spare), + case ChangedBundle of + <<>> -> ok; + PathToChange -> ok = file:write_file(PathToChange, <<"\n# changed after spare import\n">>, [append]) + end, Start = erlang:monotonic_time(microsecond), {ok, {Kernel, _}} = 'albedo@harness@extensions@python@kernel':open_with_spare( Ledger, Id, Cwd, Host, [<<"run">>], {some, Spare}), @@ -32,6 +36,22 @@ run_json(Id, Cwd) -> after albedo_python:stop(Restored) end after albedo_python:stop(Kernel) end. +stop_json() -> + Owner = spawn(fun() -> receive stop -> ok end end), + {ok, Spare} = albedo_python:start_spare(Owner), + {ok, nil} = albedo_python:stop_spare(Spare), + false = albedo_python:spare_current(Spare), + {ok, Spare2} = albedo_python:start_spare(Owner), + Owner ! stop, + Wait = fun Again(0) -> error(spare_outlived_owner); + Again(N) -> case albedo_python:spare_current(Spare2) of + false -> ok; + true -> receive after 10 -> Again(N - 1) end + end + end, + Wait(500), + json:encode(#{stopped => true}). + execute(Kernel, Id, Code) -> Data = iolist_to_binary(json:encode(#{type => <<"execute">>, id => Id, code => Code})), {ok, Reply} = albedo_python:execute(Kernel, Id, Data, 5000), diff --git a/test/e2e/kernel_spare_test.py b/test/e2e/kernel_spare_test.py index 1d69cd406..4855638a9 100644 --- a/test/e2e/kernel_spare_test.py +++ b/test/e2e/kernel_spare_test.py @@ -5,10 +5,35 @@ import unittest from harness import Albedo, exclusive from inspect_support import Inspection +from kernel_support import editable_daemon @exclusive class KernelSpareTests(unittest.TestCase): + def test_unused_spares_end_on_stop_and_owner_death(self): + with Albedo(prepare=lambda app: app.env.update(ALBEDO_INSPECT="1")) as app: + probe = Inspection( + app, Path(__file__).with_name("albedo_kernel_spare_probe.erl") + ) + self.assertTrue(probe.call_json("stop_json")["stopped"]) + + def test_stale_spare_is_cleaned_before_cold_fallback(self): + def prepare(app): + launcher, app.bundle = editable_daemon(app.root) + app.env.update(ALBEDO_INSPECT="1", ALBEDO_DAEMON=str(launcher)) + + with Albedo(prepare=prepare) as app: + session = app.session() + probe = Inspection( + app, Path(__file__).with_name("albedo_kernel_spare_probe.erl") + ) + changed = app.bundle / "albedo_bundle.py" + result = probe.call_json( + "run_json", f'[<<"{session}">>, <<"{app.workspace}">>, <<"{changed}">>]' + ) + self.assertEqual(result["recalled"]["status"], "ok", result) + self.assertIn("SPARE_OK", result["recalled"]["output"]) + def test_spare_is_single_use_and_restores_definitions(self): with Albedo(prepare=lambda app: app.env.update(ALBEDO_INSPECT="1")) as app: session = app.session() @@ -16,7 +41,7 @@ class KernelSpareTests(unittest.TestCase): app, Path(__file__).with_name("albedo_kernel_spare_probe.erl") ) result = probe.call_json( - "run_json", f'[<<"{session}">>, <<"{app.workspace}">>]' + "run_json", f'[<<"{session}">>, <<"{app.workspace}">>, <<>>]' ) self.assertEqual(result["recalled"]["status"], "ok", result) self.assertIn("SPARE_OK", result["recalled"]["output"]) -- knotmirror 0.0.1 From 239cbfdaa98d1e336686e3f83f6f25b52437616b Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:49:42 -0400 Subject: [PATCH 13/72] Add runtime spare kernel pool and spare-backed resting release --- robot-docs/kernel.md | 10 ++ src/albedo/daemon/maintenance.gleam | 24 ++- src/albedo/daemon/session.gleam | 107 +++++++++---- src/albedo/harness/runtime.gleam | 104 +++++++++++- src/albedo/harness/runtime/boot.gleam | 191 ++++++++++++++++++++++- src/albedo/harness/runtime/kernels.gleam | 13 +- src/albedo/harness/runtime/state.gleam | 29 +++- test/e2e/kernel_pool_test.py | 152 ++++++++++++++++++ 8 files changed, 585 insertions(+), 45 deletions(-) create mode 100644 test/e2e/kernel_pool_test.py diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index dc7ab9b25..243b835c4 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -498,6 +498,16 @@ it made (`work`). `runtime/state` names the generation lifecycle a request belongs to: `admit` opens one, `current_waiters` says whether a result is still for it, `generation_over` ends it and replays what waited. +### fresh spare kernels + +The runtime keeps a bounded pool of fresh local Python processes. `ALBEDO_KERNEL_SPARES` sets the target from 0 to 32; the default 0 disables the pool until the density measurements justify a default. A spare imports the kernel core without an agent namespace, workspace, plugin setup, or session environment. A spare is consumed once. Released kernels exit instead of returning to the pool. + +`boot_next` admits warmup and cleanup requests through the existing worker budget. Warmups wait behind session work and leave one admission slot free. The runtime holds one ticket per queued or running warmup. Admission removes a spare from the ready list before starting an open worker, so concurrent sessions cannot adopt the same process. An empty pool uses the ordinary cold open. Adoption consumes the spare even when an existing kernel reattaches or a remote workspace uses another launch path. + +The Python owner checks the source bundle before adoption. A stale spare stops before a cold replacement starts. Explicit reloads and upgrades retire ready spares and invalidate in-flight warmups. Failed cleanup retains its resource in the bounded pool accounting. Warmup failures retry after one second. Shutdown drains admitted workers, stops all remaining spares, then closes the ledger. A spare also monitors the runtime actor and stops when that owner dies; spares never survive a daemon restart. + +A completed turn requests a spare-availability check without waiting on the runtime actor. An empty enabled pool retains at most one callback per session; a completed warmup notifies all callbacks because release does not consume a spare. Forget, delete, and shutdown discard these callbacks. If a spare exists, the session runs the ordinary release path and saves its namespace. The release handler rechecks that the session is resting and has no live cell or job. Unknown live-work observations retain the kernel. Maintenance applies the same early-release policy to idle sessions and unowned kernels. `ALBEDO_KERNEL_RELEASE_WITH_SPARE=1` enables this early release (off by default, which keeps kernels resident); the existing idle and memory-budget limits still apply. Availability is not a reservation: a concurrent open can drain the pool before a released session resumes, in which case that session cold-boots. + ## drops - the connection drops (the relay's socket closes, or the bridge dies): the port owner reattaches with backoff (50 ms doubling to diff --git a/src/albedo/daemon/maintenance.gleam b/src/albedo/daemon/maintenance.gleam index 07cde98f0..120ce75f2 100644 --- a/src/albedo/daemon/maintenance.gleam +++ b/src/albedo/daemon/maintenance.gleam @@ -90,9 +90,15 @@ fn release_idle( ) }) let workers = list.map(held, fn(entry) { #(entry.0, entry.1) }) + let idle_ms = case + runtime.release_with_spare() && runtime.spare_available(sweep.host) + { + True -> 0 + False -> sweep.idle_ms + } reaper.victims( candidates, - reaper.Limits(sweep.idle_ms, sweep.budget_kb, sweep.detached_ms), + reaper.Limits(idle_ms, sweep.budget_kb, sweep.detached_ms), ) |> list.each(fn(victim) { case list.key_find(workers, victim.pid) { @@ -157,18 +163,26 @@ fn unload_quiet( /// A restarted daemon reattaches every recorded kernel, and only actors are /// swept above, so without this those kernels stay up for good. fn release_unowned(activity: List(#(String, Int)), sweep: Sweep) -> Nil { + let idle_ms = case + runtime.release_with_spare() && runtime.spare_available(sweep.host) + { + True -> 0 + False -> sweep.idle_ms + } runtime.held_kernels(sweep.host) |> list.each(fn(entry) { let #(id, kernel) = entry let last = list.key_find(activity, id) |> result.unwrap(0) case session.live(id) == None - && runtime.job_count(kernel) == 0 - && sweep.now_seconds * 1000 - last >= sweep.idle_ms + && runtime.live_work(kernel) == Ok(0) + && sweep.now_seconds * 1000 - last >= idle_ms { True -> { - let _ = session_namespace.save_state(sweep.home, id, kernel) - runtime.forget_session(sweep.host, id) + case session_namespace.save_state(sweep.home, id, kernel) { + Ok(_) -> runtime.forget_session(sweep.host, id) + Error(_) -> Nil + } } False -> Nil } diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 385666b12..9aab549dd 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -316,7 +316,8 @@ pub type Message { Down(process.Down) Idle(Subject(Report)) Release(Subject(Bool)) - Released(runtime.Session, Result(python.Saved, String), Subject(Bool)) + ReleaseResting + Released(runtime.Session, Result(python.Saved, String), Option(Subject(Bool))) Deleted(Result(Nil, String), Subject(Result(Nil, String))) ExpireState(Subject(Bool)) EvictHistory(Subject(Bool)) @@ -2199,39 +2200,25 @@ fn handle( } _, _ -> answer(state, reply, False) } - Release(reply) -> - case - state.kernel, - turn.running(state.activity), - uses_kernel_transition(state) || state.booting != None - { - Some(kernel), None, False -> { - let #(home, id, self) = #(state.home, state.info.id, state.self) - let _ = - process.spawn_unlinked(fn() { - process.send( - self, - Released( - kernel, - protect.guarded(fn() { - session_namespace.save_state(home, id, kernel) - }), - reply, - ), - ) - }) - actor.continue(session_state.State(..state, releasing: Some([]))) - } - _, _, _ -> answer(state, reply, False) - } - Released(kernel, saved, reply) -> { + Release(reply) -> begin_release(state, Some(reply)) + ReleaseResting -> begin_release(state, None) + Released(_, Error(_), reply) -> { + let parked = option.unwrap(state.releasing, []) + list.each(parked, process.send(state.self, _)) + release_answer( + session_state.State(..state, releasing: None), + reply, + False, + ) + } + Released(kernel, Ok(_) as saved, reply) -> { let parked = option.unwrap(state.releasing, []) session_namespace.forget(kernel) // Reset and any subsequent Open are sent by this actor, in that order. runtime.reset_session_async(state.host, state.info.id) process.send(state.self, Collect) list.each(parked, process.send(state.self, _)) - answer( + release_answer( session_state.State( ..state, kernel: None, @@ -3627,7 +3614,25 @@ fn finish_turn( |> session_state.announce report_end(state, run) process.send(state.self, Collect) - actor.continue(start_queued(state)) + let state = start_queued(state) + case + state.kernel, + turn.running(state.activity), + runtime.release_with_spare() + && option.map(state.kernel, runtime.live_work) == Some(Ok(0)) + { + Some(_), None, True -> { + let self = state.self + runtime.when_spare_available(state.host, state.info.id, fn(available) { + case available { + True -> process.send(self, ReleaseResting) + False -> Nil + } + }) + } + _, _, _ -> Nil + } + actor.continue(state) } /// Commits what a stopped or failed turn left unfinished. @@ -4522,3 +4527,47 @@ fn clear_tool_progress(state: State) -> State { @external(erlang, "albedo_session", "new_generation") fn new_generation() -> String + +fn release_answer( + state: State, + reply: Option(Subject(Bool)), + released: Bool, +) -> actor.Next(State, Message) { + case reply { + Some(reply) -> answer(state, reply, released) + None -> actor.continue(state) + } +} + +fn begin_release( + state: State, + reply: Option(Subject(Bool)), +) -> actor.Next(State, Message) { + case + state.kernel, + turn.running(state.activity), + // Only published facts: unknown work retains the kernel without calling its owner. + uses_kernel_transition(state) + || state.booting != None + || option.map(state.kernel, runtime.live_work) != Some(Ok(0)) + { + Some(kernel), None, False -> { + let #(home, id, self) = #(state.home, state.info.id, state.self) + let _ = + process.spawn_unlinked(fn() { + process.send( + self, + Released( + kernel, + protect.guarded(fn() { + session_namespace.save_state(home, id, kernel) + }), + reply, + ), + ) + }) + actor.continue(session_state.State(..state, releasing: Some([]))) + } + _, _, _ -> release_answer(state, reply, False) + } +} diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index e160adbac..43729c9df 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -221,6 +221,7 @@ pub fn start_with_config( default_enabled, quarantined, )) + process.send(subject, runtime_state.FillSpares) Ok( actor.initialised(runtime_state.State( ledger: ledger, @@ -232,6 +233,12 @@ pub fn start_with_config( booting: dict.new(), waiting: [], observing: 0, + spares: [], + spare_target: spare_target(), + warming: dict.new(), + retired_spares: [], + spare_retry: False, + spare_waiters: dict.new(), stopping: dict.new(), failed_stops: dict.new(), shutdown: None, @@ -586,6 +593,7 @@ fn continue(state: runtime_state.State) -> actor.Next(runtime_state.State, a) { dict.size(state.booting) == 0 && dict.size(state.stopping) == 0 && state.observing == 0 + && dict.size(state.warming) == 0 { True -> { boot.shutdown(state, reply) @@ -663,6 +671,10 @@ fn refuse( process.send(reply, Error(reason)) True } + runtime_state.WhenSpareAvailable(_, answer) -> { + answer(False) + True + } runtime_state.Peek(_, _, reply) -> { process.send(reply, Error(reason)) True @@ -741,6 +753,33 @@ fn serve( message: runtime_state.Message, ) -> actor.Next(runtime_state.State, a) { case message { + runtime_state.FillSpares -> + continue(boot.boot_next(runtime_state.State(..state, spare_retry: False))) + runtime_state.SpareReady(ticket, result) -> + continue(boot.spare_ready(state, ticket, result) |> boot.boot_next) + runtime_state.SpareStopped(ticket, spare, outcome) -> { + case outcome { + Error(reason) -> io.println_error("spare stop: " <> reason) + Ok(_) -> Nil + } + continue( + runtime_state.State( + ..state, + warming: dict.delete(state.warming, ticket), + retired_spares: case outcome { + Error(_) -> [spare, ..state.retired_spares] + Ok(_) -> state.retired_spares + }, + ) + |> boot.boot_next, + ) + } + runtime_state.SpareAvailable(reply) -> { + process.send(reply, list.any(state.spares, python.spare_current)) + continue(boot.boot_next(state)) + } + runtime_state.WhenSpareAvailable(id, answer) -> + continue(boot.when_spare_available(state, id, answer) |> boot.boot_next) runtime_state.Open(id, cwd, answer) -> case dict.get(state.sessions, id), dict.get(state.booting, id) { Ok(session), _ -> @@ -819,7 +858,8 @@ fn serve( ) runtime_state.Upgrade(id, answer) -> continue( - upgrade.start_kernel_upgrade(state, id, answer) |> boot.boot_next, + upgrade.start_kernel_upgrade(boot.invalidate_spares(state), id, answer) + |> boot.boot_next, ) runtime_state.UpgradedKernel(id, generation, previous, outcome, answer) -> continue( @@ -834,10 +874,19 @@ fn serve( |> boot.boot_next, ) runtime_state.Reload(id, cwd, change, reply) -> - continue(reload.reload(state, id, cwd, change, reply) |> boot.boot_next) + continue( + reload.reload(boot.invalidate_spares(state), id, cwd, change, reply) + |> boot.boot_next, + ) runtime_state.ReloadDesired(id, cwd, reply) -> continue( - reload.start_desired_reload(state, id, cwd, reply) |> boot.boot_next, + reload.start_desired_reload( + boot.invalidate_spares(state), + id, + cwd, + reply, + ) + |> boot.boot_next, ) runtime_state.Reloaded(id, generation, previous, outcome, reply) -> continue( @@ -1078,7 +1127,13 @@ fn serve( kernels.stopped(state, id, generation, outcome) |> boot.boot_next, ) runtime_state.Stop(reply) -> - continue(runtime_state.State(..state, shutdown: Some(reply))) + continue( + boot.notify_spare_waiters( + runtime_state.State(..state, shutdown: Some(reply)), + False, + ) + |> boot.boot_next, + ) runtime_state.ShutdownComplete(reply, outcome) -> { case outcome { Error(reason) -> io.println_error("runtime stop: " <> reason) @@ -1089,7 +1144,13 @@ fn serve( } runtime_state.Detach(reply) -> { process.send(reply, Nil) - continue(runtime_state.State(..state, detaching: True)) + continue( + boot.notify_spare_waiters( + runtime_state.State(..state, detaching: True), + False, + ) + |> boot.boot_next, + ) } runtime_state.Reattach(id, cwd, reply) -> continue(boot.reattach(state, id, cwd, reply) |> boot.boot_next) @@ -1726,3 +1787,36 @@ fn observe_window( } }) } + +/// A last-known spare check, not a reservation. A racing open may drain the pool. +pub fn spare_available(runtime: Runtime) -> Bool { + actor_call.try_call(runtime.subject, 1000, runtime_state.SpareAvailable) + |> result.unwrap(False) +} + +pub fn when_spare_available( + runtime: Runtime, + id: String, + answer: fn(Bool) -> Nil, +) -> Nil { + process.send(runtime.subject, runtime_state.WhenSpareAvailable(id, answer)) +} + +pub fn release_with_spare() -> Bool { + env("ALBEDO_KERNEL_RELEASE_WITH_SPARE") == "1" +} + +fn spare_target() -> Int { + env("ALBEDO_KERNEL_SPARES") + |> int.parse + |> result.map(int.clamp(_, 0, 32)) + |> result.unwrap(0) +} + +@external(erlang, "albedo_daemon", "env") +fn env(name: String) -> String + +/// Published live-cell and job count. Unknown observations retain the kernel. +pub fn live_work(session: Session) -> Result(Int, Nil) { + python.live_work(session.kernel) +} diff --git a/src/albedo/harness/runtime/boot.gleam b/src/albedo/harness/runtime/boot.gleam index 2ddc15bcc..356e40490 100644 --- a/src/albedo/harness/runtime/boot.gleam +++ b/src/albedo/harness/runtime/boot.gleam @@ -2,6 +2,7 @@ //// upgrades, and observations into a bounded set of workers, and reattaches //// recorded kernels after a daemon restart. +import albedo/clock import albedo/daemon/store import albedo/harness/extension/composition import albedo/harness/extensions/python/kernel as python @@ -15,6 +16,7 @@ import albedo/harness/runtime/upgrade import gleam/dict import gleam/erlang/process.{type Subject} import gleam/erlang/reference.{type Reference} +import gleam/io import gleam/list import gleam/option.{type Option, None, Some} import gleam/result @@ -22,6 +24,10 @@ import gleam/result /// Admit the oldest eligible request, preserving order within each class. /// Kernels belong to the store and outlive the workers that prepare them. pub fn boot_next(state: runtime_state.State) -> runtime_state.State { + schedule(refill(discard_stale_spares(state))) +} + +fn schedule(state: runtime_state.State) -> runtime_state.State { let running = runtime_state.active(state) let preparations = running - state.observing let queued_stops = @@ -36,6 +42,7 @@ pub fn boot_next(state: runtime_state.State) -> runtime_state.State { list.split_while(state.waiting, fn(request) { case request { runtime_state.StopKernel(..) -> stops >= 2 + runtime_state.WarmSpare(..) -> running >= runtime_state.boot_slots - 1 runtime_state.Observe(..) -> running >= runtime_state.boot_slots || state.observing >= runtime_state.boot_slots - 1 @@ -57,8 +64,9 @@ pub fn boot_next(state: runtime_state.State) -> runtime_state.State { _ -> 0 }, ) - start(state, request) - boot_next(state) + let #(state, spare) = reserve_spare(state, request) + start(state, request, spare) + schedule(state) } [] -> state } @@ -88,11 +96,39 @@ fn work( fn start( state: runtime_state.State, request: runtime_state.BootRequest, + spare: Option(python.Spare), ) -> Nil { let self = state.self + let assert Ok(runtime_owner) = process.subject_owner(self) let owner = state.ledger let inventory = observation.composition_inventory(state) case request { + runtime_state.WarmSpare(ticket) -> + work( + self, + fn() { + protect.attempt(fn() { python.start_spare(runtime_owner) }) + |> result.replace_error(python.Unavailable("spare worker exited")) + |> result.flatten + }, + runtime_state.SpareReady(ticket, _), + fn(outcome) { + case outcome { + Ok(spare) -> { + let _ = python.stop_spare(spare) + Nil + } + Error(_) -> Nil + } + }, + ) + runtime_state.StopSpare(ticket, spare) -> + work( + self, + fn() { python.stop_spare(spare) }, + runtime_state.SpareStopped(ticket, spare, _), + fn(_) { Nil }, + ) runtime_state.StopKernel(id, generation, run) -> stop_work(self, run, runtime_state.Stopped(id, generation, _)) runtime_state.Observe(id, home, reply, retries) -> { @@ -140,7 +176,9 @@ fn start( self, fn() { case - protect.attempt(fn() { kernels.open_kernel(owner, id, cached) }) + protect.attempt(fn() { + kernels.open_with_spare(owner, id, cached, spare) + }) { Ok(result) -> result Error(crash) -> @@ -352,10 +390,17 @@ pub fn shutdown(state: runtime_state.State, reply: Subject(Nil)) -> Nil { let sessions = dict.values(state.sessions) let compositions = dict.values(state.compositions) let detach = state.detaching + let spares = list.append(state.spares, state.retired_spares) let ledger = state.ledger stop_work( state.self, fn() { + list.each(spares, fn(spare) { + case python.stop_spare(spare) { + Error(reason) -> io.println_error("spare shutdown: " <> reason) + Ok(_) -> Nil + } + }) list.each(sessions, fn(session) { case detach { True -> python.detach(session.kernel) @@ -371,3 +416,143 @@ pub fn shutdown(state: runtime_state.State, reply: Subject(Nil)) -> Nil { runtime_state.ShutdownComplete(reply, _), ) } + +/// Reserve a ready spare before the worker starts. A ticket is never returned. +fn reserve_spare( + state: runtime_state.State, + request: runtime_state.BootRequest, +) -> #(runtime_state.State, Option(python.Spare)) { + case request, state.spares { + runtime_state.BootKernel(..), [spare, ..rest] -> #( + runtime_state.State(..state, spares: rest), + Some(spare), + ) + _, _ -> #(state, None) + } +} + +/// Refill behind ordinary work and retain a finite ticket for every warmup. +fn refill(state: runtime_state.State) -> runtime_state.State { + let #(background, foreground) = + list.partition(state.waiting, fn(request) { + case request { + runtime_state.WarmSpare(_) -> True + _ -> False + } + }) + let state = + runtime_state.State(..state, waiting: list.append(foreground, background)) + let missing = + state.spare_target + - list.length(state.spares) + - dict.size(state.warming) + - list.length(state.retired_spares) + case + missing > 0 + && state.shutdown == None + && !state.detaching + && !state.spare_retry + { + False -> state + True -> { + let ticket = reference.new() + runtime_state.State( + ..state, + warming: dict.insert(state.warming, ticket, False), + waiting: list.append(state.waiting, [runtime_state.WarmSpare(ticket)]), + ) + |> refill + } + } +} + +pub fn spare_ready( + state: runtime_state.State, + ticket: Reference, + outcome: Result(python.Spare, python.Error), +) -> runtime_state.State { + let valid = dict.get(state.warming, ticket) == Ok(False) + let state = + runtime_state.State(..state, warming: dict.delete(state.warming, ticket)) + case outcome { + Ok(spare) if valid -> + runtime_state.State(..state, spares: [spare, ..state.spares]) + |> notify_spare_waiters(state.shutdown == None && !state.detaching) + Ok(spare) -> retire_spares(state, state.spares, [spare]) + Error(_) -> { + let _ = clock.send_after(state.self, 1000, runtime_state.FillSpares) + runtime_state.State(..state, spare_retry: True) + } + } +} + +pub fn invalidate_spares(state: runtime_state.State) -> runtime_state.State { + let state = + runtime_state.State( + ..state, + warming: dict.map_values(state.warming, fn(_, _) { True }), + ) + retire_spares(state, [], state.spares) +} + +fn discard_stale_spares(state: runtime_state.State) -> runtime_state.State { + let #(current, stale) = list.partition(state.spares, python.spare_current) + retire_spares(state, current, stale) +} + +fn retire_spares( + state: runtime_state.State, + current: List(python.Spare), + stale: List(python.Spare), +) -> runtime_state.State { + list.fold( + stale, + runtime_state.State(..state, spares: current), + fn(state, spare) { + let ticket = reference.new() + runtime_state.State( + ..state, + warming: dict.insert(state.warming, ticket, True), + waiting: list.append(state.waiting, [ + runtime_state.StopSpare(ticket, spare), + ]), + ) + }, + ) +} + +/// One spare permits every resting session to release; only an open consumes it. +pub fn notify_spare_waiters( + state: runtime_state.State, + available: Bool, +) -> runtime_state.State { + state.spare_waiters + |> dict.values + |> list.each(fn(answer) { answer(available) }) + runtime_state.State(..state, spare_waiters: dict.new()) +} + +pub fn when_spare_available( + state: runtime_state.State, + id: String, + answer: fn(Bool) -> Nil, +) -> runtime_state.State { + case + list.any(state.spares, python.spare_current), + state.spare_target > 0 && !state.detaching + { + True, True -> { + answer(True) + state + } + False, True -> + runtime_state.State( + ..state, + spare_waiters: dict.insert(state.spare_waiters, id, answer), + ) + _, False -> { + answer(False) + state + } + } +} diff --git a/src/albedo/harness/runtime/kernels.gleam b/src/albedo/harness/runtime/kernels.gleam index c111683e4..b87970f0a 100644 --- a/src/albedo/harness/runtime/kernels.gleam +++ b/src/albedo/harness/runtime/kernels.gleam @@ -71,12 +71,22 @@ pub fn open_kernel( id: String, cached: runtime_state.Cached, ) -> Result(runtime_state.Session, python.Error) { - python.open( + open_with_spare(owner, id, cached, None) +} + +pub fn open_with_spare( + owner: store.Store, + id: String, + cached: runtime_state.Cached, + spare: Option(python.Spare), +) -> Result(runtime_state.Session, python.Error) { + python.open_with_spare( owner, id, cached.cwd, kernel_routes(owner, id, cached.composition), composition.python_modules(cached.composition), + spare, ) |> result.map(fn(opened) { let origin = case opened.1 { @@ -234,6 +244,7 @@ fn enqueue_stop( ) -> runtime_state.State { runtime_state.State( ..state, + spare_waiters: dict.delete(state.spare_waiters, id), stopping: dict.insert( state.stopping, id, diff --git a/src/albedo/harness/runtime/state.gleam b/src/albedo/harness/runtime/state.gleam index ee06ad292..e7e11f5c2 100644 --- a/src/albedo/harness/runtime/state.gleam +++ b/src/albedo/harness/runtime/state.gleam @@ -153,6 +153,8 @@ pub type ObservationResult { } pub type BootRequest { + WarmSpare(ticket: Reference) + StopSpare(ticket: Reference, spare: python.Spare) StopKernel( id: String, generation: Reference, @@ -238,6 +240,13 @@ pub type State { waiting: List(BootRequest), /// Observation workers share the same admission budget as preparation. observing: Int, + spares: List(python.Spare), + spare_target: Int, + /// False admits a warmup result; True retires it or tracks cleanup. + warming: Dict(Reference, Bool), + retired_spares: List(python.Spare), + spare_retry: Bool, + spare_waiters: Dict(String, fn(Bool) -> Nil), /// Reserved until stop confirmation; separate from boot admission. stopping: Dict(String, Stopping), failed_stops: Dict(String, String), @@ -261,6 +270,11 @@ pub type State { pub const boot_slots = 4 pub type Message { + FillSpares + SpareReady(Reference, Result(python.Spare, python.Error)) + SpareStopped(Reference, python.Spare, Result(Nil, String)) + SpareAvailable(Subject(Bool)) + WhenSpareAvailable(String, fn(Bool) -> Nil) /// Answered through the callback, never by blocking the caller: a session /// actor asks and keeps serving while its kernel boots. Open(String, String, fn(Result(Session, python.Error)) -> Nil) @@ -358,11 +372,22 @@ pub fn active(state: State) -> Int { let queued_preparations = list.count(state.waiting, fn(request) { case request { - Observe(..) | StopKernel(..) -> False + Observe(..) | StopKernel(..) | WarmSpare(..) | StopSpare(..) -> False _ -> True } }) - dict.size(state.booting) - queued_preparations + state.observing + let queued_spares = + list.count(state.waiting, fn(request) { + case request { + WarmSpare(..) | StopSpare(..) -> True + _ -> False + } + }) + dict.size(state.booting) + - queued_preparations + + state.observing + + dict.size(state.warming) + - queued_spares } /// Opens a generation for the session: its kernel work is on the way, and diff --git a/test/e2e/kernel_pool_test.py b/test/e2e/kernel_pool_test.py new file mode 100644 index 000000000..37aea057e --- /dev/null +++ b/test/e2e/kernel_pool_test.py @@ -0,0 +1,152 @@ +"""Fresh spare kernels are single-use, bounded, and never adopted across a bundle edit.""" + +import ast +from pathlib import Path +import subprocess +import unittest + +from harness import Albedo, Provider, alive, exclusive, python, text, wait_until +from inspect_support import Inspection +from kernel_support import MARKER, ModelCells, editable_daemon + + +@exclusive +class KernelPoolTests(ModelCells, unittest.TestCase): + bundle: Path + + def boot(self, *, spares=1, release=False): + self.cells = [] + + def script(request): + if request["input"][-1].get("role") == "user" and self.cells: + return python(self.cells.pop(0)) + return text("ok") + + def prepare(app): + launcher, self.bundle = editable_daemon(app.root) + app.env.update( + ALBEDO_DAEMON=str(launcher), + ALBEDO_INSPECT="1", + ALBEDO_KERNEL_SPARES=str(spares), + ALBEDO_KERNEL_RELEASE_WITH_SPARE="1" if release else "0", + ) + + self.provider = Provider(script) + self.addCleanup(self.provider.close) + self.app = Albedo(self.provider, protocol="responses", prepare=prepare) + self.app.__enter__() + self.addCleanup(self.app.__exit__, None, None, None) + self.session = self.app.session() + self.inspection = Inspection(self.app) + + def spare_pids(self): + """Pids of ready spares: children of a waiting `albedo_bridge.py spare`. + + An adopted kernel keeps the spare script's name but no helper parent.""" + rows = [ + line.split(None, 2) + for line in subprocess.check_output( + ["ps", "-axo", "pid=,ppid=,command="], text=True + ).splitlines() + ] + script = str(self.bundle / "albedo_spare.py") + helper = str(self.bundle / "albedo_bridge.py") + " spare" + helpers = {int(pid) for pid, _, command in rows if helper in command} + return { + int(pid) + for pid, ppid, command in rows + if script in command and int(ppid) in helpers + } + + def ready(self, *, excluding=()): + found = set() + + def available(): + nonlocal found + found = self.spare_pids() - set(excluding) + if not found: + return False + return ( + self.inspection.evaluate( + "Names = Call(erlang, registered, []), " + '[Name] = [N || N <- Names, lists:prefix("albedo_registry", atom_to_list(N))], ' + "Subject = Call('gleam@erlang@process', named_subject, [Name]), " + "{ok, Runtime} = Call('albedo@daemon@registry', host, [Subject]), " + "io:write(Call('albedo@harness@runtime', spare_available, [Runtime]))" + ) + == "true" + ) + + wait_until(available, 15, "the runtime did not refill its fresh spare") + return found + + def value(self, code): + result, _ = self.cell(code) + self.assertEqual(result["status"], "ok", result) + return ast.literal_eval(result["value"]) + + def test_spare_is_adopted_released_once_and_refilled(self): + self.boot(release=True) + before = self.ready() + first = self.value("import os\nsentinel = 41\nos.getpid()") + self.assertIn(first, before, "the first cell did not adopt a spare") + wait_until(lambda: not alive(first), 15, "the resting kernel was not released") + next_spares = self.ready() + self.assertTrue(before.isdisjoint(next_spares)) + second, sentinel = self.value("(os.getpid(), sentinel)") + self.assertIn(second, next_spares) + self.assertNotEqual(first, second) + self.assertEqual(sentinel, 41) + wait_until( + lambda: not alive(second), 15, "the adopted kernel returned to the pool" + ) + self.assertTrue(self.ready().isdisjoint({first, second})) + + def test_live_background_work_keeps_the_adopted_kernel(self): + self.boot(release=True) + self.ready() + gate = self.app.workspace / "background-gate" + program = f"import pathlib, time; p = pathlib.Path({str(gate)!r}); exec('while not p.exists(): time.sleep(0.01)')" + pid = self.value( + f"import os, sys\njob = run(sys.executable, '-c', {program!r})\nos.getpid()" + ) + self.assertTrue(alive(pid)) + self.assertEqual(self.value("(os.getpid(), job.exit_code)"), (pid, None)) + gate.touch() + self.value("await job\n42") + wait_until(lambda: not alive(pid), 15, "a finished job pinned its kernel") + + def test_an_empty_pool_uses_a_cold_kernel(self): + self.boot(spares=0) + pid = self.value("import os\nos.getpid()") + self.assertTrue(alive(pid)) + self.assertEqual(self.spare_pids(), set()) + + def test_a_changed_bundle_is_not_adopted(self): + self.boot() + before = self.ready() + with (self.bundle / "albedo_bundle.py").open("a") as source: + source.write(MARKER) + pid, marker = self.value( + "import os, albedo_bundle\n(os.getpid(), albedo_bundle.MARKER)" + ) + self.assertNotIn(pid, before) + self.assertEqual(marker, "new bundle") + wait_until( + lambda: all(not alive(old) for old in before), + 15, + "the stale spare survived its rejected adoption", + ) + + def test_shutdown_stops_spares_but_detaches_an_adopted_kernel(self): + self.boot() + self.ready() + adopted = self.value("import os\nos.getpid()") + ready = self.ready(excluding={adopted}) + self.app.restart() + wait_until( + lambda: all(not alive(pid) for pid in ready), + 15, + "a fresh spare survived daemon shutdown", + ) + self.assertTrue(alive(adopted), "shutdown ended an adopted detached kernel") -- knotmirror 0.0.1 From 25fd38fb039f63b6ae1a2690d3eb6e0fb0f75874 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:51:29 -0400 Subject: [PATCH 14/72] Keep watched or partially saved kernels out of spare-backed release --- src/albedo/daemon/maintenance.gleam | 4 ++-- src/albedo/daemon/session.gleam | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/albedo/daemon/maintenance.gleam b/src/albedo/daemon/maintenance.gleam index 120ce75f2..cfed271a8 100644 --- a/src/albedo/daemon/maintenance.gleam +++ b/src/albedo/daemon/maintenance.gleam @@ -93,7 +93,7 @@ fn release_idle( let idle_ms = case runtime.release_with_spare() && runtime.spare_available(sweep.host) { - True -> 0 + True -> sweep.detached_ms False -> sweep.idle_ms } reaper.victims( @@ -166,7 +166,7 @@ fn release_unowned(activity: List(#(String, Int)), sweep: Sweep) -> Nil { let idle_ms = case runtime.release_with_spare() && runtime.spare_available(sweep.host) { - True -> 0 + True -> sweep.detached_ms False -> sweep.idle_ms } runtime.held_kernels(sweep.host) diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 9aab549dd..a15b86c63 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -2211,6 +2211,12 @@ fn handle( False, ) } + // Automatic release keeps a kernel whose namespace did not fully save. + Released(_, Ok(python.Saved(missed: [_, ..], ..)), None) -> { + let parked = option.unwrap(state.releasing, []) + list.each(parked, process.send(state.self, _)) + actor.continue(session_state.State(..state, releasing: None)) + } Released(kernel, Ok(_) as saved, reply) -> { let parked = option.unwrap(state.releasing, []) session_namespace.forget(kernel) @@ -3619,6 +3625,7 @@ fn finish_turn( state.kernel, turn.running(state.activity), runtime.release_with_spare() + && state.watchers == [] && option.map(state.kernel, runtime.live_work) == Some(Ok(0)) { Some(_), None, True -> { -- knotmirror 0.0.1 From f0e445f1b26746246f42659afe429b9babfc8257 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 05:55:59 -0400 Subject: [PATCH 15/72] Document spare pool rules and pass daemon env to the density benchmark --- .agents/skills/gleam-design/SKILL.md | 2 ++ .../references/state-and-concurrency.md | 14 ++++++++++++++ test/manual/agent_density.py | 8 ++++++++ 3 files changed, 24 insertions(+) diff --git a/.agents/skills/gleam-design/SKILL.md b/.agents/skills/gleam-design/SKILL.md index 6e474b4ef..2888b50f9 100644 --- a/.agents/skills/gleam-design/SKILL.md +++ b/.agents/skills/gleam-design/SKILL.md @@ -186,6 +186,8 @@ Allocate a finite set of process names at application composition time, not per request or inside repeatedly restarted initialization. Avoid unbounded atom creation. Use direct subjects or a suitable dynamic registry where required. +For a pool of single-use resources (spares, tickets, waiter callbacks), read the "Pooled single-use resources" section of [state and concurrency](references/state-and-concurrency.md). + Keep these BEAM-specific rules out of JavaScript-only designs. Encapsulated local mutation in a foreign implementation can preserve an immutable API; it does not justify exposing shared mutable objects to arbitrary callers. diff --git a/.agents/skills/gleam-design/references/state-and-concurrency.md b/.agents/skills/gleam-design/references/state-and-concurrency.md index ca24f31c8..2c424b81c 100644 --- a/.agents/skills/gleam-design/references/state-and-concurrency.md +++ b/.agents/skills/gleam-design/references/state-and-concurrency.md @@ -122,3 +122,17 @@ Use `persistent_term` only after establishing that updates are rare and acceptin Put changing rate-limit marks and TTL results in lifetime-owned ETS, not compound persistent terms. In albedo's OTP 29 probe with 8,000 parked processes, 200 account-limit updates took 4.66 ms with persistent-term map replacement and 0.49 ms with ETS. ETS added about 28 ns per lookup. Use a separate entry per independently updated key; replacing a whole shared map also loses concurrent updates. Keep expired-entry cleanup and owner lifetime explicit. Keep Erlang-specific ownership, ETS, names, and supervision rules out of JavaScript-only code. Stdlib's private JavaScript dictionary transients show another approach: tightly scoped mutation behind an immutable public API [S29]. That is not shared-memory actor coordination and not a general license to expose the transients. Preserve encapsulation and test each supported target. + +## Pooled single-use resources + +The runtime's spare Python kernels (robot-docs/kernel.md, "fresh spare kernels") show the rules for a pool of resources that a process owns but another process consumes. + +Reserve at the point of use. The owner removes the resource from its ready list in the same message handler that starts the worker. Checking availability and taking it in two messages lets two sessions adopt one spare. An availability read stays advisory: a caller that acts on it must tolerate an empty pool, here by a cold boot. + +Give every asynchronous warmup or cleanup a ticket. A result that arrives after an invalidation (reload, upgrade, shutdown) is retired through a stop request instead of entering the pool. A cleanup that fails stays counted against the cap, so a failing stop cannot trigger unbounded refills. + +A waiter list needs a bound and a wake rule. A session that finds the pool empty registers one callback, replacing any earlier one. One completed warmup notifies all waiters, because the action that waiters take (releasing their kernel) does not consume the resource. + +A native result shape is part of the type contract. A helper that returned the atom `ok` where the typed API required `{ok, nil}` crashed the caller's `case` and hung the open until its deadline. Test the refusal path of a native call (stale bundle) as well as the success path. + +Decide release from published facts only. The session actor reads cached observations and treats an unknown count as live work, so it never waits on the kernel owner and never releases a kernel it could not inspect. diff --git a/test/manual/agent_density.py b/test/manual/agent_density.py index 1ac122442..79777f773 100644 --- a/test/manual/agent_density.py +++ b/test/manual/agent_density.py @@ -109,6 +109,13 @@ def main(): parser.add_argument("--idle-seconds", type=int, default=3600) parser.add_argument("--settle", type=float, default=0.2) parser.add_argument("--output", type=Path, required=True) + parser.add_argument( + "--daemon-env", + action="append", + default=[], + metavar="NAME=VALUE", + help="environment variable for the private daemon (repeatable)", + ) args = parser.parse_args() if args.agents < 1 or args.samples < 1: parser.error("agents and samples must be positive") @@ -157,6 +164,7 @@ def main(): ALBEDO_INSPECT="1", ALBEDO_IDLE_SECONDS=str(args.idle_seconds), ALBEDO_CELL_BACKGROUND_SECONDS="0.2", + **dict(item.split("=", 1) for item in args.daemon_env), ) provider = Provider(script, chunk_size=100000) -- knotmirror 0.0.1 From d841e282095dd56ec301e02f16e434ea537c7f50 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 06:08:13 -0400 Subject: [PATCH 16/72] Release resting kernels on pool health instead of a ready spare --- .../references/state-and-concurrency.md | 2 +- robot-docs/kernel.md | 4 +- src/albedo/daemon/maintenance.gleam | 4 +- src/albedo/daemon/session.gleam | 2 +- src/albedo/harness/runtime.gleam | 44 +++++++++---------- src/albedo/harness/runtime/boot.gleam | 42 +++--------------- src/albedo/harness/runtime/kernels.gleam | 1 - src/albedo/harness/runtime/state.gleam | 4 +- 8 files changed, 37 insertions(+), 66 deletions(-) diff --git a/.agents/skills/gleam-design/references/state-and-concurrency.md b/.agents/skills/gleam-design/references/state-and-concurrency.md index 2c424b81c..531dbf97b 100644 --- a/.agents/skills/gleam-design/references/state-and-concurrency.md +++ b/.agents/skills/gleam-design/references/state-and-concurrency.md @@ -131,7 +131,7 @@ Reserve at the point of use. The owner removes the resource from its ready list Give every asynchronous warmup or cleanup a ticket. A result that arrives after an invalidation (reload, upgrade, shutdown) is retired through a stop request instead of entering the pool. A cleanup that fails stays counted against the cap, so a failing stop cannot trigger unbounded refills. -A waiter list needs a bound and a wake rule. A session that finds the pool empty registers one callback, replacing any earlier one. One completed warmup notifies all waiters, because the action that waiters take (releasing their kernel) does not consume the resource. +Gate an action on pool health, not on a ready item, when the action does not consume the item. Releasing a kernel waited for a ready spare in the first design and converged slowly: at 200 agents 148 kernels were still resident 20 s later. Gating on pool health released all of them at once, at the price of a cold open when the pool is drained. A native result shape is part of the type contract. A helper that returned the atom `ok` where the typed API required `{ok, nil}` crashed the caller's `case` and hung the open until its deadline. Test the refusal path of a native call (stale bundle) as well as the success path. diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 243b835c4..9eebb17ea 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -504,9 +504,9 @@ The runtime keeps a bounded pool of fresh local Python processes. `ALBEDO_KERNEL `boot_next` admits warmup and cleanup requests through the existing worker budget. Warmups wait behind session work and leave one admission slot free. The runtime holds one ticket per queued or running warmup. Admission removes a spare from the ready list before starting an open worker, so concurrent sessions cannot adopt the same process. An empty pool uses the ordinary cold open. Adoption consumes the spare even when an existing kernel reattaches or a remote workspace uses another launch path. -The Python owner checks the source bundle before adoption. A stale spare stops before a cold replacement starts. Explicit reloads and upgrades retire ready spares and invalidate in-flight warmups. Failed cleanup retains its resource in the bounded pool accounting. Warmup failures retry after one second. Shutdown drains admitted workers, stops all remaining spares, then closes the ledger. A spare also monitors the runtime actor and stops when that owner dies; spares never survive a daemon restart. +The Python owner checks the source bundle before adoption. A stale spare stops before a cold replacement starts. Explicit reloads and upgrades retire ready spares and invalidate in-flight warmups. Failed cleanup retains its resource in the bounded pool accounting. Warmup failures retry after one second and mark the pool unhealthy until the retry. Shutdown drains admitted workers, stops all remaining spares, then closes the ledger. A spare also monitors the runtime actor and stops when that owner dies; spares never survive a daemon restart. -A completed turn requests a spare-availability check without waiting on the runtime actor. An empty enabled pool retains at most one callback per session; a completed warmup notifies all callbacks because release does not consume a spare. Forget, delete, and shutdown discard these callbacks. If a spare exists, the session runs the ordinary release path and saves its namespace. The release handler rechecks that the session is resting and has no live cell or job. Unknown live-work observations retain the kernel. Maintenance applies the same early-release policy to idle sessions and unowned kernels. `ALBEDO_KERNEL_RELEASE_WITH_SPARE=1` enables this early release (off by default, which keeps kernels resident); the existing idle and memory-budget limits still apply. Availability is not a reservation: a concurrent open can drain the pool before a released session resumes, in which case that session cold-boots. +A completed turn asks, without waiting on the runtime actor, whether the pool is healthy: enabled, not shutting down or detaching, and not in a warmup-failure retry. If it is healthy and the session has no attached client, the session runs the ordinary release path and saves its namespace. Release does not wait for a ready spare, so a drained pool costs the next open a cold boot (about 147 ms more on macOS) instead of leaving the kernel resident. The release handler rechecks that the session is resting and has no live cell or job. Unknown live-work observations and snapshots that report unsaved names retain the kernel. Maintenance applies the same early-release policy to idle sessions and unowned kernels, using the 30 s detached grace. `ALBEDO_KERNEL_RELEASE_WITH_SPARE=1` enables this early release (off by default, which keeps kernels resident); the existing idle and memory-budget limits still apply. ## drops diff --git a/src/albedo/daemon/maintenance.gleam b/src/albedo/daemon/maintenance.gleam index cfed271a8..bd24ff08a 100644 --- a/src/albedo/daemon/maintenance.gleam +++ b/src/albedo/daemon/maintenance.gleam @@ -91,7 +91,7 @@ fn release_idle( }) let workers = list.map(held, fn(entry) { #(entry.0, entry.1) }) let idle_ms = case - runtime.release_with_spare() && runtime.spare_available(sweep.host) + runtime.release_with_spare() && runtime.pool_healthy(sweep.host) { True -> sweep.detached_ms False -> sweep.idle_ms @@ -164,7 +164,7 @@ fn unload_quiet( /// swept above, so without this those kernels stay up for good. fn release_unowned(activity: List(#(String, Int)), sweep: Sweep) -> Nil { let idle_ms = case - runtime.release_with_spare() && runtime.spare_available(sweep.host) + runtime.release_with_spare() && runtime.pool_healthy(sweep.host) { True -> sweep.detached_ms False -> sweep.idle_ms diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index a15b86c63..1918ba93c 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -3630,7 +3630,7 @@ fn finish_turn( { Some(_), None, True -> { let self = state.self - runtime.when_spare_available(state.host, state.info.id, fn(available) { + runtime.when_pool_healthy(state.host, fn(available) { case available { True -> process.send(self, ReleaseResting) False -> Nil diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index 43729c9df..aa95ac04b 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -238,7 +238,6 @@ pub fn start_with_config( warming: dict.new(), retired_spares: [], spare_retry: False, - spare_waiters: dict.new(), stopping: dict.new(), failed_stops: dict.new(), shutdown: None, @@ -671,7 +670,7 @@ fn refuse( process.send(reply, Error(reason)) True } - runtime_state.WhenSpareAvailable(_, answer) -> { + runtime_state.WhenPoolHealthy(answer) -> { answer(False) True } @@ -778,8 +777,14 @@ fn serve( process.send(reply, list.any(state.spares, python.spare_current)) continue(boot.boot_next(state)) } - runtime_state.WhenSpareAvailable(id, answer) -> - continue(boot.when_spare_available(state, id, answer) |> boot.boot_next) + runtime_state.PoolHealthy(reply) -> { + process.send(reply, boot.pool_healthy(state)) + continue(state) + } + runtime_state.WhenPoolHealthy(answer) -> { + answer(boot.pool_healthy(state)) + continue(state) + } runtime_state.Open(id, cwd, answer) -> case dict.get(state.sessions, id), dict.get(state.booting, id) { Ok(session), _ -> @@ -1128,11 +1133,7 @@ fn serve( ) runtime_state.Stop(reply) -> continue( - boot.notify_spare_waiters( - runtime_state.State(..state, shutdown: Some(reply)), - False, - ) - |> boot.boot_next, + runtime_state.State(..state, shutdown: Some(reply)) |> boot.boot_next, ) runtime_state.ShutdownComplete(reply, outcome) -> { case outcome { @@ -1144,13 +1145,7 @@ fn serve( } runtime_state.Detach(reply) -> { process.send(reply, Nil) - continue( - boot.notify_spare_waiters( - runtime_state.State(..state, detaching: True), - False, - ) - |> boot.boot_next, - ) + continue(runtime_state.State(..state, detaching: True) |> boot.boot_next) } runtime_state.Reattach(id, cwd, reply) -> continue(boot.reattach(state, id, cwd, reply) |> boot.boot_next) @@ -1794,12 +1789,17 @@ pub fn spare_available(runtime: Runtime) -> Bool { |> result.unwrap(False) } -pub fn when_spare_available( - runtime: Runtime, - id: String, - answer: fn(Bool) -> Nil, -) -> Nil { - process.send(runtime.subject, runtime_state.WhenSpareAvailable(id, answer)) +/// Whether spare-backed release may run: the pool is enabled and not failing. +/// Release does not wait for a ready spare; a drained pool costs the next open +/// a cold boot. +pub fn pool_healthy(runtime: Runtime) -> Bool { + actor_call.try_call(runtime.subject, 1000, runtime_state.PoolHealthy) + |> result.unwrap(False) +} + +/// `pool_healthy` answered through `answer` without waiting for the runtime. +pub fn when_pool_healthy(runtime: Runtime, answer: fn(Bool) -> Nil) -> Nil { + process.send(runtime.subject, runtime_state.WhenPoolHealthy(answer)) } pub fn release_with_spare() -> Bool { diff --git a/src/albedo/harness/runtime/boot.gleam b/src/albedo/harness/runtime/boot.gleam index 356e40490..16d267659 100644 --- a/src/albedo/harness/runtime/boot.gleam +++ b/src/albedo/harness/runtime/boot.gleam @@ -477,7 +477,6 @@ pub fn spare_ready( case outcome { Ok(spare) if valid -> runtime_state.State(..state, spares: [spare, ..state.spares]) - |> notify_spare_waiters(state.shutdown == None && !state.detaching) Ok(spare) -> retire_spares(state, state.spares, [spare]) Error(_) -> { let _ = clock.send_after(state.self, 1000, runtime_state.FillSpares) @@ -521,38 +520,11 @@ fn retire_spares( ) } -/// One spare permits every resting session to release; only an open consumes it. -pub fn notify_spare_waiters( - state: runtime_state.State, - available: Bool, -) -> runtime_state.State { - state.spare_waiters - |> dict.values - |> list.each(fn(answer) { answer(available) }) - runtime_state.State(..state, spare_waiters: dict.new()) -} - -pub fn when_spare_available( - state: runtime_state.State, - id: String, - answer: fn(Bool) -> Nil, -) -> runtime_state.State { - case - list.any(state.spares, python.spare_current), - state.spare_target > 0 && !state.detaching - { - True, True -> { - answer(True) - state - } - False, True -> - runtime_state.State( - ..state, - spare_waiters: dict.insert(state.spare_waiters, id, answer), - ) - _, False -> { - answer(False) - state - } - } +/// The pool is enabled and not failing. Release does not wait for a ready +/// spare, so a drained pool costs the next open a cold boot. +pub fn pool_healthy(state: runtime_state.State) -> Bool { + state.spare_target > 0 + && state.shutdown == None + && !state.detaching + && !state.spare_retry } diff --git a/src/albedo/harness/runtime/kernels.gleam b/src/albedo/harness/runtime/kernels.gleam index b87970f0a..d2156edae 100644 --- a/src/albedo/harness/runtime/kernels.gleam +++ b/src/albedo/harness/runtime/kernels.gleam @@ -244,7 +244,6 @@ fn enqueue_stop( ) -> runtime_state.State { runtime_state.State( ..state, - spare_waiters: dict.delete(state.spare_waiters, id), stopping: dict.insert( state.stopping, id, diff --git a/src/albedo/harness/runtime/state.gleam b/src/albedo/harness/runtime/state.gleam index e7e11f5c2..d25a3ca34 100644 --- a/src/albedo/harness/runtime/state.gleam +++ b/src/albedo/harness/runtime/state.gleam @@ -246,7 +246,6 @@ pub type State { warming: Dict(Reference, Bool), retired_spares: List(python.Spare), spare_retry: Bool, - spare_waiters: Dict(String, fn(Bool) -> Nil), /// Reserved until stop confirmation; separate from boot admission. stopping: Dict(String, Stopping), failed_stops: Dict(String, String), @@ -274,7 +273,8 @@ pub type Message { SpareReady(Reference, Result(python.Spare, python.Error)) SpareStopped(Reference, python.Spare, Result(Nil, String)) SpareAvailable(Subject(Bool)) - WhenSpareAvailable(String, fn(Bool) -> Nil) + PoolHealthy(Subject(Bool)) + WhenPoolHealthy(fn(Bool) -> Nil) /// Answered through the callback, never by blocking the caller: a session /// actor asks and keeps serving while its kernel boots. Open(String, String, fn(Result(Session, python.Error)) -> Nil) -- knotmirror 0.0.1 From 5d2800f2c0a6fcb79ae096ef66d30d0ebde13a0a Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 06:11:49 -0400 Subject: [PATCH 17/72] Add kernel-free runtime.Prepared and prepare_session_async --- src/albedo/daemon/session.gleam | 16 ++- src/albedo/daemon/session_extensions.gleam | 10 +- src/albedo/daemon/session_prompt.gleam | 4 +- src/albedo/harness/compaction.gleam | 2 - src/albedo/harness/loop.gleam | 15 +-- src/albedo/harness/runtime.gleam | 113 ++++++++++++------ src/albedo/harness/runtime/preparation.gleam | 51 ++++++-- src/albedo/harness/runtime/state.gleam | 22 +++- test/e2e/albedo_prepare_probe.erl | 18 +++ test/e2e/kernel_prepare_test.py | 31 +++++ test/harness/compaction_projection_test.gleam | 4 +- test/harness/extension_failure_test.gleam | 4 +- test/harness/lcm_preparation_test.gleam | 6 +- test/harness/lcm_test.gleam | 10 +- test/harness/rolling_test.gleam | 6 +- test/manual/coding.gleam | 2 +- test/manual/copy_probe.gleam | 4 +- 17 files changed, 232 insertions(+), 86 deletions(-) create mode 100644 test/e2e/albedo_prepare_probe.erl create mode 100644 test/e2e/kernel_prepare_test.py diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 1918ba93c..e2222580b 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -3271,7 +3271,9 @@ fn compact( let report = turn.CompactionReport( selection_applied: strategy != None && result.is_ok(selected), - effective_strategy: option.then(state.kernel, runtime.compaction_name), + effective_strategy: option.then(state.kernel, fn(kernel) { + runtime.compaction_name(runtime.prepared(kernel)) + }), state: "failed", observation: None, failure: None, @@ -3285,10 +3287,12 @@ fn compact( use #(state, kernel, client) <- result.try( prepare_submission(state) |> result.map_error(submission_error), ) - use strategy <- result.try(case runtime.compaction_name(kernel) { - Some(strategy) -> Ok(strategy) - None -> Error("no compaction strategy is enabled") - }) + use strategy <- result.try( + case runtime.compaction_name(runtime.prepared(kernel)) { + Some(strategy) -> Ok(strategy) + None -> Error("no compaction strategy is enabled") + }, + ) use history <- result.try(projected_inputs(state)) use _ <- result.try(case history { [] -> Error("no conversation history to compact") @@ -3867,7 +3871,7 @@ fn observe(state: State, event: extension.SessionEvent) -> Nil { case option.or(state.kernel, state.released) { Some(kernel) -> runtime.observe( - kernel, + runtime.prepared(kernel), background_handle(state.info.id, state.self), event, ) diff --git a/src/albedo/daemon/session_extensions.gleam b/src/albedo/daemon/session_extensions.gleam index f3d5a265b..1cf0f1e83 100644 --- a/src/albedo/daemon/session_extensions.gleam +++ b/src/albedo/daemon/session_extensions.gleam @@ -51,7 +51,10 @@ fn apply( True -> #(state, Error("session must be idle to reload")) False -> { let previous = runtime.peek_prompt(state.host, state.info.id) - let previous_tools = option.map(state.kernel, runtime.tools) + let previous_tools = + option.map(state.kernel, fn(kernel) { + runtime.tools(runtime.prepared(kernel)) + }) case run() { runtime_state.ApplyFailed(kernel, error) -> { let state = @@ -74,7 +77,10 @@ fn apply( context: session_state.unprepared(), ) let #(state, warnings) = case - previous_tools == option.map(kernel, runtime.tools) + previous_tools + == option.map(kernel, fn(kernel) { + runtime.tools(runtime.prepared(kernel)) + }) { False -> { let state = session_prompt.reset_prompt_cache(state, reason) diff --git a/src/albedo/daemon/session_prompt.gleam b/src/albedo/daemon/session_prompt.gleam index 1e15f0c9e..6fd60cc64 100644 --- a/src/albedo/daemon/session_prompt.gleam +++ b/src/albedo/daemon/session_prompt.gleam @@ -173,7 +173,7 @@ pub fn remember_prompt( runtime.ledger(state.host), state.info.id, conversation.PinnedPrompt(instructions, context), - requests.tools_hash(runtime.tools(kernel)), + requests.tools_hash(runtime.tools(runtime.prepared(kernel))), ) { Ok(_) -> state @@ -200,7 +200,7 @@ pub fn reconcile_prompt( |> option.map(fn(prompt) { conversation.PinnedPrompt(prompt.0, prompt.1) }) let tools = option.map(state.kernel, fn(kernel) { - requests.tools_hash(runtime.tools(kernel)) + requests.tools_hash(runtime.tools(runtime.prepared(kernel))) }) case conversation.known_prompt(runtime.ledger(state.host), state.info.id) { Error(error) -> diff --git a/src/albedo/harness/compaction.gleam b/src/albedo/harness/compaction.gleam index 68e2e6fc5..c3648699b 100644 --- a/src/albedo/harness/compaction.gleam +++ b/src/albedo/harness/compaction.gleam @@ -2,7 +2,6 @@ import albedo/daemon/note import albedo/daemon/store -import albedo/harness/extensions/python/kernel import albedo/openai_api/types import albedo/text_scalars import gleam/dynamic/decode @@ -48,7 +47,6 @@ pub type Context { Context( store: store.Store, session: String, - kernel: kernel.Kernel, model: String, source: String, pinned_tokens: Int, diff --git a/src/albedo/harness/loop.gleam b/src/albedo/harness/loop.gleam index 437c3bdbc..cbf61b4c0 100644 --- a/src/albedo/harness/loop.gleam +++ b/src/albedo/harness/loop.gleam @@ -604,7 +604,7 @@ type Invoked { fn invoke(state: Loop, call: types.ToolCall) -> Result(Invoked, String) { // Before the hooks, so they judge the cell that runs. - let call = runtime.as_cell(state.kernel, call) + let call = runtime.as_cell(runtime.prepared(state.kernel), call) let asked = hook.Call(call.id, call.name, call.arguments, None) let started = requests.now() use hook.Answer(calling, _) <- result.try(hooked(state, hook.Calling(asked))) @@ -635,7 +635,7 @@ fn invoke(state: Loop, call: types.ToolCall) -> Result(Invoked, String) { } let hook.Answer(called, by) = runtime.hook( - state.kernel, + runtime.prepared(state.kernel), hook.Called( hook.Call(..asked, arguments: call.arguments), body, @@ -657,7 +657,7 @@ fn invoke(state: Loop, call: types.ToolCall) -> Result(Invoked, String) { /// Asks the session's hooks, shows the user their notes, and ends the turn /// if one of them asked to. fn hooked(state: Loop, event: hook.Event) -> Result(hook.Answer, String) { - let answer = runtime.hook(state.kernel, event) + let answer = runtime.hook(runtime.prepared(state.kernel), event) note(state, answer.verdict) case answer.verdict.halt { Some(reason) -> Error("stopped by a hook: " <> reason) @@ -778,7 +778,7 @@ fn prepare( ) -> Result(compaction.Prepared, String) { runtime.prepare_view_scoped( state.host, - state.kernel, + runtime.prepared(state.kernel), state.model, request_source(state.upstream, state.model), extension.clean_endpoint(state.upstream.endpoint), @@ -1226,14 +1226,15 @@ fn request_for( model, Some(instructions), tool_results.pair(history), - runtime.tools(kernel), + runtime.tools(runtime.prepared(kernel)), None, types.Options(..types.defaults, effort: effort), ) } fn kernel_instructions(kernel: runtime.Session) -> String { - runtime.instructions(kernel) <> context_text(runtime.context(kernel)) + runtime.instructions(runtime.prepared(kernel)) + <> context_text(runtime.context(runtime.prepared(kernel))) } fn context_text(context: List(types.Input)) -> String { @@ -1309,7 +1310,7 @@ pub fn rebuild( ) -> Result(#(types.Request, requests.Prefix), String) { use prepared <- result.map(runtime.project_view_scoped( host, - kernel, + runtime.prepared(kernel), model, request_source(upstream, model), extension.clean_endpoint(upstream.endpoint), diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index aa95ac04b..3fa809b89 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -41,6 +41,10 @@ import gleam/string pub type Runtime = runtime_state.Runtime +/// A session's composition without a kernel; see `runtime/state`. +pub type Prepared = + runtime_state.Prepared + /// One session's kernel and prepared composition; see `runtime/state`. pub type Session = runtime_state.Session @@ -302,6 +306,33 @@ pub fn open_session_async( } } +/// The session's composition for `cwd`, prepared without booting a kernel; +/// `answer` runs once it is ready or has failed. +pub fn prepare_session_async( + runtime: Runtime, + id: String, + cwd: String, + answer: fn(Result(Prepared, python.Error)) -> Nil, +) -> Nil { + case kernels.checked_id(id) { + Ok(id) -> + process.send(runtime.subject, runtime_state.Prepare(id, cwd, answer)) + Error(invalid) -> answer(Error(invalid)) + } +} + +/// The kernel-free part of a session. +pub fn prepared(session: Session) -> Prepared { + runtime_state.Prepared( + session.id, + session.cwd, + session.owner, + session.composition, + session.instructions, + session.context, + ) +} + /// Save a desired extension choice and apply it to an idle session. pub fn reload_extension( runtime: Runtime, @@ -382,8 +413,8 @@ pub fn peek_prompt( } /// Extension context blocks included in this session's system instructions. -pub fn context(session: Session) -> List(types.Input) { - session.context +pub fn context(prepared: Prepared) -> List(types.Input) { + prepared.context } pub fn extension_summaries( @@ -566,7 +597,7 @@ pub fn execute( code: String, timeout_ms: Int, ) -> Result(Execution, String) { - use _ <- result.try(owned_by(runtime, session)) + use _ <- result.try(owned_by(runtime, session.owner)) use id <- result.try(journal.begin(runtime.ledger, session.id, code)) let outcome = python.execute_saved(session.kernel, id, code, timeout_ms, types.any_images) @@ -578,8 +609,8 @@ pub fn cell(runtime: Runtime, id: String) -> Result(journal.Cell, String) { journal.get(runtime.ledger, id) } -fn owned_by(runtime: Runtime, session: Session) -> Result(Nil, String) { - case session.owner == runtime.ledger { +fn owned_by(runtime: Runtime, owner: store.Store) -> Result(Nil, String) { + case owner == runtime.ledger { True -> Ok(Nil) False -> Error("session belongs to another runtime") } @@ -678,6 +709,10 @@ fn refuse( process.send(reply, Error(reason)) True } + runtime_state.Prepare(_, _, answer) -> { + answer(Error(python.Unavailable(reason))) + True + } runtime_state.ObserveComposition(_, _, reply) -> { process.send(reply, Error(reason)) True @@ -718,6 +753,7 @@ fn settling( runtime_state.Open(id, ..) | runtime_state.Upgrade(id, ..) | runtime_state.Peek(id, ..) + | runtime_state.Prepare(id, ..) | runtime_state.Reattach(id, ..) | runtime_state.Reset(id, ..) | runtime_state.Forget(id, ..) @@ -1104,6 +1140,10 @@ fn serve( } runtime_state.Peek(id, cwd, reply) -> continue(preparation.peek(state, id, cwd, reply) |> boot.boot_next) + runtime_state.Prepare(id, cwd, answer) -> + continue( + preparation.prepare_only(state, id, cwd, answer) |> boot.boot_next, + ) runtime_state.Reset(id, reply) -> continue( kernels.begin_stop(state, id, runtime_state.ResetKernel(reply)) @@ -1157,8 +1197,8 @@ fn serve( } } -pub fn tools(session: Session) -> List(types.Tool) { - composition.tools(session.composition) +pub fn tools(prepared: Prepared) -> List(types.Tool) { + composition.tools(prepared.composition) |> list.map(fn(tool) { tool.definition }) } @@ -1192,7 +1232,7 @@ pub fn invoke( call: types.ToolCall, images: types.ImageLimits, ) -> Result(types.Input, String) { - use _ <- result.try(owned_by(runtime, session)) + use _ <- result.try(owned_by(runtime, session.owner)) case tool_call(runtime, session, call, images) { Error(_) -> Ok(refusal( @@ -1212,9 +1252,9 @@ pub fn invoke( /// `call` as the python cell it stands for when it names a kernel binding /// (`files.find`, `web_search`) and no tool: models trained on native tools /// call the bindings directly. Any other call comes back unchanged. -pub fn as_cell(session: Session, call: types.ToolCall) -> types.ToolCall { +pub fn as_cell(prepared: Prepared, call: types.ToolCall) -> types.ToolCall { let declared = fn(name) { - composition.tools(session.composition) + composition.tools(prepared.composition) |> list.any(fn(tool) { tool.definition.name == name }) } case !declared(call.name) && declared("python") && binding(call.name) { @@ -1293,28 +1333,28 @@ pub fn recover( } } -pub fn instructions(session: Session) -> String { - session.instructions +pub fn instructions(prepared: Prepared) -> String { + prepared.instructions } /// Asks every hook this session composed about one step of its turn. -pub fn hook(session: Session, event: hook.Event) -> hook.Answer { - hook.ask(composition.hooks(session.composition), event) +pub fn hook(prepared: Prepared, event: hook.Event) -> hook.Answer { + hook.ask(composition.hooks(prepared.composition), event) } /// Tells every extension this session composed about one of its events. pub fn observe( - session: Session, + prepared: Prepared, handle: extension.Session, event: extension.SessionEvent, ) -> Nil { - list.each(composition.observers(session.composition), fn(observe) { + list.each(composition.observers(prepared.composition), fn(observe) { observe(handle, event) }) } -pub fn compaction_name(session: Session) -> Option(String) { - extension.compaction(composition.extensions(session.composition)) +pub fn compaction_name(prepared: Prepared) -> Option(String) { + extension.compaction(composition.extensions(prepared.composition)) |> option.map(fn(strategy) { strategy.name }) } @@ -1322,7 +1362,7 @@ pub fn compaction_name(session: Session) -> Option(String) { /// system instructions, not the request history or durable transcript. pub fn prepare_history_with( runtime: Runtime, - session: Session, + prepared: Prepared, model: String, instructions: String, summarize: fn(compaction.SummaryRequest) -> Result(String, String), @@ -1330,7 +1370,7 @@ pub fn prepare_history_with( ) -> Result(List(types.Input), String) { prepare_view_scoped( runtime, - session, + prepared, model, model, None, @@ -1364,12 +1404,12 @@ fn reads_text_only( /// Only a catalog answer becomes a capacity; an unknown model stays unknown. fn model_info( - session: Session, + prepared: Prepared, model: String, endpoint: Option(String), ) -> Option(extension.ModelInfo) { extension.model_info( - composition.extensions(session.composition), + composition.extensions(prepared.composition), model, endpoint, ) @@ -1569,7 +1609,7 @@ fn reader(info: Option(extension.ModelInfo)) -> Option(compaction.Reader) { /// Run the active strategy now, independent of its automatic threshold. pub fn compact_history_scoped( runtime: Runtime, - session: Session, + prepared: Prepared, model: String, source: String, endpoint: Option(String), @@ -1579,7 +1619,7 @@ pub fn compact_history_scoped( ) -> Result(List(types.Input), String) { prepare_view_scoped( runtime, - session, + prepared, model, source, endpoint, @@ -1598,7 +1638,7 @@ pub fn compact_history_scoped( /// Prepare one provider request and its strategy-neutral inspection facts. pub fn prepare_view_scoped( runtime: Runtime, - session: Session, + prepared: Prepared, model: String, source: String, endpoint: Option(String), @@ -1613,7 +1653,7 @@ pub fn prepare_view_scoped( ) -> Result(compaction.Prepared, String) { view_scoped( runtime, - session, + prepared, model, source, endpoint, @@ -1634,7 +1674,7 @@ pub fn prepare_view_scoped( /// it writes nothing and calls no model. pub fn project_view_scoped( runtime: Runtime, - session: Session, + prepared: Prepared, model: String, source: String, endpoint: Option(String), @@ -1644,7 +1684,7 @@ pub fn project_view_scoped( ) -> Result(compaction.Prepared, String) { view_scoped( runtime, - session, + prepared, model, source, endpoint, @@ -1662,7 +1702,7 @@ pub fn project_view_scoped( fn view_scoped( runtime: Runtime, - session: Session, + prepared: Prepared, model: String, source: String, endpoint: Option(String), @@ -1677,13 +1717,13 @@ fn view_scoped( view: fn(compaction.Strategy, compaction.Context, List(types.Input)) -> Result(compaction.Prepared, String), ) -> Result(compaction.Prepared, String) { - use _ <- result.try(owned_by(runtime, session)) - let pinned_tokens = compaction.estimate_pinned(instructions, tools(session)) - let enabled = composition.extensions(session.composition) - let info = model_info(session, model, endpoint) + use _ <- result.try(owned_by(runtime, prepared.owner)) + let pinned_tokens = compaction.estimate_pinned(instructions, tools(prepared)) + let enabled = composition.extensions(prepared.composition) + let info = model_info(prepared, model, endpoint) use window <- result.try(session_configuration.context_window( runtime.ledger, - session.id, + prepared.id, )) case extension.compaction(enabled) { None if force -> Error("no compaction strategy is enabled") @@ -1692,8 +1732,7 @@ fn view_scoped( let context = compaction.Context( runtime.ledger, - session.id, - session.kernel, + prepared.id, model, source, pinned_tokens, @@ -1706,7 +1745,7 @@ fn view_scoped( folds.owner != strategy.name }), runtime.ledger, - session.id, + prepared.id, project, ), reader(info), diff --git a/src/albedo/harness/runtime/preparation.gleam b/src/albedo/harness/runtime/preparation.gleam index 4ca5e0b7d..baafbd39b 100644 --- a/src/albedo/harness/runtime/preparation.gleam +++ b/src/albedo/harness/runtime/preparation.gleam @@ -195,12 +195,7 @@ pub fn finish_commands( dict.get(state.commands, id) |> result.unwrap([]) |> list.reverse - |> list.each(fn(waiter) { - process.send( - waiter.reply, - outcome |> result.try(command_value(id, waiter.cwd, _)), - ) - }) + |> list.each(fn(waiter) { waiter.answer(outcome) }) runtime_state.State(..state, commands: dict.delete(state.commands, id)) } @@ -231,10 +226,50 @@ pub fn peek( id: String, cwd: String, reply: Subject(Result(#(List(command.Command), command.Context), String)), +) -> runtime_state.State { + await_composition(state, id, cwd, fn(outcome) { + process.send(reply, outcome |> result.try(command_value(id, cwd, _))) + }) +} + +/// The session's composition for `cwd` without a kernel. A prepared +/// composition of another workspace is an error; the caller resets first. +pub fn prepare_only( + state: runtime_state.State, + id: String, + cwd: String, + answer: fn(Result(runtime_state.Prepared, python.Error)) -> Nil, +) -> runtime_state.State { + let owner = state.ledger + await_composition(state, id, cwd, fn(outcome) { + answer(case outcome { + Ok(cached) if cached.cwd == cwd -> + Ok(runtime_state.Prepared( + id, + cached.cwd, + owner, + cached.composition, + cached.instructions, + cached.context, + )) + Ok(_) -> + Error(python.Invalid( + "prepared composition belongs to another workspace", + )) + Error(reason) -> Error(python.Invalid(reason)) + }) + }) +} + +fn await_composition( + state: runtime_state.State, + id: String, + cwd: String, + answer: fn(Result(runtime_state.Cached, String)) -> Nil, ) -> runtime_state.State { case dict.get(state.compositions, id) { Ok(cached) if cached.cwd == cwd -> { - process.send(reply, command_value(id, cwd, cached)) + answer(Ok(cached)) state } _ -> { @@ -243,7 +278,7 @@ pub fn peek( runtime_state.State( ..state, commands: dict.insert(state.commands, id, [ - runtime_state.CommandWaiter(cwd, reply), + runtime_state.CommandWaiter(answer), ..waiters ]), ) diff --git a/src/albedo/harness/runtime/state.gleam b/src/albedo/harness/runtime/state.gleam index d25a3ca34..8640a90f2 100644 --- a/src/albedo/harness/runtime/state.gleam +++ b/src/albedo/harness/runtime/state.gleam @@ -39,6 +39,20 @@ pub type Installed { ) } +/// A session's composition without a kernel: everything a turn needs to build a +/// request, run hooks, and declare tools. `runtime.prepared` takes it from a +/// `Session`; `runtime.prepare_session_async` makes one without booting Python. +pub type Prepared { + Prepared( + id: String, + cwd: String, + owner: store.Store, + composition: composition.Composition, + instructions: String, + context: List(types.Input), + ) +} + pub type Session { Session( id: String, @@ -219,11 +233,9 @@ pub type Preparation { Preparation(generation: Reference, work: PreparedWork) } +/// Someone who needs a session's composition without its kernel. pub type CommandWaiter { - CommandWaiter( - cwd: String, - reply: Subject(Result(#(List(command.Command), command.Context), String)), - ) + CommandWaiter(answer: fn(Result(Cached, String)) -> Nil) } pub type State { @@ -269,6 +281,8 @@ pub type State { pub const boot_slots = 4 pub type Message { + /// The session's prepared composition, booting no kernel. + Prepare(String, String, fn(Result(Prepared, python.Error)) -> Nil) FillSpares SpareReady(Reference, Result(python.Spare, python.Error)) SpareStopped(Reference, python.Spare, Result(Nil, String)) diff --git a/test/e2e/albedo_prepare_probe.erl b/test/e2e/albedo_prepare_probe.erl new file mode 100644 index 000000000..1bc04864f --- /dev/null +++ b/test/e2e/albedo_prepare_probe.erl @@ -0,0 +1,18 @@ +%% Exercise runtime.prepare_session_async against the live daemon runtime. +-module(albedo_prepare_probe). +-export([prepare_json/2]). + +host() -> + [Name] = [N || N <- registered(), lists:prefix("albedo_registry", atom_to_list(N))], + {ok, Runtime} = 'albedo@daemon@registry':host('gleam@erlang@process':named_subject(Name)), + Runtime. + +prepare_json(Id, Cwd) -> + Runtime = host(), Parent = self(), + 'albedo@harness@runtime':prepare_session_async(Runtime, Id, Cwd, + fun(Value) -> Parent ! {prepared, Value} end), + {ok, Prepared} = receive {prepared, {ok, P}} -> {ok, P} after 15000 -> error(prepare_timeout) end, + Tools = 'albedo@harness@runtime':tools(Prepared), + Held = lists:keymember(Id, 1, 'albedo@harness@runtime':held_kernels(Runtime)), + json:encode(#{tools => length(Tools), kernel_held => Held, + instructions => byte_size('albedo@harness@runtime':instructions(Prepared)) > 0}). diff --git a/test/e2e/kernel_prepare_test.py b/test/e2e/kernel_prepare_test.py new file mode 100644 index 000000000..b994470b3 --- /dev/null +++ b/test/e2e/kernel_prepare_test.py @@ -0,0 +1,31 @@ +"""A session's composition is prepared without booting a Python kernel. + +The lazy-kernel path needs a session's tools, instructions and hooks before any +cell runs; only the daemon's real runtime can show that no kernel process was +started for it, so this runs through an inspected daemon. +""" + +import unittest + +from harness import ROOT, Albedo, Provider, exclusive, text +from inspect_support import Inspection + + +@exclusive +class PrepareWithoutKernelTests(unittest.TestCase): + def test_a_prepared_session_has_tools_and_no_kernel(self): + provider = Provider(lambda request: text("ok")) + self.addCleanup(provider.close) + + def prepare(app): + app.daemon.env["ALBEDO_INSPECT"] = "1" + + with Albedo(provider, prepare=prepare) as app: + session = app.session() + probe = Inspection(app, ROOT / "test/e2e/albedo_prepare_probe.erl") + report = probe.call_json( + "prepare_json", f'[<<"{session}">>, <<"{app.workspace}">>]' + ) + self.assertGreater(report["tools"], 0, report) + self.assertTrue(report["instructions"], report) + self.assertFalse(report["kernel_held"], report) diff --git a/test/harness/compaction_projection_test.gleam b/test/harness/compaction_projection_test.gleam index 0013ae1ca..eb166b4c2 100644 --- a/test/harness/compaction_projection_test.gleam +++ b/test/harness/compaction_projection_test.gleam @@ -71,7 +71,7 @@ fn projections_write_nothing( let assert Ok(_) = runtime.compact_history_scoped( host, - session, + runtime.prepared(session), "model", "model", None, @@ -84,7 +84,7 @@ fn projections_write_nothing( let assert Ok(inputs) = runtime.prepare_history_with( host, - session, + runtime.prepared(session), "model", "", fn(_) { Error("a projection must not summarize") }, diff --git a/test/harness/extension_failure_test.gleam b/test/harness/extension_failure_test.gleam index ee8c2143d..7c81f25ba 100644 --- a/test/harness/extension_failure_test.gleam +++ b/test/harness/extension_failure_test.gleam @@ -97,7 +97,7 @@ fn plugin_only(name: String, plugin: extension.Plugin) -> extension.Extension { } fn tool_names(session: runtime.Session) -> List(String) { - runtime.tools(session) |> list.map(fn(tool) { tool.name }) + runtime.tools(runtime.prepared(session)) |> list.map(fn(tool) { tool.name }) } fn warned_about(session: runtime.Session, name: String) -> Bool { @@ -228,7 +228,7 @@ pub fn a_crashing_observer_leaves_the_session_working_test() -> Nil { healthy("working"), ]) runtime.observe( - session, + runtime.prepared(session), extension.Session( "broken-extension-test", fn(_, _) { Error("no upstream") }, diff --git a/test/harness/lcm_preparation_test.gleam b/test/harness/lcm_preparation_test.gleam index d34d251fb..f5cca4dad 100644 --- a/test/harness/lcm_preparation_test.gleam +++ b/test/harness/lcm_preparation_test.gleam @@ -81,7 +81,7 @@ pub fn below_trigger_and_stored_prior_do_not_decode_archived_payloads_test() -> count_decodes(store.owner(ledger), fn() { runtime.prepare_history_with( host, - session, + runtime.prepared(session), "model", "", fn(_) { panic as "below-trigger preparation must not summarize" }, @@ -116,7 +116,7 @@ pub fn below_trigger_and_stored_prior_do_not_decode_archived_payloads_test() -> count_decodes(store.owner(ledger), fn() { runtime.compact_history_scoped( host, - session, + runtime.prepared(session), "model", "model", None, @@ -133,7 +133,7 @@ pub fn below_trigger_and_stored_prior_do_not_decode_archived_payloads_test() -> count_decodes(store.owner(ledger), fn() { runtime.compact_history_scoped( host, - session, + runtime.prepared(session), "model", "model", None, diff --git a/test/harness/lcm_test.gleam b/test/harness/lcm_test.gleam index 9faffffb7..7371ec42f 100644 --- a/test/harness/lcm_test.gleam +++ b/test/harness/lcm_test.gleam @@ -274,7 +274,7 @@ fn compact( ) -> Result(List(types.Input), String) { runtime.compact_history_scoped( host, - session, + runtime.prepared(session), "model", "model", None, @@ -309,7 +309,7 @@ pub fn the_trigger_reads_the_tokens_the_provider_reported_test() -> Nil { let prepare = fn(reported) { runtime.prepare_view_scoped( host, - session, + runtime.prepared(session), "model", "model", None, @@ -347,7 +347,7 @@ pub fn a_leaf_summarizes_its_rows_as_the_requests_provider_reads_them_test() -> let assert Ok(_) = runtime.prepare_view_scoped( host, - session, + runtime.prepared(session), "model", "model", None, @@ -692,7 +692,7 @@ pub fn the_tail_is_the_uncovered_rows_as_the_provider_reads_them_test() -> Nil { let assert Ok(prepared) = runtime.prepare_view_scoped( host, - session, + runtime.prepared(session), "model", "model", None, @@ -756,7 +756,7 @@ fn prepare_reported( ) -> Result(compaction.Prepared, String) { runtime.prepare_view_scoped( host, - session, + runtime.prepared(session), "model", "model", None, diff --git a/test/harness/rolling_test.gleam b/test/harness/rolling_test.gleam index 7cbdb9308..120ab5e8b 100644 --- a/test/harness/rolling_test.gleam +++ b/test/harness/rolling_test.gleam @@ -68,7 +68,7 @@ pub fn legacy_item_count_state_resumes_and_compaction_upgrades_it_test() -> Nil let assert Ok([types.User(summary), _, ..tail]) = runtime.prepare_history_with( host, - session, + runtime.prepared(session), "model-a", "", fn(_) { Error("must not summarize") }, @@ -86,7 +86,7 @@ pub fn legacy_item_count_state_resumes_and_compaction_upgrades_it_test() -> Nil let assert Ok(_) = runtime.compact_history_scoped( host, - session, + runtime.prepared(session), "model-a", "model-a", None, @@ -134,7 +134,7 @@ pub fn long_eviction_summarizes_in_chunks_test() -> Nil { let assert Ok(_) = runtime.compact_history_scoped( host, - session, + runtime.prepared(session), "model-a", "model-a", None, diff --git a/test/manual/coding.gleam b/test/manual/coding.gleam index 11454e90d..962c8b641 100644 --- a/test/manual/coding.gleam +++ b/test/manual/coding.gleam @@ -53,7 +53,7 @@ pub fn main() -> Nil { types.Request( ..openai.request(env("ALBEDO_BENCH_MODEL"), [types.User(task)]), instructions: Some(instructions), - tools: runtime.tools(session), + tools: runtime.tools(runtime.prepared(session)), max_output_tokens: Some(4096), ) let start = now() diff --git a/test/manual/copy_probe.gleam b/test/manual/copy_probe.gleam index f0ee83105..1046fe4d2 100644 --- a/test/manual/copy_probe.gleam +++ b/test/manual/copy_probe.gleam @@ -43,7 +43,7 @@ pub fn main() -> Nil { list.each(managed, fn(prepared) { report(" managed " <> prepared.extension, prepared.value) }) - report(" instructions", runtime.instructions(session)) - report(" context", runtime.context(session)) + report(" instructions", runtime.instructions(runtime.prepared(session))) + report(" context", runtime.context(runtime.prepared(session))) runtime.stop(host) } -- knotmirror 0.0.1 From 5eafee505652095752a56eb26bd5e5b66a52086d Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 06:32:53 -0400 Subject: [PATCH 18/72] stalls: start returns once the monitor is installed, and its test hears only its own fixture --- src/albedo/daemon/albedo_stalls.erl | 11 +++++++---- test/daemon/albedo_stalls_test.erl | 6 +++++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/albedo/daemon/albedo_stalls.erl b/src/albedo/daemon/albedo_stalls.erl index 9092b04f4..5ba355927 100644 --- a/src/albedo/daemon/albedo_stalls.erl +++ b/src/albedo/daemon/albedo_stalls.erl @@ -12,23 +12,26 @@ start() -> start(#{}). %% Options: long_gc and long_schedule in ms, large_heap in words, report/1 for -%% each line, and name (the registered name, `undefined` for none). +%% each line, and name (the registered name, `undefined` for none). Returns +%% once the monitor is installed, so nothing after it goes unwatched. start(Options) -> Name = maps:get(name, Options, ?MODULE), case Name =/= undefined andalso whereis(Name) of Pid when is_pid(Pid) -> Pid; _ -> - Pid = spawn(fun() -> init(Options) end), + Parent = self(), + Pid = spawn(fun() -> init(Parent, Options) end), Name =:= undefined orelse register(Name, Pid), - Pid + receive {Pid, watching} -> Pid end end. -init(Options) -> +init(Parent, Options) -> erlang:system_monitor(self(), [ {long_gc, maps:get(long_gc, Options, 250)}, {long_schedule, maps:get(long_schedule, Options, 250)}, {large_heap, maps:get(large_heap, Options, 4 * 1024 * 1024)}, busy_port]), + Parent ! {self(), watching}, Report = maps:get(report, Options, fun log/1), loop(Report, erlang:monotonic_time(millisecond), 0, 0). diff --git a/test/daemon/albedo_stalls_test.erl b/test/daemon/albedo_stalls_test.erl index 9b6decb8c..31af6b634 100644 --- a/test/daemon/albedo_stalls_test.erl +++ b/test/daemon/albedo_stalls_test.erl @@ -6,7 +6,11 @@ names_the_process_with_a_large_heap_test() -> Previous = erlang:system_monitor(), Parent = self(), - Monitor = albedo_stalls:start(#{name => undefined, large_heap => 100000, + %% Only the fixture's heap passes this bound, and long schedules and + %% collections are off: other tests' events would spend the window's + %% line budget before the fixture's arrives. + Monitor = albedo_stalls:start(#{name => undefined, large_heap => 3000000, + long_gc => 3600000, long_schedule => 3600000, report => fun(Line) -> Parent ! {stall, lists:flatten(Line)} end}), try spawn(fun() -> -- knotmirror 0.0.1 From 1e2d888fa07df500eedb29701b4de28d3df2c73a Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 06:26:33 -0400 Subject: [PATCH 19/72] Keep kernels with live threads, timers, resources or env changes from release --- priv/python/albedo_api.py | 2 + priv/python/albedo_cells.py | 36 +++++- priv/python/albedo_link.py | 15 ++- .../python/albedo_plugins/browser/__init__.py | 7 ++ priv/python/albedo_plugins/cua.py | 2 + priv/python/albedo_plugins/remote.py | 4 + priv/python/albedo_quiescence.py | 93 ++++++++++++++ robot-docs/kernel.md | 17 +++ src/albedo/daemon/session_namespace.gleam | 17 +++ .../extensions/python/albedo_python.erl | 15 ++- test/e2e/albedo_kernel_spare_probe.erl | 8 +- test/e2e/idle_reap_test.py | 4 +- test/e2e/kernel_pool_test.py | 119 ++++++++++++++++++ test/e2e/kernel_state_test.py | 3 +- 14 files changed, 329 insertions(+), 13 deletions(-) create mode 100644 priv/python/albedo_quiescence.py diff --git a/priv/python/albedo_api.py b/priv/python/albedo_api.py index da5575bf7..51b06b5a4 100644 --- a/priv/python/albedo_api.py +++ b/priv/python/albedo_api.py @@ -191,6 +191,8 @@ class PythonApi: ] | None ) = None + # A resource that cannot survive a namespace save keeps this kernel alive. + owns_resources: Callable[[Callable[[], bool]], None] | None = None class PythonPlugin(Protocol): diff --git a/priv/python/albedo_cells.py b/priv/python/albedo_cells.py index 98954cd4a..fc959fcc8 100644 --- a/priv/python/albedo_cells.py +++ b/priv/python/albedo_cells.py @@ -12,6 +12,7 @@ import albedo_link import albedo_memory from albedo_protocol import parse_incoming import albedo_proc +import albedo_quiescence import albedo_shell from collections.abc import Awaitable, Callable, Iterable, Sequence from typing import cast @@ -94,6 +95,9 @@ FINISHED_IMAGE_BYTES = 8 * 1024 * 1024 EXECUTING: set[str] = set() # Interrupts that arrived while their cell was still queued, by cell id. INTERRUPTS: dict[str, str] = {} +QUIESCENCE: albedo_quiescence.Quiescence | None = None +RESOURCE_OWNERS: list[Callable[[], bool]] = [] +LAST_WORK: tuple[int, bool] | None = None READY = threading.Event() NAMESPACE: dict[str, object] = {"__name__": "__main__"} DEFINITIONS: collections.OrderedDict[str, str] = collections.OrderedDict() @@ -252,6 +256,7 @@ def hello() -> dict[str, object]: "leader": albedo_proc.leader_token(os.getpid()), "ready": READY.is_set(), "cells": len(CELL_TASKS), + "quiescent": LAST_WORK[1] if LAST_WORK is not None else False, } @@ -1494,6 +1499,26 @@ async def finish_background( CELL_ANNOUNCER = LOOP.create_task(announce_cells()) +def link_resources() -> tuple[set[threading.Thread], set[int]]: + if isinstance(LINK, albedo_link.SocketLink): + return LINK.resources() + return set(), set() + + +def publish_work() -> None: + global LAST_WORK + quiet = QUIESCENCE is not None and QUIESCENCE.ready() + observation = (len(CELL_TASKS), quiet) + if observation != LAST_WORK: + LAST_WORK = observation + send({"type": "cells", "live": observation[0], "quiescent": quiet}) + + +def refresh_work() -> None: + publish_work() + LOOP.call_later(1.0, refresh_work) + + def retain_cell_result(id: str, done: dict[str, object]) -> None: FINISHED[id] = done while len(FINISHED) > FINISHED_LIMIT: @@ -1518,7 +1543,7 @@ def retain_cell_result(id: str, done: dict[str, object]) -> None: capture.end_spill() capture.images.clear() remember(capture) - send({"type": "cells", "live": len(CELL_TASKS)}) + publish_work() def cell_timers( @@ -1604,7 +1629,7 @@ async def serve(): CELL_TASKS[capture.id] = task CELL_CAPTURES[capture.id] = capture CELL_STARTS[capture.id] = albedo_memory.footprint() or 0 - send({"type": "cells", "live": len(CELL_TASKS)}) + publish_work() interrupted = INTERRUPTS.pop(capture.id, None) if interrupted is not None: capture.interruption = interrupted @@ -1714,7 +1739,7 @@ class Bindings(ModuleType): def main(): - global NATIVE_FD + global NATIVE_FD, QUIESCENCE if os.getpgrp() != os.getpid(): os.setsid() modules = open_link(sys.argv) @@ -1759,6 +1784,7 @@ def main(): attach_image=attach_image, on_stop_job=STOP_HANDLERS.append, on_job_view=JOB_VIEWS.append, + owns_resources=RESOURCE_OWNERS.append, ) NAMESPACE.update( cells=Cells(), @@ -1796,6 +1822,10 @@ def main(): ) READY.set() task = LOOP.create_task(serve()) + QUIESCENCE = albedo_quiescence.Quiescence( + LOOP, RESOURCE_OWNERS, link_resources, refresh_work + ) + LOOP.call_soon(refresh_work) while not task.done(): try: LOOP.run_until_complete(task) diff --git a/priv/python/albedo_link.py b/priv/python/albedo_link.py index 01ac9e8d0..cc939d4bf 100644 --- a/priv/python/albedo_link.py +++ b/priv/python/albedo_link.py @@ -246,6 +246,7 @@ class SocketLink: self.jobs = JobBook() self.epoch = 0 self.connection: socket.socket | None = None + self.threads: set[threading.Thread] = set() self.detached_at = time.monotonic() self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # Bound relative to the run directory: sun_path holds ~104 bytes and a @@ -270,6 +271,11 @@ class SocketLink: def attached(self) -> bool: return self.connection is not None + def resources(self) -> tuple[set[threading.Thread], set[int]]: + with self.lock: + sockets = [self.listener, self.connection] + return set(self.threads), {s.fileno() for s in sockets if s is not None} + def idle_for(self) -> float: """Seconds with nothing attached; zero while attached.""" if self.connection is not None: @@ -280,9 +286,12 @@ class SocketLink: """Accept attaches forever; each connection reads on its own thread.""" while True: connection, _ = self.listener.accept() - threading.Thread( + thread = threading.Thread( target=self._session, args=(connection, dispatch), daemon=True - ).start() + ) + with self.lock: + self.threads.add(thread) + thread.start() def _write(self, data: bytes) -> None: connection = self.connection @@ -372,3 +381,5 @@ class SocketLink: pass finally: self._detach(connection) + with self.lock: + self.threads.discard(threading.current_thread()) diff --git a/priv/python/albedo_plugins/browser/__init__.py b/priv/python/albedo_plugins/browser/__init__.py index 79b0bf574..50783b8fc 100644 --- a/priv/python/albedo_plugins/browser/__init__.py +++ b/priv/python/albedo_plugins/browser/__init__.py @@ -133,10 +133,17 @@ async def _cleanup() -> None: await launch.cleanup_all() +def owns_resources() -> bool: + launch = sys.modules.get(f"{__name__}.launch") + return launch is not None and bool(launch._LIVE) + + def setup(api: PythonApi) -> dict[str, object]: hooks.attach_image = api.attach_image hooks.unobserved = albedo_trace.unobserved api.on_shutdown(_cleanup) + if api.owns_resources is not None: + api.owns_resources(owns_resources) return { "browser": browser, "BrowserError": BrowserError, diff --git a/priv/python/albedo_plugins/cua.py b/priv/python/albedo_plugins/cua.py index 34447f053..ae3f5ee9f 100644 --- a/priv/python/albedo_plugins/cua.py +++ b/priv/python/albedo_plugins/cua.py @@ -2084,4 +2084,6 @@ def setup(api: PythonApi) -> dict[str, object]: global attach_image attach_image = api.attach_image api.on_shutdown(_cleanup) + if api.owns_resources is not None: + api.owns_resources(_CLIENT._running) return {"cua": cua, "CuaError": CuaError} diff --git a/priv/python/albedo_plugins/remote.py b/priv/python/albedo_plugins/remote.py index d7d40df3e..8e5553aae 100644 --- a/priv/python/albedo_plugins/remote.py +++ b/priv/python/albedo_plugins/remote.py @@ -1613,6 +1613,10 @@ def setup(api: PythonApi) -> dict[str, object]: attach_image = api.attach_image session_modules = list(api.modules) api.on_shutdown(Remote.close_all) + if api.owns_resources is not None: + api.owns_resources( + lambda: any(not connection.closed for connection in connections) + ) if api.on_stop_job is not None: api.on_stop_job(stop_remote_job) return {"remote": remote, "RemoteError": RemoteError} diff --git a/priv/python/albedo_quiescence.py b/priv/python/albedo_quiescence.py new file mode 100644 index 000000000..26447babc --- /dev/null +++ b/priv/python/albedo_quiescence.py @@ -0,0 +1,93 @@ +"""Conservative release eligibility; unknown process resources keep the kernel.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable +import hashlib +import os +import threading + + +def environment_hash() -> bytes: + digest = hashlib.sha256() + for key, value in sorted(os.environ.items()): + digest.update(os.fsencode(key)) + digest.update(b"\0") + digest.update(os.fsencode(value)) + digest.update(b"\0") + return digest.digest() + + +def descriptors() -> set[tuple[int, int, int, int]] | None: + for directory in ("/proc/self/fd", "/dev/fd"): + try: + names = os.listdir(directory) + except OSError: + continue + result = set() + for name in names: + if not name.isdecimal(): + continue + fd = int(name) + try: + stat = os.fstat(fd) + except OSError: + continue # listdir's own descriptor already closed + result.add((fd, stat.st_dev, stat.st_ino, stat.st_mode)) + return result + return None + + +class Quiescence: + def __init__( + self, + loop: asyncio.AbstractEventLoop, + owns: list[Callable[[], bool]], + internal: Callable[[], tuple[set[threading.Thread], set[int]]], + monitor: Callable[[], None], + ) -> None: + self.loop = loop + self.owns = owns + self.internal = internal + self.monitor = monitor + self.environment = environment_hash() + self.threads = set(threading.enumerate()) + initial = descriptors() + _, internal_fds = internal() + self.descriptors = ( + None + if initial is None + else {fd for fd in initial if fd[0] not in internal_fds} + ) + self.tasks = asyncio.all_tasks(loop) + self.timers = set(getattr(loop, "_scheduled", ())) + + def ready(self) -> bool: + try: + if environment_hash() != self.environment: + return False + internal_threads, internal_fds = self.internal() + if set(threading.enumerate()) - self.threads - internal_threads: + return False + if asyncio.all_tasks(self.loop) - self.tasks: + return False + timers = getattr(self.loop, "_scheduled", None) + if timers is None or any( + timer not in self.timers + and not timer.cancelled() + and getattr(timer, "_callback", None) != self.monitor + for timer in timers + ): + return False + current = descriptors() + if ( + current is None + or self.descriptors is None + or {fd for fd in current if fd[0] not in internal_fds} + - self.descriptors + ): + return False + return not any(check() for check in self.owns) + except Exception: + return False diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 9eebb17ea..175782fb9 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -401,6 +401,23 @@ checks custodian liveness; the adoption checks the source digest again. jobs, without messaging a blocked owner. Unknown is an error, not zero. A session with a live job or cell must retain its kernel. +Release also requires a positive `quiescent` observation. The kernel compares +threads, asyncio tasks and timers, and open descriptors with its post-adoption +baseline; only its own link threads/sockets and sampler are excluded. A failed +sample keeps the kernel. Open remote connections, owned browsers, and a live CUA +driver keep it through plugin resource predicates. Closing the resource permits +a later release; a plain namespace snapshot cannot revive these resources. + +Environment additions, changes, or deletions also keep the kernel. Only a hash +of the post-adoption environment is retained in memory; environment values are +not written to namespace snapshots. Returning the environment to its original +values permits release again. Eligibility is published with cell counts before +results and refreshed once a second while the event loop can run. + +A lossless namespace restore gives the model a short note that the namespace +was restored and source definitions re-run. Missed values or ended work retain +the detailed loss notice. + ## handshake the daemon writes `{"attach": {"kernel", "token", "ack", "grace"}}` first. the diff --git a/src/albedo/daemon/session_namespace.gleam b/src/albedo/daemon/session_namespace.gleam index 1d2caecca..1e3190fe2 100644 --- a/src/albedo/daemon/session_namespace.gleam +++ b/src/albedo/daemon/session_namespace.gleam @@ -265,6 +265,23 @@ fn restored_notice( saved: python.Saved, jobs: List(String), cells: List(#(String, String)), +) -> String { + case saved.missed, jobs, cells { + [], [], [] -> + "The python namespace was restored from disk." + <> case saved.defs { + [] -> "" + _ -> " Functions, classes, and imports were re-run from source." + } + <> "" + _, _, _ -> detailed_restored_notice(saved, jobs, cells) + } +} + +fn detailed_restored_notice( + saved: python.Saved, + jobs: List(String), + cells: List(#(String, String)), ) -> String { "The python kernel restarted. These variables were restored from disk: " <> names(saved.names) diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 9fa81d8f8..ca1e5fa2d 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -400,7 +400,11 @@ publish_observation(S) -> maps:get(observation_table, S), [{observation, {ok, observation_value(S)}}, {os_pid, os_pid_value(S)}, - {job_count, {ok, job_count_value(S)}}]), + {job_count, {ok, job_count_value(S)}}, + {live_work, case maps:get(quiescent, S, false) of + true -> {ok, job_count_value(S)}; + false -> {error, nil} + end}]), S. os_pid_value(#{target := #{pid := KernelPid}, remote := none}) -> {ok, KernelPid}; @@ -438,7 +442,7 @@ execute(Pid, Id, Data, Timeout) -> call(Pid, {execute, Id, Data, Timeout}). %% remote jobs the remote plugin reported through "jobs" frames, plus running %% cells. A released kernel would end them, so the idle sweep keeps it alive. live_work(Pid) -> - cached_call(Pid, job_count, fun() -> {error, nil} end). + cached_call(Pid, live_work, fun() -> {error, nil} end). job_count(Pid) -> case cached_call(Pid, job_count, fun() -> call(Pid, job_count) end) of @@ -840,7 +844,7 @@ hello(Hello, S0) -> link_record(S, #{<<"pid">> => maps:get(pid, Target), <<"pgid">> => maps:get(pgid, Target), <<"leader">> => maps:get(leader, Target), <<"epoch">> => maps:get(<<"epoch">>, Hello, 0)}), Jobs = [Job || Job <- maps:get(<<"jobs">>, Hello, []), is_map(Job)], - S1 = lists:foldl(fun track/2, S#{target => Target}, Jobs), + S1 = lists:foldl(fun track/2, S#{target => Target, quiescent => maps:get(<<"quiescent">>, Hello, false) =:= true}, Jobs), Cells = case maps:get(<<"cells">>, Hello, 0) of N when is_integer(N), N >= 0 -> N; _ -> 0 @@ -935,9 +939,9 @@ handle_frame(#{<<"type">> := <<"call">>, <<"id">> := Id} = Message, S = #{host : end; handle_frame(#{<<"type">> := <<"job">>} = Message, S) -> journal(Message, track(Message, S)); -handle_frame(#{<<"type">> := <<"cells">>, <<"live">> := Live}, S) +handle_frame(#{<<"type">> := <<"cells">>, <<"live">> := Live} = Message, S) when is_integer(Live), Live >= 0 -> - S#{cells => Live}; + S#{cells => Live, quiescent => maps:get(<<"quiescent">>, Message, false) =:= true}; handle_frame(#{<<"type">> := <<"jobs">>, <<"live">> := Live} = Message, S) when is_integer(Live), Live >= 0 -> case maps:get(<<"awaited">>, Message, 0) of @@ -972,6 +976,7 @@ facts(S) -> maps:get(awaited_external, S, 0), maps:get(external_jobs, S, []), maps:get(cells, S, 0), + maps:get(quiescent, S, false), maps:get(target, S, none)}. host_reply(Id, Reply, S = #{calls := Calls, out := Out}) -> diff --git a/test/e2e/albedo_kernel_spare_probe.erl b/test/e2e/albedo_kernel_spare_probe.erl index 174b21ab5..70bc5d007 100644 --- a/test/e2e/albedo_kernel_spare_probe.erl +++ b/test/e2e/albedo_kernel_spare_probe.erl @@ -31,7 +31,13 @@ run_json(Id, Cwd, ChangedBundle) -> try {ok, _} = 'albedo@harness@extensions@python@kernel':restore(Restored, Path, 5000), Recalled = execute(Restored, <<"recall">>, <<"assert helper(21)==3 and rows==[1,2,3]\nprint('SPARE_OK')">>), - {ok, Idle} = albedo_python:live_work(Restored), + WaitIdle = fun Again(0) -> error(kernel_not_quiet); + Again(N) -> case albedo_python:live_work(Restored) of + {ok, Count} -> Count; + _ -> receive after 10 -> Again(N - 1) end + end + end, + Idle = WaitIdle(500), json:encode(#{defined => Defined, recalled => Recalled, live_work => Idle, adopt_us => AdoptUs}) after albedo_python:stop(Restored) end after albedo_python:stop(Kernel) end. diff --git a/test/e2e/idle_reap_test.py b/test/e2e/idle_reap_test.py index 7c9cfd500..26a3dae48 100644 --- a/test/e2e/idle_reap_test.py +++ b/test/e2e/idle_reap_test.py @@ -113,7 +113,9 @@ class IdleReapTests(unittest.TestCase): self.turn(session, "recall them") prompt = latest_user(self.provider.requests[-1]["request"]) self.assertTrue(prompt.startswith("recall them"), prompt) - self.assertIn("restored from disk: answer, rows", prompt) + self.assertIn("namespace was restored from disk", prompt) + self.assertNotIn("variables are gone", prompt) + self.assertNotIn("earlier cells are gone", prompt) self.assertTrue( any( "recalled 7 [1, 2, 3]" in item.get("output", "") diff --git a/test/e2e/kernel_pool_test.py b/test/e2e/kernel_pool_test.py index 37aea057e..70fc918b7 100644 --- a/test/e2e/kernel_pool_test.py +++ b/test/e2e/kernel_pool_test.py @@ -3,6 +3,8 @@ import ast from pathlib import Path import subprocess +import socket +import time import unittest from harness import Albedo, Provider, alive, exclusive, python, text, wait_until @@ -85,6 +87,123 @@ class KernelPoolTests(ModelCells, unittest.TestCase): self.assertEqual(result["status"], "ok", result) return ast.literal_eval(result["value"]) + def test_changed_environment_keeps_its_kernel_without_saving_secrets(self): + self.boot(release=True) + self.ready() + pid = self.value( + "import os\nos.environ['DENSITY_EPHEMERAL_SECRET']='private'\nos.getpid()" + ) + time.sleep(1.2) + self.assertTrue(alive(pid), "environment changes were lost at turn end") + self.assertEqual( + self.value("(os.getpid(), os.environ['DENSITY_EPHEMERAL_SECRET'])"), + (pid, "private"), + ) + state = self.app.home / "kernels" / f"{self.session}.state" + self.assertFalse(state.exists(), "environment values must not be saved") + self.value("del os.environ['DENSITY_EPHEMERAL_SECRET']\n42") + wait_until( + lambda: not alive(pid), 15, "restoring the environment did not unpin" + ) + + def test_user_thread_survives_turn_end(self): + self.boot(release=True) + self.ready() + pid = self.value( + "import os, threading\n_gate=threading.Event()\n_worker=threading.Thread(target=_gate.wait, daemon=True)\n_worker.start()\nos.getpid()" + ) + time.sleep(1.2) + self.assertTrue(alive(pid), "a running user thread was terminated") + self.assertEqual(self.value("(os.getpid(), _worker.is_alive())"), (pid, True)) + self.value("_gate.set()\n_worker.join()\ndel _gate, _worker\n42") + wait_until( + lambda: not alive(pid), 15, "a finished user thread pinned its kernel" + ) + + def test_listening_socket_survives_turn_end(self): + self.boot(release=True) + self.ready() + pid, port = self.value( + "import os, socket\n_server=socket.socket()\n_server.bind(('127.0.0.1', 0))\n_server.listen()\n(os.getpid(), _server.getsockname()[1])" + ) + time.sleep(1.2) + self.assertTrue(alive(pid), "a listening server was terminated") + with socket.create_connection(("127.0.0.1", port), timeout=2): + pass + self.assertEqual(self.value("os.getpid()"), pid) + self.value("_server.close()\ndel _server\n42") + wait_until(lambda: not alive(pid), 15, "a closed server pinned its kernel") + + def test_user_timer_survives_turn_end(self): + self.boot(release=True) + self.ready() + pid = self.value( + "import os\n_timer=asyncio.get_running_loop().call_later(300, lambda: None)\nos.getpid()" + ) + time.sleep(1.2) + self.assertTrue(alive(pid), "a scheduled user callback was discarded") + self.assertEqual(self.value("os.getpid()"), pid) + self.value("_timer.cancel()\ndel _timer\n42") + wait_until( + lambda: not alive(pid), 15, "a cancelled user timer pinned its kernel" + ) + + def test_user_async_task_survives_turn_end(self): + self.boot(release=True) + self.ready() + pid = self.value( + "import os\n_task=asyncio.create_task(asyncio.sleep(300))\nos.getpid()" + ) + time.sleep(1.2) + self.assertTrue(alive(pid), "a user asyncio task was cancelled") + self.assertEqual(self.value("(os.getpid(), _task.done())"), (pid, False)) + self.value( + "_task.cancel()\nawait asyncio.gather(_task, return_exceptions=True)\ndel _task\n42" + ) + wait_until(lambda: not alive(pid), 15, "a finished user task pinned its kernel") + + def test_owned_cua_driver_survives_turn_end(self): + from cua_test import FAKE_DRIVER + + self.boot(release=True) + route = f"/sessions/{self.session}?view=configuration" + with self.app.api(route) as response: + response.read() + etag = response.headers["ETag"] + self.app.api( + route, + {"selection": {"extensions": {"cua": True}}}, + method="PATCH", + headers={"If-Match": etag}, + ).close() + self.app.api(f"/sessions/{self.session}/reload", {"target": "session"}).close() + self.ready() + driver = self.app.workspace / "fake-cua-driver" + driver.write_text(FAKE_DRIVER) + driver.chmod(0o755) + pid = self.value( + f"cua.configure(executable={str(driver)!r}, socket='/tmp/fake-density-cua.sock')\nawait cua.health()\nos.getpid()" + ) + time.sleep(1.2) + self.assertTrue(alive(pid), "an owned desktop driver was ended") + self.assertEqual(self.value("await cua.health()\nos.getpid()"), pid) + self.value("await cua.close()\n42") + wait_until( + lambda: not alive(pid), 15, "a closed desktop driver pinned its kernel" + ) + + def test_owned_browser_survives_turn_end(self): + self.boot(release=True) + self.ready() + pid = self.value( + "_browser=await browser.spawn()\n_page=await _browser.new_page()\nos.getpid()" + ) + time.sleep(1.2) + self.assertTrue(alive(pid), "an owned browser was ended") + self.assertEqual(self.value("await _page.evaluate('1+1')"), 2) + self.value("await _browser.close()\ndel _page, _browser\n42") + wait_until(lambda: not alive(pid), 15, "a closed browser pinned its kernel") + def test_spare_is_adopted_released_once_and_refilled(self): self.boot(release=True) before = self.ready() diff --git a/test/e2e/kernel_state_test.py b/test/e2e/kernel_state_test.py index 5e9f81f18..0ba81ba80 100644 --- a/test/e2e/kernel_state_test.py +++ b/test/e2e/kernel_state_test.py @@ -95,4 +95,5 @@ class KernelStateTests(unittest.TestCase): self.assertIn("RESULT 42 3 [1] 7 5 alive b xml.dom False False False", output) notice = latest_user(self.provider.requests[-2]["request"]) self.assertIn("re-run from source", notice) - self.assertIn("helper", notice) + self.assertIn("namespace was restored from disk", notice) + self.assertNotIn("earlier cells are gone", notice) -- knotmirror 0.0.1 From b550297534dfffac94776622dec0ec46f1c6a867 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 06:32:36 -0400 Subject: [PATCH 20/72] Resample kernel quiescence soon after a cell ends --- priv/python/albedo_cells.py | 15 ++++++++++++++- priv/python/albedo_quiescence.py | 5 +++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/priv/python/albedo_cells.py b/priv/python/albedo_cells.py index fc959fcc8..0b47935fb 100644 --- a/priv/python/albedo_cells.py +++ b/priv/python/albedo_cells.py @@ -1505,10 +1505,23 @@ def link_resources() -> tuple[set[threading.Thread], set[int]]: return set(), set() +RECHECK: asyncio.TimerHandle | None = None + + +def recheck_work() -> None: + global RECHECK + RECHECK = None + publish_work() + + def publish_work() -> None: - global LAST_WORK + global LAST_WORK, RECHECK quiet = QUIESCENCE is not None and QUIESCENCE.ready() observation = (len(CELL_TASKS), quiet) + if not quiet and not CELL_TASKS and RECHECK is None: + # A finishing cell's own task and timer thread are still unwinding; + # sample again soon instead of waiting for the periodic refresh. + RECHECK = LOOP.call_later(0.05, recheck_work) if observation != LAST_WORK: LAST_WORK = observation send({"type": "cells", "live": observation[0], "quiescent": quiet}) diff --git a/priv/python/albedo_quiescence.py b/priv/python/albedo_quiescence.py index 26447babc..f53b7988e 100644 --- a/priv/python/albedo_quiescence.py +++ b/priv/python/albedo_quiescence.py @@ -50,7 +50,7 @@ class Quiescence: self.loop = loop self.owns = owns self.internal = internal - self.monitor = monitor + self.monitor = monitor # the periodic sampler's own callback self.environment = environment_hash() self.threads = set(threading.enumerate()) initial = descriptors() @@ -76,7 +76,8 @@ class Quiescence: if timers is None or any( timer not in self.timers and not timer.cancelled() - and getattr(timer, "_callback", None) != self.monitor + and getattr(getattr(timer, "_callback", None), "__name__", "") + not in ("refresh_work", "recheck_work") for timer in timers ): return False -- knotmirror 0.0.1 From 0ba15e65183691318c3699782748662cbe901e5d Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 06:26:44 -0400 Subject: [PATCH 21/72] Add burst and per-prompt latency to the density benchmark --- test/manual/agent_density.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/test/manual/agent_density.py b/test/manual/agent_density.py index 79777f773..c6e1dab53 100644 --- a/test/manual/agent_density.py +++ b/test/manual/agent_density.py @@ -109,6 +109,12 @@ def main(): parser.add_argument("--idle-seconds", type=int, default=3600) parser.add_argument("--settle", type=float, default=0.2) parser.add_argument("--output", type=Path, required=True) + parser.add_argument( + "--burst", + type=int, + default=0, + help="recall in this many agents at once after the sequential samples", + ) parser.add_argument( "--daemon-env", action="append", @@ -229,6 +235,33 @@ def main(): "p50": ordered[math.ceil(len(ordered) * 0.5) - 1], "p95": ordered[math.ceil(len(ordered) * 0.95) - 1], } + if args.burst: + prompts = [f"recall:burst{i}" for i in range(args.burst)] + started = time.perf_counter() + submitted = {} + for index, prompt in enumerate(prompts): + submitted[prompt] = time.perf_counter() + app.prompt(sessions[index % len(sessions)], prompt).close() + submit_ms = (time.perf_counter() - started) * 1000 + with condition: + if not condition.wait_for( + lambda: all(p in finished for p in prompts), timeout=180 + ): + raise AssertionError("burst results timed out") + burst = sorted((finished[p] - started) * 1000 for p in prompts) + own = sorted((finished[p] - submitted[p]) * 1000 for p in prompts) + result["burst_ms"] = { + "agents": args.burst, + "p50": burst[len(burst) // 2], + "p95": burst[math.ceil(len(burst) * 0.95) - 1], + "max": burst[-1], + "submit_ms": submit_ms, + "own_p50": own[len(own) // 2], + "own_p95": own[math.ceil(len(own) * 0.95) - 1], + } + for index in range(args.burst): + app.idle(sessions[index % len(sessions)], timeout=180) + print(json.dumps(result["burst_ms"]), flush=True) turns("mail") time.sleep(args.settle) result["states"].append(measure(app, "waiting_mail", args.agents, baseline)) -- knotmirror 0.0.1 From 0fb357ec983957ae75c817a54f8e84b4df70ae2f Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 07:09:02 -0400 Subject: [PATCH 22/72] Re-evaluate spare-backed release when the kernel reports changed facts --- src/albedo/daemon/session.gleam | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index e2222580b..83652431f 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -1346,7 +1346,10 @@ fn handle( CaptureIn(db, reply) -> answer(state, reply, capture_in(state, db)) ReadSummary(reply) -> answer(state, reply, summary_state(state)) ReadStatus(reply) -> answer(state, reply, status_state(state)) - KernelJobs -> actor.continue(session_namespace.announce_kernel(state)) + KernelJobs -> { + request_resting_release(state) + actor.continue(session_namespace.announce_kernel(state)) + } WorkspaceReset(pending, outcome) -> actor.continue(workspace_reset(state, pending, outcome)) GlancesDue -> actor.continue(glances_due(state)) @@ -3625,11 +3628,22 @@ fn finish_turn( report_end(state, run) process.send(state.self, Collect) let state = start_queued(state) + request_resting_release(state) + actor.continue(state) +} + +/// Asks the runtime whether the pool allows releasing this resting session's +/// kernel, and sends `ReleaseResting` when it does. Runs when a turn ends and +/// when the kernel reports changed facts (a thread that was still unwinding at +/// turn end has stopped), so release never waits for the maintenance sweep. +/// `begin_release` rechecks every condition. +fn request_resting_release(state: State) -> Nil { case state.kernel, turn.running(state.activity), runtime.release_with_spare() && state.watchers == [] + && state.releasing == None && option.map(state.kernel, runtime.live_work) == Some(Ok(0)) { Some(_), None, True -> { @@ -3643,7 +3657,6 @@ fn finish_turn( } _, _, _ -> Nil } - actor.continue(state) } /// Commits what a stopped or failed turn left unfinished. -- knotmirror 0.0.1 From 5fd47c344764946bdd7da345034e52a3efb0d7fb Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 07:07:44 -0400 Subject: [PATCH 23/72] Test that an open remote connection alone keeps a released kernel --- test/e2e/kernel_pool_test.py | 51 +++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/test/e2e/kernel_pool_test.py b/test/e2e/kernel_pool_test.py index 70fc918b7..aa7035d68 100644 --- a/test/e2e/kernel_pool_test.py +++ b/test/e2e/kernel_pool_test.py @@ -1,6 +1,7 @@ """Fresh spare kernels are single-use, bounded, and never adopted across a bundle edit.""" import ast +import os from pathlib import Path import subprocess import socket @@ -11,12 +12,30 @@ from harness import Albedo, Provider, alive, exclusive, python, text, wait_until from inspect_support import Inspection from kernel_support import MARKER, ModelCells, editable_daemon +# An ssh that runs its command here with no environment of its own. Host +# `oldhost` reaches a python too old for a kernel, so remote.connect degrades +# to command mode: a connection that holds no process or descriptor. +FAKE_SSH = """#!/bin/sh +while [ $# -gt 0 ]; do + case "$1" in + -o) shift 2 ;; + -*) shift ;; + *) break ;; + esac +done +target=$1 +shift +path={path} +[ "$target" = oldhost ] && path={old}:$path +exec env -i HOME={home} PATH="$path" SHELL=/bin/sh /bin/sh -c "$*" +""" + @exclusive class KernelPoolTests(ModelCells, unittest.TestCase): bundle: Path - def boot(self, *, spares=1, release=False): + def boot(self, *, spares=1, release=False, ssh=False): self.cells = [] def script(request): @@ -32,6 +51,20 @@ class KernelPoolTests(ModelCells, unittest.TestCase): ALBEDO_KERNEL_SPARES=str(spares), ALBEDO_KERNEL_RELEASE_WITH_SPARE="1" if release else "0", ) + if ssh: + # On the daemon's PATH, so a kernel's environment is unchanged + # by connecting and only the connection itself can keep it. + local, old, home = (app.root / name for name in ("bin", "old", "rhome")) + for directory in (local, old, home): + directory.mkdir() + path = f"{app.daemon.env['PATH']}" + (local / "ssh").write_text( + FAKE_SSH.format(path=path, old=old, home=home) + ) + (old / "python3").write_text("#!/bin/sh\necho 3.9\n") + for script in (local / "ssh", old / "python3"): + script.chmod(0o755) + app.daemon.env["PATH"] = f"{local}{os.pathsep}{path}" self.provider = Provider(script) self.addCleanup(self.provider.close) @@ -204,6 +237,22 @@ class KernelPoolTests(ModelCells, unittest.TestCase): self.value("await _browser.close()\ndel _page, _browser\n42") wait_until(lambda: not alive(pid), 15, "a closed browser pinned its kernel") + def test_open_remote_connection_survives_turn_end(self): + self.boot(release=True, ssh=True) + self.ready() + pid = self.value( + "_rem = await remote.connect('oldhost')\nassert _rem._stdin is None\nos.getpid()" + ) + time.sleep(1.2) + self.assertTrue(alive(pid), "an open remote connection was ended") + self.assertEqual( + self.value("(os.getpid(), len(remote.connections()))"), (pid, 1) + ) + self.value("await _rem.close()\ndel _rem\n42") + wait_until( + lambda: not alive(pid), 15, "a closed remote connection pinned its kernel" + ) + def test_spare_is_adopted_released_once_and_refilled(self): self.boot(release=True) before = self.ready() -- knotmirror 0.0.1 From 37df0a588de15f232d56b78e44c8344b50fab6c6 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 08:08:02 -0400 Subject: [PATCH 24/72] Stop kernels through one long-lived signal helper instead of a Python start per stop --- priv/python/albedo_signal.py | 59 +++++++- .../extensions/python/albedo_python.erl | 18 ++- .../extensions/python/albedo_signals.erl | 142 ++++++++++++++++++ test/e2e/albedo_stop_load_probe.erl | 19 +++ test/e2e/kernel_stop_load_test.py | 62 ++++++++ test/harness/signal_helper_test.py | 86 +++++++++++ 6 files changed, 374 insertions(+), 12 deletions(-) create mode 100644 src/albedo/harness/extensions/python/albedo_signals.erl create mode 100644 test/e2e/albedo_stop_load_probe.erl create mode 100644 test/e2e/kernel_stop_load_test.py create mode 100644 test/harness/signal_helper_test.py diff --git a/priv/python/albedo_signal.py b/priv/python/albedo_signal.py index 57dff9792..9203f1366 100644 --- a/priv/python/albedo_signal.py +++ b/priv/python/albedo_signal.py @@ -11,6 +11,7 @@ verdict. from __future__ import annotations import signal +import threading import asyncio import json @@ -53,19 +54,17 @@ def target(spec: object) -> albedo_proc.Group: ) -def supervise(request: object) -> dict[str, object]: +async def supervise_async(request: object) -> dict[str, object]: if not isinstance(request, dict): raise ValueError("request must be an object") specs = request.get("targets") if not isinstance(specs, list): raise ValueError("request needs a target list") targets = [target(spec) for spec in specs] - endings = asyncio.run( - albedo_proc.terminate( - targets, - term=budget(request, "term_ms", TERM_MS), - kill=budget(request, "kill_ms", KILL_MS), - ) + endings = await albedo_proc.terminate( + targets, + term=budget(request, "term_ms", TERM_MS), + kill=budget(request, "kill_ms", KILL_MS), ) return { "targets": [ @@ -75,6 +74,49 @@ def supervise(request: object) -> dict[str, object]: } +def supervise(request: object) -> dict[str, object]: + return asyncio.run(supervise_async(request)) + + +async def serve() -> None: + """Answer one JSON request per stdin line until end of input. + + The daemon keeps one of these running, so a stop does not pay for an + interpreter start. Requests run concurrently; each answer is one stdout line + carrying the request's id. The first line says the interpreter is ready. + """ + loop = asyncio.get_running_loop() + lines: asyncio.Queue[str | None] = asyncio.Queue() + + def read() -> None: + for line in sys.stdin: + loop.call_soon_threadsafe(lines.put_nowait, line) + loop.call_soon_threadsafe(lines.put_nowait, None) + + threading.Thread(target=read, daemon=True).start() + + async def answer(line: str) -> None: + identity = None + try: + message = json.loads(line) + identity = message["id"] + reply: dict[str, object] = { + "ok": True, + **await supervise_async(message["request"]), + } + except Exception as error: + reply = {"ok": False, "error": f"{type(error).__name__}: {error}"} + print(json.dumps({"id": identity, "answer": reply}), flush=True) + + print(json.dumps({"ready": True}), flush=True) + running: set[asyncio.Task[None]] = set() + while (line := await lines.get()) is not None: + task = asyncio.create_task(answer(line)) + running.add(task) + task.add_done_callback(running.discard) + await asyncio.gather(*running) + + def main(request: str) -> int: try: answer: dict[str, object] = {"ok": True, **supervise(json.loads(request))} @@ -87,6 +129,9 @@ def main(request: str) -> int: if __name__ == "__main__": + if sys.argv[1:] == ["--serve"]: + asyncio.run(serve()) + sys.exit(0) # Default SIGALRM terminates even a wedged interpreter; no Python handler. # The owning port waits longer than this before reporting a helper timeout. signal.signal(signal.SIGALRM, signal.SIG_DFL) diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index ca1e5fa2d..8f41369c4 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -165,6 +165,7 @@ warm_launch(S, Launch) -> %% Boot is the Gleam kernel.Boot record; Link is kernel.Link. start({boot, Owner, Python, Bridge, Cwd, Host, Modules, Link, RunDir, Kernel, Token, Grace, OutSeq, Owned, Fresh, Remote, Spare}) -> + albedo_signals:warm(), Parent = self(), Ref = make_ref(), {Pid, Mon} = spawn_monitor(fun() -> albedo_inspect:label(<<"albedo_kernel">>, Kernel), @@ -1187,8 +1188,13 @@ supervise(S, Targets, TermMs, KillMs) -> _ -> case local_paths() of {ok, {Python, Script}} -> - Helper = filename:join(filename:dirname(Script), <<"albedo_signal.py">>), - run_helper(Python, [<<"-u">>, Helper, Request], clean_environment(), ?HELPER_WAIT, []); + case albedo_signals:request(Request, ?HELPER_WAIT) of + unavailable -> + Helper = filename:join(filename:dirname(Script), <<"albedo_signal.py">>), + run_helper(Python, [<<"-u">>, Helper, Request], clean_environment(), ?HELPER_WAIT, []); + {error, _} = Failed -> Failed; + Answer -> decode_answer(Answer) + end; {error, Reason} -> {error, detail(Reason)} end end. @@ -1249,12 +1255,14 @@ collect(Port, Buffer, Deadline) -> decode_verdict(Buffer) -> try json:decode(Buffer) of - #{<<"ok">> := true, <<"targets">> := Targets} when is_list(Targets) -> {ok, Targets}; - #{<<"ok">> := false, <<"error">> := Error} -> {error, Error}; - _ -> {error, <<"termination helper returned no verdict">>} + Answer -> decode_answer(Answer) catch _:Reason -> {error, detail({bad_verdict, Reason, Buffer})} end. +decode_answer(#{<<"ok">> := true, <<"targets">> := Targets}) when is_list(Targets) -> {ok, Targets}; +decode_answer(#{<<"ok">> := false, <<"error">> := Error}) -> {error, Error}; +decode_answer(_) -> {error, <<"termination helper returned no verdict">>}. + verdict({ok, Verdicts}) -> verdict(Verdicts); verdict({error, Reason}) when is_binary(Reason) -> {error, Reason}; verdict({error, Reason}) -> {error, detail(Reason)}; diff --git a/src/albedo/harness/extensions/python/albedo_signals.erl b/src/albedo/harness/extensions/python/albedo_signals.erl new file mode 100644 index 000000000..37a2979c1 --- /dev/null +++ b/src/albedo/harness/extensions/python/albedo_signals.erl @@ -0,0 +1,142 @@ +%% One long-lived signal helper (albedo_signal.py --serve) for the daemon. +%% +%% A stop needs an interpreter that checks and ends process groups. Starting a +%% fresh one for every stop competes with the kernel boots that saturate the +%% machine during a burst, so the daemon keeps one running and sends it +%% requests. The wait for an answer starts when the helper has the request, so +%% interpreter start has its own, longer budget. +-module(albedo_signals). +-export([request/2, warm/0]). + +-define(STARTUP_MS, 20000). + +%% Starts the helper without waiting for it. +warm() -> + _ = spawn(fun() -> _ = ensure() end), + ok. + +%% The helper's answer to one termination request (a JSON binary): its decoded +%% map, `{error, Reason}`, or `unavailable` when no helper can run, in which +%% case the caller starts a one-shot helper. `Wait` bounds the helper's work. +request(Request, Wait) -> + case ensure() of + {ok, Server} -> call(Server, Request, Wait); + error -> unavailable + end. + +ensure() -> + case whereis(?MODULE) of + undefined -> start(); + Server -> {ok, Server} + end. + +start() -> + Parent = self(), Ref = make_ref(), + {Pid, Mon} = spawn_monitor(fun() -> init(Parent, Ref) end), + receive + {Ref, started} -> demonitor(Mon, [flush]), {ok, Pid}; + {Ref, taken} -> demonitor(Mon, [flush]), ensure(); + {Ref, failed} -> demonitor(Mon, [flush]), error; + {'DOWN', Mon, process, Pid, _} -> error + after ?STARTUP_MS -> exit(Pid, kill), error + end. + +init(Parent, Ref) -> + process_flag(trap_exit, true), + try register(?MODULE, self()) of + true -> open(Parent, Ref) + catch error:badarg -> Parent ! {Ref, taken} + end. + +open(Parent, Ref) -> + case albedo_python:local_paths() of + {ok, {Python, Script}} -> + Helper = filename:join(filename:dirname(Script), <<"albedo_signal.py">>), + try open_port({spawn_executable, binary_to_list(Python)}, + [binary, exit_status, use_stdio, {line, 1048576}, + {args, ["-u", binary_to_list(Helper), "--serve"]}, + {env, albedo_python:clean_environment()}]) of + Port -> Parent ! {Ref, started}, loop(Port, false, 0, #{}, <<>>) + catch _:_ -> Parent ! {Ref, failed} + end; + _ -> Parent ! {Ref, failed} + end. + +%% Ready is true once the helper printed its ready line; requests written +%% earlier wait in its stdin. Pending maps a request id to its caller. +loop(Port, Ready, Next, Pending, Partial) -> + receive + {request, From, Ref, Request} -> + Id = Next + 1, + port_command(Port, [<<"{\"id\":">>, integer_to_binary(Id), + <<",\"request\":">>, Request, $}, $\n]), + Ready andalso (From ! {Ref, accepted}), + loop(Port, Ready, Id, Pending#{Id => {From, Ref}}, Partial); + {expired, Ref} -> + Rest = maps:filter(fun(_, {_, R}) -> R =/= Ref end, Pending), + %% A helper that overran its budget with nothing else in flight may + %% be wedged: end it, and the next request starts another. + case map_size(Rest) of + 0 -> stop(Port); + _ -> loop(Port, Ready, Next, Rest, Partial) + end; + {Port, {data, {noeol, Part}}} -> + loop(Port, Ready, Next, Pending, <>); + {Port, {data, {eol, Line}}} -> + handle(Port, Ready, Next, Pending, <>); + {Port, {exit_status, _}} -> fail(Pending); + {'EXIT', Port, _} -> fail(Pending); + _ -> loop(Port, Ready, Next, Pending, Partial) + end. + +handle(Port, Ready, Next, Pending, Line) -> + try json:decode(Line) of + #{<<"ready">> := true} -> + _ = [From ! {Ref, accepted} || _ := {From, Ref} <- Pending], + loop(Port, true, Next, Pending, <<>>); + #{<<"id">> := Id, <<"answer">> := Answer} -> + case maps:take(Id, Pending) of + {{From, Ref}, Rest} -> + From ! {Ref, {answer, Answer}}, + loop(Port, Ready, Next, Rest, <<>>); + error -> loop(Port, Ready, Next, Pending, <<>>) + end; + _ -> loop(Port, Ready, Next, Pending, <<>>) + catch _:_ -> loop(Port, Ready, Next, Pending, <<>>) + end. + +%% The helper ended: every caller still waiting hears that, and the next +%% request starts a new one. +fail(Pending) -> + _ = [From ! {Ref, exited} || _ := {From, Ref} <- Pending], + ok. + +stop(Port) -> + Os = case erlang:port_info(Port, os_pid) of {os_pid, N} -> N; _ -> undefined end, + catch port_close(Port), + _ = Os =:= undefined orelse os:cmd("kill -9 " ++ integer_to_list(Os)), + ok. + +call(Server, Request, Wait) -> + Ref = make_ref(), Mon = monitor(process, Server), + Server ! {request, self(), Ref, Request}, + Result = receive + {Ref, accepted} -> answered(Server, Ref, Mon, Wait); + {Ref, Reply} -> reply(Reply); + {'DOWN', Mon, process, Server, _} -> {error, <<"termination helper exited">>} + after ?STARTUP_MS -> + Server ! {expired, Ref}, {error, <<"termination helper did not start">>} + end, + demonitor(Mon, [flush]), + Result. + +answered(Server, Ref, Mon, Wait) -> + receive + {Ref, Reply} -> reply(Reply); + {'DOWN', Mon, process, Server, _} -> {error, <<"termination helper exited">>} + after Wait -> + Server ! {expired, Ref}, {error, <<"termination helper timed out">>} + end. + +reply({answer, Answer}) -> Answer; +reply(exited) -> {error, <<"termination helper exited">>}. diff --git a/test/e2e/albedo_stop_load_probe.erl b/test/e2e/albedo_stop_load_probe.erl new file mode 100644 index 000000000..59ba7fa6b --- /dev/null +++ b/test/e2e/albedo_stop_load_probe.erl @@ -0,0 +1,19 @@ +%% Release and reopen many sessions at once through the live runtime. +-module(albedo_stop_load_probe). +-export([mass_json/2]). + +host() -> + [Name] = [N || N <- registered(), lists:prefix("albedo_registry", atom_to_list(N))], + {ok, Runtime} = 'albedo@daemon@registry':host('gleam@erlang@process':named_subject(Name)), + Runtime. + +%% Every session resets (a kernel stop) and opens again at the same moment. +mass_json(Ids, Cwd) -> + Runtime = host(), Parent = self(), + [spawn(fun() -> + 'albedo@harness@runtime':reset_session(Runtime, Id), + Parent ! {opened, Id, 'albedo@harness@runtime':open_session(Runtime, Id, Cwd)} + end) || Id <- Ids], + Results = [receive {opened, Id, R} -> {Id, R} after 120000 -> {Id, timeout} end || Id <- Ids], + Failed = [Id || {Id, R} <- Results, element(1, R) =/= ok], + json:encode(#{sessions => length(Ids), failed => length(Failed)}). diff --git a/test/e2e/kernel_stop_load_test.py b/test/e2e/kernel_stop_load_test.py new file mode 100644 index 000000000..36e2b00a7 --- /dev/null +++ b/test/e2e/kernel_stop_load_test.py @@ -0,0 +1,62 @@ +"""Releasing many kernels at once on a saturated machine confirms every stop. + +A stop ends the kernel's process groups through a helper. When the helper was a +fresh Python interpreter per stop, a burst of stops competed with the kernel +boots for the CPU, missed its deadline, and left the session refusing to open +("previous kernel stop is unconfirmed"). Only a real daemon with real kernels +under CPU load shows that, so this runs through an inspected daemon. +""" + +import json +import os +import subprocess +import sys +import unittest + +from harness import ROOT, Albedo, Provider, exclusive, python, text +from inspect_support import Inspection + +SESSIONS = int(os.environ.get("STOP_LOAD_SESSIONS", "24")) +BURNERS = int(os.environ.get("STOP_LOAD_BURNERS", str(os.cpu_count() or 4))) + + +@exclusive +class StopUnderLoadTests(unittest.TestCase): + def test_a_burst_of_stops_on_a_busy_machine_confirms_every_kernel(self): + def script(request): + if request["messages"][-1].get("role") == "tool": + return text("ready") + return python("sentinel = 1") + + provider = Provider(script) + self.addCleanup(provider.close) + + def prepare(app): + app.daemon.env["ALBEDO_INSPECT"] = "1" + + with Albedo(provider, prepare=prepare) as app: + sessions = [app.session() for _ in range(SESSIONS)] + for session in sessions: + app.prompt(session, "boot").close() + for session in sessions: + app.idle(session) + burners = [ + subprocess.Popen([sys.executable, "-c", "while True: pass"]) + for _ in range(BURNERS) + ] + try: + probe = Inspection(app, ROOT / "test/e2e/albedo_stop_load_probe.erl") + ids = ",".join(f'<<"{session}">>' for session in sessions) + report = json.loads( + probe.evaluate( + "io:put_chars(Call(albedo_stop_load_probe, mass_json, " + f'[[{ids}], <<"{app.workspace}">>]))', + timeout=180, + ) + ) + finally: + for burner in burners: + burner.kill() + self.assertEqual(report["failed"], 0, report) + log = (app.home / "daemon.log").read_text(errors="replace") + self.assertNotIn("termination helper", log) diff --git a/test/harness/signal_helper_test.py b/test/harness/signal_helper_test.py new file mode 100644 index 000000000..3a1842b8d --- /dev/null +++ b/test/harness/signal_helper_test.py @@ -0,0 +1,86 @@ +"""The daemon's one long-lived signal helper answers concurrent stop requests. + +A stop that starts a fresh Python interpreter costs 0.1 s on an idle machine and +over 0.8 s on a loaded one, and the daemon waits a fixed 4 s for it. The helper +(`albedo_signal.py --serve`) is started once; these checks need real child +process groups and one real helper process, which only a controlled test can +arrange without daemon timing. +""" + +import json +import os +import signal +import subprocess +import sys +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +HELPER = os.path.join(ROOT, "priv", "python", "albedo_signal.py") +SLEEPER = "import time\nwhile True: time.sleep(1)" + + +class SignalHelperTests(unittest.TestCase): + def setUp(self): + self.helper = subprocess.Popen( + [sys.executable, "-u", HELPER, "--serve"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + ) + assert self.helper.stdin is not None and self.helper.stdout is not None + self.stdin, self.stdout = self.helper.stdin, self.helper.stdout + self.addCleanup(self.finish) + self.assertEqual(json.loads(self.stdout.readline()), {"ready": True}) + + def finish(self): + if self.helper.poll() is None: + self.helper.kill() + self.helper.wait() + self.stdout.close() + if not self.stdin.closed: + self.stdin.close() + + def ask(self, identity, request): + line = json.dumps({"id": identity, "request": request}) + "\n" + self.stdin.write(line) + self.stdin.flush() + + def answers(self, count): + return { + reply["id"]: reply["answer"] + for reply in (json.loads(self.stdout.readline()) for _ in range(count)) + } + + def test_concurrent_stops_are_answered_by_the_same_helper(self): + children = [ + subprocess.Popen([sys.executable, "-c", SLEEPER], start_new_session=True) + for _ in range(8) + ] + self.addCleanup(lambda: [c.kill() for c in children]) + for index, child in enumerate(children): + target = {"pid": child.pid, "pgid": child.pid, "label": f"k{index}"} + self.ask(index, {"targets": [target], "term_ms": 250, "kill_ms": 1000}) + answers = self.answers(len(children)) + self.assertEqual(sorted(answers), list(range(8))) + for index, child in enumerate(children): + ending = answers[index]["targets"][0] + self.assertTrue(answers[index]["ok"], answers[index]) + self.assertTrue(ending["gone"], ending) + self.assertEqual(ending["label"], f"k{index}") + self.assertEqual(child.wait(5), -signal.SIGTERM) + self.assertIsNone(self.helper.poll(), "the helper ended after its first stops") + + def test_a_bad_request_is_answered_and_the_helper_keeps_serving(self): + self.ask(1, {"targets": "not a list"}) + self.ask(2, {"targets": [{"pid": 999999, "label": "gone"}]}) + answers = self.answers(2) + self.assertFalse(answers[1]["ok"]) + self.assertTrue(answers[2]["ok"], answers[2]) + + def test_the_helper_exits_when_its_input_closes(self): + self.stdin.close() + self.assertEqual(self.helper.wait(10), 0) + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1 From ccdea0ad130027e8e7f7532417b9d1cd0a4b7b70 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 08:06:37 -0400 Subject: [PATCH 25/72] Remote keep test: give the fake host a login shell that sources no profile --- test/e2e/kernel_pool_test.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test/e2e/kernel_pool_test.py b/test/e2e/kernel_pool_test.py index aa7035d68..8229584c2 100644 --- a/test/e2e/kernel_pool_test.py +++ b/test/e2e/kernel_pool_test.py @@ -27,7 +27,7 @@ target=$1 shift path={path} [ "$target" = oldhost ] && path={old}:$path -exec env -i HOME={home} PATH="$path" SHELL=/bin/sh /bin/sh -c "$*" +exec env -i HOME={home} PATH="$path" SHELL={old}/loginsh /bin/sh -c "$*" """ @@ -62,7 +62,11 @@ class KernelPoolTests(ModelCells, unittest.TestCase): FAKE_SSH.format(path=path, old=old, home=home) ) (old / "python3").write_text("#!/bin/sh\necho 3.9\n") - for script in (local / "ssh", old / "python3"): + # A login shell that sources no profile, which could reset PATH. + (old / "loginsh").write_text( + '#!/bin/sh\n[ "$1" = -l ] && shift\nexec /bin/sh "$@"\n' + ) + for script in (local / "ssh", old / "python3", old / "loginsh"): script.chmod(0o755) app.daemon.env["PATH"] = f"{local}{os.pathsep}{path}" -- knotmirror 0.0.1 From 146aad3d8d89ef1004d9ddcb21c1ae358666615d Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 06:35:52 -0400 Subject: [PATCH 26/72] Acquire the session kernel at a turn's first tool call behind ALBEDO_KERNEL_LAZY --- src/albedo/daemon/session.gleam | 282 ++++++++++++++---- src/albedo/daemon/session_extensions.gleam | 5 + src/albedo/daemon/session_history.gleam | 10 + src/albedo/daemon/session_last_call.gleam | 5 +- src/albedo/daemon/session_prompt.gleam | 11 +- src/albedo/daemon/session_run.gleam | 25 +- src/albedo/daemon/session_state.gleam | 18 ++ src/albedo/harness/loop.gleam | 71 +++-- .../bedrock_replay_preflight_test.gleam | 1 + test/daemon/session_run_test.gleam | 1 + test/e2e/kernel_lazy_test.py | 179 +++++++++++ 11 files changed, 517 insertions(+), 91 deletions(-) create mode 100644 test/e2e/kernel_lazy_test.py diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 83652431f..c0e5427fb 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -358,6 +358,13 @@ pub type Message { ) /// The runtime answered this session's kernel request. KernelOpened(Result(runtime.Session, python.Error)) + /// The runtime answered this session's request for a kernel-free composition. + PreparedOpened(Result(runtime.Prepared, python.Error)) + /// A run's worker asks for the kernel its next tool call runs in. + AcquireKernel( + String, + Subject(Result(#(runtime.Session, Option(String)), String)), + ) WorkspaceReset(session_workspace.Pending, Result(Nil, String)) /// A workspace probe completed outside the actor; stale generations are ignored. WorkspaceReady(String, WorkspaceProbe, Result(Nil, String)) @@ -432,6 +439,7 @@ pub fn start( host: host, kernel: None, released: None, + prepared: None, home: home, self: self, history: None, @@ -1413,6 +1421,8 @@ fn handle( } } KernelOpened(result) -> actor.continue(kernel_opened(state, result)) + PreparedOpened(result) -> actor.continue(prepared_opened(state, result)) + AcquireKernel(id, reply) -> acquire_kernel(state, id, reply) WorkspaceReady(token, purpose, result) -> actor.continue(workspace_ready(state, token, purpose, result)) StartQueued -> actor.continue(start_queued(state)) @@ -2736,19 +2746,171 @@ fn discard(path: String) -> Nil fn prepare_submission( state: State, -) -> Result(#(State, runtime.Session, extension.Upstream), SubmissionError) { +) -> Result(#(State, runtime.Prepared, extension.Upstream), SubmissionError) { use state <- result.try( session_history.ensure_history(state) |> result.map_error(Rejected), ) use #(state, client) <- result.try( session_provider.configured_client(state) |> result.map_error(Rejected), ) - case session_namespace.ready(state) { - #(state, Some(kernel)) -> Ok(#(state, kernel, client)) - #(_, None) -> Error(Rejected("the session python kernel is not ready")) + let #(state, _) = session_namespace.ready(state) + case session_state.composition(state) { + Some(prepared) -> Ok(#(state, prepared, client)) + None -> Error(Rejected("the session python kernel is not ready")) + } +} + +@external(erlang, "albedo_daemon", "env") +fn env(name: String) -> String + +/// ALBEDO_KERNEL_LAZY=1: a turn starts from the session's composition and +/// acquires its kernel at its first tool call. +fn lazy_kernel() -> Bool { + env("ALBEDO_KERNEL_LAZY") == "1" +} + +/// Whether a turn can start now. With lazy kernels it needs only the +/// composition, unless it owes results for calls a crash interrupted, which +/// only the kernel can recover. +fn turn_ready(state: State) -> #(State, Bool) { + let #(state, kernel) = session_namespace.ready(state) + case lazy_kernel() { + False -> #(state, kernel != None) + True -> { + let state = session_history.ensure_history(state) |> result.unwrap(state) + case session_history.needs_kernel(state.history) { + True -> #(state, kernel != None) + False -> #(state, session_state.composition(state) != None) + } + } + } +} + +/// `kernel_or_park` for a turn: the state when it can start now, else `work` +/// parked until the kernel, or with lazy kernels just the composition, is here. +fn turn_or_park(state: State, work: Message) -> Result(State, State) { + case state.closing, uses_kernel_transition(state) { + True, _ -> Error(state) + _, True -> Error(park(state, work)) + _, False -> + case turn_ready(state) { + #(state, True) -> Ok(state) + #(state, False) -> + case + lazy_kernel() + && option.is_none(state.booting) + && !session_history.needs_kernel(state.history) + { + True -> Error(request_composition(state, work)) + False -> Error(park(state, work)) + } + } + } +} + +/// Asks the runtime for the session's composition without a kernel, parking +/// `work` in `booting` until it arrives. +fn request_composition(state: State, work: Message) -> State { + let self = state.self + runtime.prepare_session_async( + state.host, + state.info.id, + state.info.cwd, + fn(result) { process.send(self, PreparedOpened(result)) }, + ) + session_state.State(..state, booting: Some(#(1, [work]))) + |> session_state.announce +} + +fn prepared_opened( + state: State, + result: Result(runtime.Prepared, python.Error), +) -> State { + case state.booting, result { + None, Ok(prepared) -> session_state.State(..state, prepared: Some(prepared)) + None, Error(_) -> state + Some(_), Error(error) -> kernel_opened(state, Error(error)) + Some(#(_, parked)), Ok(prepared) -> + session_state.State(..state, prepared: Some(prepared), booting: None) + |> session_prompt.reconcile_prompt + |> run_parked(parked) } } +/// Answers a run's worker with the kernel for its next tool call and the +/// notice the kernel's arrival left, booting or adopting one if none is held. +fn acquire_kernel( + state: State, + id: String, + reply: Subject(Result(#(runtime.Session, Option(String)), String)), +) -> actor.Next(State, Message) { + case turn.live(state.activity, id) && !state.closing { + False -> answer(state, reply, Error(acquire_refused)) + True -> + case state.kernel { + // A stale bundle is swapped between turns, not under one. + Some(kernel) -> + case runtime.alive(kernel) { + True -> hand_kernel(state, kernel, reply) + False -> acquire_parked(state, id, reply) + } + None -> acquire_parked(state, id, reply) + } + } +} + +fn acquire_parked( + state: State, + id: String, + reply: Subject(Result(#(runtime.Session, Option(String)), String)), +) -> actor.Next(State, Message) { + case kernel_or_park(state, AcquireKernel(id, reply)) { + Error(state) -> actor.continue(state) + Ok(state) -> + case state.kernel { + Some(kernel) -> hand_kernel(state, kernel, reply) + None -> answer(state, reply, Error(acquire_refused)) + } + } +} + +/// Adopting loaded the history the running worker already holds; the actor +/// drops its copy again. +fn hand_kernel( + state: State, + kernel: runtime.Session, + reply: Subject(Result(#(runtime.Session, Option(String)), String)), +) -> actor.Next(State, Message) { + answer( + session_state.State(..state, notice: None, history: None), + reply, + Ok(#(kernel, state.notice)), + ) +} + +const acquire_refused = "the turn ended before its python kernel was ready" + +/// Refuses the kernel requests a cancelled run left parked, so its worker +/// stops now instead of when the kernel arrives. +fn refuse_acquires(state: State) -> State { + let refuse = fn(parked: List(Message)) { + list.filter(parked, fn(work) { + case work { + AcquireKernel(_, reply) -> { + process.send(reply, Error(acquire_refused)) + False + } + _ -> True + } + }) + } + session_state.State( + ..state, + booting: option.map(state.booting, fn(boot) { #(boot.0, refuse(boot.1)) }), + releasing: option.map(state.releasing, refuse), + ) +} + /// The state when a live kernel is here; otherwise `work` is parked until one /// arrives and the state that asked for it comes back as the error. fn kernel_or_park(state: State, work: Message) -> Result(State, State) { @@ -2930,23 +3092,10 @@ fn kernel_opened( } Some(#(_, parked)), Ok(kernel) -> { let state = adopt(session_state.State(..state, booting: None), kernel) - let state = - list.fold(runtime.warnings(kernel), state, fn(state, warning) { - session_state.emit(state, view.note("daemon", "Warning: " <> warning)) - }) - // Turns start here and now, so no status read can fall between the - // kernel arriving and its turn starting; work that answers a caller is - // handled as a message again. - list.fold(parked, state, fn(state, work) { - case work { - StartQueued -> start_queued(state) - Resume -> resume(state) - other -> { - process.send(state.self, other) - state - } - } + list.fold(runtime.warnings(kernel), state, fn(state, warning) { + session_state.emit(state, view.note("daemon", "Warning: " <> warning)) }) + |> run_parked(parked) } Some(#(_, parked)), Error(error) -> { let why = @@ -2969,6 +3118,10 @@ fn kernel_opened( process.send(reply, Error(why)) state } + AcquireKernel(_, reply) -> { + process.send(reply, Error(why)) + state + } StartSummary(_, _, _, ack) -> { process.send(ack, Error(why)) state @@ -2981,6 +3134,22 @@ fn kernel_opened( } } +/// Turns start here and now, so no status read can fall between the kernel +/// or composition arriving and its turn starting; work that answers a caller +/// is handled as a message again. +fn run_parked(state: State, parked: List(Message)) -> State { + list.fold(parked, state, fn(state, work) { + case work { + StartQueued -> start_queued(state) + Resume -> resume(state) + other -> { + process.send(state.self, other) + state + } + } + }) +} + fn failed_queued(state: State, error: String) -> State { let _ = operations.block( @@ -3138,14 +3307,16 @@ fn park_submission( submission: Submission, reply: Subject(Result(Bool, SubmissionError)), ) -> actor.Next(State, Message) { + let state = + session_state.State( + ..state, + steering: list.append(state.steering, [submission]), + ) answer( - park( - session_state.State( - ..state, - steering: list.append(state.steering, [submission]), - ), - StartQueued, - ), + case turn_or_park(state, StartQueued) { + Error(state) -> state + Ok(state) -> start_queued(state) + }, reply, Ok(False), ) @@ -3190,10 +3361,10 @@ fn admit_within_limits( Ok(True), ) turn.Start -> - case session_namespace.ready(state) { + case turn_ready(state) { // It starts once the kernel boots, not behind another turn, so to // the caller it is not queued; the actor keeps answering meanwhile. - #(state, None) -> + #(state, False) -> case workspace_probe_target(state) { Some(_) -> case cached_workspace_error(state) { @@ -3206,7 +3377,7 @@ fn admit_within_limits( Ok(Nil) -> park_submission(state, submission, reply) } } - #(state, Some(_)) -> start_now(state, submission, reply) + #(state, True) -> start_now(state, submission, reply) } } } @@ -3274,9 +3445,10 @@ fn compact( let report = turn.CompactionReport( selection_applied: strategy != None && result.is_ok(selected), - effective_strategy: option.then(state.kernel, fn(kernel) { - runtime.compaction_name(runtime.prepared(kernel)) - }), + effective_strategy: option.then( + session_state.composition(state), + runtime.compaction_name, + ), state: "failed", observation: None, failure: None, @@ -3290,12 +3462,10 @@ fn compact( use #(state, kernel, client) <- result.try( prepare_submission(state) |> result.map_error(submission_error), ) - use strategy <- result.try( - case runtime.compaction_name(runtime.prepared(kernel)) { - Some(strategy) -> Ok(strategy) - None -> Error("no compaction strategy is enabled") - }, - ) + use strategy <- result.try(case runtime.compaction_name(kernel) { + Some(strategy) -> Ok(strategy) + None -> Error("no compaction strategy is enabled") + }) use history <- result.try(projected_inputs(state)) use _ <- result.try(case history { [] -> Error("no conversation history to compact") @@ -3403,7 +3573,7 @@ fn prepare_turn_pipeline( state: State, submissions: List(Submission), ) -> Result( - #(State, runtime.Session, extension.Upstream, List(types.Input), String), + #(State, runtime.Prepared, extension.Upstream, List(types.Input), String), #(State, SubmissionError), ) { use state <- result.try(case turn.running(state.activity) { @@ -3415,13 +3585,17 @@ fn prepare_turn_pipeline( use #(state, kernel, client) <- result.try( prepare_submission(state) |> result.map_error(fn(err) { #(state, err) }), ) - let recovered = - session_history.recover_pending( - state.host, - state.history, - kernel, - client.images, - ) + // `turn_ready` holds the turn for a kernel when calls need recovering. + let recovered = case state.kernel { + Some(held) -> + session_history.recover_pending( + state.host, + state.history, + held, + client.images, + ) + None -> [] + } let accepted = list.append(recovered, session_submission.inputs(submissions)) |> with_notice(state.notice) @@ -3881,10 +4055,10 @@ fn stirred(state: State) -> State { /// Tells the extensions this session composed about one of its events, those /// of a released kernel too: its composition outlives it. fn observe(state: State, event: extension.SessionEvent) -> Nil { - case option.or(state.kernel, state.released) { + case session_state.composition(state) { Some(kernel) -> runtime.observe( - runtime.prepared(kernel), + kernel, background_handle(state.info.id, state.self), event, ) @@ -4055,7 +4229,7 @@ fn finish_workspace_probe( Error(error), ResumeStart -> failed_queued(session_state.State(..state, activity: turn.Resting), error) Ok(Nil), ResumeStart -> - case kernel_or_park(state, Resume) { + case turn_or_park(state, Resume) { Error(state) -> state Ok(state) -> resume(state) } @@ -4076,7 +4250,7 @@ fn workspace_ready( } fn start_in_workspace(state: State) -> State { - case kernel_or_park(state, StartQueued) { + case turn_or_park(state, StartQueued) { Error(state) -> state Ok(state) -> case prepare_turn_pipeline(state, state.steering) { @@ -4115,7 +4289,7 @@ fn wake(session: Session, submission: Submission) -> run.Wake { fn start_worker( state: State, - kernel: runtime.Session, + kernel: runtime.Prepared, client: extension.Upstream, model_history: List(types.Input), work: turn.Work, @@ -4154,6 +4328,7 @@ fn run_messages() -> session_run.Messages(Message) { ReportCompacting, Finished, Collect, + AcquireKernel, RequestBoundary, ) } @@ -4256,6 +4431,7 @@ fn workspace_reset( ..state, kernel: None, released: None, + prepared: None, notice: Some(session_namespace.lost_notice), context: session_state.unprepared(), ), @@ -4513,7 +4689,7 @@ fn interrupt_waiting( let _ = clock.send_after(state.self, 2500, Abort(run.id)) answer( session_state.State( - ..clear_tool_progress(state), + ..clear_tool_progress(refuse_acquires(state)), steering: [], blocked_until: 0, activity: cancel_turn(state), diff --git a/src/albedo/daemon/session_extensions.gleam b/src/albedo/daemon/session_extensions.gleam index 1cf0f1e83..dfa81d4ac 100644 --- a/src/albedo/daemon/session_extensions.gleam +++ b/src/albedo/daemon/session_extensions.gleam @@ -61,6 +61,8 @@ fn apply( session_state.State( ..state, kernel: kernel, + released: None, + prepared: None, context: session_state.unprepared(), ) #(reloaded(state), Error(error)) @@ -71,9 +73,12 @@ fn apply( None -> state } let state = + // A composition kept without a kernel predates this reload. session_state.State( ..state, kernel: kernel, + released: None, + prepared: None, context: session_state.unprepared(), ) let #(state, warnings) = case diff --git a/src/albedo/daemon/session_history.gleam b/src/albedo/daemon/session_history.gleam index b9fff43c6..497c07b35 100644 --- a/src/albedo/daemon/session_history.gleam +++ b/src/albedo/daemon/session_history.gleam @@ -91,6 +91,16 @@ pub fn rename_profiles( ) } +/// Whether the transcript ends with calls no result answers, which only the +/// kernel that ran them can recover. +pub fn needs_kernel(history: Option(List(transcript.Entry))) -> Bool { + case history { + Some(history) -> + tool_results.unanswered(history |> list.reverse |> raw_inputs) != [] + None -> False + } +} + pub fn recover_pending( host: runtime.Runtime, history: Option(List(transcript.Entry)), diff --git a/src/albedo/daemon/session_last_call.gleam b/src/albedo/daemon/session_last_call.gleam index 8e15ccb5b..7065bcebd 100644 --- a/src/albedo/daemon/session_last_call.gleam +++ b/src/albedo/daemon/session_last_call.gleam @@ -38,7 +38,10 @@ fn rebuild( #(session_state.State(message), Option(#(extension.SentCall, Int))), String, ) { - use kernel <- result.try(option.to_result(state.kernel, "no kernel")) + use kernel <- result.try(option.to_result( + session_state.composition(state), + "no composition", + )) use last <- result.try(requests.last_turn( runtime.ledger(state.host), state.info.id, diff --git a/src/albedo/daemon/session_prompt.gleam b/src/albedo/daemon/session_prompt.gleam index 6fd60cc64..963546eff 100644 --- a/src/albedo/daemon/session_prompt.gleam +++ b/src/albedo/daemon/session_prompt.gleam @@ -166,14 +166,17 @@ fn changes(previous: String, current: String) -> String { pub fn remember_prompt( state: session_state.State(message), ) -> session_state.State(message) { - case state.kernel, runtime.peek_prompt(state.host, state.info.id) { + case + session_state.composition(state), + runtime.peek_prompt(state.host, state.info.id) + { Some(kernel), Some(#(instructions, context)) -> case conversation.remember_prompt( runtime.ledger(state.host), state.info.id, conversation.PinnedPrompt(instructions, context), - requests.tools_hash(runtime.tools(runtime.prepared(kernel))), + requests.tools_hash(runtime.tools(kernel)), ) { Ok(_) -> state @@ -199,8 +202,8 @@ pub fn reconcile_prompt( runtime.peek_prompt(state.host, state.info.id) |> option.map(fn(prompt) { conversation.PinnedPrompt(prompt.0, prompt.1) }) let tools = - option.map(state.kernel, fn(kernel) { - requests.tools_hash(runtime.tools(runtime.prepared(kernel))) + option.map(session_state.composition(state), fn(kernel) { + requests.tools_hash(runtime.tools(kernel)) }) case conversation.known_prompt(runtime.ledger(state.host), state.info.id) { Error(error) -> diff --git a/src/albedo/daemon/session_run.gleam b/src/albedo/daemon/session_run.gleam index 136198f07..48bca75fa 100644 --- a/src/albedo/daemon/session_run.gleam +++ b/src/albedo/daemon/session_run.gleam @@ -61,6 +61,10 @@ pub type Messages(message) { compacting: fn(String, Subject(Nil)) -> message, finished: fn(String, Result(Nil, String)) -> message, collect: message, + acquire: fn( + String, + Subject(Result(#(runtime.Session, Option(String)), String)), + ) -> message, boundary: fn(String, Subject(Result(Option(loop.Selection), String))) -> message, ) @@ -279,6 +283,22 @@ pub fn drain_fn( } } +/// The session's kernel for the call about to run. The session answers once +/// one is live, booting or adopting one if it holds none, and refuses a run +/// that was cancelled meanwhile. +fn acquire_fn( + owner: Subject(message), + run_id: String, + messages: Messages(message), +) -> fn() -> Result(#(runtime.Session, Option(String)), String) { + fn() { + confirm(owner, "python kernel", waiting: 185_000, sending: messages.acquire( + run_id, + _, + )) + } +} + /// Bookkeeping the turn can go on without: a stalled session actor must not /// kill the turn over it; fire and forget after the bound. fn report(owner: Subject(message), make: fn(Subject(Nil)) -> message) -> Nil { @@ -385,7 +405,7 @@ fn label(kind: String, id: String) -> Nil pub fn start( state: session_state.State(message), - kernel: runtime.Session, + prepared: runtime.Prepared, client: extension.Upstream, model_history: List(types.Input), work: turn.Work, @@ -407,7 +427,8 @@ pub fn start( state.info.model, state.info.effort, state.host, - kernel, + prepared, + acquire_fn(owner, run_id, messages), state.pin, client, publish_fn(owner, run_id, messages, stop, waiting: 30_000), diff --git a/src/albedo/daemon/session_state.gleam b/src/albedo/daemon/session_state.gleam index acdd16a77..43d648c95 100644 --- a/src/albedo/daemon/session_state.gleam +++ b/src/albedo/daemon/session_state.gleam @@ -49,6 +49,9 @@ pub type State(message) { /// The kernel the idle sweep released, whose composition stays prepared /// for the next open: its extensions keep hearing the session meanwhile. released: Option(runtime.Session), + /// The composition the runtime prepared without a kernel, for a turn + /// that starts while the session holds none. + prepared: Option(runtime.Prepared), home: String, self: Subject(message), history: Option(List(transcript.Entry)), @@ -474,3 +477,18 @@ pub fn unprepared() -> context_snapshot.Snapshot { "runtime session has not prepared a provider request", ) } + +/// What a turn composes from: the held kernel's, else the released one's, +/// else one prepared without a kernel, each only for the current workspace. +pub fn composition(state: State(message)) -> Option(runtime.Prepared) { + let current = fn(prepared: runtime.Prepared) { + case prepared.cwd == state.info.cwd { + True -> Some(prepared) + False -> None + } + } + case state.kernel, state.released { + Some(kernel), _ | None, Some(kernel) -> current(runtime.prepared(kernel)) + None, None -> option.then(state.prepared, current) + } +} diff --git a/src/albedo/harness/loop.gleam b/src/albedo/harness/loop.gleam index cbf61b4c0..a77237d54 100644 --- a/src/albedo/harness/loop.gleam +++ b/src/albedo/harness/loop.gleam @@ -47,7 +47,11 @@ pub type Loop { model: String, effort: Option(String), host: runtime.Runtime, - kernel: runtime.Session, + /// The session's composition: instructions, tools, and hooks. + prepared: runtime.Prepared, + /// The session's kernel for one tool call, and the notice its arrival + /// left for the model; the turn holds no kernel between calls. + acquire: fn() -> Result(#(runtime.Session, Option(String)), String), pin: Pin, upstream: extension.Upstream, publish: fn(view.Event) -> Bool, @@ -453,7 +457,7 @@ pub fn compact(state: Loop, inputs: List(types.Input)) -> Result(Nil, String) { } state.report_pin(Some(evicted)) let instructions = case changed { - True -> kernel_instructions(state.kernel) + True -> kernel_instructions(state.prepared) False -> request_instructions(state) } // A forced compaction keeps the default options; an ordinary turn sets effort. @@ -604,7 +608,7 @@ type Invoked { fn invoke(state: Loop, call: types.ToolCall) -> Result(Invoked, String) { // Before the hooks, so they judge the cell that runs. - let call = runtime.as_cell(runtime.prepared(state.kernel), call) + let call = runtime.as_cell(state.prepared, call) let asked = hook.Call(call.id, call.name, call.arguments, None) let started = requests.now() use hook.Answer(calling, _) <- result.try(hooked(state, hook.Calling(asked))) @@ -613,21 +617,17 @@ fn invoke(state: Loop, call: types.ToolCall) -> Result(Invoked, String) { ..call, arguments: option.unwrap(calling.arguments, call.arguments), ) - use output <- result.try(case calling.block { - Some(reason) -> - Ok( - types.ToolOutput( - call.id, - json.to_string( - json.object([ - #("error", json.string("blocked by a hook: " <> reason)), - ]), - ), - [], - ), - ) + use #(output, notice) <- result.try(case calling.block { + Some(reason) -> Ok(#(refused(call, "blocked by a hook: " <> reason), None)) None -> - runtime.invoke(state.host, state.kernel, call, state.upstream.images) + case state.acquire() { + // The model hears why and may go on; a cancelled turn stops at its + // next checkpoint. + Error(why) -> Ok(#(refused(call, why), None)) + Ok(#(kernel, notice)) -> + runtime.invoke(state.host, kernel, call, state.upstream.images) + |> result.map(fn(output) { #(output, notice) }) + } }) let body = case output { types.ToolOutput(_, body, _) -> body @@ -635,7 +635,7 @@ fn invoke(state: Loop, call: types.ToolCall) -> Result(Invoked, String) { } let hook.Answer(called, by) = runtime.hook( - runtime.prepared(state.kernel), + state.prepared, hook.Called( hook.Call(..asked, arguments: call.arguments), body, @@ -647,6 +647,7 @@ fn invoke(state: Loop, call: types.ToolCall) -> Result(Invoked, String) { // A block after the call cannot undo it: its reason is context. let added = list.flatten([ + option.values([notice]), calling.context, option.values([option.map(called.block, hook.input(by, _))]), called.context, @@ -654,10 +655,19 @@ fn invoke(state: Loop, call: types.ToolCall) -> Result(Invoked, String) { Ok(Invoked(call, output, list.map(added, types.User), called.halt)) } +/// A call that did not run, answered in the JSON shape tools report errors in. +fn refused(call: types.ToolCall, message: String) -> types.Input { + types.ToolOutput( + call.id, + json.to_string(json.object([#("error", json.string(message))])), + [], + ) +} + /// Asks the session's hooks, shows the user their notes, and ends the turn /// if one of them asked to. fn hooked(state: Loop, event: hook.Event) -> Result(hook.Answer, String) { - let answer = runtime.hook(runtime.prepared(state.kernel), event) + let answer = runtime.hook(state.prepared, event) note(state, answer.verdict) case answer.verdict.halt { Some(reason) -> Error("stopped by a hook: " <> reason) @@ -778,7 +788,7 @@ fn prepare( ) -> Result(compaction.Prepared, String) { runtime.prepare_view_scoped( state.host, - runtime.prepared(state.kernel), + state.prepared, state.model, request_source(state.upstream, state.model), extension.clean_endpoint(state.upstream.endpoint), @@ -1158,12 +1168,12 @@ fn accepted_timeout(error: types.Error) -> Bool { } fn request_instructions(state: Loop) -> String { - instructions_for(state.pin, state.kernel) + instructions_for(state.pin, state.prepared) } /// The system prompt a request carries: the pinned one while a pin holds, /// else the kernel's current one. -fn instructions_for(pin: Pin, kernel: runtime.Session) -> String { +fn instructions_for(pin: Pin, kernel: runtime.Prepared) -> String { case pin { Pinned(prompt, _) -> prompt.instructions <> context_text(prompt.context) Unpinned -> kernel_instructions(kernel) @@ -1180,7 +1190,7 @@ fn request( request_for( state.model, state.effort, - state.kernel, + state.prepared, instructions, readable(state.upstream.images, history), ) @@ -1218,7 +1228,7 @@ fn omitted_images(images: List(types.Image)) -> String { fn request_for( model: String, effort: Option(String), - kernel: runtime.Session, + kernel: runtime.Prepared, instructions: String, history: List(types.Input), ) -> types.Request { @@ -1226,15 +1236,14 @@ fn request_for( model, Some(instructions), tool_results.pair(history), - runtime.tools(runtime.prepared(kernel)), + runtime.tools(kernel), None, types.Options(..types.defaults, effort: effort), ) } -fn kernel_instructions(kernel: runtime.Session) -> String { - runtime.instructions(runtime.prepared(kernel)) - <> context_text(runtime.context(runtime.prepared(kernel))) +fn kernel_instructions(kernel: runtime.Prepared) -> String { + runtime.instructions(kernel) <> context_text(runtime.context(kernel)) } fn context_text(context: List(types.Input)) -> String { @@ -1301,7 +1310,7 @@ fn settled( /// sent is for the caller to judge, by comparing their prefix identities. pub fn rebuild( host: runtime.Runtime, - kernel: runtime.Session, + kernel: runtime.Prepared, model: String, effort: Option(String), pin: Pin, @@ -1310,7 +1319,7 @@ pub fn rebuild( ) -> Result(#(types.Request, requests.Prefix), String) { use prepared <- result.map(runtime.project_view_scoped( host, - runtime.prepared(kernel), + kernel, model, request_source(upstream, model), extension.clean_endpoint(upstream.endpoint), @@ -1406,7 +1415,7 @@ fn summarize( request_for( model, state.effort, - state.kernel, + state.prepared, instructions, readable(state.upstream.images, history), ) diff --git a/test/daemon/bedrock_replay_preflight_test.gleam b/test/daemon/bedrock_replay_preflight_test.gleam index a5cdfe04f..e7a986081 100644 --- a/test/daemon/bedrock_replay_preflight_test.gleam +++ b/test/daemon/bedrock_replay_preflight_test.gleam @@ -151,6 +151,7 @@ fn state(home: String, host: runtime.Runtime) -> session_state.State(Nil) { host: host, kernel: None, released: None, + prepared: None, home: home, self: process.new_subject(), history: Some([]), diff --git a/test/daemon/session_run_test.gleam b/test/daemon/session_run_test.gleam index 61f3175bb..c653813b5 100644 --- a/test/daemon/session_run_test.gleam +++ b/test/daemon/session_run_test.gleam @@ -49,6 +49,7 @@ fn messages() -> session_run.Messages(Owner) { compacting: fn(_, _) { Unused }, finished: fn(_, _) { Unused }, collect: Unused, + acquire: fn(_, _) { Unused }, boundary: fn(_, _) { Unused }, ) } diff --git a/test/e2e/kernel_lazy_test.py b/test/e2e/kernel_lazy_test.py new file mode 100644 index 000000000..8e2659a80 --- /dev/null +++ b/test/e2e/kernel_lazy_test.py @@ -0,0 +1,179 @@ +"""Lazy kernels: a turn holds no Python kernel until its first tool call.""" + +import json +from pathlib import Path +import subprocess +import threading +import time +import unittest + +from harness import Albedo, Provider, exclusive, latest_user, python, text +from kernel_support import editable_daemon + +IDLE_SECONDS = 2 + + +def kernels(home): + """Pids of the kernels whose run directory is under this daemon's home.""" + listing = subprocess.run( + ["ps", "-axo", "pid=,command="], capture_output=True, text=True, check=True + ).stdout + return [ + int(line.split(None, 1)[0]) + for line in listing.splitlines() + if "albedo_kernel.py" in line and f"{home}/run/" in line + ] + + +def wait_until(predicate, timeout=20): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return True + time.sleep(0.05) + return predicate() + + +def inputs(record): + return record["request"]["input"] + + +# exclusive: lazy kernels and the idle timeout are daemon-wide, and the tests +# count every kernel the daemon runs +@exclusive +class KernelLazyTests(unittest.TestCase): + def setUp(self): + self.model_gate = threading.Event() + self.model_waiting = threading.Event() + self.cells = {} + + def script(request): + if request["input"][-1].get("role") == "user": + prompt = latest_user(request).split("")[0] + if prompt in self.cells: + return python(self.cells[prompt]) + if prompt.startswith("wait for the model"): + self.model_waiting.set() + self.model_gate.wait(60) + return text("waited") + return text("ok") + + self.provider = Provider(script) + self.addCleanup(self.provider.close) + + def start(self, slow_marker=None): + def prepare(app): + app.env.update( + ALBEDO_KERNEL_LAZY="1", + ALBEDO_TEST_TIME_SCALE="100", + ALBEDO_IDLE_SECONDS=str(IDLE_SECONDS), + ) + if slow_marker is not None: + launcher, bundle = editable_daemon(app.root) + kernel = bundle / "albedo_kernel.py" + kernel.write_text( + "import os as _os, time as _time\n" + f"if _os.path.exists({str(slow_marker)!r}):\n" + " _time.sleep(3)\n" + kernel.read_text() + ) + app.env.update(ALBEDO_DAEMON=str(launcher)) + + app = Albedo(self.provider, protocol="responses", prepare=prepare) + app.__enter__() + self.addCleanup(app.__exit__, None, None, None) + return app + + def turn(self, app, session, prompt): + app.prompt(session, prompt).close() + app.idle(session) + + def test_text_turns_and_model_waits_hold_no_kernel(self): + app = self.start() + existing = set(kernels(app.home)) + session = app.session() + self.turn(app, session, "just talk") + self.assertEqual(set(kernels(app.home)) - existing, set()) + + self.cells["remember"] = "answer = 7\nrows = [1, 2, 3]" + self.turn(app, session, "remember") + self.assertEqual(len(set(kernels(app.home)) - existing), 1) + self.assertTrue( + wait_until(lambda: not set(kernels(app.home)) - existing), + "idle kernel outlived its limit", + ) + + app.prompt(session, "wait for the model").close() + self.assertTrue(self.model_waiting.wait(30)) + time.sleep(0.5) + self.assertEqual( + set(kernels(app.home)) - existing, + set(), + "a turn waiting on its model must not hold a kernel", + ) + self.model_gate.set() + app.idle(session) + + self.cells["recall"] = "print('recalled', answer, rows)" + self.turn(app, session, "recall") + after = inputs(self.provider.requests[-1]) + self.assertTrue( + any("recalled 7 [1, 2, 3]" in item.get("output", "") for item in after), + after, + ) + notices = [ + json.dumps(item) + for item in after + if item.get("role") == "user" and "restored from disk" in json.dumps(item) + ] + self.assertEqual(len(notices), 1, after) + + def test_interrupt_while_the_kernel_starts_runs_no_cell(self): + slow = Path("/tmp") / f"albedo-slow-{time.monotonic_ns()}" + self.addCleanup(lambda: slow.unlink(missing_ok=True)) + app = self.start(slow_marker=slow) + session = app.session() + written = app.workspace / "written" + self.cells["write"] = f"open({str(written)!r}, 'w').write('x')" + slow.touch() + start = len(self.provider.requests) + with app.prompt(session, "write") as response: + input_id = json.load(response)["id"] + self.assertTrue(wait_until(lambda: len(self.provider.requests) > start)) + with app.api(f"/sessions/{session}?tail=0") as response: + captured = json.load(response) + # The cell is now waiting on the slow kernel. + time.sleep(0.5) + interrupted = time.monotonic() + app.api( + f"/sessions/{session}/interrupt", + { + "run_id": captured["status"]["run_id"], + "through_input_order": captured["input_order"], + }, + ).close() + + def receipt(): + with app.api(f"/sessions/{session}/inputs/{input_id}") as response: + return json.load(response).get("turn") or {} + + # The run ends at once, not when the kernel it was waiting on starts. + self.assertTrue( + wait_until(lambda: receipt().get("state") == "interrupted", timeout=2) + ) + self.assertLess(time.monotonic() - interrupted, 2.0) + app.idle(session) + time.sleep(4) + self.assertFalse(written.exists(), "a cancelled turn ran its cell") + slow.unlink() + self.cells["after"] = "print('after', 6 * 7)" + self.turn(app, session, "after") + self.assertTrue( + any( + "after 42" in item.get("output", "") + for item in inputs(self.provider.requests[-1]) + ) + ) + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1 From 1caf4a12941d318e6ec5de0b8c66ce6ffad6030e Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 08:09:53 -0400 Subject: [PATCH 27/72] Report no lost namespace for a kernel whose session never ran a tool --- src/albedo/daemon/session_namespace.gleam | 67 +++++++++++++++-------- 1 file changed, 43 insertions(+), 24 deletions(-) diff --git a/src/albedo/daemon/session_namespace.gleam b/src/albedo/daemon/session_namespace.gleam index 1e3190fe2..31a50cbeb 100644 --- a/src/albedo/daemon/session_namespace.gleam +++ b/src/albedo/daemon/session_namespace.gleam @@ -8,6 +8,7 @@ import albedo/harness/location import albedo/harness/runtime import albedo/harness/runtime/state as runtime_state import albedo/harness/ssh +import albedo/openai_api/types import albedo/text_scalars import gleam/erlang/process import gleam/int @@ -669,30 +670,48 @@ fn revive( Some(notice), _ if notice == lost_notice -> session_state.State(..state, kernel: Some(kernel)) _, None | _, Some([]) -> session_state.State(..state, kernel: Some(kernel)) - _, Some(_) -> { - let #(state, ended) = end_unfinished(state) - let jobs = - list.map(lost_jobs, fn(job) { #(job.0, short(job.1)) }) |> labels - let revived = case state_path(state.home, state.info.id) { - Some(path) -> runtime.load_state(kernel, path, state_timeout) - None -> Error(python.Invalid("session has no state file")) + // A lazy kernel's first boot comes after its turn is committed: a + // transcript without a tool result never had a namespace to lose. + _, Some(entries) -> + case list.any(entries, fn(entry) { is_tool_output(entry.input) }) { + False -> session_state.State(..state, kernel: Some(kernel)) + True -> revive_saved(state, kernel, lost_jobs) } - case revived { - Ok(python.Saved([_, ..], _, _, _, _) as saved) -> - adopted( - state, - kernel, - restored_notice(saved, jobs, ended), - restored_text(saved, jobs, ended), - ) - _ -> - adopted( - state, - kernel, - lost_notice_for(jobs, ended), - lost_text(jobs, ended), - ) - } - } + } +} + +fn is_tool_output(input: types.Input) -> Bool { + case input { + types.ToolOutput(..) -> True + _ -> False + } +} + +fn revive_saved( + state: session_state.State(message), + kernel: runtime.Session, + lost_jobs: List(#(String, String)), +) -> session_state.State(message) { + let #(state, ended) = end_unfinished(state) + let jobs = list.map(lost_jobs, fn(job) { #(job.0, short(job.1)) }) |> labels + let revived = case state_path(state.home, state.info.id) { + Some(path) -> runtime.load_state(kernel, path, state_timeout) + None -> Error(python.Invalid("session has no state file")) + } + case revived { + Ok(python.Saved([_, ..], _, _, _, _) as saved) -> + adopted( + state, + kernel, + restored_notice(saved, jobs, ended), + restored_text(saved, jobs, ended), + ) + _ -> + adopted( + state, + kernel, + lost_notice_for(jobs, ended), + lost_text(jobs, ended), + ) } } -- knotmirror 0.0.1 From f2961902e2fa4ecb811102f83a5debb543abe253 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 08:09:53 -0400 Subject: [PATCH 28/72] Release a lazy turn's kernel once its model wait passes ALBEDO_KERNEL_REST_MS --- robot-docs/runtime.md | 18 +++ src/albedo/daemon/session.gleam | 117 +++++++++++++++--- src/albedo/daemon/session_state.gleam | 3 + .../bedrock_replay_preflight_test.gleam | 1 + test/e2e/kernel_lazy_test.py | 88 ++++++++++++- 5 files changed, 205 insertions(+), 22 deletions(-) diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index 75050e95a..809e72cad 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -179,6 +179,24 @@ keeps its Gleam OTP receive loop and system-message handling intact. Any message wakes it immediately; the timer never delays handling a message. Existing `Collect` messages still perform a major collection when a handler drops state. +## turns without a kernel + +With `ALBEDO_KERNEL_LAZY=1` a turn starts from the session's composition +(`session_state.composition`: the held kernel's, else the released one's, else +`runtime.prepare_session_async`) and holds no Python kernel. The worker's +`acquire` sends `AcquireKernel` before each tool call; the session answers with +its live kernel or parks the request behind `kernel_or_park`, and refuses it once +the run is cancelled. The adoption notice (restored or lost namespace) reaches +the model as a user note after that call's result. A turn whose transcript ends +in unanswered calls still waits for the kernel, which alone can recover them. + +With the spare pool on (`ALBEDO_KERNEL_RELEASE_WITH_SPARE=1`), each model +request arms a rest timer: once the wait passes `ALBEDO_KERNEL_REST_MS` (3 s) +with no tool call, the kernel is released through the resting release's guards +(no live work, no watcher, no transition, pool healthy), rechecked every second +while they fail. Releasing at once cost 132 ms per step of a fast tool loop; at +3 s a fast loop never releases. + ## finite actor calls `actor_call.try_call` uses a monitored process alias for its reply subject. diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index c0e5427fb..357f86d56 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -360,6 +360,10 @@ pub type Message { KernelOpened(Result(runtime.Session, python.Error)) /// The runtime answered this session's request for a kernel-free composition. PreparedOpened(Result(runtime.Prepared, python.Error)) + /// The model wait a rest timer measured has passed; see `arm_rest`. + RestKernel(String, Int) + /// The spare pool can refill what a rest release takes. + RestHealthy(String, Int) /// A run's worker asks for the kernel its next tool call runs in. AcquireKernel( String, @@ -440,6 +444,7 @@ pub fn start( kernel: None, released: None, prepared: None, + rest_token: 0, home: home, self: self, history: None, @@ -1383,7 +1388,7 @@ fn handle( False -> answer(state, reply, Error("stale run")) True -> { let #(state, selection) = session_switch.apply_pending(state) - answer(state, reply, Ok(selection)) + answer(arm_rest(state, id), reply, Ok(selection)) } } } @@ -1423,6 +1428,32 @@ fn handle( KernelOpened(result) -> actor.continue(kernel_opened(state, result)) PreparedOpened(result) -> actor.continue(prepared_opened(state, result)) AcquireKernel(id, reply) -> acquire_kernel(state, id, reply) + RestKernel(id, token) -> { + let self = state.self + case token == state.rest_token && turn.live(state.activity, id) { + // A tool call or the next request armed a newer timer. + False -> Nil + True -> + case restable(state, id, token) { + True -> + runtime.when_pool_healthy(state.host, fn(available) { + case available { + True -> process.send(self, RestHealthy(id, token)) + False -> rest_later(self, id, token) + } + }) + // Work still running, a watcher, or a transition: look again. + False -> rest_later(self, id, token) + } + } + actor.continue(state) + } + RestHealthy(id, token) -> + case restable(state, id, token), state.kernel { + True, Some(kernel) -> + actor.continue(release_kernel(state, kernel, None)) + _, _ -> actor.continue(state) + } WorkspaceReady(token, purpose, result) -> actor.continue(workspace_ready(state, token, purpose, result)) StartQueued -> actor.continue(start_queued(state)) @@ -2844,6 +2875,7 @@ fn acquire_kernel( id: String, reply: Subject(Result(#(runtime.Session, Option(String)), String)), ) -> actor.Next(State, Message) { + let state = session_state.State(..state, rest_token: state.rest_token + 1) case turn.live(state.activity, id) && !state.closing { False -> answer(state, reply, Error(acquire_refused)) True -> @@ -2890,6 +2922,46 @@ fn hand_kernel( const acquire_refused = "the turn ended before its python kernel was ready" +/// ALBEDO_KERNEL_REST_MS, else 3 s: how long a turn waits on its model before +/// its idle kernel is released. +fn rest_ms() -> Int { + case int.parse(env("ALBEDO_KERNEL_REST_MS")) { + Ok(ms) if ms >= 0 -> ms + _ -> 3000 + } +} + +/// A turn about to wait on its model releases its kernel if the wait outlasts +/// `rest_ms`; its next tool call reacquires one. A tool call or the next +/// request makes the timer stale. +fn arm_rest(state: State, id: String) -> State { + case lazy_kernel() && runtime.release_with_spare(), state.kernel { + True, Some(_) -> { + let token = state.rest_token + 1 + let _ = clock.send_after(state.self, rest_ms(), RestKernel(id, token)) + session_state.State(..state, rest_token: token) + } + _, _ -> state + } +} + +/// Checks a turn's kernel again while its model wait lasts. +fn rest_later(self: Subject(Message), id: String, token: Int) -> Nil { + let _ = clock.send_after(self, 1000, RestKernel(id, token)) + Nil +} + +/// The resting release's guards, for a kernel under a live turn waiting on +/// its model since the timer `token` was armed. +fn restable(state: State, id: String, token: Int) -> Bool { + token == state.rest_token + && turn.live(state.activity, id) + && !uses_kernel_transition(state) + && state.booting == None + && state.watchers == [] + && option.map(state.kernel, runtime.live_work) == Some(Ok(0)) +} + /// Refuses the kernel requests a cancelled run left parked, so its worker /// stops now instead of when the kernel arrives. fn refuse_acquires(state: State) -> State { @@ -4751,23 +4823,32 @@ fn begin_release( || state.booting != None || option.map(state.kernel, runtime.live_work) != Some(Ok(0)) { - Some(kernel), None, False -> { - let #(home, id, self) = #(state.home, state.info.id, state.self) - let _ = - process.spawn_unlinked(fn() { - process.send( - self, - Released( - kernel, - protect.guarded(fn() { - session_namespace.save_state(home, id, kernel) - }), - reply, - ), - ) - }) - actor.continue(session_state.State(..state, releasing: Some([]))) - } + Some(kernel), None, False -> + actor.continue(release_kernel(state, kernel, reply)) _, _, _ -> release_answer(state, reply, False) } } + +/// Saves the namespace outside the actor and answers `Released`; work that +/// needs the kernel meanwhile parks behind `releasing`. +fn release_kernel( + state: State, + kernel: runtime.Session, + reply: Option(Subject(Bool)), +) -> State { + let #(home, id, self) = #(state.home, state.info.id, state.self) + let _ = + process.spawn_unlinked(fn() { + process.send( + self, + Released( + kernel, + protect.guarded(fn() { + session_namespace.save_state(home, id, kernel) + }), + reply, + ), + ) + }) + session_state.State(..state, releasing: Some([])) +} diff --git a/src/albedo/daemon/session_state.gleam b/src/albedo/daemon/session_state.gleam index 43d648c95..3a9680648 100644 --- a/src/albedo/daemon/session_state.gleam +++ b/src/albedo/daemon/session_state.gleam @@ -52,6 +52,9 @@ pub type State(message) { /// The composition the runtime prepared without a kernel, for a turn /// that starts while the session holds none. prepared: Option(runtime.Prepared), + /// Bumped at each model request and tool call; a rest timer armed under + /// an older value is stale. + rest_token: Int, home: String, self: Subject(message), history: Option(List(transcript.Entry)), diff --git a/test/daemon/bedrock_replay_preflight_test.gleam b/test/daemon/bedrock_replay_preflight_test.gleam index e7a986081..6493cb34b 100644 --- a/test/daemon/bedrock_replay_preflight_test.gleam +++ b/test/daemon/bedrock_replay_preflight_test.gleam @@ -152,6 +152,7 @@ fn state(home: String, host: runtime.Runtime) -> session_state.State(Nil) { kernel: None, released: None, prepared: None, + rest_token: 0, home: home, self: process.new_subject(), history: Some([]), diff --git a/test/e2e/kernel_lazy_test.py b/test/e2e/kernel_lazy_test.py index 8e2659a80..302dfd5ca 100644 --- a/test/e2e/kernel_lazy_test.py +++ b/test/e2e/kernel_lazy_test.py @@ -7,7 +7,7 @@ import threading import time import unittest -from harness import Albedo, Provider, exclusive, latest_user, python, text +from harness import Albedo, Provider, exclusive, python, text from kernel_support import editable_daemon IDLE_SECONDS = 2 @@ -38,6 +38,22 @@ def inputs(record): return record["request"]["input"] +def is_note(item): + return item.get("role") == "user" and str(item.get("content", "")).startswith( + "" + ) + + +def prompt_of(request): + """The latest user prompt, not a system note that follows a tool result.""" + users = [ + item + for item in request["input"] + if item.get("role") == "user" and not is_note(item) + ] + return str(users[-1].get("content", "")).split("")[0] if users else "" + + # exclusive: lazy kernels and the idle timeout are daemon-wide, and the tests # count every kernel the daemon runs @exclusive @@ -46,27 +62,44 @@ class KernelLazyTests(unittest.TestCase): self.model_gate = threading.Event() self.model_waiting = threading.Event() self.cells = {} + self.follow = {} def script(request): - if request["input"][-1].get("role") == "user": - prompt = latest_user(request).split("")[0] + last = request["input"][-1] + prompt = prompt_of(request) + if last.get("role") == "user" and not is_note(last): if prompt in self.cells: return python(self.cells[prompt]) if prompt.startswith("wait for the model"): self.model_waiting.set() self.model_gate.wait(60) return text("waited") + outputs = [ + item + for item in request["input"] + if item.get("type") == "function_call_output" + ] + follow = self.follow.get(prompt, []) + if prompt in self.cells and len(outputs) <= len(follow): + # Each follow-up cell waits on the model first when asked to. + wait, code = follow[len(outputs) - 1] if outputs else (False, None) + if code is not None: + if wait: + self.model_waiting.set() + self.model_gate.wait(60) + return python(code) return text("ok") self.provider = Provider(script) self.addCleanup(self.provider.close) - def start(self, slow_marker=None): + def start(self, slow_marker=None, **env): def prepare(app): app.env.update( ALBEDO_KERNEL_LAZY="1", ALBEDO_TEST_TIME_SCALE="100", ALBEDO_IDLE_SECONDS=str(IDLE_SECONDS), + **env, ) if slow_marker is not None: launcher, bundle = editable_daemon(app.root) @@ -97,6 +130,11 @@ class KernelLazyTests(unittest.TestCase): self.cells["remember"] = "answer = 7\nrows = [1, 2, 3]" self.turn(app, session, "remember") self.assertEqual(len(set(kernels(app.home)) - existing), 1) + # Nothing ran before, so the first kernel has no namespace to call lost. + self.assertFalse( + any(is_note(item) for item in inputs(self.provider.requests[-1])), + inputs(self.provider.requests[-1]), + ) self.assertTrue( wait_until(lambda: not set(kernels(app.home)) - existing), "idle kernel outlived its limit", @@ -174,6 +212,48 @@ class KernelLazyTests(unittest.TestCase): ) ) + def test_a_long_model_wait_mid_turn_releases_and_restores_the_kernel(self): + app = self.start( + ALBEDO_KERNEL_SPARES="1", + ALBEDO_KERNEL_RELEASE_WITH_SPARE="1", + ALBEDO_KERNEL_REST_MS="50", + ) + session = app.session() + place = app.workspace / "place" + place.mkdir() + self.cells["work"] = f"import os\nanswer = 7\nos.chdir({str(place)!r})" + self.follow["work"] = [ + (True, "import os\nprint('kept', answer, os.getcwd())"), + (False, "print('again', answer)"), + ] + + def kernel_state(): + with app.api(f"/sessions/{session}?tail=0") as response: + return json.load(response)["kernel"]["state"] + + app.prompt(session, "work").close() + self.assertTrue(self.model_waiting.wait(30)) + self.assertTrue( + wait_until(lambda: kernel_state() == "none"), + "a turn waiting on its model past the rest time kept its kernel", + ) + self.model_gate.set() + app.idle(session) + outputs = [ + item.get("output", "") + for item in inputs(self.provider.requests[-1]) + if item.get("type") == "function_call_output" + ] + self.assertTrue(any("kept 7" in output for output in outputs), outputs) + self.assertTrue( + any( + f"{place.resolve()}" in output or str(place) in output + for output in outputs + ), + outputs, + ) + self.assertTrue(any("again 7" in output for output in outputs), outputs) + if __name__ == "__main__": unittest.main() -- knotmirror 0.0.1 From d8f89502b62678636fca18a53b7f40678e9c5cc1 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 08:11:39 -0400 Subject: [PATCH 29/72] Wait out a kernel release before handing a turn its kernel; test a kernel dying at start --- src/albedo/daemon/session.gleam | 5 ++-- test/e2e/kernel_lazy_test.py | 41 +++++++++++++++++++++++++++------ 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 357f86d56..dfcb01215 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -2880,9 +2880,10 @@ fn acquire_kernel( False -> answer(state, reply, Error(acquire_refused)) True -> case state.kernel { - // A stale bundle is swapped between turns, not under one. + // A stale bundle is swapped between turns, not under one; a kernel + // being released or reset is waited out. Some(kernel) -> - case runtime.alive(kernel) { + case runtime.alive(kernel) && !uses_kernel_transition(state) { True -> hand_kernel(state, kernel, reply) False -> acquire_parked(state, id, reply) } diff --git a/test/e2e/kernel_lazy_test.py b/test/e2e/kernel_lazy_test.py index 302dfd5ca..599d905a5 100644 --- a/test/e2e/kernel_lazy_test.py +++ b/test/e2e/kernel_lazy_test.py @@ -93,7 +93,7 @@ class KernelLazyTests(unittest.TestCase): self.provider = Provider(script) self.addCleanup(self.provider.close) - def start(self, slow_marker=None, **env): + def start(self, slow_marker=None, crash_marker=None, **env): def prepare(app): app.env.update( ALBEDO_KERNEL_LAZY="1", @@ -101,14 +101,15 @@ class KernelLazyTests(unittest.TestCase): ALBEDO_IDLE_SECONDS=str(IDLE_SECONDS), **env, ) - if slow_marker is not None: + if slow_marker is not None or crash_marker is not None: launcher, bundle = editable_daemon(app.root) kernel = bundle / "albedo_kernel.py" - kernel.write_text( - "import os as _os, time as _time\n" - f"if _os.path.exists({str(slow_marker)!r}):\n" - " _time.sleep(3)\n" + kernel.read_text() - ) + prelude = "import os as _os, sys as _sys, time as _time\n" + if slow_marker is not None: + prelude += f"if _os.path.exists({str(slow_marker)!r}):\n _time.sleep(3)\n" + if crash_marker is not None: + prelude += f"if _os.path.exists({str(crash_marker)!r}):\n _sys.exit(3)\n" + kernel.write_text(prelude + kernel.read_text()) app.env.update(ALBEDO_DAEMON=str(launcher)) app = Albedo(self.provider, protocol="responses", prepare=prepare) @@ -254,6 +255,32 @@ class KernelLazyTests(unittest.TestCase): ) self.assertTrue(any("again 7" in output for output in outputs), outputs) + def test_a_kernel_that_dies_while_starting_fails_only_its_call(self): + crash = Path("/tmp") / f"albedo-crash-{time.monotonic_ns()}" + self.addCleanup(lambda: crash.unlink(missing_ok=True)) + app = self.start(crash_marker=crash) + session = app.session() + self.cells["boom"] = "print('ran', 6 * 7)" + crash.touch() + self.turn(app, session, "boom") + outputs = [ + item.get("output", "") + for item in inputs(self.provider.requests[-1]) + if item.get("type") == "function_call_output" + ] + self.assertEqual(len(outputs), 1, outputs) + self.assertIn("could not start the session python kernel", outputs[0]) + self.assertNotIn("ran 42", outputs[0]) + crash.unlink() + self.cells["again"] = "print('ran', 6 * 7)" + self.turn(app, session, "again") + self.assertTrue( + any( + "ran 42" in item.get("output", "") + for item in inputs(self.provider.requests[-1]) + ) + ) + if __name__ == "__main__": unittest.main() -- knotmirror 0.0.1 From ed821938b42fd1f85209f290ab07edfebef47591 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:22:25 -0400 Subject: [PATCH 30/72] Rewarm a session's cache from its composition, booting no kernel when lazy --- src/albedo/daemon/session.gleam | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index dfcb01215..840f157be 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -1408,7 +1408,9 @@ fn handle( case busy(state) || state.steering != [] { True -> actor.continue(state) False -> - case kernel_or_park(state, Rewarm) { + // Rewarming rebuilds the last request, which needs only the + // composition a turn would start from. + case turn_or_park(state, Rewarm) { Error(state) -> actor.continue(state) Ok(state) -> actor.continue(restore_last_call(state)) } -- knotmirror 0.0.1 From 61944e8019fb9ca32eb09d69501d7f54f23e1ea8 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 08:01:08 -0400 Subject: [PATCH 31/72] Start local kernels directly instead of through a bridge launch interpreter --- priv/python/albedo_bridge.py | 9 ++------ priv/python/albedo_kernel.py | 21 ++++++++++++++++++- robot-docs/kernel.md | 8 ++++--- .../extensions/python/albedo_python.erl | 13 +++++++----- test/e2e/agents_swarm_test.py | 2 +- 5 files changed, 36 insertions(+), 17 deletions(-) diff --git a/priv/python/albedo_bridge.py b/priv/python/albedo_bridge.py index 8c66f474a..0284f5bc1 100644 --- a/priv/python/albedo_bridge.py +++ b/priv/python/albedo_bridge.py @@ -2,7 +2,6 @@ albedo_bridge.py start albedo_bridge.py attach - albedo_bridge.py launch albedo_bridge.py --frame `--frame` takes the same arguments from its first stdin frame instead, @@ -18,9 +17,8 @@ argv), and waits for its socket; `attach` connects to a kernel that is already r process announces the bundle it runs from, then copies bytes both ways until one side closes. Killing it never touches the kernel. -`launch` only starts the kernel, its token read as one stdin line, and exits 0 -once the socket answers: a local daemon connects to that socket itself, so no -bridge stays running beside a local kernel. +A local daemon starts the kernel itself and connects to its socket, so no +bridge runs beside a local kernel. Exit status 3 means no kernel is there to attach to, so the daemon can tell a kernel that is gone from a connection that merely dropped. @@ -195,9 +193,6 @@ def main(argv: list[str]) -> None: if argv[1:] == ["--frame"]: argv = framed() mode, run_dir = argv[1], argv[2] - if mode == "launch": - start(run_dir, argv[3], sys.stdin.readline().strip()).close() - return if mode == "start": attach = albedo_link.read_frame(stdin) if not isinstance(attach, dict) or not isinstance(attach.get("attach"), dict): diff --git a/priv/python/albedo_kernel.py b/priv/python/albedo_kernel.py index cc7230da3..aecc0eb23 100644 --- a/priv/python/albedo_kernel.py +++ b/priv/python/albedo_kernel.py @@ -3,8 +3,27 @@ A script is compiled from source each time it starts; a module loads its cached bytecode. The kernel is long, so this keeps about 4 MB of compile work out of every kernel's memory. + +With `--run ` the daemon starts this file directly: it leaves the +daemon's session and sends what it writes before its own output capture +starts to `/kernel.log`. """ -import runpy +import os +import sys + +if sys.argv[1:2] == ["--run"]: + if os.getpgrp() != os.getpid(): + os.setsid() + os.makedirs(sys.argv[2], mode=0o700, exist_ok=True) + log = os.open( + os.path.join(sys.argv[2], "kernel.log"), + os.O_WRONLY | os.O_CREAT | os.O_APPEND, + 0o600, + ) + os.dup2(log, 2) + os.close(log) + +import runpy # noqa: E402 runpy.run_module("albedo_cells", run_name="__main__", alter_sys=True) diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 175782fb9..c586c6636 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -357,9 +357,11 @@ completion. A read racing with the completion journal also retires the wake. - **relay** (in `albedo_python.erl`): how the port owner reaches a local kernel. an erlang process owns a `gen_tcp` connection to `kernel.sock` (`{packet, 4}`) and passes frames to the port owner as a bridge port would, - so no python process stays beside a local kernel. a fresh boot first runs - `albedo_bridge.py launch ` (token as its one stdin - line), which starts the kernel and exits once the socket answers. the relay + so no python process stays beside a local kernel. a fresh boot starts + `albedo_kernel.py --run ` itself (token as its one + stdin line; no bridge interpreter, which cost ~45 ms CPU per boot on macOS). + the kernel leaves the daemon's session, sends early stderr to `kernel.log`, + and closes its stdout once its socket listens, which the relay waits for. the relay announces nothing, so the port owner hashes the bundle itself, the same way `albedo_bundle.digest()` does. a refused or missing socket reads as exit 3. a run directory whose socket path does not fit `sun_path` (104 bytes) keeps diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 8f41369c4..772c80cd1 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -235,7 +235,8 @@ open_bridge(S = #{python := Python, bridge := Bridge, run_dir := RunDir}, Mode) open_relay(S = #{python := Python, bridge := Bridge, run_dir := RunDir}, Mode) -> Owner = self(), Launch = case Mode of - start -> {Python, [<<"-u">>, Bridge, <<"launch">>, RunDir, maps:get(modules, S)], + start -> {Python, [<<"-u">>, filename:join(filename:dirname(Bridge), <<"albedo_kernel.py">>), + <<"--run">>, RunDir, maps:get(modules, S)], maps:get(cwd, S), maps:get(token, S)}; attach -> none end, @@ -257,7 +258,7 @@ handshake(S, Port, First) -> %% Owns a local kernel's socket for Owner and speaks as a bridge port would: %% {self(), {data, Frame}} and {self(), {exit_status, Status}} go out, %% {Owner, {command, Frame}} and {Owner, close} come in. Starting a kernel -%% runs the bridge script's launch mode first, which exits once it listens. +%% waits until it listens, without a bridge process. relay(Owner, Launch, Socket, Warm) -> Watch = monitor(process, Owner), Status = case Launch of none -> 0; _ -> warm_launch(Warm, Launch) end, @@ -287,10 +288,12 @@ relay_loop(Owner, Watch, Connection) -> erlang:hibernate(?MODULE, relay_loop, [Owner, Watch, Connection]) end. -%% The launcher's exit status; it gets the token as its one line of stdin. +%% Starts the kernel itself, the token as its one line of stdin. The kernel +%% closes its stdout once it listens (or exits); 0 then means "try the socket". +%% No exit_status: with it, erts holds the eof until the kernel exits. launch({Python, Args, Cwd, Token}) -> try open_port({spawn_executable, binary_to_list(Python)}, - [binary, exit_status, use_stdio, hide, + [binary, eof, use_stdio, hide, {args, [binary_to_list(A) || A <- Args]}, {cd, binary_to_list(Cwd)}, {env, clean_environment()}]) of @@ -302,7 +305,7 @@ launch({Python, Args, Cwd, Token}) -> launched(Port) -> receive - {Port, {exit_status, Status}} -> Status; + {Port, eof} -> catch port_close(Port), 0; {Port, {data, _}} -> launched(Port) end. diff --git a/test/e2e/agents_swarm_test.py b/test/e2e/agents_swarm_test.py index 76830a852..f25f0caea 100644 --- a/test/e2e/agents_swarm_test.py +++ b/test/e2e/agents_swarm_test.py @@ -125,7 +125,7 @@ class AgentsSwarmTests(unittest.TestCase): "import os, sys\n" "from pathlib import Path\n" f"gate = Path({str(gate)!r})\n" - "if ('launch' in sys.argv or 'start' in sys.argv) and gate.exists():\n" + "if ('--run' in sys.argv or 'start' in sys.argv) and gate.exists():\n" f" Path({str(app.workspace / 'boot-ready')!r}).touch()\n" " with gate.open('rb') as reader: reader.read(1)\n" f"os.execv({sys.executable!r}, [{sys.executable!r}, *sys.argv[1:]])\n" -- knotmirror 0.0.1 From 48a6452b1cbf292beaf0e718c7262d7d03046d1c Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 08:01:10 -0400 Subject: [PATCH 32/72] Density benchmark: skip system-note user items when finding the prompt --- test/manual/agent_density.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/test/manual/agent_density.py b/test/manual/agent_density.py index c6e1dab53..2e549df14 100644 --- a/test/manual/agent_density.py +++ b/test/manual/agent_density.py @@ -24,7 +24,7 @@ import time ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "test/e2e")) import harness # noqa: E402 -from harness import Albedo, Daemon, Provider, latest_user, python, text # noqa: E402 +from harness import Albedo, Daemon, Provider, python, text # noqa: E402 from inspect_support import Inspection # noqa: E402 DEFINE = """import fractions @@ -136,8 +136,19 @@ def main(): gate = daemon.root / "cell-gate" def script(request): - prompt = latest_user(request).split("")[0] - if request["input"][-1].get("role") == "user": + # Notes (a restored namespace, hook context) arrive as their own user + # items; neither is the prompt nor starts a fresh turn. + users = [ + item.get("content", "") + for item in request["input"] + if item.get("role") == "user" + and not str(item.get("content", "")).startswith("") + ] + prompt = (users[-1] if users else "").split("")[0] + last = request["input"][-1] + if last.get("role") == "user" and not str(last.get("content", "")).startswith( + "" + ): if prompt.startswith("define:"): return python(DEFINE) if prompt.startswith("recall:"): -- knotmirror 0.0.1 From 6fcbafbe0caf70d7e8a724d37f52c24a4593c155 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 08:03:10 -0400 Subject: [PATCH 33/72] Check that a restarted daemon reattaches an adopted spare kernel with its namespace --- test/e2e/kernel_pool_test.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/e2e/kernel_pool_test.py b/test/e2e/kernel_pool_test.py index 8229584c2..aef2b7edb 100644 --- a/test/e2e/kernel_pool_test.py +++ b/test/e2e/kernel_pool_test.py @@ -313,7 +313,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): def test_shutdown_stops_spares_but_detaches_an_adopted_kernel(self): self.boot() self.ready() - adopted = self.value("import os\nos.getpid()") + adopted = self.value("import os\nsentinel = 41\nos.getpid()") ready = self.ready(excluding={adopted}) self.app.restart() wait_until( @@ -322,3 +322,8 @@ class KernelPoolTests(ModelCells, unittest.TestCase): "a fresh spare survived daemon shutdown", ) self.assertTrue(alive(adopted), "shutdown ended an adopted detached kernel") + self.assertEqual( + self.value("(os.getpid(), sentinel)"), + (adopted, 41), + "the restarted daemon did not reattach the adopted kernel", + ) -- knotmirror 0.0.1 From 4beffab88341480fc2aa8c3dc1052719375c82bf Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 08:12:37 -0400 Subject: [PATCH 34/72] Density benchmark: accept ALBEDO_DENSITY_COMMIT for synced copies without .git --- test/manual/agent_density.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/manual/agent_density.py b/test/manual/agent_density.py index 2e549df14..5a66816dd 100644 --- a/test/manual/agent_density.py +++ b/test/manual/agent_density.py @@ -7,6 +7,7 @@ The default keeps kernels resident; --idle-seconds and --settle test reaping. from __future__ import annotations +import os import argparse from concurrent.futures import ThreadPoolExecutor import ctypes @@ -188,7 +189,9 @@ def main(): result = { "platform": platform.platform(), "python": sys.version, - "commit": subprocess.check_output( + # A synced copy without .git (a remote run) names its commit itself. + "commit": os.environ.get("ALBEDO_DENSITY_COMMIT") + or subprocess.check_output( ["git", "rev-parse", "HEAD"], cwd=ROOT, text=True ).strip(), "metric": "phys_footprint" if sys.platform == "darwin" else "pss", -- knotmirror 0.0.1 From 83142a9c531e3a226dd31a6f1c4b5773e7810279 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:19:14 -0400 Subject: [PATCH 35/72] Start spare kernels directly instead of under a bridge helper interpreter --- priv/python/albedo_bridge.py | 50 ------------------- priv/python/albedo_spare.py | 4 ++ robot-docs/kernel.md | 12 +++-- .../extensions/python/albedo_python.erl | 45 +++++++++++------ test/e2e/kernel_pool_test.py | 25 +++------- 5 files changed, 48 insertions(+), 88 deletions(-) diff --git a/priv/python/albedo_bridge.py b/priv/python/albedo_bridge.py index 0284f5bc1..fcd99eea4 100644 --- a/priv/python/albedo_bridge.py +++ b/priv/python/albedo_bridge.py @@ -28,7 +28,6 @@ from __future__ import annotations import contextlib import errno -import json import os import socket import subprocess @@ -140,56 +139,7 @@ def framed() -> list[str]: return [sys.argv[0], *argv] -def spare() -> None: - """Keep a detached fresh interpreter until one adoption or owner EOF.""" - script = os.path.join(os.path.dirname(KERNEL), "albedo_spare.py") - child = subprocess.Popen( - [sys.executable, "-u", script, os.environ.get("ALBEDO_HOME", "")], - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=sys.stderr, - start_new_session=True, - close_fds=True, - ) - adopted = False - try: - assert child.stdout is not None and child.stdin is not None - ready = child.stdout.readline(65536) - if not ready or not isinstance(json.loads(ready).get("ready"), str): - raise RuntimeError("spare exited before imports completed") - sys.stdout.buffer.write(ready) - sys.stdout.buffer.flush() - line = sys.stdin.buffer.readline(1024 * 1024 + 1) - if not line: - return - spec = json.loads(line) - os.makedirs(spec["run_dir"], mode=0o700, exist_ok=True) - spec["environment"] = dict(os.environ) - child.stdin.write((json.dumps(spec) + "\n").encode()) - child.stdin.close() - deadline = time.monotonic() + START_TIMEOUT - while time.monotonic() < deadline: - connection = connect(spec["run_dir"]) - if connection is not None: - connection.close() - adopted = True - print(json.dumps({"adopted": True}), flush=True) - return - if child.poll() is not None: - raise RuntimeError("spare exited during adoption") - time.sleep(0.001) - raise RuntimeError("spare adoption timed out") - finally: - if not adopted: - with contextlib.suppress(ProcessLookupError): - child.kill() - child.wait() - - def main(argv: list[str]) -> None: - if argv[1:2] == ["spare"]: - spare() - return if argv[1:] == ["--frame"]: argv = framed() mode, run_dir = argv[1], argv[2] diff --git a/priv/python/albedo_spare.py b/priv/python/albedo_spare.py index 0486348aa..d166c1a4f 100644 --- a/priv/python/albedo_spare.py +++ b/priv/python/albedo_spare.py @@ -19,6 +19,9 @@ PREIMPORT = ( def main() -> None: + # The daemon starts this directly; a kernel never shares its session. + if os.getpgrp() != os.getpid(): + os.setsid() for name in PREIMPORT: importlib.import_module("albedo_plugins." + name) bundle = albedo_bundle.digest() @@ -49,6 +52,7 @@ def main() -> None: for key, value in environment.items() ): raise ValueError("invalid spare adoption environment") + os.makedirs(spec["run_dir"], mode=0o700, exist_ok=True) os.chdir(spec["cwd"]) os.environ.clear() os.environ.update(environment) diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index c586c6636..ff66578ce 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -359,7 +359,7 @@ completion. A read racing with the completion journal also retires the wake. (`{packet, 4}`) and passes frames to the port owner as a bridge port would, so no python process stays beside a local kernel. a fresh boot starts `albedo_kernel.py --run ` itself (token as its one - stdin line; no bridge interpreter, which cost ~45 ms CPU per boot on macOS). + stdin line; no bridge interpreter, which cost 36 ms CPU per boot on macOS). the kernel leaves the daemon's session, sends early stderr to `kernel.log`, and closes its stdout once its socket listens, which the relay waits for. the relay announces nothing, so the port owner hashes the bundle itself, the same way @@ -387,10 +387,12 @@ that. ## fresh spares `albedo_spare.py` imports the kernel and packaged default plugins without calling -plugin setup or starting kernel threads. A monitored bridge keeps its detached -process waiting on one private stdin adoption frame. Adoption installs the -session's cwd, sanitized launcher environment, module list, run directory, and -token, then starts the ordinary kernel. A spare is consumed once; it never sees +plugin setup or starting kernel threads. The custodian's erlang port starts it +directly (no helper interpreter); it leaves the daemon's session and waits on one +private stdin adoption frame. Adoption installs the session's cwd, sanitized +launcher environment (sent by the custodian), module list, run directory, and +token, then starts the ordinary kernel. The kernel closes its stdout once its +socket listens; the custodian confirms that socket before reporting adoption. A spare is consumed once; it never sees a second agent. Namespace restore still uses the existing state file. The native custodian monitors the runtime owner. Stopping an unused spare checks diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 772c80cd1..42a91bb1a 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -90,9 +90,11 @@ spare_start(Owner, Parent, Ref) -> case paths() of {error, Reason} -> Parent ! {Ref, {error, Reason}}; {ok, {Python, Bridge}} -> + %% No exit_status: with it, erts holds the eof until the process exits. + Script = filename:join(filename:dirname(Bridge), <<"albedo_spare.py">>), Port = open_port({spawn_executable, binary_to_list(Python)}, - [binary, {line, 1048576}, use_stdio, exit_status, hide, - {args, ["-u", binary_to_list(Bridge), "spare", os:getenv("ALBEDO_HOME", "")]}, {env, clean_environment()}]), + [binary, {line, 1048576}, use_stdio, eof, hide, + {args, ["-u", binary_to_list(Script), os:getenv("ALBEDO_HOME", "")]}, {env, clean_environment()}]), receive {Port, {data, {eol, Data}}} -> Ready = try json:decode(Data) catch _:_ -> #{} end, @@ -103,7 +105,7 @@ spare_start(Owner, Parent, Ref) -> spare_wait(Port, Watch, target_of(Ready)); _ -> port_close(Port), Parent ! {Ref, {error, {unavailable, <<"invalid spare readiness">>}}} end; - {Port, {exit_status, Status}} -> Parent ! {Ref, {error, {unavailable, detail(Status)}}}; + {Port, eof} -> port_close(Port), Parent ! {Ref, {error, {unavailable, <<"spare exited before imports completed">>}}}; {'DOWN', Watch, process, Owner, _} -> port_close(Port) after ?STARTUP_TIMEOUT -> port_close(Port), Parent ! {Ref, {error, {unavailable, <<"spare imports timed out">>}}} @@ -118,24 +120,31 @@ spare_wait(Port, Watch, Target) -> Error -> From ! {Ref, Error}, spare_wait(Port, Watch, Target) end; {spare_call, From, Ref, {adopt, Spec}} -> - port_command(Port, [json:encode(Spec), $\n]), - spare_adopting(Port, Watch, Target, From, Ref, false); + Environment = maps:from_list([{list_to_binary(Name), list_to_binary(Value)} + || {Name, Value} <- spare_environment()]), + port_command(Port, [json:encode(Spec#{environment => Environment}), $\n]), + spare_adopting(Port, Watch, Target, From, Ref, maps:get(run_dir, Spec)); stop -> spare_cleanup(Port, Target); {'DOWN', Watch, process, _, _} -> spare_cleanup(Port, Target); - {Port, {exit_status, _}} -> spare_cleanup(Port, Target); + {Port, eof} -> spare_cleanup(Port, Target); {'EXIT', Port, _} -> spare_cleanup(Port, Target) end. -spare_adopting(Port, Watch, Target, From, Ref, Adopted) -> +%% The adopted kernel closes its stdout once its socket listens; a spare that +%% died closes it too, so the socket decides. +spare_adopting(Port, Watch, Target, From, Ref, RunDir) -> receive - {Port, {data, {eol, Data}}} -> - Confirmed = try json:decode(Data) =:= #{<<"adopted">> => true} catch _:_ -> false end, - spare_adopting(Port, Watch, Target, From, Ref, Confirmed); - {Port, {exit_status, 0}} when Adopted -> From ! {Ref, {ok, nil}}; - {Port, {exit_status, _}} -> - case spare_cleanup(Port, Target) of - {ok, nil} -> From ! {Ref, {error, lost}}; - Error -> From ! {Ref, Error} + {Port, {data, _}} -> spare_adopting(Port, Watch, Target, From, Ref, RunDir); + {Port, eof} -> + Socket = <>, + case gen_tcp:connect({local, Socket}, 0, [local], 1000) of + {ok, Connection} -> + gen_tcp:close(Connection), catch port_close(Port), From ! {Ref, {ok, nil}}; + {error, _} -> + case spare_cleanup(Port, Target) of + {ok, nil} -> From ! {Ref, {error, lost}}; + Error -> From ! {Ref, Error} + end end; {'DOWN', Watch, process, _, _} -> spare_cleanup(Port, Target), From ! {Ref, {error, <<"spare owner stopped">>}} @@ -150,6 +159,12 @@ spare_cleanup(Port, Target) -> Error -> Error end. +%% What a spare adopts: the daemon's environment without its secrets. +spare_environment() -> + Blocked = [Name || {Name, false} <- clean_environment()], + [{Name, Value} || Entry <- os:getenv(), [Name, Value] <- [string:split(Entry, "=")], + not lists:member(Name, Blocked)]. + warm_launch(S, Launch) -> case maps:get(spare, S, none) of none -> launch(Launch); diff --git a/test/e2e/kernel_pool_test.py b/test/e2e/kernel_pool_test.py index aef2b7edb..cf65b461d 100644 --- a/test/e2e/kernel_pool_test.py +++ b/test/e2e/kernel_pool_test.py @@ -3,7 +3,6 @@ import ast import os from pathlib import Path -import subprocess import socket import time import unittest @@ -79,23 +78,13 @@ class KernelPoolTests(ModelCells, unittest.TestCase): self.inspection = Inspection(self.app) def spare_pids(self): - """Pids of ready spares: children of a waiting `albedo_bridge.py spare`. - - An adopted kernel keeps the spare script's name but no helper parent.""" - rows = [ - line.split(None, 2) - for line in subprocess.check_output( - ["ps", "-axo", "pid=,ppid=,command="], text=True - ).splitlines() - ] - script = str(self.bundle / "albedo_spare.py") - helper = str(self.bundle / "albedo_bridge.py") + " spare" - helpers = {int(pid) for pid, _, command in rows if helper in command} - return { - int(pid) - for pid, ppid, command in rows - if script in command and int(ppid) in helpers - } + """Pids of ready spares: the runtime's live spare custodians label + themselves with their process. An adopted kernel's custodian is gone.""" + listed = self.inspection.evaluate( + "io:write([Call(erlang, binary_to_integer, [Id]) || P <- Call(erlang, processes, []), " + "{albedo_spare, Id} <- [Call(proc_lib, get_label, [P])]])" + ) + return {int(pid) for pid in ast.literal_eval(listed or "[]") if alive(int(pid))} def ready(self, *, excluding=()): found = set() -- knotmirror 0.0.1 From 6e99286ff68b7ba958c2f7aa4dff4d8eac34ade6 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:39:25 -0400 Subject: [PATCH 36/72] Spare adoption: encode the environment as unicode, not latin-1 --- src/albedo/harness/extensions/python/albedo_python.erl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 42a91bb1a..874cd2b05 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -120,7 +120,7 @@ spare_wait(Port, Watch, Target) -> Error -> From ! {Ref, Error}, spare_wait(Port, Watch, Target) end; {spare_call, From, Ref, {adopt, Spec}} -> - Environment = maps:from_list([{list_to_binary(Name), list_to_binary(Value)} + Environment = maps:from_list([{unicode:characters_to_binary(Name), unicode:characters_to_binary(Value)} || {Name, Value} <- spare_environment()]), port_command(Port, [json:encode(Spec#{environment => Environment}), $\n]), spare_adopting(Port, Watch, Target, From, Ref, maps:get(run_dir, Spec)); -- knotmirror 0.0.1 From 9c2c6b5fe99c2223ddcc7e735018df371ba9331d Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:39:35 -0400 Subject: [PATCH 37/72] Fork spares from a preimported zygote on Linux --- priv/python/albedo_spare.py | 17 +- priv/python/albedo_zygote.py | 90 ++++++++ robot-docs/kernel.md | 14 +- .../extensions/python/albedo_python.erl | 194 ++++++++++++++---- test/e2e/kernel_pool_test.py | 32 ++- 5 files changed, 304 insertions(+), 43 deletions(-) create mode 100644 priv/python/albedo_zygote.py diff --git a/priv/python/albedo_spare.py b/priv/python/albedo_spare.py index d166c1a4f..b9c207364 100644 --- a/priv/python/albedo_spare.py +++ b/priv/python/albedo_spare.py @@ -18,13 +18,22 @@ PREIMPORT = ( ).split() -def main() -> None: +def preimport() -> str: + """Import the packaged plugins; returns the bundle digest they came from.""" + bundle = albedo_bundle.digest() + for name in PREIMPORT: + importlib.import_module("albedo_plugins." + name) + return bundle + + +def main(bundle: str | None = None) -> None: + """Serve one adoption over stdio. `bundle` is the digest a forked child's + already imported code came from; adoption refuses a bundle edited since.""" # The daemon starts this directly; a kernel never shares its session. if os.getpgrp() != os.getpid(): os.setsid() - for name in PREIMPORT: - importlib.import_module("albedo_plugins." + name) - bundle = albedo_bundle.digest() + if bundle is None: + bundle = preimport() print( json.dumps( { diff --git a/priv/python/albedo_zygote.py b/priv/python/albedo_zygote.py new file mode 100644 index 000000000..4a7add232 --- /dev/null +++ b/priv/python/albedo_zygote.py @@ -0,0 +1,90 @@ +"""Fork fresh spares from one interpreter that already imported the kernel (Linux). + + albedo_zygote.py + +Imports what a spare imports, freezes the heap so children share its pages, +prints `{"ready": bundle}`, then forks one child per connection to the unix +socket. The child serves albedo_spare's stdio protocol over that connection. +The zygote stays single-threaded, so forking is safe; it exits on stdin EOF +(its owner closed the port) or once the bundle changes under it. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import gc +import json +import os +import select +import signal +import socket +import sys +import traceback +from typing import Any + +import albedo_bundle +import albedo_cells +import albedo_proc +import albedo_spare + + +def child(connection: socket.socket, bundle: str) -> None: + os.dup2(connection.fileno(), 0) + os.dup2(connection.fileno(), 1) + connection.close() + signal.signal(signal.SIGCHLD, signal.SIG_DFL) + # Every child needs its own selector. Closing the inherited loop would + # unregister its self-pipe from the epoll set the zygote shares, so only + # this process's copies of its descriptors are dropped (macOS does not + # inherit a kqueue at all). + inherited: Any = albedo_cells.LOOP + for resource in (inherited._ssock, inherited._csock, inherited._selector._selector): + with contextlib.suppress(OSError, ValueError): + resource.close() + albedo_cells.LOOP = asyncio.new_event_loop() + asyncio.set_event_loop(albedo_cells.LOOP) + albedo_proc.reap_stopped_safely(albedo_cells.LOOP) + albedo_spare.main(bundle) + + +def main(path: str) -> None: + if os.getpgrp() != os.getpid(): + os.setsid() + bundle = albedo_spare.preimport() + listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + directory, name = os.path.split(path) + os.chdir(directory) + if os.path.exists(name): + os.unlink(name) + listener.bind(name) + os.chmod(name, 0o600) + listener.listen(64) + # Children are reaped by the kernel; each resets this before running code. + signal.signal(signal.SIGCHLD, signal.SIG_IGN) + gc.collect() + gc.freeze() + print(json.dumps({"ready": bundle, "pid": os.getpid()}), flush=True) + while True: + readable, _, _ = select.select([listener, 0], [], []) + if 0 in readable and not os.read(0, 4096): + return + if listener not in readable: + continue + connection, _ = listener.accept() + if albedo_bundle.digest() != bundle: + connection.close() + return + if os.fork() == 0: + listener.close() + try: + child(connection, bundle) + except BaseException: + traceback.print_exc() + finally: + os._exit(1) + connection.close() + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index ff66578ce..0687408b8 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -392,7 +392,19 @@ directly (no helper interpreter); it leaves the daemon's session and waits on on private stdin adoption frame. Adoption installs the session's cwd, sanitized launcher environment (sent by the custodian), module list, run directory, and token, then starts the ordinary kernel. The kernel closes its stdout once its -socket listens; the custodian confirms that socket before reporting adoption. A spare is consumed once; it never sees +socket listens; the custodian confirms that socket before reporting adoption. + +On Linux (or anywhere with `ALBEDO_KERNEL_ZYGOTE=1`; `0` turns it off) spares +are forked rather than started. `albedo_zygote.py` imports what a spare imports, +runs `gc.freeze()` so children share those pages, and forks one child per +connection to its unix socket; the child speaks the same ready/adoption lines +over that connection and gets its own event loop. The zygote stays +single-threaded, is held by a registered `albedo_zygote` process that serves +the first runtime owner and stops with it, and exits by itself when the bundle +digest changes at a fork, so the next spare starts a fresh one. A forked child +remembers the digest its code was imported from, so a bundle edit between fork +and adoption is refused like any stale spare. Any zygote failure falls back to +a directly started spare. A spare is consumed once; it never sees a second agent. Namespace restore still uses the existing state file. The native custodian monitors the runtime owner. Stopping an unused spare checks diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 874cd2b05..0601a5a18 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -87,73 +87,124 @@ spare_request(Pid, Request) -> spare_start(Owner, Parent, Ref) -> process_flag(trap_exit, true), Watch = monitor(process, Owner), - case paths() of + Ready = case zygote_path(Owner) of + {ok, Path} -> + case spare_ready(spare_connect(Path), Watch, Owner) of + {error, _} -> spare_ready(spare_port(), Watch, Owner); + Forked -> Forked + end; + none -> spare_ready(spare_port(), Watch, Owner) + end, + case Ready of + {ok, Chan, Fields = #{<<"pid">> := Pid}} -> + albedo_inspect:label(<<"albedo_spare">>, integer_to_binary(Pid)), + Parent ! {Ref, {ok, {spare, self()}}}, + spare_wait(Chan, Watch, target_of(Fields)); {error, Reason} -> Parent ! {Ref, {error, Reason}}; + owner_down -> ok + end. + +%% A spare's stdio is a port to a fresh interpreter, or a connection to a +%% child the zygote forked for it; both carry the same lines. +spare_port() -> + case paths() of + {error, Reason} -> {error, Reason}; {ok, {Python, Bridge}} -> - %% No exit_status: with it, erts holds the eof until the process exits. Script = filename:join(filename:dirname(Bridge), <<"albedo_spare.py">>), - Port = open_port({spawn_executable, binary_to_list(Python)}, + %% No exit_status: with it, erts holds the eof until the process exits. + {ok, open_port({spawn_executable, binary_to_list(Python)}, [binary, {line, 1048576}, use_stdio, eof, hide, - {args, ["-u", binary_to_list(Script), os:getenv("ALBEDO_HOME", "")]}, {env, clean_environment()}]), - receive - {Port, {data, {eol, Data}}} -> - Ready = try json:decode(Data) catch _:_ -> #{} end, - case Ready of - #{<<"ready">> := Bundle, <<"pid">> := Pid} when is_binary(Bundle), is_integer(Pid), Pid > 1 -> - albedo_inspect:label(<<"albedo_spare">>, integer_to_binary(Pid)), - Parent ! {Ref, {ok, {spare, self()}}}, - spare_wait(Port, Watch, target_of(Ready)); - _ -> port_close(Port), Parent ! {Ref, {error, {unavailable, <<"invalid spare readiness">>}}} - end; - {Port, eof} -> port_close(Port), Parent ! {Ref, {error, {unavailable, <<"spare exited before imports completed">>}}}; - {'DOWN', Watch, process, Owner, _} -> port_close(Port) - after ?STARTUP_TIMEOUT -> - port_close(Port), Parent ! {Ref, {error, {unavailable, <<"spare imports timed out">>}}} - end + {args, ["-u", binary_to_list(Script), os:getenv("ALBEDO_HOME", "")]}, + {env, clean_environment()}])} end. -spare_wait(Port, Watch, Target) -> +spare_connect(Path) -> + case gen_tcp:connect({local, Path}, 0, [local, binary, {packet, line}, {buffer, 1048576}, {active, true}], 1000) of + {ok, Socket} -> {ok, Socket}; + {error, Reason} -> {error, {unavailable, detail(Reason)}} + end. + +spare_ready({error, Reason}, _, _) -> {error, Reason}; +spare_ready({ok, Chan}, Watch, Owner) -> + Line = receive + {Chan, {data, {eol, Data}}} -> {line, Data}; + {tcp, Chan, Data} -> {line, string:trim(Data, trailing, "\n")}; + {Chan, eof} -> closed; + {tcp_closed, Chan} -> closed; + {'DOWN', Watch, process, Owner, _} -> owner_down + after ?STARTUP_TIMEOUT -> timeout + end, + case Line of + {line, Text} -> + case try json:decode(Text) catch _:_ -> #{} end of + Ready = #{<<"ready">> := Bundle, <<"pid">> := Pid} when is_binary(Bundle), is_integer(Pid), Pid > 1 -> + {ok, Chan, Ready}; + _ -> chan_close(Chan), {error, {unavailable, <<"invalid spare readiness">>}} + end; + closed -> chan_close(Chan), {error, {unavailable, <<"spare exited before imports completed">>}}; + timeout -> chan_close(Chan), {error, {unavailable, <<"spare imports timed out">>}}; + owner_down -> chan_close(Chan), owner_down + end. + +%% A gen_tcp socket is a port too, so only the driver tells them apart. +chan_send(Chan, Data) -> + case socket_chan(Chan) of + true -> gen_tcp:send(Chan, Data); + false -> port_command(Chan, Data) + end. + +chan_close(Chan) -> + case socket_chan(Chan) of + true -> gen_tcp:close(Chan); + false -> catch port_close(Chan) + end. + +socket_chan(Chan) -> erlang:port_info(Chan, name) =:= {name, "tcp_inet"}. + +spare_wait(Chan, Watch, Target) -> receive {spare_call, From, Ref, stop} -> - case spare_cleanup(Port, Target) of + case spare_cleanup(Chan, Target) of {ok, nil} -> From ! {Ref, {ok, nil}}; - Error -> From ! {Ref, Error}, spare_wait(Port, Watch, Target) + Error -> From ! {Ref, Error}, spare_wait(Chan, Watch, Target) end; {spare_call, From, Ref, {adopt, Spec}} -> Environment = maps:from_list([{unicode:characters_to_binary(Name), unicode:characters_to_binary(Value)} || {Name, Value} <- spare_environment()]), - port_command(Port, [json:encode(Spec#{environment => Environment}), $\n]), - spare_adopting(Port, Watch, Target, From, Ref, maps:get(run_dir, Spec)); - stop -> spare_cleanup(Port, Target); - {'DOWN', Watch, process, _, _} -> spare_cleanup(Port, Target); - {Port, eof} -> spare_cleanup(Port, Target); - {'EXIT', Port, _} -> spare_cleanup(Port, Target) + chan_send(Chan, [json:encode(Spec#{environment => Environment}), $\n]), + spare_adopting(Chan, Watch, Target, From, Ref, maps:get(run_dir, Spec)); + stop -> spare_cleanup(Chan, Target); + {'DOWN', Watch, process, _, _} -> spare_cleanup(Chan, Target); + {Chan, eof} -> spare_cleanup(Chan, Target); + {tcp_closed, Chan} -> spare_cleanup(Chan, Target); + {'EXIT', Chan, _} -> spare_cleanup(Chan, Target) end. %% The adopted kernel closes its stdout once its socket listens; a spare that %% died closes it too, so the socket decides. -spare_adopting(Port, Watch, Target, From, Ref, RunDir) -> +spare_adopting(Chan, Watch, Target, From, Ref, RunDir) -> receive - {Port, {data, _}} -> spare_adopting(Port, Watch, Target, From, Ref, RunDir); - {Port, eof} -> + {Chan, {data, _}} -> spare_adopting(Chan, Watch, Target, From, Ref, RunDir); + {tcp, Chan, _} -> spare_adopting(Chan, Watch, Target, From, Ref, RunDir); + Closed when Closed =:= {Chan, eof}; Closed =:= {tcp_closed, Chan} -> Socket = <>, case gen_tcp:connect({local, Socket}, 0, [local], 1000) of {ok, Connection} -> - gen_tcp:close(Connection), catch port_close(Port), From ! {Ref, {ok, nil}}; + gen_tcp:close(Connection), chan_close(Chan), From ! {Ref, {ok, nil}}; {error, _} -> - case spare_cleanup(Port, Target) of + case spare_cleanup(Chan, Target) of {ok, nil} -> From ! {Ref, {error, lost}}; Error -> From ! {Ref, Error} end end; {'DOWN', Watch, process, _, _} -> - spare_cleanup(Port, Target), From ! {Ref, {error, <<"spare owner stopped">>}} + spare_cleanup(Chan, Target), From ! {Ref, {error, <<"spare owner stopped">>}} after ?STARTUP_TIMEOUT -> - spare_cleanup(Port, Target), From ! {Ref, {error, <<"spare adoption timed out">>}} + spare_cleanup(Chan, Target), From ! {Ref, {error, <<"spare adoption timed out">>}} end. -spare_cleanup(Port, Target) -> - catch port_close(Port), +spare_cleanup(Chan, Target) -> + chan_close(Chan), case verdict(supervise(#{remote => none}, [target_spec(<<"spare">>, Target)], ?TERM_MS, ?KILL_MS)) of ok -> {ok, nil}; Error -> Error @@ -165,6 +216,75 @@ spare_environment() -> [{Name, Value} || Entry <- os:getenv(), [Name, Value] <- [string:split(Entry, "=")], not lists:member(Name, Blocked)]. +%% The zygote: one interpreter per daemon that imported what a spare imports +%% and forks a child per spare (albedo_zygote.py). Linux only unless +%% ALBEDO_KERNEL_ZYGOTE=1; 0 turns it off. It serves the first runtime owner +%% that asks, stops with that owner, and exits on its own once the bundle +%% changes, so the next spare starts a fresh one. None means "use a port". +zygote_path(Owner) -> + Enabled = case os:getenv("ALBEDO_KERNEL_ZYGOTE") of + "0" -> false; + "1" -> true; + _ -> os:type() =:= {unix, linux} + end, + case Enabled of + false -> none; + true -> + Holder = case whereis(albedo_zygote) of + undefined -> spawn(fun() -> zygote_start(Owner) end); + Pid -> Pid + end, + Alias = alias(), Mon = monitor(process, Holder), + Holder ! {zygote_path, Alias, Mon, Owner}, + Result = receive + {Mon, Reply} -> Reply; + {'DOWN', Mon, process, Holder, _} -> none + after ?STARTUP_TIMEOUT -> none + end, + unalias(Alias), demonitor(Mon, [flush]), Result + end. + +zygote_start(Owner) -> + try register(albedo_zygote, self()) of + true -> + albedo_inspect:label(<<"albedo_zygote">>, <<>>), + Watch = monitor(process, Owner), + Dir = filename:join(os:getenv("TMPDIR", "/tmp"), + "albedo-z-" ++ os:getpid() ++ "-" ++ integer_to_list(erlang:unique_integer([positive]))), + Path = filename:join(Dir, "s"), + case {file:make_dir(Dir), paths()} of + {ok, {ok, {Python, Bridge}}} -> + ok = file:change_mode(Dir, 8#700), + Script = filename:join(filename:dirname(Bridge), <<"albedo_zygote.py">>), + Port = open_port({spawn_executable, binary_to_list(Python)}, + [binary, {line, 1048576}, use_stdio, eof, hide, + {args, ["-u", binary_to_list(Script), Path]}, {env, clean_environment()}]), + Ready = receive + {Port, {data, {eol, _}}} -> ok; + {Port, eof} -> closed + after ?STARTUP_TIMEOUT -> timeout + end, + case Ready of + ok -> zygote_loop(Owner, Watch, Port, list_to_binary(Path)); + _ -> ok + end, + catch port_close(Port); + _ -> ok + end, + file:del_dir_r(Dir) + catch error:badarg -> ok %% another holder registered first; callers see DOWN + end. + +zygote_loop(Owner, Watch, Port, Path) -> + receive + {zygote_path, From, Ref, Asker} -> + From ! {Ref, case Asker of Owner -> {ok, Path}; _ -> none end}, + zygote_loop(Owner, Watch, Port, Path); + {'DOWN', Watch, process, Owner, _} -> ok; + {Port, eof} -> ok; + {Port, {data, _}} -> zygote_loop(Owner, Watch, Port, Path) + end. + warm_launch(S, Launch) -> case maps:get(spare, S, none) of none -> launch(Launch); diff --git a/test/e2e/kernel_pool_test.py b/test/e2e/kernel_pool_test.py index cf65b461d..244b3e477 100644 --- a/test/e2e/kernel_pool_test.py +++ b/test/e2e/kernel_pool_test.py @@ -4,6 +4,7 @@ import ast import os from pathlib import Path import socket +import subprocess import time import unittest @@ -34,7 +35,7 @@ exec env -i HOME={home} PATH="$path" SHELL={old}/loginsh /bin/sh -c "$*" class KernelPoolTests(ModelCells, unittest.TestCase): bundle: Path - def boot(self, *, spares=1, release=False, ssh=False): + def boot(self, *, spares=1, release=False, ssh=False, zygote=None): self.cells = [] def script(request): @@ -50,6 +51,8 @@ class KernelPoolTests(ModelCells, unittest.TestCase): ALBEDO_KERNEL_SPARES=str(spares), ALBEDO_KERNEL_RELEASE_WITH_SPARE="1" if release else "0", ) + if zygote is not None: + app.env["ALBEDO_KERNEL_ZYGOTE"] = zygote if ssh: # On the daemon's PATH, so a kernel's environment is unchanged # by connecting and only the connection itself can keep it. @@ -277,6 +280,33 @@ class KernelPoolTests(ModelCells, unittest.TestCase): self.value("await job\n42") wait_until(lambda: not alive(pid), 15, "a finished job pinned its kernel") + def zygote_of(self, pid): + """The zygote that forked this spare, or None.""" + parent = subprocess.check_output( + ["ps", "-o", "ppid=", "-p", str(pid)], text=True + ).strip() + command = subprocess.run( + ["ps", "-o", "command=", "-p", parent], capture_output=True, text=True + ).stdout + return int(parent) if "albedo_zygote.py" in command else None + + def test_zygote_forks_spares_and_is_recycled_after_a_bundle_edit(self): + self.boot(zygote="1") + [spare] = self.ready() + zygote = self.zygote_of(spare) + self.assertIsNotNone(zygote, "the spare was not forked by a zygote") + self.assertEqual(self.value("import os\nos.getpid()"), spare) + with (self.bundle / "albedo_bundle.py").open("a") as source: + source.write(MARKER) + # A new session's kernel must run the edited code, not the zygote's. + self.session = self.app.session() + self.assertEqual( + self.value("import albedo_bundle\nalbedo_bundle.MARKER"), "new bundle" + ) + wait_until( + lambda: not alive(zygote), 15, "the stale zygote outlived its bundle" + ) + def test_an_empty_pool_uses_a_cold_kernel(self): self.boot(spares=0) pid = self.value("import os\nos.getpid()") -- knotmirror 0.0.1 From fa962f6005529b5a9ef876ae910ac69ee758680a Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:33:28 -0400 Subject: [PATCH 38/72] Keep a released session's context snapshot; opt-in daemon env for the e2e suite; test the request across a release --- src/albedo/daemon/session.gleam | 1 - test/e2e/harness.py | 6 ++++ test/e2e/release_request_test.py | 54 ++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 test/e2e/release_request_test.py diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 840f157be..89f09f31d 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -2276,7 +2276,6 @@ fn handle( kernel: None, released: Some(kernel), releasing: None, - context: session_state.unprepared(), ) |> session_state.emit(view.note( "daemon", diff --git a/test/e2e/harness.py b/test/e2e/harness.py index 174b0ea29..a72e14978 100644 --- a/test/e2e/harness.py +++ b/test/e2e/harness.py @@ -401,6 +401,12 @@ class Daemon: self.env["ALBEDO_DAEMON"] = _executable if "ALBEDO_TEST_CLI" in os.environ: self.env["ALBEDO_TEST_CLI"] = os.environ["ALBEDO_TEST_CLI"] + # Opt-in: NAME=VALUE pairs, space separated, for every test daemon, so + # the whole suite can run under a non-default daemon setting. A test's + # own `prepare` still overrides them. + for pair in os.environ.get("ALBEDO_E2E_DAEMON_ENV", "").split(): + name, _, value = pair.partition("=") + self.env[name] = value # A (soft, hard) open-file limit the CLI, and so the daemon it boots, # starts under; None passes on the test process's own. self.open_files = None diff --git a/test/e2e/release_request_test.py b/test/e2e/release_request_test.py new file mode 100644 index 000000000..89e417b0d --- /dev/null +++ b/test/e2e/release_request_test.py @@ -0,0 +1,54 @@ +"""A released kernel does not change the provider request, so the prompt cache survives. + +Every request carries the tools and system prompt. When any of it is computed +from the live kernel, a release followed by a restore changes the bytes and the +provider reads no cache on every resumed turn. Only real requests recorded by +the fake provider across a real release show it. +""" + +import json +import unittest + +from harness import Albedo, Provider, exclusive, latest_user, python, text, wait_until + + +@exclusive +class ReleaseRequestTests(unittest.TestCase): + def test_the_request_after_a_release_extends_the_one_before_it(self): + def script(request): + if request["input"][-1].get("role") == "user": + if latest_user(request).split("")[0] == "define": + return python("answer = 42") + return text("ok") + + provider = Provider(script) + self.addCleanup(provider.close) + + def prepare(app): + app.env.update( + ALBEDO_IDLE_SECONDS="1", + ALBEDO_KERNEL_SPARES="2", + ALBEDO_KERNEL_RELEASE_WITH_SPARE="1", + ) + + with Albedo(provider, protocol="responses", prepare=prepare) as app: + session = app.session() + app.prompt(session, "define").close() + app.idle(session) + before = len(provider.requests) + state = app.home / "kernels" / f"{session}.state" + wait_until(state.exists, 20, "the resting kernel was not released") + app.prompt(session, "again").close() + app.idle(session) + requests = [item["request"] for item in provider.requests] + last_before, first_after = requests[before - 1], requests[before] + self.assertEqual(first_after["tools"], last_before["tools"]) + self.assertEqual( + first_after.get("instructions"), last_before.get("instructions") + ) + prefix = last_before["input"] + self.assertEqual( + json.dumps(first_after["input"][: len(prefix)], sort_keys=True), + json.dumps(prefix, sort_keys=True), + "history before the release changed", + ) -- knotmirror 0.0.1 From 36626106c85726636db8d5e60f9d6ca62fb6f4c2 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:52:05 -0400 Subject: [PATCH 39/72] Tests that observe a resident kernel run with release off; scripted prompts ignore a trailing system note --- test/e2e/agents_swarm_test.py | 2 ++ test/e2e/agents_test.py | 17 +++++++++-------- test/e2e/artifacts_test.py | 4 ++-- test/e2e/daemon_test.py | 2 ++ test/e2e/extensions_test.py | 4 ++++ test/e2e/harness.py | 15 +++++++++++++++ test/e2e/idle_reap_test.py | 3 +++ test/e2e/kernel_detach_test.py | 5 +++++ test/e2e/kernel_reset_test.py | 2 ++ test/e2e/kernel_state_test.py | 2 ++ test/e2e/kernel_stop_test.py | 2 ++ test/e2e/kernel_upgrade_test.py | 3 +++ test/e2e/mcp_test.py | 2 ++ test/e2e/operations_retention_test.py | 2 ++ test/e2e/operations_test.py | 3 +++ test/e2e/python_test.py | 3 +++ test/e2e/remote_kernels_test.py | 4 ++++ test/e2e/run.py | 4 ++++ test/e2e/session_actor_test.py | 2 ++ test/e2e/session_configure_test.py | 2 ++ test/e2e/session_status_test.py | 2 ++ test/e2e/traces_test.py | 3 +++ test/e2e/warm_test.py | 2 ++ 23 files changed, 80 insertions(+), 10 deletions(-) diff --git a/test/e2e/agents_swarm_test.py b/test/e2e/agents_swarm_test.py index f25f0caea..809265f91 100644 --- a/test/e2e/agents_swarm_test.py +++ b/test/e2e/agents_swarm_test.py @@ -9,6 +9,7 @@ import unittest import urllib.error from harness import ( + resident_kernel, Albedo, Provider, exclusive, @@ -99,6 +100,7 @@ class AgentsSwarmTests(unittest.TestCase): provider.close() @exclusive + @resident_kernel def test_closed_child_does_not_start_when_its_kernel_finishes_booting(self): def script(request): if request["messages"][-1].get("role") != "user": diff --git a/test/e2e/agents_test.py b/test/e2e/agents_test.py index 0e3a4b286..12502909d 100644 --- a/test/e2e/agents_test.py +++ b/test/e2e/agents_test.py @@ -19,6 +19,7 @@ from harness import ( Reply, exclusive, latest_user, + prompt_text, operation_id, python, text, @@ -203,7 +204,7 @@ class AgentsTests(unittest.TestCase): def dispatch(request): if ( request["messages"][-1].get("role") == "user" - and latest_user(request) == marker + and prompt_text(request) == marker ): return python( "import json\n" @@ -237,7 +238,7 @@ class AgentsTests(unittest.TestCase): def dispatch(request): messages = request.get("messages", request.get("input", [])) - if messages[-1].get("role") == "user" and latest_user(request) == marker: + if messages[-1].get("role") == "user" and prompt_text(request) == marker: return python(source) return answer(request) @@ -354,7 +355,7 @@ class AgentsTests(unittest.TestCase): def dispatch(request): if ( - latest_user(request) == marker + prompt_text(request) == marker and request["messages"][-1]["role"] == "user" ): entered.set() @@ -416,7 +417,7 @@ class AgentsTests(unittest.TestCase): def dispatch(request): if ( - latest_user(request) == marker + prompt_text(request) == marker and request["messages"][-1]["role"] == "user" ): return python( @@ -458,7 +459,7 @@ class AgentsTests(unittest.TestCase): marker = "receive an opaque response before the switch" def dispatch(request): - if request["model"] == old_model and latest_user(request) == marker: + if request["model"] == old_model and prompt_text(request) == marker: entered.set() if not release.wait(timeout=30): raise AssertionError("test never released opaque response") @@ -670,7 +671,7 @@ for target, model in [({child!r}, 'no-such-switch-model'), def progress(request): if ( request["messages"][-1].get("role") == "user" - and latest_user(request) == marker + and prompt_text(request) == marker ): return python('await agents.progress("tracing delivery")') return answer(request) @@ -1345,7 +1346,7 @@ for target, model in [({child!r}, 'no-such-switch-model'), def dispatch(request): if ( request["messages"][-1].get("role") == "user" - and latest_user(request) == marker + and prompt_text(request) == marker ): return python( "try:\n" @@ -1382,7 +1383,7 @@ for target, model in [({child!r}, 'no-such-switch-model'), def dispatch(request): if ( request["messages"][-1].get("role") == "user" - and latest_user(request) == marker + and prompt_text(request) == marker ): return python( "peer = await agents.start(" diff --git a/test/e2e/artifacts_test.py b/test/e2e/artifacts_test.py index 6b34eff00..1195fa4f6 100644 --- a/test/e2e/artifacts_test.py +++ b/test/e2e/artifacts_test.py @@ -10,7 +10,7 @@ import time import unittest import urllib.error -from harness import Albedo, Provider, latest_user, python, text +from harness import Albedo, Provider, prompt_text, python, text PAGE = ( "timeline" @@ -44,7 +44,7 @@ class ArtifactsTest(unittest.TestCase): def script(request): last = request["messages"][-1] - prompt = latest_user(request) + prompt = prompt_text(request) if last.get("role") == "user" and prompt in CELLS: prelude = f"import json\nPAGE = {PAGE!r}\nID = {self.artifact!r}\n" return python(prelude + CELLS[prompt]) diff --git a/test/e2e/daemon_test.py b/test/e2e/daemon_test.py index 5589e4b2e..1200569d0 100644 --- a/test/e2e/daemon_test.py +++ b/test/e2e/daemon_test.py @@ -21,6 +21,7 @@ import urllib.parse from inspect_support import Inspection from harness import ( + resident_kernel, Albedo, Provider, Reply, @@ -567,6 +568,7 @@ class DaemonTest(unittest.TestCase): # exclusive: holds the daemon's store locked while it shuts down @exclusive + @resident_kernel def test_a_shutdown_stopped_by_a_stalled_step_still_ends_by_its_deadline(self): # A drain step that cannot finish (here a session that cannot reach the # store) once left the daemon serving forever: the stop request's diff --git a/test/e2e/extensions_test.py b/test/e2e/extensions_test.py index ddcff73aa..e5ad84ab4 100644 --- a/test/e2e/extensions_test.py +++ b/test/e2e/extensions_test.py @@ -9,6 +9,7 @@ import unittest import urllib.error import urllib.parse +from harness import resident_kernel from harness import Albedo, Provider, exclusive, operation_id, python, text @@ -644,6 +645,7 @@ class ExtensionTests(unittest.TestCase): # exclusive: restarts the daemon @exclusive + @resident_kernel def test_reload_pins_system_prompt_until_compaction(self): self.turn("first turn") catalog_route = f"/sessions/{self.sid}/catalog" @@ -868,6 +870,7 @@ class ExtensionTests(unittest.TestCase): ) self.assertIn("older conversation summary", json.dumps(requests[-1]["input"])) + @resident_kernel def test_failed_snapshot_retains_kernel_and_saved_choice_for_retry(self): self.turn("hot probe before reload", expected=2) before = self.snapshot()["kernel"]["instance_id"] @@ -890,6 +893,7 @@ class ExtensionTests(unittest.TestCase): self.assertNotEqual(self.snapshot()["kernel"]["instance_id"], before) self.assertNotIn("/demo", [entry["slash_name"] for entry in self.commands()]) + @resident_kernel def test_compaction_applies_saved_strategy_and_keeps_matching_kernel(self): self.turn("first turn") self.turn("second turn") diff --git a/test/e2e/harness.py b/test/e2e/harness.py index a72e14978..6f6f6d060 100644 --- a/test/e2e/harness.py +++ b/test/e2e/harness.py @@ -160,6 +160,14 @@ def exclusive(target): return target +def resident_kernel(target): + """Like `exclusive`, and the daemon keeps every kernel resident: the test + observes a kernel's pid, link row or reattachment, which a released kernel + has none of. A test that only reads a kernel's results does not need this.""" + target._e2e_resident = True + return exclusive(target) + + _providers = {} _provider_ids = itertools.count(1) _server = None @@ -692,6 +700,13 @@ def latest_user(request): ) +def prompt_text(request): + """The last user's text without a trailing ``: a daemon note + (a restore after a kernel release, a switch) rides on the user turn, and a + scripted provider keyed on the prompt must still match it.""" + return latest_user(request).split("")[0] + + def wait_until(condition, seconds, message): deadline = time.monotonic() + seconds while time.monotonic() < deadline: diff --git a/test/e2e/idle_reap_test.py b/test/e2e/idle_reap_test.py index 26a3dae48..62770475e 100644 --- a/test/e2e/idle_reap_test.py +++ b/test/e2e/idle_reap_test.py @@ -7,6 +7,7 @@ import time import unittest from pathlib import Path +from harness import resident_kernel from harness import alive, latest_user from harness import Albedo, Provider, exclusive, python, text from stream_support import StreamProbe @@ -87,6 +88,7 @@ class IdleReapTests(unittest.TestCase): self.app.prompt(session, prompt).close() self.app.idle(session) + @resident_kernel def test_idle_kernel_reaps_and_restores_variables_with_notices(self): app = self.app existing = set(kernels(app.home)) @@ -148,6 +150,7 @@ class IdleReapTests(unittest.TestCase): outputs, ) + @resident_kernel def test_reattached_kernel_without_a_loaded_session_is_released(self): app = self.app app.restart(prepare=lambda a: a.env.update(ALBEDO_IDLE_SECONDS="600")) diff --git a/test/e2e/kernel_detach_test.py b/test/e2e/kernel_detach_test.py index 9013b72f6..7e424a1cb 100644 --- a/test/e2e/kernel_detach_test.py +++ b/test/e2e/kernel_detach_test.py @@ -17,6 +17,7 @@ import time import unittest import harness +from harness import resident_kernel from harness import alive from harness import Albedo, Provider, exclusive, python, text @@ -73,6 +74,7 @@ class KernelDetachTests(unittest.TestCase): ] return results[-1] + @resident_kernel def test_variables_survive_graceful_and_crash_restarts(self): first = self.cell("import os\nsurvivor = 41\nos.getpid()") self.app.restart() @@ -103,6 +105,7 @@ class KernelDetachTests(unittest.TestCase): self.assertEqual(survivor, 42) self.assertNotEqual(pid, kernel) + @resident_kernel def test_a_daemon_booted_on_a_copy_of_the_database_leaves_its_kernels_alone(self): """The copy carries this daemon's kernel records (socket, token, process group); its daemon forgets them instead of attaching.""" @@ -125,6 +128,7 @@ class KernelDetachTests(unittest.TestCase): after = self.cell("survivor += 1\n(survivor, os.getpid())") self.assertEqual(after["value"], f"(42, {first['value']})") + @resident_kernel def test_a_connection_dropped_mid_cell_still_delivers_the_result(self): first = self.cell("import os\nos.getpid()") self.assertEqual(bridges(self.app.home), [], "a local kernel kept a bridge") @@ -243,6 +247,7 @@ class KernelDetachTests(unittest.TestCase): self.assertIn("The python kernel restarted", prompt) self.assertIn(f"Jobs stopped by the restart: {handle} (sleep 300)", prompt) + @resident_kernel def test_a_restart_tells_the_model_when_nothing_was_running(self): self.cell("survivor = 1") self.app.restart() diff --git a/test/e2e/kernel_reset_test.py b/test/e2e/kernel_reset_test.py index 3b7db3421..e092672bd 100644 --- a/test/e2e/kernel_reset_test.py +++ b/test/e2e/kernel_reset_test.py @@ -6,6 +6,7 @@ import json import urllib.error import unittest +from harness import resident_kernel from harness import latest_user from harness import Albedo, Provider, exclusive, python, text @@ -42,6 +43,7 @@ class KernelResetTests(unittest.TestCase): self.app.idle(session) return latest_user(self.provider.requests[-1]["request"]) + @resident_kernel def test_kernel_crash_emits_one_shot_reset_notice_and_daemon_crash_none(self): app = self.app session = app.session() diff --git a/test/e2e/kernel_state_test.py b/test/e2e/kernel_state_test.py index 0ba81ba80..b2cbd8705 100644 --- a/test/e2e/kernel_state_test.py +++ b/test/e2e/kernel_state_test.py @@ -7,6 +7,7 @@ restore path lives in the kernel and the notice in the daemon. import unittest +from harness import resident_kernel from harness import latest_user, wait_until from harness import Albedo, Provider, exclusive, python, text @@ -83,6 +84,7 @@ class KernelStateTests(unittest.TestCase): for item in self.provider.requests[-1]["request"]["input"] ) + @resident_kernel def test_helpers_classes_imports_and_failed_cells_survive_a_restart(self): session = self.app.session() self.turn(session, "define") diff --git a/test/e2e/kernel_stop_test.py b/test/e2e/kernel_stop_test.py index add199d29..6d7baff09 100644 --- a/test/e2e/kernel_stop_test.py +++ b/test/e2e/kernel_stop_test.py @@ -3,12 +3,14 @@ import json import unittest +from harness import resident_kernel from harness import ROOT, Albedo, Provider, exclusive, python, text from inspect_support import Inspection @exclusive class KernelStopTests(unittest.TestCase): + @resident_kernel def test_runtime_serves_reads_and_other_boots_while_stopping(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" diff --git a/test/e2e/kernel_upgrade_test.py b/test/e2e/kernel_upgrade_test.py index 9a6b543fe..ef95e596b 100644 --- a/test/e2e/kernel_upgrade_test.py +++ b/test/e2e/kernel_upgrade_test.py @@ -18,6 +18,7 @@ import unittest import urllib.error import harness +from harness import resident_kernel from harness import alive from harness import Albedo, Provider, exclusive, python, text from kernel_support import MARKER, ModelCells, editable_daemon @@ -95,6 +96,7 @@ class KernelUpgradeTests(Swaps): "import albedo_bundle, os\n(survivor, getattr(albedo_bundle, 'MARKER', None), os.getpid())" ) + @resident_kernel def test_restart_onto_a_new_bundle_swaps_the_kernel_and_keeps_variables(self): first, _ = self.cell("import os\nsurvivor = 41\nos.getpid()") self.edit_bundle() @@ -178,6 +180,7 @@ class ModuleSkewTests(Swaps): def probe(self): return self.cell("import os\n(survivor, 'skills' in globals(), os.getpid())") + @resident_kernel def test_a_changed_module_set_swaps_the_kernel_and_keeps_variables(self): first, _ = self.cell( "import os\nsurvivor = 41\n('skills' in globals(), os.getpid())" diff --git a/test/e2e/mcp_test.py b/test/e2e/mcp_test.py index 22e852736..0ff05a968 100644 --- a/test/e2e/mcp_test.py +++ b/test/e2e/mcp_test.py @@ -11,6 +11,7 @@ import time import unittest from pathlib import Path +from harness import resident_kernel from harness import Albedo, Provider, exclusive, operation_id, Reply, text SERVER = Path(__file__).with_name("fake_mcp_server.py") @@ -140,6 +141,7 @@ class McpTests(unittest.TestCase): self.app.idle(session, timeout=60) return [entry["request"] for entry in self.provider.requests[before:]] + @resident_kernel def test_cold_command_and_recorded_recovery_do_not_block_another_session(self): other = self.app.session() for session, enabled in ((self.session, True), (other, False)): diff --git a/test/e2e/operations_retention_test.py b/test/e2e/operations_retention_test.py index 9464d5e3c..ea4cbb097 100644 --- a/test/e2e/operations_retention_test.py +++ b/test/e2e/operations_retention_test.py @@ -7,6 +7,7 @@ import threading import time import urllib.error +from harness import resident_kernel from harness import Albedo, Provider, exclusive, operation_id, text from operations_test import InputScenario @@ -232,6 +233,7 @@ class OperationRetentionTests(InputScenario): database.execute("SELECT count(*) FROM pending_inputs").fetchone()[0], 0 ) + @resident_kernel def test_continuation_marker_survives_receipt_pruning_and_restart(self): session = self.app.session() self.app.prompt(session, "start").close() diff --git a/test/e2e/operations_test.py b/test/e2e/operations_test.py index c8e3c38f6..060bd151e 100644 --- a/test/e2e/operations_test.py +++ b/test/e2e/operations_test.py @@ -14,6 +14,7 @@ import time import unittest import urllib.error +from harness import resident_kernel from harness import Albedo, Provider, exclusive, operation_id, python, text from image_limits_test import png @@ -575,6 +576,7 @@ class PreparingOperationsTests(InputScenario): self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) + @resident_kernel def test_kernel_preparation_admission_survives_restart(self): session = self.app.session() input_id = operation_id() @@ -596,6 +598,7 @@ class PreparingOperationsTests(InputScenario): [entry["input_id"] for entry in self.users(session)], [input_id] ) + @resident_kernel def test_full_kernel_opening_queue_delivers_once_and_replays_rejection(self): session = self.app.session() inputs = [ diff --git a/test/e2e/python_test.py b/test/e2e/python_test.py index 0ed1d33cd..86d0beab7 100644 --- a/test/e2e/python_test.py +++ b/test/e2e/python_test.py @@ -3,6 +3,7 @@ import json import unittest +from harness import resident_kernel from harness import Albedo, Provider, Reply, python, text @@ -44,6 +45,7 @@ class PythonToolsTests(unittest.TestCase): def execute(self, code): return self.run_cell(code, self.app.session())["output"] + @resident_kernel def test_host_replies_preserve_escaped_call_ids_and_argument_errors(self): output = self.execute( "kernel = sys.modules['__main__']\n" @@ -64,6 +66,7 @@ class PythonToolsTests(unittest.TestCase): }, ) + @resident_kernel def test_deleting_shadowed_tools_recovers_the_original_bindings(self): (self.app.workspace / "note.txt").write_text("recovered\n") session = self.app.session() diff --git a/test/e2e/remote_kernels_test.py b/test/e2e/remote_kernels_test.py index 5a8908afb..b3ee0f65b 100644 --- a/test/e2e/remote_kernels_test.py +++ b/test/e2e/remote_kernels_test.py @@ -22,6 +22,7 @@ import urllib.error import urllib.parse from pathlib import Path +from harness import resident_kernel from harness import Albedo, Provider, exclusive, operation_id, python, text FAKE_SSH = """#!/bin/sh @@ -591,6 +592,7 @@ print('live spill pages, disk failures, atomic saves, and pruning verified') self.assertEqual(result["status"], "ok", result) self.assertIn("staging", seen) + @resident_kernel def test_a_bridge_killed_mid_cell_reattaches_over_ssh(self): session = self.create(f"fakehost:{self.project}")["id"] first = self.cell(session, "import os\nos.getpid()") @@ -617,6 +619,7 @@ print('live spill pages, disk failures, atomic saves, and pruning verified') ] self.assertGreaterEqual(len(bridges), 2, "the reattach did not go over ssh") + @resident_kernel def test_a_remote_kernel_outlives_a_daemon_restart(self): session = self.create(f"fakehost:{self.project}")["id"] first = self.cell(session, "import os\nsurvivor = 41\nos.getpid()") @@ -624,6 +627,7 @@ print('live spill pages, disk failures, atomic saves, and pruning verified') after = self.cell(session, "survivor += 1\n(survivor, os.getpid())") self.assertEqual(after["value"], f"(42, {first['value']})") + @resident_kernel def test_a_kernel_survives_ssh_being_down_while_the_daemon_restarts(self): session = self.create(f"fakehost:{self.project}")["id"] first = self.cell(session, "import os\nsurvivor = 41\nos.getpid()") diff --git a/test/e2e/run.py b/test/e2e/run.py index bae9389ab..b1e2e8aca 100644 --- a/test/e2e/run.py +++ b/test/e2e/run.py @@ -63,6 +63,10 @@ def execute(test, daemon): def execute_alone(test): daemon = harness.Daemon("exclusive") + if marked(test, "_e2e_resident"): + daemon.env.update( + ALBEDO_KERNEL_SPARES="0", ALBEDO_KERNEL_RELEASE_WITH_SPARE="0" + ) try: return execute(test, daemon) finally: diff --git a/test/e2e/session_actor_test.py b/test/e2e/session_actor_test.py index 77a287d53..370c6f2f5 100644 --- a/test/e2e/session_actor_test.py +++ b/test/e2e/session_actor_test.py @@ -6,6 +6,7 @@ import threading import unittest from harness import ( + resident_kernel, ROOT, Albedo, Provider, @@ -61,6 +62,7 @@ class SessionActorStallTests(unittest.TestCase): storage.call("release") self.assertTrue(self.wait_file(marker).startswith("{ok,")) + @resident_kernel def test_release_does_not_wait_for_runtime_and_reset_precedes_next_open(self): def script(request): if request["messages"][-1].get("role") == "tool": diff --git a/test/e2e/session_configure_test.py b/test/e2e/session_configure_test.py index ae66448f9..d3c646b02 100644 --- a/test/e2e/session_configure_test.py +++ b/test/e2e/session_configure_test.py @@ -6,6 +6,7 @@ from pathlib import Path import threading import unittest +from harness import resident_kernel from harness import Albedo, Provider, ROOT, exclusive, release_fifo, text, wait_until from inspect_support import Inspection from kernel_support import editable_daemon @@ -204,6 +205,7 @@ class SessionConfigureTest(unittest.TestCase): release.set() self.app.idle(self.session) + @resident_kernel def test_commands_reject_changes_during_kernel_boot(self): self.app.prompt(self.session, "wait for the kernel").close() wait_until( diff --git a/test/e2e/session_status_test.py b/test/e2e/session_status_test.py index 6850f6347..1b355885b 100644 --- a/test/e2e/session_status_test.py +++ b/test/e2e/session_status_test.py @@ -11,6 +11,7 @@ import urllib.error import urllib.parse import uuid +from harness import resident_kernel from harness import ROOT, Albedo, Provider, exclusive, latest_user, python, text from inspect_support import Inspection @@ -139,6 +140,7 @@ class SessionStatusPushTests(unittest.TestCase): ) @exclusive + @resident_kernel def test_kernel_notifications_do_not_retain_session_state(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" diff --git a/test/e2e/traces_test.py b/test/e2e/traces_test.py index bbcdbc08e..0cc566c91 100644 --- a/test/e2e/traces_test.py +++ b/test/e2e/traces_test.py @@ -4,6 +4,7 @@ import json import unittest import urllib.parse +from harness import resident_kernel from harness import Albedo, Provider, python, text @@ -128,6 +129,7 @@ open('binary.dat', 'wb').write(b'\\0binary') ) ) + @resident_kernel def test_many_edit_heavy_cells_release_buffers_and_keep_old_traces(self): oldest = None oldest_trace = None @@ -150,6 +152,7 @@ print('released') self.assertIn("released", result["output"]) self.assertEqual(self.read_trace(oldest), oldest_trace) + @resident_kernel def test_late_background_edits_execute_without_changing_finalized_trace(self): result, trace = self.run_cell(""" import asyncio diff --git a/test/e2e/warm_test.py b/test/e2e/warm_test.py index 750019ae6..f3982ce96 100644 --- a/test/e2e/warm_test.py +++ b/test/e2e/warm_test.py @@ -23,6 +23,7 @@ import time import unittest from harness import ( + resident_kernel, LOOPBACK_REMOTE, Albedo, alive, @@ -566,6 +567,7 @@ job.id""" # exclusive: shortens the daemon's idle and unload limits, restarts @exclusive + @resident_kernel def test_a_parent_waiting_on_its_child_keeps_warming_once_released(self): (self.app.home / "cache-ttl.json").write_text(json.dumps(RESTART_TTL)) self.app.restart( -- knotmirror 0.0.1 From e718a210ef813027630ef0ec406233f33bb99904 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:57:00 -0400 Subject: [PATCH 40/72] Start the local signal helper only for local kernels --- src/albedo/harness/extensions/python/albedo_python.erl | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 0601a5a18..e7ab1fc6c 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -300,7 +300,11 @@ warm_launch(S, Launch) -> %% Boot is the Gleam kernel.Boot record; Link is kernel.Link. start({boot, Owner, Python, Bridge, Cwd, Host, Modules, Link, RunDir, Kernel, Token, Grace, OutSeq, Owned, Fresh, Remote, Spare}) -> - albedo_signals:warm(), + %% A remote kernel is ended over ssh; only local ones need the helper. + case Remote of + none -> albedo_signals:warm(); + _ -> ok + end, Parent = self(), Ref = make_ref(), {Pid, Mon} = spawn_monitor(fun() -> albedo_inspect:label(<<"albedo_kernel">>, Kernel), -- knotmirror 0.0.1 From 79d3cb60855ac409713a68b96e5fee5f45ea60ca Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:57:00 -0400 Subject: [PATCH 41/72] Spill a remote kernel's output under the remote home, not a shared /tmp directory --- priv/python/albedo_cells.py | 3 +++ test/e2e/remote_kernels_test.py | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/priv/python/albedo_cells.py b/priv/python/albedo_cells.py index 0b47935fb..38a0f8c37 100644 --- a/priv/python/albedo_cells.py +++ b/priv/python/albedo_cells.py @@ -1757,9 +1757,12 @@ def main(): os.setsid() modules = open_link(sys.argv) # Beside the run directories: $ALBEDO_HOME/output, ~/.albedo-remote/output. + # A shared /tmp directory another user created would refuse every spill. albedo_capture.prune_spills( os.path.join(os.path.dirname(os.path.dirname(RUN_DIR)), "output") if RUN_DIR is not None + else os.path.join(os.path.expanduser("~"), ".albedo-remote", "output") + if os.environ.get("ALBEDO_REMOTE_TARGET") else os.path.join(tempfile.gettempdir(), "albedo-output") ) _ = os.dup2(os.open(os.devnull, os.O_RDONLY), 0) diff --git a/test/e2e/remote_kernels_test.py b/test/e2e/remote_kernels_test.py index b3ee0f65b..a43196ca0 100644 --- a/test/e2e/remote_kernels_test.py +++ b/test/e2e/remote_kernels_test.py @@ -466,6 +466,10 @@ print('complete output preserved for all three job kinds') self.assertEqual(result["status"], "ok", result) self.assertIn("complete output preserved", result["output"]) self.assertIn("refusals preserve destinations", result["output"]) + # Spills stay in the remote user's home: a shared /tmp directory another + # user owns would refuse them all. + spills = self.remote_home / ".albedo-remote" / "output" + self.assertTrue(spills.is_dir() and any(spills.iterdir()), spills) def test_job_spill_is_live_and_failures_preserve_artifacts(self): session = self.create(str(self.app.workspace))["id"] -- knotmirror 0.0.1 From 06aca6503070a08571a2c6fd21c7184021b95e5a Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:57:00 -0400 Subject: [PATCH 42/72] Accept a remote kernel's cells frames instead of dropping the connection --- priv/python/albedo_protocol.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/priv/python/albedo_protocol.py b/priv/python/albedo_protocol.py index 85d2ee49c..d58694f32 100644 --- a/priv/python/albedo_protocol.py +++ b/priv/python/albedo_protocol.py @@ -407,6 +407,8 @@ def parse_remote(value: object) -> RemoteMessage: _field(message, "ok", bool, kind) _field(message, "code", str, kind, optional=True) _field(message, "error", str, kind, optional=True) - elif kind not in {"job_start", "job", "trace", "done"}: + # A remote kernel publishes its cell count and quiescence for a local + # owner; over a remote connection nothing reads them. + elif kind not in {"job_start", "job", "trace", "done", "cells"}: raise ValueError(f"{kind}.type: unknown message type") return cast(RemoteMessage, message) -- knotmirror 0.0.1 From 1b51d861b19a9481025461ed202b96790dcc72c4 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 10:00:21 -0400 Subject: [PATCH 43/72] Keep the lazy kernel tests independent of a suite-wide spare pool --- test/e2e/kernel_lazy_test.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/test/e2e/kernel_lazy_test.py b/test/e2e/kernel_lazy_test.py index 599d905a5..d347d438b 100644 --- a/test/e2e/kernel_lazy_test.py +++ b/test/e2e/kernel_lazy_test.py @@ -95,11 +95,18 @@ class KernelLazyTests(unittest.TestCase): def start(self, slow_marker=None, crash_marker=None, **env): def prepare(app): + # The spare pool stays off unless a test asks for it: the edited + # kernel scripts below run only in a kernel booted cold, and the + # idle reap counts kernel processes. app.env.update( - ALBEDO_KERNEL_LAZY="1", - ALBEDO_TEST_TIME_SCALE="100", - ALBEDO_IDLE_SECONDS=str(IDLE_SECONDS), - **env, + { + "ALBEDO_KERNEL_LAZY": "1", + "ALBEDO_TEST_TIME_SCALE": "100", + "ALBEDO_IDLE_SECONDS": str(IDLE_SECONDS), + "ALBEDO_KERNEL_SPARES": "0", + "ALBEDO_KERNEL_RELEASE_WITH_SPARE": "0", + **env, + } ) if slow_marker is not None or crash_marker is not None: launcher, bundle = editable_daemon(app.root) -- knotmirror 0.0.1 From 6a2d46894a42f00677df349d5ce508865a26d6c1 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 10:00:21 -0400 Subject: [PATCH 44/72] Sample release eligibility only in local kernels --- priv/python/albedo_cells.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/priv/python/albedo_cells.py b/priv/python/albedo_cells.py index 38a0f8c37..61399d191 100644 --- a/priv/python/albedo_cells.py +++ b/priv/python/albedo_cells.py @@ -1838,10 +1838,13 @@ def main(): ) READY.set() task = LOOP.create_task(serve()) - QUIESCENCE = albedo_quiescence.Quiescence( - LOOP, RESOURCE_OWNERS, link_resources, refresh_work - ) - LOOP.call_soon(refresh_work) + # Release eligibility is for the local owner; a remote kernel's stdio link + # has nobody reading it, and the timer would wake it every second. + if RUN_DIR is not None: + QUIESCENCE = albedo_quiescence.Quiescence( + LOOP, RESOURCE_OWNERS, link_resources, refresh_work + ) + LOOP.call_soon(refresh_work) while not task.done(): try: LOOP.run_until_complete(task) -- knotmirror 0.0.1 From a42a5b26c69d0d6ed6dab0c35406e41f3703a0f2 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:52:47 -0400 Subject: [PATCH 45/72] Keep retained output and the job book across a kernel release; serve /jobs from the saved book without a kernel --- priv/python/albedo_api.py | 13 +- priv/python/albedo_capture.py | 59 ++++++- priv/python/albedo_cells.py | 48 ++++- priv/python/albedo_output.py | 3 +- priv/python/albedo_plugins/run.py | 111 +++++++++++- priv/python/albedo_state.py | 24 ++- robot-docs/kernel.md | 20 +++ src/albedo/daemon/albedo_session.erl | 3 +- src/albedo/daemon/albedo_state_expiry.erl | 2 +- .../extensions/python/albedo_job_window.erl | 117 ++++++++++++ .../harness/extensions/python/job_book.gleam | 95 +++++++++- .../harness/extensions/run/service.gleam | 18 +- test/e2e/kernel_pool_test.py | 42 +++++ test/harness/saved_job_window_test.py | 167 ++++++++++++++++++ 14 files changed, 698 insertions(+), 24 deletions(-) create mode 100644 src/albedo/harness/extensions/python/albedo_job_window.erl create mode 100644 test/harness/saved_job_window_test.py diff --git a/priv/python/albedo_api.py b/priv/python/albedo_api.py index 51b06b5a4..1dae81e49 100644 --- a/priv/python/albedo_api.py +++ b/priv/python/albedo_api.py @@ -3,7 +3,7 @@ from __future__ import annotations import asyncio -from collections.abc import Awaitable, Callable, Sequence +from collections.abc import Awaitable, Callable, Mapping, Sequence import importlib import inspect import keyword @@ -146,6 +146,12 @@ class OutputCapture(Protocol): def read(self, offset: int = 0, limit: int = 4000) -> str: ... + def persist(self) -> dict[str, object] | None: ... + + +SaveState = Callable[[str], object] +RestoreState = Callable[[object, Mapping[str, OutputCapture]], None] + @dataclass(frozen=True) class PythonApi: @@ -193,6 +199,11 @@ class PythonApi: ) = None # A resource that cannot survive a namespace save keeps this kernel alive. owns_resources: Callable[[Callable[[], bool]], None] | None = None + # Registers a plugin's own state under its name: save(state_path) returns + # a picklable value, and a kernel restored from that state calls + # restore(value, captures) before unpickling the namespace; captures are + # the retained outputs revived from disk, by id. + on_state: Callable[[str, SaveState, RestoreState], None] | None = None class PythonPlugin(Protocol): diff --git a/priv/python/albedo_capture.py b/priv/python/albedo_capture.py index c451a771b..f95dd7557 100644 --- a/priv/python/albedo_capture.py +++ b/priv/python/albedo_capture.py @@ -8,7 +8,7 @@ import re import struct import tempfile import time -from typing import BinaryIO +from typing import BinaryIO, cast import albedo_api import albedo_trace @@ -70,6 +70,12 @@ class Capture: self.spill: str | None = None self.spilled: int = 0 self._spill_file: BinaryIO | None = None + self._copy: tuple[int, str] | None = None # persist()'s file, at `seen` bytes + + def _new_spill_file(self) -> tuple[int, str]: + return tempfile.mkstemp( + prefix=re.sub(r"[^\w.-]", "_", self.id) + "-", suffix=".txt", dir=SPILL_DIR + ) def spills(self) -> bool: return self.kind in {"cell", "job"} and SPILL_DIR is not None @@ -114,11 +120,7 @@ class Capture: if self.spill is not None or self.spilled or SPILL_DIR is None: return # closed, full, refused, or failed try: - fd, path = tempfile.mkstemp( - prefix=re.sub(r"[^\w.-]", "_", self.id) + "-", - suffix=".txt", - dir=SPILL_DIR, - ) + fd, path = self._new_spill_file() self._spill_file = os.fdopen(fd, "wb", buffering=0) self.spill = path # Before this write the stream fit in `data` whole. @@ -169,9 +171,54 @@ class Capture: limit = min(limit, PREVIEW) if limit <= 0: return b"" + if self._tail is None and not self.data and self.spill and self.seen: + # Revived: the whole output is in the spill file. + start = max(0, self.seen - limit) + return self.read_bytes(start, self.seen - start) source = self.data if self._tail is None else self._tail return bytes(source[-limit:]) + def persist(self) -> dict[str, object] | None: + """What a later kernel needs to read this output again, with the bytes + held only in memory copied to a file; None when that copy fails. The + capture itself is unchanged, so output still being written goes on.""" + spill, spilled = self.spill, max(self.spilled, 0) + if spill is None and self.data: + if self._copy is not None and self._copy[0] == self.seen: + spill = self._copy[1] + elif SPILL_DIR is None: + return None + else: + try: + fd, spill = self._new_spill_file() + with os.fdopen(fd, "wb") as file: + file.write(self.data) + except OSError: + return None + self._copy = (self.seen, spill) + spilled = len(self.data) + return { + "id": self.id, + "kind": self.kind, + "seen": self.seen, + "spill": spill, + "spilled": spilled, + # The end the file lacks: output past what was kept on disk. + "tail": self.tail() if self.seen > spilled else None, + } + + @classmethod + def revive(cls, saved: dict[str, object]) -> Capture: + """A capture read from its spill file, holding no output in memory.""" + capture = cls(str(saved["id"]), str(saved["kind"])) + capture.seen = int(cast(int, saved["seen"])) + capture.spill = cast("str | None", saved["spill"]) + capture.spilled = int(cast(int, saved["spilled"])) + tail = saved.get("tail") + if isinstance(tail, bytes): + capture._tail = bytearray(tail) + return capture + @property def retained(self) -> int: return max(len(self.data), self.spilled if self.spill else 0) diff --git a/priv/python/albedo_cells.py b/priv/python/albedo_cells.py index 61399d191..7a66beb46 100644 --- a/priv/python/albedo_cells.py +++ b/priv/python/albedo_cells.py @@ -97,6 +97,8 @@ EXECUTING: set[str] = set() INTERRUPTS: dict[str, str] = {} QUIESCENCE: albedo_quiescence.Quiescence | None = None RESOURCE_OWNERS: list[Callable[[], bool]] = [] +# Plugins' own saved state (the run plugin's job book), by plugin name. +STATE_HOOKS: dict[str, tuple[albedo_api.SaveState, albedo_api.RestoreState]] = {} LAST_WORK: tuple[int, bool] | None = None READY = threading.Event() NAMESPACE: dict[str, object] = {"__name__": "__main__"} @@ -537,7 +539,7 @@ class Output: cell's subprocesses write land in that cell's own output instead. """ return albedo_api.ReadyList( - {"id": c.id, "kind": c.kind, "bytes": c.seen, "retained": len(c.data)} + {"id": c.id, "kind": c.kind, "bytes": c.seen, "retained": c.retained} for c in ARCHIVES.values() ) @@ -968,14 +970,51 @@ def remember(capture: Capture) -> None: counts[held.kind] -= 1 +def save_kernel(path: str) -> dict[str, object]: + """Retained cell and job output, moved to spill files, and the plugins' + own state, so a kernel restored from `path` reads them as this one did.""" + archives = [ + saved + for capture in ARCHIVES.values() + if capture.kind in ("cell", "job") + for saved in [capture.persist()] + if saved is not None + ] + plugins: dict[str, object] = {} + for name, (save, _) in STATE_HOOKS.items(): + try: + plugins[name] = save(path) + except Exception: + pass # that plugin's state is lost, as before it could be saved + return {"archives": archives, "plugins": plugins} + + +def restore_kernel(saved: object) -> None: + if not isinstance(saved, dict): + return + captures: dict[str, Capture] = {} + for entry in cast(list[dict[str, object]], saved.get("archives", [])): + capture = Capture.revive(entry) + captures[capture.id] = capture + if capture.id not in ARCHIVES: + remember(capture) + plugins = cast(dict[str, object], saved.get("plugins", {})) + for name, (_, restore) in STATE_HOOKS.items(): + if name in plugins: + restore(plugins[name], captures) + + def state_reply( message: albedo_api.State, state: dict[str, object] | None = None ) -> dict[str, object]: if state is None: + path = message["path"] state = ( - albedo_state.save_state(message["path"], NAMESPACE, DEFINITIONS, INJECTED) + albedo_state.save_state( + path, NAMESPACE, DEFINITIONS, INJECTED, save_kernel(path) + ) if message["type"] == "snapshot" - else albedo_state.load_state(message["path"], NAMESPACE, DEFINITIONS) + else albedo_state.load_state(path, NAMESPACE, DEFINITIONS, restore_kernel) ) return { "type": "done", @@ -1801,6 +1840,9 @@ def main(): on_stop_job=STOP_HANDLERS.append, on_job_view=JOB_VIEWS.append, owns_resources=RESOURCE_OWNERS.append, + on_state=lambda name, save, restore: STATE_HOOKS.update( + {name: (save, restore)} + ), ) NAMESPACE.update( cells=Cells(), diff --git a/priv/python/albedo_output.py b/priv/python/albedo_output.py index 084a4341a..d7a1258d2 100644 --- a/priv/python/albedo_output.py +++ b/priv/python/albedo_output.py @@ -122,7 +122,8 @@ class JobOutput: def head(self, n: int = 4000, *, lines: int | None = None) -> Text: """The first n characters or lines, within the 64 KiB preview window.""" - data = self.capture.data[:OUTPUT_PREVIEW] + size = min(OUTPUT_PREVIEW, self.capture.seen, self.capture.retained) + data = self.capture.read_bytes(0, size) result = excerpt( data.decode("utf-8", errors="ignore"), n, diff --git a/priv/python/albedo_plugins/run.py b/priv/python/albedo_plugins/run.py index f8ef54cff..51d408c39 100644 --- a/priv/python/albedo_plugins/run.py +++ b/priv/python/albedo_plugins/run.py @@ -23,7 +23,7 @@ from __future__ import annotations from albedo_output import JobOutput, plain, read_window from collections import OrderedDict -from collections.abc import Callable, Generator +from collections.abc import Callable, Generator, Mapping from typing import NoReturn, cast from albedo_api import ( OUTPUT_PREVIEW, @@ -34,6 +34,7 @@ from albedo_api import ( Text, check_timeout, ) +import albedo_capture import albedo_direnv import albedo_proc import albedo_shell @@ -41,11 +42,15 @@ from albedo_plugins import hook import albedo_shims import albedo_trace import asyncio +import base64 +import contextlib +import json import os import re import shlex import shutil import sys +import tempfile import time import uuid @@ -340,7 +345,7 @@ class Job(JobOutput): data = None if isinstance(stdin, Job) else stdin with albedo_trace.unobserved(): # the cell ran argv, not the wrapper around it self.spawning = loop.create_task(self._launch(cwd, env, data, self.feed)) - self.task: asyncio.Task[Job] = loop.create_task(self._run(timeout)) + self.task: asyncio.Future[Job] = loop.create_task(self._run(timeout)) self.task.add_done_callback(self._cancelled) active[self.id] = self jobs[self.id] = self @@ -668,6 +673,53 @@ class Job(JobOutput): f"bytes={self.capture.seen})" ) + def _saved(self) -> dict[str, object] | None: + """A finished job as a later kernel restores it, or None when its + output cannot be kept.""" + persist = getattr(self.capture, "persist", None) + output = persist() if persist is not None else None + if output is None or self.duration is None: + return None + return { + "id": self.id, + "argv": self.argv, + "command": self.command, + "exit_code": self.exit_code, + "timed_out": self.timed_out, + "duration": self.duration, + "started": time.time() - (loop.time() - self.started), + "service": self.service, + "traced": self.traced, + "read": self._read, + "output": output, + } + + @classmethod + def _restored(cls, saved: dict[str, object], capture: OutputCapture) -> Job: + """A finished job from before the kernel was released: how it ended, + with its output read back from disk.""" + job = cls.__new__(cls) + job.service, job.traced = bool(saved["service"]), bool(saved["traced"]) + job.source, job.feed, job.outlet = None, None, Outlet() + job.outlet.close() + job.id, job.capture = str(saved["id"]), capture + job.argv, job.command = ( + list(cast(list[str], saved["argv"])), + str(saved["command"]), + ) + job.process, job.group, job._hooked = None, None, None + job.exit_code = cast("int | None", saved["exit_code"]) + job.timed_out = bool(saved["timed_out"]) + job.duration = float(cast(float, saved["duration"])) + job.started = loop.time() - (time.time() - float(cast(float, saved["started"]))) + job.termination = albedo_proc.Termination(None, (), True) + job.ending, job._done, job._remote = None, None, None + job._awaited, job._waiters, job._starting = True, 0, False + job._read = bool(saved["read"]) + job.task = loop.create_future() + job.task.set_result(job) + return job + def __reduce__(self): # Saved kernel state keeps a variable holding a job: in this kernel it # resolves to the live handle, after a restart to how the job ended. @@ -749,12 +801,65 @@ def release(job: Job) -> None: return retained.pop(job.id, None) retained[job.id] = job + trim_retained() + + +def trim_retained() -> None: while len(retained) > RETAINED_LIMIT: _, evicted = retained.popitem(last=False) if jobs.get(evicted.id) is evicted: del jobs[evicted.id] +def save_jobs(path: str) -> list[dict[str, object]]: + """The finished jobs, oldest first, and beside the state at `path` the + listing the daemon serves while no kernel is attached (robot-docs/kernel.md).""" + book = [saved for job in retained.values() for saved in [job._saved()] if saved] + listing = [] + for saved in book: + if not saved["traced"]: + continue + job = retained[cast(str, saved["id"])] + output = cast(dict[str, object], saved["output"]) + tail = output["tail"] + listing.append( + job_record(job) + | { + "spill": output["spill"], + "spilled": output["spilled"], + "tail": base64.b64encode(tail).decode() + if isinstance(tail, bytes) + else None, + } + ) + listing.reverse() # newest first, as job_list answers + sidecar = path + ".jobs.json" + fd, temporary = tempfile.mkstemp( + dir=os.path.dirname(sidecar) or ".", prefix=".jobs." + ) + try: + with os.fdopen(fd, "w") as file: + json.dump({"jobs": listing[:MAX_LISTED]}, file) + os.replace(temporary, sidecar) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(temporary) + raise + return book + + +def restore_jobs(book: object, captures: Mapping[str, OutputCapture]) -> None: + for saved in cast(list[dict[str, object]], book): + id = cast(str, saved["id"]) + if id in jobs: + continue + output = cast(dict[str, object], saved["output"]) + capture = captures.get(id) or albedo_capture.Capture.revive(output) + job = Job._restored(saved, capture) + jobs[id] = retained[id] = job + trim_retained() + + def job_record(job: Job) -> dict[str, object]: """What the daemon lists of one job, with wall-clock times in milliseconds.""" begun = (time.time() - loop.time() + job.started) * 1000 @@ -1034,6 +1139,8 @@ def setup(api: PythonApi) -> dict[str, object]: jobs, active, retained = {}, {}, OrderedDict() api.background_handle(Job) + if api.on_state is not None: + api.on_state("run", save_jobs, restore_jobs) api.on_shutdown(close) if api.on_stop_job is not None: api.on_stop_job(stop_local_job) diff --git a/priv/python/albedo_state.py b/priv/python/albedo_state.py index fa81d0643..46625627a 100644 --- a/priv/python/albedo_state.py +++ b/priv/python/albedo_state.py @@ -8,6 +8,7 @@ import pickle import sys import tempfile import types +from collections.abc import Callable from typing import Any, cast # Saved state is the session's own namespace, written by this kernel into the @@ -68,8 +69,11 @@ def save_state( namespace: dict[str, object], definitions: dict[str, str], injected: set[str], + kernel: object = None, ) -> dict[str, object]: - """Serialise values and readable top-level definitions within fixed caps.""" + """Serialise values and readable top-level definitions within fixed caps. + `kernel` is the kernel's own state (retained output, the job book), saved + as it is and handed back to load_state's `restore_kernel`.""" serialiser, kind = cast("Any", engine()) payload: dict[str, bytes] = {} modules: dict[str, str] = {} @@ -143,6 +147,7 @@ def save_state( "modules": modules, "names": payload, "definitions": saved_definitions, + "kernel": kernel, }, file, ) @@ -166,10 +171,14 @@ def save_state( def load_state( - path: str, namespace: dict[str, object], definitions: dict[str, str] + path: str, + namespace: dict[str, object], + definitions: dict[str, str], + restore_kernel: Callable[[object], None] | None = None, ) -> dict[str, object]: - """Restore the added sys.path entries and modules, then pickled values, then - replay definitions in their saved order.""" + """Restore the added sys.path entries and modules, the kernel's own state, + then pickled values (which may refer to it), then replay definitions in + their saved order.""" try: with open(path, "rb") as file: saved = cast(dict[str, object], pickle.load(file)) @@ -197,6 +206,13 @@ def load_state( ) else: restored.append(name) + if restore_kernel is not None and saved.get("kernel") is not None: + try: + restore_kernel(saved["kernel"]) + except BaseException as error: + failed.append( + {"name": "", "reason": f"{type(error).__name__}: {error}"[:200]} + ) for name, blob in cast(dict[str, bytes], saved.get("names", {})).items(): try: namespace[name] = cast(object, serialiser.loads(blob)) diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 0687408b8..8ac0c1ec4 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -430,6 +430,26 @@ not written to namespace snapshots. Returning the environment to its original values permits release again. Eligibility is published with cell counts before results and refreshed once a second while the event loop can run. +Release keeps what the kernel retained. At save, every retained cell and +job output is described by a spill file under `$ALBEDO_HOME/output` (bytes +held only in memory are copied there first, and the capture itself is left +alone, so a save while work runs does not stop its spill), with the tail +the file lacks kept in the index; the run plugin saves its finished-job book +(ids, commands, exit codes, durations, start times) through `on_state`. Both +go into the saved state, and a restore revives them before the namespace, so +`output.read`, a job handle's `read`/`tail`/`head`, and `jobs` answer as +before, from disk, holding no output in memory. Retention rules stay the +kernel's: 16 cells, 64 jobs, 16 MiB spills, 14 days. + +The run plugin also writes `.jobs.json` atomically beside the state: +the finished jobs as the job book lists them, plus each one's spill path and +stored tail. While no kernel is attached the run routes (`/jobs/recent`, +`/jobs//output`) answer from it, so a viewer polling jobs never boots a +kernel; with a kernel attached they ask the kernel as before. +`albedo_job_window.erl` pages it exactly as `read_window` pages a finished +job (`test/harness/saved_job_window_test.py` pages one file through both). +The file is deleted with the state. + A lossless namespace restore gives the model a short note that the namespace was restored and source definitions re-run. Missed values or ended work retain the detailed loss notice. diff --git a/src/albedo/daemon/albedo_session.erl b/src/albedo/daemon/albedo_session.erl index ae37ed98c..709c74ba0 100644 --- a/src/albedo/daemon/albedo_session.erl +++ b/src/albedo/daemon/albedo_session.erl @@ -2,7 +2,8 @@ -export([kill/1, discard/1, collect/0, collect_over/1, activity/2, quiet/2, decode_submission/1, new_generation/0]). kill(Pid) -> exit(Pid,kill), nil. %% Monotonic: idle time must not move when the wall clock does. -discard(Path) -> file:delete(Path), nil. +%% The saved job book (`.jobs.json`, robot-docs/kernel.md) goes with its state. +discard(Path) -> file:delete(Path), file:delete(<>), nil. collect() -> erlang:garbage_collect(), nil. %% Collects only when the heap has grown past Words, so a steady stream of small %% messages never pays for a collection. diff --git a/src/albedo/daemon/albedo_state_expiry.erl b/src/albedo/daemon/albedo_state_expiry.erl index beb28db7a..ca7a6f28b 100644 --- a/src/albedo/daemon/albedo_state_expiry.erl +++ b/src/albedo/daemon/albedo_state_expiry.erl @@ -21,7 +21,7 @@ reclaim_one(Dir, Name0, Expired, Protected, Known, Now, {Count, Bytes}) -> 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}; + ok -> file:delete(<>), {Count + 1, Bytes + Size}; _ -> {Count, Bytes} end; _ -> {Count, Bytes} diff --git a/src/albedo/harness/extensions/python/albedo_job_window.erl b/src/albedo/harness/extensions/python/albedo_job_window.erl new file mode 100644 index 000000000..c034c1f99 --- /dev/null +++ b/src/albedo/harness/extensions/python/albedo_job_window.erl @@ -0,0 +1,117 @@ +%% Pages of a released kernel's saved job output, for the run routes while no +%% kernel is attached. Mirrors albedo_output.read_window for a finished job +%% (test/harness/job_window_test.py pages one file through both). +-module(albedo_job_window). +-export([read/6, window/6, decode/1, listing/1]). + +-define(PREVIEW, 65536). + +%% The sidecar a released kernel wrote beside its state, or an empty listing. +listing(StatePath) -> + case file:read_file(<>) of + {ok, Bytes} -> Bytes; + {error, _} -> <<"{\"jobs\": []}">> + end. + +%% Spill: the file holding bytes [0, Spilled); Tail: the stored end the file +%% lacks; Offset: none for the page that ends the output. Options are Gleam's. +read(Spill, Spilled, Seen, Tail, Offset, Limit) -> + window(unwrap(Spill), Spilled, Seen, unwrap(Tail), unwrap(Offset), Limit). + +unwrap({some, Value}) -> Value; +unwrap(none) -> undefined. + +window(Spill, Spilled, Seen, Tail, Offset, Limit) -> + try + TailBytes = tail(Spill, Spilled, Seen, Tail), + Kept = Seen - byte_size(TailBytes), + Start0 = case Offset of undefined -> max(0, Seen - Limit); _ -> min(Offset, Seen) end, + End = min(Start0 + Limit, Seen), + Data0 = case Start0 >= Kept of + true -> binary:part(TailBytes, Start0 - Kept, End - Start0); + false -> range(Spill, Spilled, Seen, Start0, End - Start0) + end, + {Start, Data1} = case Offset of + undefined -> Skip = continuations(Data0, 0), {Start0 + Skip, binary:part(Data0, Skip, byte_size(Data0) - Skip)}; + _ -> {Start0, Data0} + end, + Data = case Start + byte_size(Data1) =:= Seen of + true -> Data1; + false -> binary:part(Data1, 0, whole_characters(Data1)) + end, + {ok, {Start, Start + byte_size(Data), decode(Data)}} + catch throw:lost -> {error, nil} + end. + +tail(_, _, _, Tail) when is_binary(Tail) -> Tail; +tail(_, _, 0, _) -> <<>>; +tail(Spill, Spilled, Seen, _) -> + Start = max(0, Seen - ?PREVIEW), + range(Spill, Spilled, Seen, Start, Seen - Start). + +range(_, _, _, _, Size) when Size =< 0 -> <<>>; +range(_, _, Seen, Offset, _) when Offset >= Seen -> <<>>; +range(Spill, Spilled, Seen, Offset, Size) -> + End = min(Offset + Size, Seen), + case Spill =/= undefined andalso End =< Spilled of + false -> throw(lost); + true -> + case file:open(Spill, [read, raw, binary]) of + {ok, File} -> + Read = file:pread(File, Offset, End - Offset), + file:close(File), + case Read of + {ok, Data} when byte_size(Data) =:= End - Offset -> Data; + _ -> throw(lost) + end; + _ -> throw(lost) + end + end. + +continuations(Data, Skip) when Skip < 3, Skip < byte_size(Data) -> + case binary:at(Data, Skip) band 16#C0 of + 16#80 -> continuations(Data, Skip + 1); + _ -> Skip + end; +continuations(_, Skip) -> Skip. + +%% How many leading bytes end on a character (albedo_output.whole_characters). +whole_characters(Data) -> whole_characters(Data, 1). +whole_characters(Data, Back) when Back =< 4, Back =< byte_size(Data) -> + Byte = binary:at(Data, byte_size(Data) - Back), + case Byte band 16#C0 of + 16#80 -> whole_characters(Data, Back + 1); + _ -> + Size = if Byte >= 16#F0 -> 4; Byte >= 16#E0 -> 3; Byte >= 16#C0 -> 2; true -> 1 end, + case Back >= Size of + true -> byte_size(Data); + false -> byte_size(Data) - Back + end + end; +whole_characters(Data, _) -> byte_size(Data). + +%% UTF-8 with each maximal invalid subpart replaced by U+FFFD, as Python's +%% bytes.decode("utf-8", errors="replace") does. +decode(Data) -> unicode:characters_to_binary(lists:reverse(decode(Data, []))). + +decode(<<>>, Acc) -> Acc; +decode(<>, Acc) -> decode(Rest, [C | Acc]); +decode(<>, Acc) -> + decode(skip(Lead, Rest), [16#FFFD | Acc]). + +%% Drop the continuation bytes that still fit Lead's sequence. +skip(Lead, Rest) when Lead >= 16#C2, Lead =< 16#DF -> Rest; +skip(Lead, Rest) when Lead >= 16#E0, Lead =< 16#EF -> + {Low, High} = case Lead of 16#E0 -> {16#A0, 16#BF}; 16#ED -> {16#80, 16#9F}; _ -> {16#80, 16#BF} end, + case Rest of + <> when B >= Low, B =< High -> More; + _ -> Rest + end; +skip(Lead, Rest) when Lead >= 16#F0, Lead =< 16#F4 -> + {Low, High} = case Lead of 16#F0 -> {16#90, 16#BF}; 16#F4 -> {16#80, 16#8F}; _ -> {16#80, 16#BF} end, + case Rest of + <> when B >= Low, B =< High, C >= 16#80, C =< 16#BF -> More; + <> when B >= Low, B =< High -> More; + _ -> Rest + end; +skip(_, Rest) -> Rest. diff --git a/src/albedo/harness/extensions/python/job_book.gleam b/src/albedo/harness/extensions/python/job_book.gleam index 9235bd254..9239fa2e0 100644 --- a/src/albedo/harness/extensions/python/job_book.gleam +++ b/src/albedo/harness/extensions/python/job_book.gleam @@ -1,14 +1,18 @@ //// The kernel's own book of jobs: every job its run plugin still knows, the //// finished ones too, and pages of what they printed. The daemon asks the //// kernel each time and keeps nothing, so the book is as long-lived as the -//// kernel's retained output. +//// kernel's retained output; a released kernel's book is read from the file +//// it saved beside its state. import albedo/harness/extensions/python/kernel.{type Kernel} +import gleam/bit_array import gleam/bool import gleam/dynamic/decode import gleam/json +import gleam/list import gleam/option.{type Option, Some} import gleam/result +import gleam/string /// One job. `state` is `running` or `exited`; times are wall-clock /// milliseconds, and `bytes` is everything the job has written. @@ -126,6 +130,95 @@ fn refusal(code: String, error: String) -> Failure { } } +/// The finished jobs a released kernel saved beside the session's state, +/// newest first: what the routes show while no kernel is attached, so a +/// viewer never boots one. +pub fn saved_list( + home: String, + session: String, +) -> Result(List(Record), Failure) { + use saved <- result.map(saved(home, session)) + list.map(saved, fn(job) { job.record }) +} + +/// A page of a saved job's output, cut exactly as the kernel's read_window +/// cuts a finished job's. +pub fn saved_read( + home: String, + session: String, + id: String, + offset: Option(Int), + limit: Int, +) -> Result(Page, Failure) { + use saved <- result.try(saved(home, session)) + use job <- result.try( + list.find(saved, fn(job) { job.record.id == id }) + |> result.replace_error(NoSuchJob), + ) + case + window_read( + job.spill, + job.spilled, + job.record.bytes, + job.tail, + offset, + limit, + ) + { + Ok(#(start, end, text)) -> Ok(Page(job.record, start, end, text)) + Error(_) -> Error(OutputLost("requested output was not retained")) + } +} + +type Saved { + Saved( + record: Record, + spill: Option(String), + spilled: Int, + tail: Option(BitArray), + ) +} + +fn saved(home: String, session: String) -> Result(List(Saved), Failure) { + // session_namespace.state_path's rule: an id that is no file name has none. + use <- bool.guard( + session == "" + || string.contains(session, "/") + || string.contains(session, ".."), + Ok([]), + ) + let state_path = home <> "/kernels/" <> session <> ".state" + let job = { + use record <- decode.then(record()) + use spill <- decode.field("spill", decode.optional(decode.string)) + use spilled <- decode.field("spilled", decode.int) + use tail <- decode.field("tail", decode.optional(decode.string)) + decode.success(Saved( + record, + spill, + spilled, + option.then(tail, fn(text) { + bit_array.base64_decode(text) |> option.from_result + }), + )) + } + json.parse(listing(state_path), decode.at(["jobs"], decode.list(job))) + |> result.replace_error(Unavailable("the saved job book is unreadable")) +} + +@external(erlang, "albedo_job_window", "listing") +fn listing(state_path: String) -> String + +@external(erlang, "albedo_job_window", "read") +fn window_read( + spill: Option(String), + spilled: Int, + seen: Int, + tail: Option(BitArray), + offset: Option(Int), + limit: Int, +) -> Result(#(Int, Int, String), Nil) + fn record() -> decode.Decoder(Record) { use id <- decode.field("id", decode.string) use command <- decode.field("command", decode.string) diff --git a/src/albedo/harness/extensions/run/service.gleam b/src/albedo/harness/extensions/run/service.gleam index 696f3900c..f89586022 100644 --- a/src/albedo/harness/extensions/run/service.gleam +++ b/src/albedo/harness/extensions/run/service.gleam @@ -34,12 +34,12 @@ pub fn operation() -> client_api.Operation { } pub fn handle( - _daemon: extension.Daemon, + daemon: extension.Daemon, path: List(String), req: request.Request(BitArray), _live: request.Request(mist.Connection), ) -> response.Response(mist.ResponseData) { - case dispatch(path, req) { + case dispatch(daemon.home, path, req) { Ok(value) -> value Error(error) -> api.fail(error) } @@ -72,6 +72,7 @@ fn refusal(failure: job_book.Failure) -> String { } fn dispatch( + home: String, path: List(String), req: request.Request(BitArray), ) -> Result(response.Response(mist.ResponseData), api.Failure) { @@ -126,7 +127,13 @@ fn dispatch( json.array(jobs, job_book.record_json) }) |> result.map_error(refusal) - None -> Ok(json.array([], job_book.record_json)) + // A released kernel's book, read from disk: viewing never boots one. + None -> + job_book.saved_list(home, id) + |> result.map(fn(jobs) { + json.array(jobs, job_book.record_json) + }) + |> result.map_error(refusal) } }), ) @@ -159,7 +166,10 @@ fn dispatch( job_book.read(kernel, job, offset, limit) |> result.map(job_book.page_json) |> result.map_error(refusal) - None -> Error("job not found") + None -> + job_book.saved_read(home, id, job, offset, limit) + |> result.map(job_book.page_json) + |> result.map_error(refusal) } }), ) diff --git a/test/e2e/kernel_pool_test.py b/test/e2e/kernel_pool_test.py index 244b3e477..da23520a0 100644 --- a/test/e2e/kernel_pool_test.py +++ b/test/e2e/kernel_pool_test.py @@ -1,12 +1,14 @@ """Fresh spare kernels are single-use, bounded, and never adopted across a bundle edit.""" import ast +import json import os from pathlib import Path import socket import subprocess import time import unittest +import urllib.parse from harness import Albedo, Provider, alive, exclusive, python, text, wait_until from inspect_support import Inspection @@ -249,6 +251,46 @@ class KernelPoolTests(ModelCells, unittest.TestCase): lambda: not alive(pid), 15, "a closed remote connection pinned its kernel" ) + def jobs_api(self, path, **query): + suffix = ("?" + urllib.parse.urlencode(query)) if query else "" + route = f"/extensions/run/sessions/{self.session}/jobs/{path}{suffix}" + with self.app.api(route) as response: + return json.load(response) + + def test_release_keeps_retained_output_and_the_job_book(self): + self.boot(release=True) + self.ready() + # A cell whose output spills past the preview (its result is stored + # by reference, so it is not read back here), then one naming it. + self.cells.append("print('é' * 70000 + 'end')") + self.app.prompt(self.session, "run it").close() + self.app.idle(self.session) + cell, pid, job_id, text = self.value( + "import os, sys\n" + "job = run(sys.executable, '-c', 'print(\"first \\\\u00e9\"); print(\"second\")')\n" + "await job\n" + "([c['id'] for c in output.list() if c['bytes'] > 100000][0], os.getpid(), job.id, job.read())" + ) + self.assertEqual(text, "first é\nsecond\n") + wait_until(lambda: not alive(pid), 15, "the resting kernel was not released") + # No kernel now: the routes answer from the saved book and wake none. + [job] = self.jobs_api("recent")["items"] + self.assertEqual( + (job["id"], job["state"], job["exit_code"]), (job_id, "exited", 0) + ) + self.assertEqual(job["bytes"], 16) + page = self.jobs_api(f"{job_id}/output", offset=6, limit=4) + self.assertEqual( + (page["offset"], page["next_offset"], page["text"]), (6, 10, "é\ns") + ) + self.assertEqual(self.jobs_api(f"{job_id}/output")["text"], text) + self.assertEqual(self.spare_pids() & {pid}, set()) + restored = self.value( + f"(output.read({cell!r}, offset=139990, limit=100), jobs[{job_id!r}].tail(lines=1), " + f"jobs[{job_id!r}].exit_code, job.read())" + ) + self.assertEqual(restored, ("ééééé" + "end\n", "second\n", 0, text)) + def test_spare_is_adopted_released_once_and_refilled(self): self.boot(release=True) before = self.ready() diff --git a/test/harness/saved_job_window_test.py b/test/harness/saved_job_window_test.py new file mode 100644 index 000000000..ee18a025a --- /dev/null +++ b/test/harness/saved_job_window_test.py @@ -0,0 +1,167 @@ +"""A released kernel's saved job output pages the same from disk as from a kernel. + +The run routes answer from the saved job book while no kernel is attached +(robot-docs/kernel.md). Their Erlang paging must cut exactly where the kernel's +read_window cuts: a viewer switching between the two may neither lose nor +repeat a byte. E2E reads one job; this pages every boundary through both. +""" + +import json +from pathlib import Path +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "priv" / "python")) +import albedo_capture # noqa: E402 +from albedo_capture import PREVIEW, RETAIN, Capture # noqa: E402 +from albedo_output import JobOutput, read_window # noqa: E402 + +EBIN = ROOT / "build/dev/erlang/albedo/ebin" + + +class Ended(JobOutput): + def __init__(self, capture: Capture) -> None: + self.capture, self.duration, self.exit_code, self._read = capture, 1.0, 0, False + + +def erlang_windows(cases: list[dict]) -> list[object]: + with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as file: + json.dump(cases, file) + script = ( + f'{{ok, B}} = file:read_file("{file.name}"), ' + "Out = [case albedo_job_window:window(" + 'maps:get(<<"spill">>, C), maps:get(<<"spilled">>, C), maps:get(<<"seen">>, C), ' + 'case maps:get(<<"tail">>, C) of null -> undefined; T -> base64:decode(T) end, ' + 'case maps:get(<<"offset">>, C) of null -> undefined; O -> O end, maps:get(<<"limit">>, C)) of ' + '{ok, {S, E, Text}} -> [S, E, Text]; {error, _} -> <<"lost">> end ' + '|| C0 <- json:decode(B), C <- [C0#{<<"spill">> => case maps:get(<<"spill">>, C0) of null -> undefined; P -> P end}]], ' + "io:put_chars(json:encode(Out)), halt()." + ) + result = subprocess.run( + ["erl", "-noshell", "-pa", str(EBIN), "-eval", script], + capture_output=True, + text=True, + check=True, + ) + os.unlink(file.name) + return json.loads(result.stdout) + + +def outcome(read, capture: Capture) -> object: + try: + return read(Ended(capture)) + except ValueError as error: + return str(error) + + +class SavedJobWindowTest(unittest.TestCase): + def setUp(self): + if ( + shutil.which("erl") is None + or not (EBIN / "albedo_job_window.beam").exists() + ): + self.skipTest("needs erl and a built daemon") + self.spills = tempfile.mkdtemp(prefix="saved-window-") + self.addCleanup(shutil.rmtree, self.spills) + previous = albedo_capture.SPILL_DIR + albedo_capture.SPILL_DIR = self.spills + self.addCleanup(setattr, albedo_capture, "SPILL_DIR", previous) + + def revived( + self, data: bytes, spills: bool = True + ) -> tuple[Capture, Capture, dict]: + albedo_capture.SPILL_DIR = self.spills if spills else None + capture = Capture("job-" + str(len(data)), "job") + capture.write_bytes(data) + capture.end_spill() + albedo_capture.SPILL_DIR = self.spills + saved = capture.persist() + assert saved is not None + return capture, Capture.revive(saved), saved + + def compare(self, data: bytes, spills: bool = True) -> None: + live, revived, saved = self.revived(data, spills) + seen = live.seen + requests = [] + for offset in [ + None, + 0, + 1, + 2, + 3, + 5, + RETAIN - 1, + RETAIN + 2, + seen - 7, + seen - 1, + seen, + seen + 9, + ]: + if offset is not None and offset < 0: + continue + for limit in (4, 5, 7, 1000, PREVIEW): + requests.append((offset, limit)) + expected = [] + for offset, limit in requests: + try: + start, end, text = read_window(revived, offset, limit, True) + expected.append([start, end, text]) + # A capture that never left memory pages the same where it kept the bytes. + try: + self.assertEqual( + read_window(live, offset, limit, True), (start, end, text) + ) + except LookupError: + pass + except LookupError: + expected.append("lost") + tail = saved["tail"] + cases = [ + { + "spill": saved["spill"], + "spilled": saved["spilled"], + "seen": saved["seen"], + "tail": None + if tail is None + else __import__("base64").b64encode(tail).decode(), + "offset": offset, + "limit": limit, + } + for offset, limit in requests + ] + self.assertEqual(erlang_windows(cases), expected) + for n in (1, 3, 100): + for read in ( + lambda job: job.tail(n), + lambda job: job.tail(lines=n), + lambda job: job.head(n), + lambda job: job.head(lines=n), + ): + self.assertEqual(outcome(read, revived), outcome(read, live)) + + def test_text_with_multibyte_characters(self): + self.compare(("héllo wörld — ✓ 漢字 🙂\n" * 40).encode()) + + def test_output_that_spilled_past_retention(self): + self.compare(("é" * (RETAIN // 2 + 3 * PREVIEW) + "漢\n").encode()) + + def test_output_whose_middle_was_lost(self): + # Without a spill file only the first RETAIN bytes and the tail survive. + self.compare(b"x" * RETAIN + "漢".encode() * (PREVIEW // 2), spills=False) + + def test_invalid_utf8_is_replaced_the_same_way(self): + self.compare( + b"ok \xff\xfe a\xe0\x80b \xed\xa0\x80 c\xf0\x90\x80d \xf4\x90 e\xc0\xafz\xe6\xbc" + ) + + def test_empty_output(self): + self.compare(b"") + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1 From 5d8fcacab39be2ff8f4cca1e1a12c62c97b353fe Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 09:56:42 -0400 Subject: [PATCH 46/72] Fork cold opens from a running zygote before launching --- robot-docs/kernel.md | 4 +- .../extensions/python/albedo_python.erl | 58 ++++++++++++++++--- test/e2e/kernel_pool_test.py | 22 +++++++ 3 files changed, 74 insertions(+), 10 deletions(-) diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 8ac0c1ec4..7cbdc0c8f 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -404,7 +404,9 @@ the first runtime owner and stops with it, and exits by itself when the bundle digest changes at a fork, so the next spare starts a fresh one. A forked child remembers the digest its code was imported from, so a bundle edit between fork and adoption is refused like any stale spare. Any zygote failure falls back to -a directly started spare. A spare is consumed once; it never sees +a directly started spare. A cold open with no spare in hand also takes +a fork from a running zygote (any owner's), adopting it at once, and launches +only when that fails, so a burst past the spares costs forks, not launches. A spare is consumed once; it never sees a second agent. Namespace restore still uses the existing state file. The native custodian monitors the runtime owner. Stopping an unused spare checks diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index e7ab1fc6c..1d2545cc7 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -169,9 +169,7 @@ spare_wait(Chan, Watch, Target) -> Error -> From ! {Ref, Error}, spare_wait(Chan, Watch, Target) end; {spare_call, From, Ref, {adopt, Spec}} -> - Environment = maps:from_list([{unicode:characters_to_binary(Name), unicode:characters_to_binary(Value)} - || {Name, Value} <- spare_environment()]), - chan_send(Chan, [json:encode(Spec#{environment => Environment}), $\n]), + chan_send(Chan, adoption(Spec)), spare_adopting(Chan, Watch, Target, From, Ref, maps:get(run_dir, Spec)); stop -> spare_cleanup(Chan, Target); {'DOWN', Watch, process, _, _} -> spare_cleanup(Chan, Target); @@ -210,11 +208,49 @@ spare_cleanup(Chan, Target) -> Error -> Error end. -%% What a spare adopts: the daemon's environment without its secrets. -spare_environment() -> +%% The one line a spare adopts: the session's identity and the daemon's +%% environment without its secrets. +adoption(Spec) -> Blocked = [Name || {Name, false} <- clean_environment()], - [{Name, Value} || Entry <- os:getenv(), [Name, Value] <- [string:split(Entry, "=")], - not lists:member(Name, Blocked)]. + Environment = maps:from_list([{unicode:characters_to_binary(Name), unicode:characters_to_binary(Value)} + || Entry <- os:getenv(), [Name, Value] <- [string:split(Entry, "=")], + not lists:member(Name, Blocked)]), + [json:encode(Spec#{environment => Environment}), $\n]. + +%% A cold open with no spare in hand forks one from a zygote that is already +%% running (a fork costs ~5 ms of CPU where a launch costs ~100), adopting it +%% at once; without a zygote, or when the fork fails, the caller launches. +forked_launch(S) -> + case whereis(albedo_zygote) of + undefined -> error; + Holder -> + Alias = alias(), Mon = monitor(process, Holder), + Holder ! {zygote_path, Alias, Mon, any}, + Path = receive + {Mon, {ok, P}} -> P; + {Mon, _} -> none; + {'DOWN', Mon, process, Holder, _} -> none + after ?STARTUP_TIMEOUT -> none + end, + unalias(Alias), demonitor(Mon, [flush]), + case Path of + none -> error; + _ -> forked_adopt(Path, S) + end + end. + +forked_adopt(Path, S) -> + Watch = make_ref(), %% no owner to watch: the relay waits itself + case spare_ready(spare_connect(Path), Watch, self()) of + {ok, Chan, Ready} -> + Ref = make_ref(), + Spec = #{cwd => maps:get(cwd, S), run_dir => maps:get(run_dir, S), + modules => maps:get(modules, S), token => maps:get(token, S)}, + chan_send(Chan, adoption(Spec)), + spare_adopting(Chan, Watch, target_of(Ready), self(), Ref, maps:get(run_dir, Spec)), + receive {Ref, {ok, nil}} -> ok; {Ref, _} -> error end; + _ -> error + end. %% The zygote: one interpreter per daemon that imported what a spare imports %% and forks a child per spare (albedo_zygote.py). Linux only unless @@ -278,7 +314,7 @@ zygote_start(Owner) -> zygote_loop(Owner, Watch, Port, Path) -> receive {zygote_path, From, Ref, Asker} -> - From ! {Ref, case Asker of Owner -> {ok, Path}; _ -> none end}, + From ! {Ref, case Asker of Owner -> {ok, Path}; any -> {ok, Path}; _ -> none end}, zygote_loop(Owner, Watch, Port, Path); {'DOWN', Watch, process, Owner, _} -> ok; {Port, eof} -> ok; @@ -287,7 +323,11 @@ zygote_loop(Owner, Watch, Port, Path) -> warm_launch(S, Launch) -> case maps:get(spare, S, none) of - none -> launch(Launch); + none -> + case forked_launch(S) of + ok -> 0; + error -> launch(Launch) + end; {some, {spare, Pid}} -> Spec = #{cwd => maps:get(cwd, S), run_dir => maps:get(run_dir, S), modules => maps:get(modules, S), token => maps:get(token, S)}, diff --git a/test/e2e/kernel_pool_test.py b/test/e2e/kernel_pool_test.py index da23520a0..abd00ad4a 100644 --- a/test/e2e/kernel_pool_test.py +++ b/test/e2e/kernel_pool_test.py @@ -349,6 +349,28 @@ class KernelPoolTests(ModelCells, unittest.TestCase): lambda: not alive(zygote), 15, "the stale zygote outlived its bundle" ) + def test_opens_past_the_spares_fork_from_the_zygote(self): + self.boot(zygote="1") + [spare] = self.ready() + zygote = self.zygote_of(spare) + sessions = [self.app.session() for _ in range(3)] + for session in sessions: + self.cells.append("import os\nos.getpid()") + self.app.prompt(session, "run it").close() + pids = [] + for session in sessions: + self.session = session + self.app.idle(session) + [result] = [ + json.loads(part["value"]) + for entry in self.app.history(session)["items"] + if entry["kind"] == "tool_result" + for part in entry["content"] + if part["kind"] == "json" and part["field"] == "result" + ] + pids.append(ast.literal_eval(result["value"])) + self.assertEqual({self.zygote_of(pid) for pid in pids}, {zygote}) + def test_an_empty_pool_uses_a_cold_kernel(self): self.boot(spares=0) pid = self.value("import os\nos.getpid()") -- knotmirror 0.0.1 From 5f31e46e38b3a7b2e18d3bef36cef0b4e99fea82 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 10:02:03 -0400 Subject: [PATCH 47/72] Report retained output and job book lost in a restore as output_lost --- priv/python/albedo_cells.py | 42 +++++++++++++++-------- priv/python/albedo_state.py | 16 +++++---- robot-docs/kernel.md | 6 +++- test/harness/restore_loss_test.py | 55 +++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 21 deletions(-) create mode 100644 test/harness/restore_loss_test.py diff --git a/priv/python/albedo_cells.py b/priv/python/albedo_cells.py index 7a66beb46..613925cd9 100644 --- a/priv/python/albedo_cells.py +++ b/priv/python/albedo_cells.py @@ -971,37 +971,51 @@ def remember(capture: Capture) -> None: def save_kernel(path: str) -> dict[str, object]: - """Retained cell and job output, moved to spill files, and the plugins' - own state, so a kernel restored from `path` reads them as this one did.""" - archives = [ - saved - for capture in ARCHIVES.values() - if capture.kind in ("cell", "job") - for saved in [capture.persist()] - if saved is not None - ] + """Retained cell and job output, described by spill files, and the plugins' + own state, so a kernel restored from `path` reads them as this one did. + What could not be kept is named in "lost" for the restore to report.""" + archives: list[dict[str, object]] = [] + lost: list[str] = [] + for capture in ARCHIVES.values(): + if capture.kind in ("cell", "job"): + saved = capture.persist() + if saved is None: + lost.append(capture.id) + else: + archives.append(saved) plugins: dict[str, object] = {} for name, (save, _) in STATE_HOOKS.items(): try: plugins[name] = save(path) except Exception: - pass # that plugin's state is lost, as before it could be saved - return {"archives": archives, "plugins": plugins} + lost.append(name) # that plugin's state, as before it could be saved + return {"archives": archives, "plugins": plugins, "lost": lost} -def restore_kernel(saved: object) -> None: +def restore_kernel(saved: object) -> list[str]: + """Revive retained output and the plugins' state; returns what was lost: + output the save could not keep or whose file is gone, and plugin state + that would not save or restore.""" if not isinstance(saved, dict): - return + return [] + lost = list(cast(list[str], saved.get("lost", []))) captures: dict[str, Capture] = {} for entry in cast(list[dict[str, object]], saved.get("archives", [])): capture = Capture.revive(entry) + if capture.spill is not None and not os.path.exists(capture.spill): + lost.append(capture.id) + continue captures[capture.id] = capture if capture.id not in ARCHIVES: remember(capture) plugins = cast(dict[str, object], saved.get("plugins", {})) for name, (_, restore) in STATE_HOOKS.items(): if name in plugins: - restore(plugins[name], captures) + try: + restore(plugins[name], captures) + except Exception: + lost.append(name) + return lost def state_reply( diff --git a/priv/python/albedo_state.py b/priv/python/albedo_state.py index 46625627a..d5e17392a 100644 --- a/priv/python/albedo_state.py +++ b/priv/python/albedo_state.py @@ -174,7 +174,7 @@ def load_state( path: str, namespace: dict[str, object], definitions: dict[str, str], - restore_kernel: Callable[[object], None] | None = None, + restore_kernel: Callable[[object], list[str]] | None = None, ) -> dict[str, object]: """Restore the added sys.path entries and modules, the kernel's own state, then pickled values (which may refer to it), then replay definitions in @@ -206,13 +206,14 @@ def load_state( ) else: restored.append(name) + # Retained output and job book channels that did not come back; absent + # when the state predates saving them. + output_lost: list[str] | None = None if restore_kernel is not None and saved.get("kernel") is not None: try: - restore_kernel(saved["kernel"]) + output_lost = restore_kernel(saved["kernel"]) except BaseException as error: - failed.append( - {"name": "", "reason": f"{type(error).__name__}: {error}"[:200]} - ) + output_lost = [f" {type(error).__name__}: {error}"[:200]] for name, blob in cast(dict[str, bytes], saved.get("names", {})).items(): try: namespace[name] = cast(object, serialiser.loads(blob)) @@ -249,9 +250,12 @@ def load_state( directory = saved.get("cwd") if isinstance(directory, str) and os.path.isdir(directory): os.chdir(directory) - return { + result: dict[str, object] = { "restored": sorted(set(restored)), "defs": defs, "failed": failed, "engine": kind, } + if output_lost is not None: + result["output_lost"] = output_lost + return result diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index 7cbdc0c8f..d8d9cb1fa 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -441,7 +441,11 @@ the file lacks kept in the index; the run plugin saves its finished-job book go into the saved state, and a restore revives them before the namespace, so `output.read`, a job handle's `read`/`tail`/`head`, and `jobs` answer as before, from disk, holding no output in memory. Retention rules stay the -kernel's: 16 cells, 64 jobs, 16 MiB spills, 14 days. +kernel's: 16 cells, 64 jobs, 16 MiB spills, 14 days. The restore result's +`output_lost` names every retained channel that did not come back (output +the save could not copy, a spill file gone since, plugin state that failed to +save or restore); empty means nothing was lost, and it is absent for a state +saved before this existed. The run plugin also writes `.jobs.json` atomically beside the state: the finished jobs as the job book lists them, plus each one's spill path and diff --git a/test/harness/restore_loss_test.py b/test/harness/restore_loss_test.py new file mode 100644 index 000000000..356422b6f --- /dev/null +++ b/test/harness/restore_loss_test.py @@ -0,0 +1,55 @@ +"""A restore reports which retained output it could not bring back. + +The daemon says nothing to the model after a lossless restore and names what +was lost otherwise (robot-docs/kernel.md), so `output_lost` must be empty only +when every retained channel came back. E2E restores real kernels; this +removes a spill file between save and restore, which E2E cannot time. +""" + +from pathlib import Path +import os +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "priv" / "python")) +import albedo_capture # noqa: E402 +import albedo_cells # noqa: E402 +import albedo_state # noqa: E402 + + +class RestoreLossTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + previous = albedo_capture.SPILL_DIR + albedo_capture.SPILL_DIR = self.directory.name + self.addCleanup(setattr, albedo_capture, "SPILL_DIR", previous) + albedo_cells.ARCHIVES.clear() + self.addCleanup(albedo_cells.ARCHIVES.clear) + self.path = os.path.join(self.directory.name, "session.state") + capture = albedo_capture.Capture("cell-1", "cell") + capture.write("kept output\n") + albedo_cells.remember(capture) + albedo_state.save_state( + self.path, {}, {}, set(), albedo_cells.save_kernel(self.path) + ) + saved = capture.persist() + assert saved is not None and isinstance(saved["spill"], str) + self.spill: str = saved["spill"] + albedo_cells.ARCHIVES.clear() + + def restore(self) -> dict[str, object]: + return albedo_state.load_state(self.path, {}, {}, albedo_cells.restore_kernel) + + def test_a_complete_restore_reports_nothing_lost(self): + self.assertEqual(self.restore()["output_lost"], []) + self.assertEqual(albedo_cells.retained("cell-1").read(0, 100), "kept output\n") + + def test_a_vanished_spill_file_is_named(self): + os.unlink(self.spill) + self.assertEqual(self.restore()["output_lost"], ["cell-1"]) + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1 From da26a443ffcf9f9c613b6d416475bd3fdcbc1c3a Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 10:04:02 -0400 Subject: [PATCH 48/72] Clear the prepared context on release and rebuild it on demand for a session without a kernel --- src/albedo/daemon/session.gleam | 55 ++++++++++++- src/albedo/daemon/session_diagnostics.gleam | 6 ++ src/albedo/daemon/session_last_call.gleam | 82 +++++++++++++++---- src/albedo/harness/loop.gleam | 24 +++++- test/daemon/albedo_context_snapshot_probe.erl | 6 +- test/e2e/context_retention_test.py | 3 +- test/e2e/context_test.py | 9 +- test/e2e/session_configure_test.py | 4 +- 8 files changed, 164 insertions(+), 25 deletions(-) diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 89f09f31d..835dbd6f0 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -2145,7 +2145,10 @@ fn handle( reply, Nil, ) - ReadContext(reply) -> answer(state, reply, state.context) + ReadContext(reply) -> { + let #(state, snapshot) = context_read(state) + answer(state, reply, snapshot) + } RecordUsage(id, metadata, reply) -> case turn.owner(state.activity, id) { Some(_) -> { @@ -2276,6 +2279,7 @@ fn handle( kernel: None, released: Some(kernel), releasing: None, + context: session_state.unprepared(), ) |> session_state.emit(view.note( "daemon", @@ -2291,7 +2295,12 @@ fn handle( None -> { let evicted = state.history != None process.send(state.self, Collect) - answer(session_state.State(..state, history: None), reply, evicted) + answer( + session_state.State(..state, history: None) + |> forget_recomputed_context, + reply, + evicted, + ) } } Collect -> { @@ -4854,3 +4863,45 @@ fn release_kernel( }) session_state.State(..state, releasing: Some([])) } + +/// The prepared request a client reads at rest. A released session holds none +/// (its actor keeps no request sections), so the last turn call is rebuilt from +/// the transcript, as the cache warmer does after a restart, and kept until the +/// next release or history eviction so a polling client does not rebuild it. +fn context_read(state: State) -> #(State, context_snapshot.Snapshot) { + case + context_snapshot.identity(state.context), + turn.running(state.activity), + state.kernel + { + None, None, None -> + case session_last_call.restore_context(state) { + #(state, Some(#(request, observation, protocol))) -> { + let rebuilt = + context_snapshot.from_request( + Some(usage.now()), + state.info.provider, + conversation.protocol(protocol), + protocol, + request, + observation, + ) + let snapshot = case state.latest_usage { + Some(metadata) -> context_snapshot.with_usage(rebuilt, metadata) + None -> rebuilt + } + #(session_state.State(..state, context: snapshot), snapshot) + } + #(state, None) -> #(state, state.context) + } + _, _, _ -> #(state, state.context) + } +} + +/// A snapshot rebuilt for a session without a kernel goes with its history. +fn forget_recomputed_context(state: State) -> State { + case state.kernel { + None -> session_state.State(..state, context: session_state.unprepared()) + Some(_) -> state + } +} diff --git a/src/albedo/daemon/session_diagnostics.gleam b/src/albedo/daemon/session_diagnostics.gleam index 65b1a82aa..16fb8cd4e 100644 --- a/src/albedo/daemon/session_diagnostics.gleam +++ b/src/albedo/daemon/session_diagnostics.gleam @@ -1,5 +1,6 @@ //// Typed facts for native diagnostics inspecting a live session state. +import albedo/daemon/context_snapshot import albedo/daemon/session_state.{type State} import albedo/daemon/tool_progress import albedo/daemon/turn @@ -19,6 +20,11 @@ pub fn history_unloaded(state: State(message)) -> Bool { state.history == None } +/// Whether the actor holds no prepared request (a read at rest rebuilds one). +pub fn context_pending(state: State(message)) -> Bool { + context_snapshot.identity(state.context) == None +} + pub fn progress(state: State(message)) -> tool_progress.Projection { state.tool_progress } diff --git a/src/albedo/daemon/session_last_call.gleam b/src/albedo/daemon/session_last_call.gleam index 7065bcebd..d7557b380 100644 --- a/src/albedo/daemon/session_last_call.gleam +++ b/src/albedo/daemon/session_last_call.gleam @@ -10,6 +10,7 @@ import albedo/daemon/session_history import albedo/daemon/session_provider import albedo/daemon/session_state import albedo/daemon/transcript +import albedo/harness/compaction import albedo/harness/extension import albedo/harness/loop import albedo/harness/runtime @@ -27,17 +28,63 @@ pub fn restore( state: session_state.State(message), ) -> #(session_state.State(message), Option(#(extension.SentCall, Int))) { case rebuild(state) { - Ok(restored) -> restored + Ok(#(state, Some(rebuilt))) -> #( + state, + matching( + rebuilt.turn, + rebuilt.pings, + rebuilt.upstream, + rebuilt.request, + rebuilt.prefix, + ), + ) + Ok(#(state, None)) -> #(state, None) Error(_) -> #(state, None) } } -fn rebuild( +/// The last turn call's request with what the strategy observed building it, +/// for a read of the prepared context after the kernel and snapshot went, or +/// `None` on the same conditions as `restore`. +pub fn restore_context( state: session_state.State(message), -) -> Result( - #(session_state.State(message), Option(#(extension.SentCall, Int))), - String, +) -> #( + session_state.State(message), + Option(#(types.Request, Option(compaction.Observation), types.Protocol)), ) { + case rebuild(state) { + Ok(#(state, Some(rebuilt))) -> + case rebuilt.prefix == requests.row_prefix(rebuilt.turn) { + True -> #( + state, + Some(#( + rebuilt.request, + rebuilt.observation, + rebuilt.upstream.protocol, + )), + ) + False -> #(state, None) + } + Ok(#(state, None)) -> #(state, None) + Error(_) -> #(state, None) + } +} + +/// One turn call built again from the transcript. +type Rebuilt { + Rebuilt( + turn: requests.Row, + pings: List(requests.Row), + upstream: extension.Upstream, + request: types.Request, + prefix: requests.Prefix, + observation: Option(compaction.Observation), + ) +} + +fn rebuild( + state: session_state.State(message), +) -> Result(#(session_state.State(message), Option(Rebuilt)), String) { use kernel <- result.try(option.to_result( session_state.composition(state), "no composition", @@ -67,16 +114,21 @@ fn rebuild( state.info.provider, state.info.protocol, )) - use #(request, prefix) <- result.map(loop.rebuild( - state.host, - kernel, - state.info.model, - state.info.effort, - state.pin, - upstream, - list.reverse(inputs), - )) - #(state, matching(turn, pings, upstream, request, prefix)) + use #(request, prefix, observation) <- result.map( + loop.rebuild_observed( + state.host, + kernel, + state.info.model, + state.info.effort, + state.pin, + upstream, + list.reverse(inputs), + ), + ) + #( + state, + Some(Rebuilt(turn, pings, upstream, request, prefix, observation)), + ) } _ -> Ok(#(state, None)) } diff --git a/src/albedo/harness/loop.gleam b/src/albedo/harness/loop.gleam index a77237d54..f8994d8e7 100644 --- a/src/albedo/harness/loop.gleam +++ b/src/albedo/harness/loop.gleam @@ -1317,6 +1317,24 @@ pub fn rebuild( upstream: extension.Upstream, original: List(types.Input), ) -> Result(#(types.Request, requests.Prefix), String) { + rebuild_observed(host, kernel, model, effort, pin, upstream, original) + |> result.map(fn(rebuilt) { #(rebuilt.0, rebuilt.1) }) +} + +/// `rebuild` with what the strategy observed preparing the request, which an +/// inspector shows beside it. +pub fn rebuild_observed( + host: runtime.Runtime, + kernel: runtime.Prepared, + model: String, + effort: Option(String), + pin: Pin, + upstream: extension.Upstream, + original: List(types.Input), +) -> Result( + #(types.Request, requests.Prefix, Option(compaction.Observation)), + String, +) { use prepared <- result.map(runtime.project_view_scoped( host, kernel, @@ -1330,7 +1348,11 @@ pub fn rebuild( let history = prepared.inputs let instructions = instructions_for(settled(pin, original, history), kernel) let request = request_for(model, effort, kernel, instructions, history) - #(request, request_prefix(request, original, prepared.observation)) + #( + request, + request_prefix(request, original, prepared.observation), + prepared.observation, + ) } fn describe( diff --git a/test/daemon/albedo_context_snapshot_probe.erl b/test/daemon/albedo_context_snapshot_probe.erl index d63ccac7d..fc1188639 100644 --- a/test/daemon/albedo_context_snapshot_probe.erl +++ b/test/daemon/albedo_context_snapshot_probe.erl @@ -105,8 +105,8 @@ actor(Id) -> erlang:garbage_collect(Pid), DidRelease end), - {ok, Pending} = 'albedo@daemon@session':prepared_context(Session, none), - {pending, _} = Pending, + %% A read at rest rebuilds the request, so retention is read from the state. + ContextCleared = 'albedo@daemon@session_diagnostics':context_pending(sys:get_state(Pid)), SessionMonitor = monitor(process, Pid), _ = 'albedo@daemon@session':close(Session), Stopped = receive {'DOWN', SessionMonitor, process, Pid, _} -> true after 5000 -> false end, @@ -114,7 +114,7 @@ actor(Id) -> history_readable => element(1, HistoryPage) =:= ok, actor_binary_bytes => Retained, replay_backing_binary_bytes => Backing, replay_backing_before_bytes => lists:sum(maps:values(LargePointers)), - kernel_released => Released, context_cleared => element(1, Pending) =:= pending, + kernel_released => Released, context_cleared => ContextCleared, actor_stopped => Stopped, workers_terminated => true, phases => [EvictionMetric, IdleMetric, ClearMetric]}. actor_json(Id) -> iolist_to_binary(json:encode(actor(Id))). diff --git a/test/e2e/context_retention_test.py b/test/e2e/context_retention_test.py index 59f022a18..8fd3e9b49 100644 --- a/test/e2e/context_retention_test.py +++ b/test/e2e/context_retention_test.py @@ -6,12 +6,13 @@ from pathlib import Path import unittest from inspect_support import Inspection -from harness import Albedo, Provider, Reply, ROOT, exclusive +from harness import Albedo, Provider, Reply, ROOT, exclusive, resident_kernel # exclusive: enables daemon inspection and global rolling settings @exclusive class ContextRetentionTest(unittest.TestCase): + @resident_kernel def test_eviction_releases_replay_while_inspection_survives(self): payload = "REPLAY_SENTINEL:" + "x" * (256 * 1024) reply = Reply( diff --git a/test/e2e/context_test.py b/test/e2e/context_test.py index 46d3f60fe..8069d4362 100644 --- a/test/e2e/context_test.py +++ b/test/e2e/context_test.py @@ -208,8 +208,13 @@ class ContextTest(unittest.TestCase): json.load(response) with self.app.api(configuration) as response: self.assertIsNone(json.load(response)["context_window"]) - # Clearing the session window invalidates the prepared context snapshot. - self.assertEqual(self.read(f"/sessions/{session}/context")["state"], "pending") + # Clearing the session window invalidates the prepared context snapshot; + # a session without a kernel rebuilds it on demand under the new window. + snapshot = self.read(f"/sessions/{session}/context") + if snapshot["state"] == "ready": + self.assertEqual(snapshot["context_window_tokens"], 200000) + else: + self.assertEqual(snapshot["state"], "pending") # The window answers without a prepared request. window = self.read(f"/sessions/{session}/context-window") self.assertIsNone(window["context_window"]) diff --git a/test/e2e/session_configure_test.py b/test/e2e/session_configure_test.py index d3c646b02..285ccda36 100644 --- a/test/e2e/session_configure_test.py +++ b/test/e2e/session_configure_test.py @@ -137,7 +137,9 @@ class SessionConfigureTest(unittest.TestCase): changed = self.invoke("effort", " MEDIUM ")["ok"] self.assertEqual(changed["effort"], "medium") self.assertEqual(self.defaults(), defaults) - self.assertEqual(self.context()["state"], "pending") + # Effort is not part of the prepared request's sections: a session + # without a kernel may rebuild its context on demand. + self.assertIn(self.context()["state"], ("pending", "ready")) before = self.configuration() rejected = self.model("third", effort="high") -- knotmirror 0.0.1 From df0af27f694abbcd688b2248fd859d8d47f21da6 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 10:14:54 -0400 Subject: [PATCH 49/72] Density benchmark: count the zygote and its forked kernels --- test/manual/agent_density.py | 66 ++++++++++++++++++++++++++---------- 1 file changed, 48 insertions(+), 18 deletions(-) diff --git a/test/manual/agent_density.py b/test/manual/agent_density.py index 5a66816dd..058cb2300 100644 --- a/test/manual/agent_density.py +++ b/test/manual/agent_density.py @@ -7,6 +7,7 @@ The default keeps kernels resident; --idle-seconds and --settle test reaping. from __future__ import annotations +import collections import os import argparse from concurrent.futures import ThreadPoolExecutor @@ -53,24 +54,52 @@ def process_bytes(pid): def processes(app): - listing = subprocess.check_output(["ps", "-axo", "pid=,command="], text=True) - result = [{"pid": app.connection["pid"], "kind": "daemon"}] - for line in listing.splitlines(): - pid, command = line.strip().split(None, 1) - if str(app.home) in command and any( - name in command - for name in ("albedo_kernel.py", "albedo_bridge.py", "albedo_spare.py") - ): - result.append( - { - "pid": int(pid), - "kind": "spare" - if "albedo_spare.py" in command - else "kernel" - if "albedo_kernel.py" in command - else "bridge", - } - ) + """The daemon and its Python processes: kernels, spares, bridges, the + zygote, and the children it forked (they keep the zygote's command line; + PSS apportions the pages they share with it).""" + rows = [ + line.strip().split(None, 2) + for line in subprocess.check_output( + ["ps", "-axo", "pid=,ppid=,command="], text=True + ).splitlines() + ] + rows = [(int(pid), int(ppid), command) for pid, ppid, command in rows] + daemon = app.connection["pid"] + children: dict[int, list[int]] = {} + for pid, ppid, _ in rows: + children.setdefault(ppid, []).append(pid) + descendants, frontier = set(), [daemon] + while frontier: + for child in children.get(frontier.pop(), []): + if child not in descendants: + descendants.add(child) + frontier.append(child) + commands = {pid: command for pid, _, command in rows} + zygotes = { + pid + for pid, ppid, command in rows + if "albedo_zygote.py" in command + and pid in descendants + and "albedo_zygote.py" not in commands.get(ppid, "") + } + result = [{"pid": daemon, "kind": "daemon"}] + for pid, ppid, command in rows: + ours = str(app.home) in command or pid in descendants + if not ours: + continue + if pid in zygotes: + kind = "zygote" + elif ppid in zygotes: + kind = "forked" + elif "albedo_spare.py" in command: + kind = "spare" + elif "albedo_kernel.py" in command: + kind = "kernel" + elif "albedo_bridge.py" in command: + kind = "bridge" + else: + continue + result.append({"pid": pid, "kind": kind}) return result @@ -87,6 +116,7 @@ def measure(app, label, count, baseline): "agents": count, "total_bytes": total, "marginal_bytes_per_agent": (total - baseline) / count, + "kinds": dict(collections.Counter(item["kind"] for item in items)), "processes": items, "beam": json.loads(memory), } -- knotmirror 0.0.1 From c8930684679fa5841b6dc1c47b000e1064dba2ab Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 10:14:56 -0400 Subject: [PATCH 50/72] Name the reason when a plugin's state fails to save or restore --- priv/python/albedo_cells.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/priv/python/albedo_cells.py b/priv/python/albedo_cells.py index 613925cd9..256bfceb7 100644 --- a/priv/python/albedo_cells.py +++ b/priv/python/albedo_cells.py @@ -987,8 +987,9 @@ def save_kernel(path: str) -> dict[str, object]: for name, (save, _) in STATE_HOOKS.items(): try: plugins[name] = save(path) - except Exception: - lost.append(name) # that plugin's state, as before it could be saved + except Exception as error: + # Lost like before it could be saved; the reason reaches the daemon. + lost.append(f"{name}: {type(error).__name__}: {error}"[:200]) return {"archives": archives, "plugins": plugins, "lost": lost} @@ -1013,8 +1014,8 @@ def restore_kernel(saved: object) -> list[str]: if name in plugins: try: restore(plugins[name], captures) - except Exception: - lost.append(name) + except Exception as error: + lost.append(f"{name}: {type(error).__name__}: {error}"[:200]) return lost -- knotmirror 0.0.1 From fb1ef0eb837fe028a168c7fb81c3b8db30c2af78 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 10:15:18 -0400 Subject: [PATCH 51/72] Say nothing to the model when a restore lost nothing; create the job book directory before its first save --- priv/python/albedo_plugins/run.py | 2 ++ src/albedo/daemon/session_namespace.gleam | 32 +++++++++---------- .../harness/extensions/python/kernel.gleam | 26 +++++++++------ test/e2e/idle_reap_test.py | 8 ++--- test/e2e/kernel_lazy_test.py | 5 +-- test/e2e/kernel_state_test.py | 6 ++-- test/e2e/release_request_test.py | 5 +++ 7 files changed, 48 insertions(+), 36 deletions(-) diff --git a/priv/python/albedo_plugins/run.py b/priv/python/albedo_plugins/run.py index 51d408c39..37e879639 100644 --- a/priv/python/albedo_plugins/run.py +++ b/priv/python/albedo_plugins/run.py @@ -834,6 +834,8 @@ def save_jobs(path: str) -> list[dict[str, object]]: ) listing.reverse() # newest first, as job_list answers sidecar = path + ".jobs.json" + # The first save of a home runs before the state file's own directory exists. + os.makedirs(os.path.dirname(sidecar) or ".", exist_ok=True) fd, temporary = tempfile.mkstemp( dir=os.path.dirname(sidecar) or ".", prefix=".jobs." ) diff --git a/src/albedo/daemon/session_namespace.gleam b/src/albedo/daemon/session_namespace.gleam index 31a50cbeb..f22e25435 100644 --- a/src/albedo/daemon/session_namespace.gleam +++ b/src/albedo/daemon/session_namespace.gleam @@ -262,20 +262,20 @@ fn missed_names(missed: List(#(String, String))) -> String { |> string.join(", ") } +/// What the model is told when a saved namespace came back, or nothing. A +/// restore is lossless when no variable was missed, no job or cell ended, every +/// definition re-ran, and the kernel reports no retained output or job book +/// lost; it says nothing then. A state saved before the kernel reported that +/// is not known lossless. Library-internal module state is not detectable and +/// does not count. fn restored_notice( saved: python.Saved, jobs: List(String), cells: List(#(String, String)), -) -> String { - case saved.missed, jobs, cells { - [], [], [] -> - "The python namespace was restored from disk." - <> case saved.defs { - [] -> "" - _ -> " Functions, classes, and imports were re-run from source." - } - <> "" - _, _, _ -> detailed_restored_notice(saved, jobs, cells) +) -> Option(String) { + case saved.missed, jobs, cells, saved.output_lost { + [], [], [], Some([]) -> None + _, _, _, _ -> Some(detailed_restored_notice(saved, jobs, cells)) } } @@ -372,7 +372,7 @@ pub fn released_text( ) -> String { let prefix = "python kernel released: " <> reason <> "; " case saved { - Ok(python.Saved([_, ..] as names, missed, engine, _defs, _largest)) -> + Ok(python.Saved([_, ..] as names, missed, engine, _defs, _largest, _lost)) -> prefix <> int.to_string(list.length(names)) <> " variables saved to disk" @@ -412,10 +412,10 @@ pub fn ready( fn adopted( state: session_state.State(message), kernel: runtime.Session, - notice: String, + notice: Option(String), text: String, ) -> session_state.State(message) { - session_state.State(..state, kernel: Some(kernel), notice: Some(notice)) + session_state.State(..state, kernel: Some(kernel), notice: notice) |> session_state.emit(view.note("daemon", text)) } @@ -589,7 +589,7 @@ fn upgraded( adopted( state, kernel, - upgraded_notice(carried, ended), + Some(upgraded_notice(carried, ended)), upgraded_text(carried, ended), ) } @@ -699,7 +699,7 @@ fn revive_saved( None -> Error(python.Invalid("session has no state file")) } case revived { - Ok(python.Saved([_, ..], _, _, _, _) as saved) -> + Ok(python.Saved([_, ..], _, _, _, _, _) as saved) -> adopted( state, kernel, @@ -710,7 +710,7 @@ fn revive_saved( adopted( state, kernel, - lost_notice_for(jobs, ended), + Some(lost_notice_for(jobs, ended)), lost_text(jobs, ended), ) } diff --git a/src/albedo/harness/extensions/python/kernel.gleam b/src/albedo/harness/extensions/python/kernel.gleam index 3fb3c23b9..cf8b84b78 100644 --- a/src/albedo/harness/extensions/python/kernel.gleam +++ b/src/albedo/harness/extensions/python/kernel.gleam @@ -217,6 +217,9 @@ pub type Saved { engine: String, defs: List(String), largest: List(#(String, Int)), + /// Retained cell output and job book that did not come back; `None` for a + /// state saved before the kernel reported it, which is not known lossless. + output_lost: Option(List(String)), ) } @@ -281,6 +284,11 @@ fn saved_decoder() -> decode.Decoder(Result(Saved, Error)) { [], decode.list(largest_entry), ) + use output_lost <- decode.optional_field( + "output_lost", + None, + decode.map(names, Some), + ) use failure <- decode.optional_field("error", "", decode.string) decode.success(case failure { "" -> @@ -290,6 +298,7 @@ fn saved_decoder() -> decode.Decoder(Result(Saved, Error)) { engine, defs, largest, + output_lost, )) message -> Error(Invalid(message)) }) @@ -902,15 +911,14 @@ pub fn upgrade( }) use restored <- result.try(case saved { None -> - Ok( - Saved( - [], - [#("namespace", "the old kernel could not save it")], - "", - [], - [], - ), - ) + Ok(Saved( + [], + [#("namespace", "the old kernel could not save it")], + "", + [], + [], + None, + )) Some(snapshot) -> restore(kernel, path, state_timeout) |> result.map(fn(restored) { diff --git a/test/e2e/idle_reap_test.py b/test/e2e/idle_reap_test.py index 62770475e..a6b2e8734 100644 --- a/test/e2e/idle_reap_test.py +++ b/test/e2e/idle_reap_test.py @@ -114,10 +114,8 @@ class IdleReapTests(unittest.TestCase): self.turn(session, "recall them") prompt = latest_user(self.provider.requests[-1]["request"]) - self.assertTrue(prompt.startswith("recall them"), prompt) - self.assertIn("namespace was restored from disk", prompt) - self.assertNotIn("variables are gone", prompt) - self.assertNotIn("earlier cells are gone", prompt) + # A restore that lost nothing tells the model nothing. + self.assertEqual(prompt, "recall them") self.assertTrue( any( "recalled 7 [1, 2, 3]" in item.get("output", "") @@ -146,7 +144,7 @@ class IdleReapTests(unittest.TestCase): for item in self.provider.requests[-1]["request"]["input"] ] self.assertTrue( - any("handles helper [1] 0 true EndedJob" in output for output in outputs), + any("handles helper [1] 0 true Job" in output for output in outputs), outputs, ) diff --git a/test/e2e/kernel_lazy_test.py b/test/e2e/kernel_lazy_test.py index d347d438b..ac84c71da 100644 --- a/test/e2e/kernel_lazy_test.py +++ b/test/e2e/kernel_lazy_test.py @@ -166,12 +166,13 @@ class KernelLazyTests(unittest.TestCase): any("recalled 7 [1, 2, 3]" in item.get("output", "") for item in after), after, ) + # The restore lost nothing, so the model is told nothing. notices = [ json.dumps(item) for item in after - if item.get("role") == "user" and "restored from disk" in json.dumps(item) + if item.get("role") == "user" and "" in json.dumps(item) ] - self.assertEqual(len(notices), 1, after) + self.assertEqual(notices, [], after) def test_interrupt_while_the_kernel_starts_runs_no_cell(self): slow = Path("/tmp") / f"albedo-slow-{time.monotonic_ns()}" diff --git a/test/e2e/kernel_state_test.py b/test/e2e/kernel_state_test.py index b2cbd8705..9f43d8736 100644 --- a/test/e2e/kernel_state_test.py +++ b/test/e2e/kernel_state_test.py @@ -95,7 +95,5 @@ class KernelStateTests(unittest.TestCase): self.turn(session, "recall") output = self.outputs() self.assertIn("RESULT 42 3 [1] 7 5 alive b xml.dom False False False", output) - notice = latest_user(self.provider.requests[-2]["request"]) - self.assertIn("re-run from source", notice) - self.assertIn("namespace was restored from disk", notice) - self.assertNotIn("earlier cells are gone", notice) + # Every definition re-ran, so the restore is lossless and silent. + self.assertEqual(latest_user(self.provider.requests[-2]["request"]), "recall") diff --git a/test/e2e/release_request_test.py b/test/e2e/release_request_test.py index 89e417b0d..373574f7e 100644 --- a/test/e2e/release_request_test.py +++ b/test/e2e/release_request_test.py @@ -41,6 +41,11 @@ class ReleaseRequestTests(unittest.TestCase): app.prompt(session, "again").close() app.idle(session) requests = [item["request"] for item in provider.requests] + self.assertEqual( + latest_user(provider.requests[before]["request"]), + "again", + "a lossless restore added a note to the turn", + ) last_before, first_after = requests[before - 1], requests[before] self.assertEqual(first_after["tools"], last_before["tools"]) self.assertEqual( -- knotmirror 0.0.1 From 7051c59ea9b791912847d96d34786b4a44f08e79 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 10:30:27 -0400 Subject: [PATCH 52/72] Rebuild /context on demand without requiring the last call's recorded prefix --- src/albedo/daemon/session_last_call.gleam | 25 +++++++++-------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/src/albedo/daemon/session_last_call.gleam b/src/albedo/daemon/session_last_call.gleam index d7557b380..29cb57489 100644 --- a/src/albedo/daemon/session_last_call.gleam +++ b/src/albedo/daemon/session_last_call.gleam @@ -43,9 +43,12 @@ pub fn restore( } } -/// The last turn call's request with what the strategy observed building it, -/// for a read of the prepared context after the kernel and snapshot went, or -/// `None` on the same conditions as `restore`. +/// The request the last turn call would send now, with what the strategy +/// observed building it, for a read of the prepared context after the kernel +/// and snapshot went. Unlike `restore` it does not require the prefix identity +/// the turn recorded: an inspector shows the rebuilt request, which a changed +/// instruction or saved strategy state may have moved. `None` when there is no +/// such turn or it was another model or provider. pub fn restore_context( state: session_state.State(message), ) -> #( @@ -53,18 +56,10 @@ pub fn restore_context( Option(#(types.Request, Option(compaction.Observation), types.Protocol)), ) { case rebuild(state) { - Ok(#(state, Some(rebuilt))) -> - case rebuilt.prefix == requests.row_prefix(rebuilt.turn) { - True -> #( - state, - Some(#( - rebuilt.request, - rebuilt.observation, - rebuilt.upstream.protocol, - )), - ) - False -> #(state, None) - } + Ok(#(state, Some(rebuilt))) -> #( + state, + Some(#(rebuilt.request, rebuilt.observation, rebuilt.upstream.protocol)), + ) Ok(#(state, None)) -> #(state, None) Error(_) -> #(state, None) } -- knotmirror 0.0.1 From 69282477c6902c1b16bfdfca37c405913e92ddcf Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 10:37:04 -0400 Subject: [PATCH 53/72] Create the kernel run directory in the daemon before launching it --- .../harness/extensions/python/albedo_python.erl | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/albedo/harness/extensions/python/albedo_python.erl b/src/albedo/harness/extensions/python/albedo_python.erl index 1d2545cc7..0d26097d0 100644 --- a/src/albedo/harness/extensions/python/albedo_python.erl +++ b/src/albedo/harness/extensions/python/albedo_python.erl @@ -414,7 +414,8 @@ open_bridge(S = #{python := Python, bridge := Bridge, run_dir := RunDir}, Mode) open_relay(S = #{python := Python, bridge := Bridge, run_dir := RunDir}, Mode) -> Owner = self(), Launch = case Mode of - start -> {Python, [<<"-u">>, filename:join(filename:dirname(Bridge), <<"albedo_kernel.py">>), + start -> ok = ensure_run_dir(RunDir), + {Python, [<<"-u">>, filename:join(filename:dirname(Bridge), <<"albedo_kernel.py">>), <<"--run">>, RunDir, maps:get(modules, S)], maps:get(cwd, S), maps:get(token, S)}; attach -> none @@ -428,6 +429,14 @@ open_relay(S = #{python := Python, bridge := Bridge, run_dir := RunDir}, Mode) - end), {ok, handshake(S#{bundle => bundle_digest(filename:dirname(Bridge))}, Relay, [])}. +%% The kernel chdirs into its run directory before anything else, so the daemon +%% makes it rather than trusting the entry script to: a replaced or older +%% entry script (a test gate, a bundle from before `--run`) skips that step. +ensure_run_dir(RunDir) -> + ok = filelib:ensure_dir(filename:join(RunDir, <<"x">>)), + _ = file:change_mode(RunDir, 8#700), + ok. + handshake(S, Port, First) -> Attach = #{attach => #{kernel => maps:get(kernel, S), token => maps:get(token, S), ack => maps:get(in, S), grace => maps:get(grace, S)}}, -- knotmirror 0.0.1 From c157791386ac9487567143e3735a52bf3090ccd0 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 10:52:20 -0400 Subject: [PATCH 54/72] Remote kernel tests that need a resident kernel or no local helper run with the pool off --- test/e2e/remote_kernels_test.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/e2e/remote_kernels_test.py b/test/e2e/remote_kernels_test.py index a43196ca0..2b227def7 100644 --- a/test/e2e/remote_kernels_test.py +++ b/test/e2e/remote_kernels_test.py @@ -815,6 +815,7 @@ print('live spill pages, disk failures, atomic saves, and pruning verified') self.assertEqual(host["state"], "needs_auth", host) self.assertTrue(host["authentication"]["control_path"].endswith("/%C"), host) + @resident_kernel def test_a_remote_kernel_is_ended_on_its_host_never_here(self): session = self.create(f"fakehost:{self.project}")["id"] started = self.cell( -- knotmirror 0.0.1 From 271332e52c1aa589431239e7ce8ea34e52c78f71 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 11:07:26 -0400 Subject: [PATCH 55/72] Collect a turn's request-building garbage before it waits on the provider --- src/albedo/daemon/session_run.gleam | 6 ++++++ src/albedo/openai_api/albedo_openai_transport.erl | 12 +++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/albedo/daemon/session_run.gleam b/src/albedo/daemon/session_run.gleam index 48bca75fa..12b182a75 100644 --- a/src/albedo/daemon/session_run.gleam +++ b/src/albedo/daemon/session_run.gleam @@ -367,6 +367,9 @@ pub fn stoppable( process.kill(helper) #(Error(types.Cancelled), ServedCall(None, None)) }) + // The request is built; what building it left behind need not + // stay on the worker's heap for the whole provider wait. + let _ = collect_garbage() let #(outcome, served) = await_stream(helper, selector, stop) save_call(slot, served) process.demonitor_process(monitor) @@ -397,6 +400,9 @@ fn await_stream( } } +@external(erlang, "erlang", "garbage_collect") +fn collect_garbage() -> Bool + @external(erlang, "albedo_native", "new_id") fn new_id() -> String diff --git a/src/albedo/openai_api/albedo_openai_transport.erl b/src/albedo/openai_api/albedo_openai_transport.erl index 7cb9bcb13..667cdac5d 100644 --- a/src/albedo/openai_api/albedo_openai_transport.erl +++ b/src/albedo/openai_api/albedo_openai_transport.erl @@ -35,6 +35,9 @@ open(URL, Headers, Body, Timeout) {ok, State} -> Ref = make_ref(), put({?MODULE, Ref}, State), + %% Encoding the request left garbage the caller may sit on + %% for the whole response; drop it before waiting. + erlang:garbage_collect(), {ok, {albedo_http, self(), Ref}}; {error, _} = Error -> Error end; @@ -150,7 +153,7 @@ start(#{transport := Transport, host := Host, port := Port} = Request, ok -> Guard = maps:get(guard, Request), Retry = case {Pooled, Guard} of - {true, undefined} -> {Request, Headers, Body}; + {true, undefined} -> {Request, Headers, compact(Body)}; _ -> none end, {ok, #{socket => Socket, transport => Transport, @@ -251,6 +254,13 @@ write(Send, [{attest, _, _} = Segment | Rest], Hasher) -> Value = marker_value(Segment, Rest, Hasher), then(Send(Value), fun() -> write(Send, Rest, done) end). +%% A plain body as one binary: a retry keeps it off the heap, not as the +%% encoder's many small pieces. Segmented bodies stay as they are. +compact(Body) -> + try iolist_to_binary(Body) + catch error:badarg -> Body + end. + then(ok, Next) -> Next(); then({error, _} = Error, _) -> Error. -- knotmirror 0.0.1 From 49cd34d6aea3ee1c3fb2241b97305933ac8d720c Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 11:07:26 -0400 Subject: [PATCH 56/72] Copy only the fields the stream callbacks use into the stream process --- src/albedo/harness/loop.gleam | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/albedo/harness/loop.gleam b/src/albedo/harness/loop.gleam index f8994d8e7..a14cfb0d7 100644 --- a/src/albedo/harness/loop.gleam +++ b/src/albedo/harness/loop.gleam @@ -217,23 +217,26 @@ fn converse( prepared.observation, prepared.compacted, ) + // The stream callbacks run in the stream's own process and are copied there + // with everything they capture: they take these fields, not the loop state. + let #(run_id, publish, progress_delta) = #( + state.run_id, + state.publish, + state.progress_delta, + ) let answer = fn(request: types.Request, original: List(types.Input)) { call( call_context(state), requests.Turn, request, request_prefix(request, original, prepared.observation), - state.publish, + publish, fn(event) { case - view.stream_event( - state.run_id, - state.run_id <> ":" <> int.to_string(step), - event, - ) + view.stream_event(run_id, run_id <> ":" <> int.to_string(step), event) { Some(serialized) -> - case state.publish(serialized) { + case publish(serialized) { True -> types.Continue False -> types.Stop } @@ -243,9 +246,7 @@ fn converse( fn(attempt, event) { case event { types.ArgumentsDelta(output_index, name, fragment) -> - case - state.progress_delta(step, attempt, output_index, name, fragment) - { + case progress_delta(step, attempt, output_index, name, fragment) { True -> types.Continue False -> types.Stop } -- knotmirror 0.0.1 From c0e1021d10fb1e5d806bbb3a0f58e4eae2a9bdd7 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 11:15:06 -0400 Subject: [PATCH 57/72] stalls: busy_port and max_lines options, so the test's monitor hears only its own fixture on a loaded machine --- src/albedo/daemon/albedo_stalls.erl | 20 +++++++++++--------- test/daemon/albedo_stalls_test.erl | 9 +++++---- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/albedo/daemon/albedo_stalls.erl b/src/albedo/daemon/albedo_stalls.erl index 5ba355927..a92d4c954 100644 --- a/src/albedo/daemon/albedo_stalls.erl +++ b/src/albedo/daemon/albedo_stalls.erl @@ -11,8 +11,9 @@ start() -> start(#{}). -%% Options: long_gc and long_schedule in ms, large_heap in words, report/1 for -%% each line, and name (the registered name, `undefined` for none). Returns +%% Options: long_gc and long_schedule in ms, large_heap in words, busy_port +%% (default true), max_lines per window, report/1 for each line, and name (the +%% registered name, `undefined` for none). Returns %% once the monitor is installed, so nothing after it goes unwatched. start(Options) -> Name = maps:get(name, Options, ?MODULE), @@ -29,24 +30,25 @@ init(Parent, Options) -> erlang:system_monitor(self(), [ {long_gc, maps:get(long_gc, Options, 250)}, {long_schedule, maps:get(long_schedule, Options, 250)}, - {large_heap, maps:get(large_heap, Options, 4 * 1024 * 1024)}, - busy_port]), + {large_heap, maps:get(large_heap, Options, 4 * 1024 * 1024)} + | [busy_port || maps:get(busy_port, Options, true)]]), Parent ! {self(), watching}, Report = maps:get(report, Options, fun log/1), - loop(Report, erlang:monotonic_time(millisecond), 0, 0). + Max = maps:get(max_lines, Options, ?MAX_LINES), + loop(Report, Max, erlang:monotonic_time(millisecond), 0, 0). -loop(Report, Since, Lines, Dropped) -> +loop(Report, Max, Since, Lines, Dropped) -> receive {monitor, Pid, Kind, Info} -> Now = erlang:monotonic_time(millisecond), {Since1, Lines1, Dropped1} = window(Report, Now, Since, Lines, Dropped), Overloaded = element(2, process_info(self(), message_queue_len)) > ?MAX_QUEUE, - case Lines1 < ?MAX_LINES andalso not Overloaded of + case Lines1 < Max andalso not Overloaded of true -> Report(describe(Pid, Kind, Info)), - loop(Report, Since1, Lines1 + 1, Dropped1); + loop(Report, Max, Since1, Lines1 + 1, Dropped1); false -> - loop(Report, Since1, Lines1, Dropped1 + 1) + loop(Report, Max, Since1, Lines1, Dropped1 + 1) end end. diff --git a/test/daemon/albedo_stalls_test.erl b/test/daemon/albedo_stalls_test.erl index 31af6b634..cbd648a20 100644 --- a/test/daemon/albedo_stalls_test.erl +++ b/test/daemon/albedo_stalls_test.erl @@ -6,11 +6,12 @@ names_the_process_with_a_large_heap_test() -> Previous = erlang:system_monitor(), Parent = self(), - %% Only the fixture's heap passes this bound, and long schedules and - %% collections are off: other tests' events would spend the window's - %% line budget before the fixture's arrives. + %% Only the fixture's heap passes this bound; long schedules and + %% collections and busy ports are off, and the budget is unbounded, so + %% other tests' events on a loaded machine cannot crowd the fixture out. Monitor = albedo_stalls:start(#{name => undefined, large_heap => 3000000, - long_gc => 3600000, long_schedule => 3600000, + long_gc => 3600000, long_schedule => 3600000, busy_port => false, + max_lines => 1000000, report => fun(Line) -> Parent ! {stall, lists:flatten(Line)} end}), try spawn(fun() -> -- knotmirror 0.0.1 From 7ce9c2b6e74b1b1a98ee7c4d725f60cda9972ca6 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 11:19:27 -0400 Subject: [PATCH 58/72] Density benchmark: CPU seconds per idle window and per operation --- test/manual/agent_density.py | 115 +++++++++++++++++++++++++++++++++-- 1 file changed, 109 insertions(+), 6 deletions(-) diff --git a/test/manual/agent_density.py b/test/manual/agent_density.py index 058cb2300..8a41cbb38 100644 --- a/test/manual/agent_density.py +++ b/test/manual/agent_density.py @@ -103,7 +103,52 @@ def processes(app): return result -def measure(app, label, count, baseline): +_TIMEBASE = None + + +def process_cpu(pid): + """User plus system CPU seconds a live process has used, or None if gone.""" + global _TIMEBASE + if sys.platform == "darwin": + buffer = ctypes.create_string_buffer(96) + libproc = ctypes.CDLL("/usr/lib/libproc.dylib") + if libproc.proc_pid_rusage(pid, 0, buffer) != 0: + return None + user, system = struct.unpack_from("=QQ", buffer.raw, 16) + if _TIMEBASE is None: + # rusage times are mach absolute ticks, not nanoseconds on arm64. + info = (ctypes.c_uint32 * 2)() + ctypes.CDLL("/usr/lib/libSystem.dylib").mach_timebase_info(info) + _TIMEBASE = info[0] / info[1] + return (user + system) * _TIMEBASE / 1e9 + try: + fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split() + except OSError: + return None + return (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK") + + +def cpu_snapshot(app): + """CPU seconds of the daemon and its Python processes, by pid and kind.""" + snapshot = {} + for item in processes(app): + seconds = process_cpu(item["pid"]) + if seconds is not None: + snapshot[item["pid"]] = (item["kind"], seconds) + return snapshot + + +def cpu_spent(before, after): + """CPU used between two snapshots, by kind; a process that started in + between counts from zero, one that ended in between is lost.""" + spent = {} + for pid, (kind, seconds) in after.items(): + start = before[pid][1] if pid in before else 0.0 + spent[kind] = spent.get(kind, 0.0) + max(0.0, seconds - start) + return spent + + +def measure(app, label, count, baseline, window=0.0): items = processes(app) for item in items: item["bytes"] = process_bytes(item["pid"]) @@ -120,12 +165,28 @@ def measure(app, label, count, baseline): "processes": items, "beam": json.loads(memory), } + if window > 0: + before = cpu_snapshot(app) + time.sleep(window) + spent = cpu_spent(before, cpu_snapshot(app)) + total = sum(spent.values()) + result["idle_cpu"] = { + "window_s": window, + "cpu_s": total, + "by_kind": spent, + "per_agent_ms_per_s": total / count / window * 1000, + } print( json.dumps( { key: value for key, value in result.items() - if key not in ("processes", "beam") + if key not in ("processes", "beam", "idle_cpu") + } + | { + "idle_cpu_ms_per_agent_s": result.get("idle_cpu", {}).get( + "per_agent_ms_per_s" + ) } ), flush=True, @@ -140,6 +201,12 @@ def main(): parser.add_argument("--idle-seconds", type=int, default=3600) parser.add_argument("--settle", type=float, default=0.2) parser.add_argument("--output", type=Path, required=True) + parser.add_argument( + "--idle-window", + type=float, + default=0.0, + help="seconds of CPU sampling after each idle state's memory reading", + ) parser.add_argument( "--burst", type=int, @@ -239,8 +306,19 @@ def main(): app.idle(recipient) baseline = sum(process_bytes(item["pid"]) for item in processes(app)) result["empty_daemon_bytes"] = baseline + if args.idle_window > 0: + before = cpu_snapshot(app) + time.sleep(args.idle_window) + spent = cpu_spent(before, cpu_snapshot(app)) + result["empty_idle_cpu"] = { + "window_s": args.idle_window, + "cpu_s": sum(spent.values()), + "by_kind": spent, + } sessions = [app.session() for _ in range(args.agents)] - result["states"].append(measure(app, "created", args.agents, baseline)) + result["states"].append( + measure(app, "created", args.agents, baseline, args.idle_window) + ) def turn(pair): session, prompt = pair @@ -259,9 +337,27 @@ def main(): ) ) + phase_cpu = result["phase_cpu"] = {} + + def charge(name, operations, before): + spent = cpu_spent(before, cpu_snapshot(app)) + total = sum(spent.values()) + phase_cpu[name] = { + "operations": operations, + "cpu_s": total, + "by_kind": spent, + "per_operation_ms": total / operations * 1000, + } + + before = cpu_snapshot(app) turns("define") time.sleep(args.settle) - result["states"].append(measure(app, "resting", args.agents, baseline)) + # A cell in a new session, then whatever release the settle allows. + charge("first_turn_and_release", args.agents, before) + result["states"].append( + measure(app, "resting", args.agents, baseline, args.idle_window) + ) + before = cpu_snapshot(app) latencies = [] for index in range(args.samples): prompt = f"recall:{index}" @@ -273,6 +369,9 @@ def main(): latencies.append((finished[prompt] - started) * 1000) app.idle(sessions[index % len(sessions)]) time.sleep(args.settle) + # Each sample restores a namespace if it was released, runs a cell, + # and settles, which may release it again. + charge("recall_turn", args.samples, before) ordered = sorted(latencies) result["first_cell_ms"] = { "samples": latencies, @@ -280,6 +379,7 @@ def main(): "p95": ordered[math.ceil(len(ordered) * 0.95) - 1], } if args.burst: + before = cpu_snapshot(app) prompts = [f"recall:burst{i}" for i in range(args.burst)] started = time.perf_counter() submitted = {} @@ -305,10 +405,13 @@ def main(): } for index in range(args.burst): app.idle(sessions[index % len(sessions)], timeout=180) + charge("burst", args.burst, before) print(json.dumps(result["burst_ms"]), flush=True) turns("mail") time.sleep(args.settle) - result["states"].append(measure(app, "waiting_mail", args.agents, baseline)) + result["states"].append( + measure(app, "waiting_mail", args.agents, baseline, args.idle_window) + ) for index, session in enumerate(sessions): app.prompt(session, f"model:{index}").close() with condition: @@ -318,7 +421,7 @@ def main(): raise AssertionError(f"only {len(held)} model waits admitted") time.sleep(args.settle) result["states"].append( - measure(app, "waiting_model", args.agents, baseline) + measure(app, "waiting_model", args.agents, baseline, args.idle_window) ) release_model.set() for session in sessions: -- knotmirror 0.0.1 From 5c3026a7d33902ebd130a8d5114749e944910520 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 12:00:50 -0400 Subject: [PATCH 59/72] Wake a waiting worker on cancel instead of polling its stop latch every 25 ms --- src/albedo/daemon/albedo_session.erl | 8 +++++- src/albedo/daemon/session_run.gleam | 41 ++++++++++++++++------------ src/albedo/daemon/turn.gleam | 23 ++++++++++++++-- test/daemon/session_run_test.gleam | 8 ++++-- 4 files changed, 57 insertions(+), 23 deletions(-) diff --git a/src/albedo/daemon/albedo_session.erl b/src/albedo/daemon/albedo_session.erl index 709c74ba0..ea8642f40 100644 --- a/src/albedo/daemon/albedo_session.erl +++ b/src/albedo/daemon/albedo_session.erl @@ -1,5 +1,5 @@ -module(albedo_session). --export([kill/1, discard/1, collect/0, collect_over/1, activity/2, quiet/2, decode_submission/1, new_generation/0]). +-export([kill/1, discard/1, collect/0, collect_over/1, activity/2, quiet/2, decode_submission/1, new_generation/0, wake_run/1]). kill(Pid) -> exit(Pid,kill), nil. %% Monotonic: idle time must not move when the wall clock does. %% The saved job book (`.jobs.json`, robot-docs/kernel.md) goes with its state. @@ -40,3 +40,9 @@ decode_submission(Payload) -> binary_to_term(Payload, [safe]). new_generation() -> base64:encode(crypto:strong_rand_bytes(16), #{mode => urlsafe, padding => false}). + +%% Tells a run's worker its cancel latch went up, so a worker waiting on its +%% provider wakes for it instead of polling the latch. +wake_run(Pid) -> + Pid ! {albedo_run_stop}, + nil. diff --git a/src/albedo/daemon/session_run.gleam b/src/albedo/daemon/session_run.gleam index 12b182a75..bb34162e4 100644 --- a/src/albedo/daemon/session_run.gleam +++ b/src/albedo/daemon/session_run.gleam @@ -306,10 +306,9 @@ fn report(owner: Subject(message), make: fn(Subject(Nil)) -> message) -> Nil { Nil } -/// How often a worker waiting on the provider checks its run's stop latch. -/// The check is one atomic read, so the cost is wakeups, and an interrupt -/// settles within one interval of the latch going up. -const stop_poll_ms = 25 +/// How often a waiting worker reads its latch anyway. A cancel wakes it at +/// once (`turn.select_stop`); this only bounds a wake that went missing. +const stop_poll_ms = 60_000 type ServedCall { ServedCall(account: Option(String), explanation: Option(String)) @@ -361,12 +360,9 @@ pub fn stoppable( }) let selector = process.new_selector() - |> process.select_map(answer, fn(outcome) { outcome }) - |> process.select_specific_monitor(monitor, fn(_) { - process.unlink(helper) - process.kill(helper) - #(Error(types.Cancelled), ServedCall(None, None)) - }) + |> process.select_map(answer, Ok) + |> process.select_specific_monitor(monitor, fn(_) { Error(Nil) }) + |> turn.select_stop(Error(Nil)) // The request is built; what building it left behind need not // stay on the worker's heap for the whole provider wait. let _ = collect_garbage() @@ -380,26 +376,35 @@ pub fn stoppable( ) } +/// The helper's answer, or `Cancelled` once the run is stopped or its session +/// is gone (the selector answers `Error(Nil)` for both). fn await_stream( helper: process.Pid, - selector: process.Selector(#(Result(types.Turn, types.Error), ServedCall)), + selector: process.Selector( + Result(#(Result(types.Turn, types.Error), ServedCall), Nil), + ), stop: turn.Latch, ) -> #(Result(types.Turn, types.Error), ServedCall) { case turn.raised(stop) { - True -> { - // Unlink before killing so the helper's forced exit cannot kill its worker. - process.unlink(helper) - process.kill(helper) - #(Error(types.Cancelled), ServedCall(None, None)) - } + True -> abandon(helper) False -> case process.selector_receive(selector, stop_poll_ms) { - Ok(outcome) -> outcome + Ok(Ok(outcome)) -> outcome + Ok(Error(Nil)) -> abandon(helper) Error(Nil) -> await_stream(helper, selector, stop) } } } +fn abandon( + helper: process.Pid, +) -> #(Result(types.Turn, types.Error), ServedCall) { + // Unlink before killing so the helper's forced exit cannot kill its worker. + process.unlink(helper) + process.kill(helper) + #(Error(types.Cancelled), ServedCall(None, None)) +} + @external(erlang, "erlang", "garbage_collect") fn collect_garbage() -> Bool diff --git a/src/albedo/daemon/turn.gleam b/src/albedo/daemon/turn.gleam index aa3c621b4..fa30743ba 100644 --- a/src/albedo/daemon/turn.gleam +++ b/src/albedo/daemon/turn.gleam @@ -1,14 +1,15 @@ //// A session's run bookkeeping as plain values: what a submission may do, //// whether a late worker message still belongs to the active run, and which //// stage a finished run leaves behind. The session actor performs every -//// effect but the cancel latch; these functions only decide, so the rules -//// are testable without a kernel, a provider, or an actor. +//// effect but the cancel latch and its wake; these functions only decide, so +//// the rules are testable without a kernel, a provider, or an actor. import albedo/daemon/conversation import albedo/daemon/mail import albedo/harness/compaction import albedo/openai_api/types import gleam/dynamic.{type Dynamic} +import gleam/erlang/atom import gleam/erlang/process import gleam/list import gleam/option.{type Option, None, Some} @@ -136,6 +137,23 @@ pub fn raised(latch: Latch) -> Bool { get(latch, 1) == 1 } +@external(erlang, "albedo_session", "wake_run") +fn wake(worker: process.Pid) -> Nil + +/// `selector`, also answering `stopped` once the session raised this +/// worker's latch: the cancel that raises it also wakes the worker. +pub fn select_stop( + selector: process.Selector(payload), + stopped: payload, +) -> process.Selector(payload) { + process.select_record( + selector, + tag: atom.create("albedo_run_stop"), + fields: 0, + mapping: fn(_) { stopped }, + ) +} + pub type Activity { Resting /// Idle after a restart that found an unfinished turn it did not resume. @@ -285,6 +303,7 @@ pub fn cancel(activity: Activity, cut_off: List(String)) -> Activity { case running(activity) { Some(run) -> { raise(run.stop) + wake(run.pid) Running(Run(..run, cancelled: True, cut_off:)) } None -> activity diff --git a/test/daemon/session_run_test.gleam b/test/daemon/session_run_test.gleam index c653813b5..e338977c8 100644 --- a/test/daemon/session_run_test.gleam +++ b/test/daemon/session_run_test.gleam @@ -164,7 +164,11 @@ pub fn a_stalled_commit_ends_the_turn_without_a_retry_test() -> Nil { } fn cancel(stop: turn.Latch) -> Nil { - let pid = process.self() + cancel_worker(stop, process.self()) +} + +/// Cancels a run whose worker is `pid`, which the cancel wakes. +fn cancel_worker(stop: turn.Latch, pid: process.Pid) -> Nil { let monitor = process.monitor(pid) let _ = turn.cancel( @@ -348,7 +352,7 @@ fn idle_provider_cleanup(owner_dies: Bool) -> Nil { process.unlink(owner_pid) process.kill(owner_pid) } - False -> cancel(stop) + False -> cancel_worker(stop, worker) } process.receive(finished, 1000) |> should.equal(Ok(Error(types.Cancelled))) process.new_selector() -- knotmirror 0.0.1 From bb144bc830ec34da69eca138dd2612fb75d62e8d Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 14:53:21 -0400 Subject: [PATCH 60/72] test runner: run each module's tests in order; a bare module under inparallel ran its tests concurrently --- test/albedo_test_runner.erl | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/albedo_test_runner.erl b/test/albedo_test_runner.erl index 4c3df4aca..52033f0af 100644 --- a/test/albedo_test_runner.erl +++ b/test/albedo_test_runner.erl @@ -1,6 +1,8 @@ %% gleeunit's runner with every test module started at once, after the timed %% ones. A module's tests keep running in order, one after another, so tests -%% that share a module's fixtures never race each other. There is no cap: +%% that share a module's fixtures never race each other: each module is its own +%% {inorder, _} group, since a bare module under {inparallel, _} inherits that +%% order and runs its tests concurrently too. There is no cap: %% eunit's {inparallel, N, _} runs batches of N and waits out each batch's %% slowest module. -module(albedo_test_runner). @@ -30,7 +32,8 @@ main() -> {report, {gleeunit_progress, [{colored, true}]}}, {scale_timeouts, 10} ], - Result = eunit:test([{inorder, Timed}, {inparallel, Modules -- Timed}], Options), + Result = eunit:test( + [{inorder, Timed}, {inparallel, [{inorder, M} || M <- Modules -- Timed]}], Options), albedo_test_home:cleanup(), erlang:halt(case Result of ok -> 0; _ -> 1 end). -- knotmirror 0.0.1 From 8a6a0e2f8e4b32b08cf966895ab8c32340022d73 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 16:34:30 -0400 Subject: [PATCH 61/72] Walk a new session's sources fewer times and look each shared path component up once per walk --- robot-docs/runtime.md | 2 +- .../extensions/skills/albedo_skills.erl | 40 +++++++++++++++--- src/albedo/harness/runtime/catalog.gleam | 11 +++++ src/albedo/harness/runtime/observation.gleam | 10 ++++- test/e2e/albedo_observe_probe.erl | 26 ++++++++++++ test/e2e/observation_walk_test.py | 42 +++++++++++++++++++ 6 files changed, 123 insertions(+), 8 deletions(-) create mode 100644 test/e2e/albedo_observe_probe.erl create mode 100644 test/e2e/observation_walk_test.py diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index 809e72cad..ada17f7ce 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -152,7 +152,7 @@ Session read messages, including capture, status, summary, stream replay, and id Session lifecycle waits also stay off the session actor. Release saves variables on a worker, parks kernel-dependent work, then enqueues Reset from the actor before replaying that work. Reset and the subsequent Open therefore preserve sender order; an expired acknowledgment wait never retries Reset. Workspace teardown parks boot requests and reports `preparing` until its worker confirms deletion, then acknowledges the captured workspace revision and replays them. Run completion settles pending workspace intent before publishing idle; a superseding move stays preparing through its own teardown. Deletion cancels the run before killing its worker, so a worker-down message during asynchronous teardown still records interruption, not failure. Child-work checks for unload and rewind run off-actor and recheck the session's own idleness on completion. Awaited observations are closures finished by their callers; stale kernel notifications without a held kernel are ignored. Remote workspace readiness follows the same rule: SSH reachability probes run off the session actor, and a generation-checked reply resumes the queued turn. -Capture and status reads never call the runtime actor from the session actor. The runtime observes composition on boot slots; kernel teardown runs on separate monitored stop slots. The session answers with a closure (`Unobserved`, `session_namespace.kernel_observer`) that the caller finishes: a session without a held kernel learns what the runtime has loaded there, under the same 15 s budget as the composition observation. A read made while the runtime is busy waits for it instead of failing at the session's 5 s call deadline, and the session keeps answering everything else meanwhile. +Capture and status reads never call the runtime actor from the session actor. The runtime observes composition on boot slots; kernel teardown runs on separate monitored stop slots. The session answers with a closure (`Unobserved`, `session_namespace.kernel_observer`) that the caller finishes: a session without a held kernel learns what the runtime has loaded there, under the same 15 s budget as the composition observation. A read made while the runtime is busy waits for it instead of failing at the session's 5 s call deadline, and the session keeps answering everything else meanwhile. A session's first observation walks its skill and instruction files for the retained-discovery key and once more to confirm they did not change; discovery itself does not walk them a third time (`session_catalog.inspect_with` takes the inputs already read), and one walk looks each shared path component up once (`albedo_skills:with_link_memo`), since every lookup waits for the CPU on a loaded machine. Writer callbacks held for at least one second are logged once with their duration, caller label, and generated callback module/function name. Only function metadata is logged, never closure environments or SQL parameter values. diff --git a/src/albedo/harness/extensions/skills/albedo_skills.erl b/src/albedo/harness/extensions/skills/albedo_skills.erl index c934dbcb6..23f09a58c 100644 --- a/src/albedo/harness/extensions/skills/albedo_skills.erl +++ b/src/albedo/harness/extensions/skills/albedo_skills.erl @@ -13,6 +13,7 @@ -define(MAX_RESOURCE_ENTRIES, 2048). -define(MAX_RESOURCE_DEPTH, 16). -define(MAX_READ_BYTES, 65536). +-define(LINK_MEMO, albedo_skills_link_memo). xml_escape(Value) -> try @@ -64,8 +65,37 @@ catalog(Workspace, Home, Builtin) -> inputs(Workspace, Home, Builtin) -> Roots = roots(text_list(Workspace), text_list(Home)) ++ builtin_roots(text_list(Builtin)), - {Sources, _Count} = input_roots(Roots, [], 0), - Sources. + with_link_memo(fun() -> + {Sources, _Count} = input_roots(Roots, [], 0), + Sources + end). + +%% One walk resolves every skill's directory and file through the same path +%% prefixes. Within the walk each component is looked at once instead of once +%% per skill: on a machine starved of CPU every look is a wait, so the same +%% facts are read in far fewer of them. +with_link_memo(Fun) -> + Outer = put(?LINK_MEMO, #{}), + try Fun() + after + case Outer of + undefined -> erase(?LINK_MEMO); + _ -> put(?LINK_MEMO, Outer) + end + end. + +link_info(Path) -> + case get(?LINK_MEMO) of + undefined -> file:read_link_info(Path); + Memo -> + case Memo of + #{Path := Known} -> Known; + _ -> + Fresh = file:read_link_info(Path), + put(?LINK_MEMO, Memo#{Path => Fresh}), + Fresh + end + end. input_roots([], Sources, Count) -> {lists:reverse(Sources), Count}; input_roots([Root | Rest], Sources, Count) when Count >= ?MAX_SKILLS -> @@ -83,7 +113,7 @@ input_entries(_Entries, Root, Sources, Count) when Count >= ?MAX_SKILLS -> {[{Root, limited} | Sources], Count}; input_entries([Entry | Rest], Root, Sources, Count) -> Path = filename:join(Root, Entry), - case file:read_link_info(Path) of + case link_info(Path) of {ok, #file_info{type = Type}} when Type =:= directory; Type =:= symlink -> case file:read_file_info(Path) of {ok, #file_info{type = directory}} -> @@ -634,7 +664,7 @@ resolve_path(Path, Depth) -> resolve_parts(Root, Parts, Depth). resolve_parts(Current, [], Depth) -> - case file:read_link_info(Current) of + case link_info(Current) of {ok, #file_info{type = symlink}} -> resolve_link(Current, [], Depth); {ok, _} -> {ok, filename:absname(Current)}; {error, Reason} -> {error, Reason} @@ -645,7 +675,7 @@ resolve_parts(Current, [".." | Rest], Depth) -> resolve_parts(filename:dirname(Current), Rest, Depth); resolve_parts(Current, [Part | Rest], Depth) -> Candidate = filename:join(Current, Part), - case file:read_link_info(Candidate) of + case link_info(Candidate) of {ok, #file_info{type = symlink}} -> resolve_link(Candidate, Rest, Depth); {ok, _} -> resolve_parts(Candidate, Rest, Depth); {error, Reason} -> {error, Reason} diff --git a/src/albedo/harness/runtime/catalog.gleam b/src/albedo/harness/runtime/catalog.gleam index fd11f8f66..a0d04de67 100644 --- a/src/albedo/harness/runtime/catalog.gleam +++ b/src/albedo/harness/runtime/catalog.gleam @@ -149,6 +149,17 @@ pub fn inspect( id: String, ) -> Result(Snapshot, String) { use observed_inputs <- result.try(inputs(home, inventory, id)) + inspect_with(home, inventory, id, observed_inputs) +} + +/// `inspect` for a caller that already read `observed_inputs` and rechecks +/// them afterwards, so the source files are not walked a second time. +pub fn inspect_with( + home: String, + inventory: Inventory, + id: String, + observed_inputs: Inputs, +) -> Result(Snapshot, String) { use captured <- result.try(conversation.capture(inventory.ledger, id)) use summaries <- result.try(selection.summaries( inventory.ledger, diff --git a/src/albedo/harness/runtime/observation.gleam b/src/albedo/harness/runtime/observation.gleam index c9787c990..560c0f71b 100644 --- a/src/albedo/harness/runtime/observation.gleam +++ b/src/albedo/harness/runtime/observation.gleam @@ -128,10 +128,11 @@ pub fn composition_basis( case list.find(retained, fn(value) { value.inputs == inputs.key }) { Ok(observation) -> Ok(Some(observation)) Error(_) -> { - use snapshot <- result.try(session_catalog.inspect( + use snapshot <- result.try(session_catalog.inspect_with( home, inventory, id, + inputs, )) use after <- result.try(session_catalog.inputs(home, inventory, id)) case after.key == inputs.key { @@ -162,7 +163,12 @@ pub fn desired( case list.find(retained, fn(value) { value.inputs == inputs.key }) { Ok(value) -> Ok(value) Error(_) -> { - use snapshot <- result.try(session_catalog.inspect(home, inventory, id)) + use snapshot <- result.try(session_catalog.inspect_with( + home, + inventory, + id, + inputs, + )) use after <- result.try(session_catalog.inputs(home, inventory, id)) case after.key == inputs.key { True -> Ok(runtime_state.Desired(inputs.key, inputs.saved, snapshot)) diff --git a/test/e2e/albedo_observe_probe.erl b/test/e2e/albedo_observe_probe.erl new file mode 100644 index 000000000..015d815b2 --- /dev/null +++ b/test/e2e/albedo_observe_probe.erl @@ -0,0 +1,26 @@ +%% Count how often the runtime walks sessions' source files, and how many +%% link lookups those walks make, between trace_start and trace_stop. +-module(albedo_observe_probe). +-export([trace_start/0, trace_stop/0]). + +count(Walks, Links) -> + receive + {trace, _, call, {albedo_runtime_catalog, inputs, _}} -> count(Walks + 1, Links); + {trace, _, call, {file, read_link_info, _}} -> count(Walks, Links + 1); + {report, From} -> From ! {counted, Walks, Links} + end. + +trace_start() -> + Tracer = spawn(fun() -> count(0, 0) end), + register(albedo_observe_tracer, Tracer), + {module, albedo_runtime_catalog} = code:ensure_loaded(albedo_runtime_catalog), + 1 = erlang:trace_pattern({albedo_runtime_catalog, inputs, 4}, true, [local]), + 1 = erlang:trace_pattern({file, read_link_info, 1}, true, [local]), + erlang:trace(all, true, [call, {tracer, Tracer}]), + json:encode(#{started => true}). + +trace_stop() -> + erlang:trace(all, false, [call]), + albedo_observe_tracer ! {report, self()}, + {Walks, Links} = receive {counted, W, L} -> {W, L} after 5000 -> error(no_report) end, + json:encode(#{walks => Walks, link_lookups => Links}). diff --git a/test/e2e/observation_walk_test.py b/test/e2e/observation_walk_test.py new file mode 100644 index 000000000..2b931c898 --- /dev/null +++ b/test/e2e/observation_walk_test.py @@ -0,0 +1,42 @@ +"""Creating a session walks its source files at most three times, cheaply. + +A session's first observation has no retained discovery: it reads every skill +and instruction file for the key and once more to check that nothing changed +while it discovered (two walks); a later observation of the same session +re-checks the retained discovery with one. Discovery also used to walk once +more inside, a fourth. A walk resolves every skill's directory and file one +path component at a time, which cost over a thousand link lookups for one new +session before a walk looked each shared component up once. On a loaded +machine each lookup waits for the CPU, so the extra walk and the repeated +lookups pushed session writes past the observation's deadline (503). Only the +daemon's real runtime shows how many times it walked, so this runs through an +inspected daemon. +""" + +import unittest + +from harness import ROOT, Albedo, Provider, exclusive, text +from inspect_support import Inspection + + +@exclusive +class ObservationWalkTests(unittest.TestCase): + def test_a_new_session_walks_its_sources_no_more_than_three_times(self): + provider = Provider(lambda request: text("ok")) + self.addCleanup(provider.close) + + def prepare(app): + app.daemon.env["ALBEDO_INSPECT"] = "1" + + with Albedo(provider, prepare=prepare) as app: + probe = Inspection(app, ROOT / "test/e2e/albedo_observe_probe.erl") + probe.call_json("trace_start") + app.session() + report = probe.call_json("trace_stop") + self.assertGreaterEqual(report["walks"], 1, report) + self.assertLessEqual(report["walks"], 3, report) + self.assertLessEqual(report["link_lookups"], 750, report) + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1 From 13a2b611223c269e767a2089d945d397f7accd29 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 16:29:44 -0400 Subject: [PATCH 62/72] Share the per-walk link lookups with skill discovery, not only the inputs walk --- robot-docs/runtime.md | 2 +- .../extensions/skills/albedo_skills.erl | 20 +++++++++++-------- test/e2e/observation_walk_test.py | 4 ++-- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index ada17f7ce..2a02c7da6 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -152,7 +152,7 @@ Session read messages, including capture, status, summary, stream replay, and id Session lifecycle waits also stay off the session actor. Release saves variables on a worker, parks kernel-dependent work, then enqueues Reset from the actor before replaying that work. Reset and the subsequent Open therefore preserve sender order; an expired acknowledgment wait never retries Reset. Workspace teardown parks boot requests and reports `preparing` until its worker confirms deletion, then acknowledges the captured workspace revision and replays them. Run completion settles pending workspace intent before publishing idle; a superseding move stays preparing through its own teardown. Deletion cancels the run before killing its worker, so a worker-down message during asynchronous teardown still records interruption, not failure. Child-work checks for unload and rewind run off-actor and recheck the session's own idleness on completion. Awaited observations are closures finished by their callers; stale kernel notifications without a held kernel are ignored. Remote workspace readiness follows the same rule: SSH reachability probes run off the session actor, and a generation-checked reply resumes the queued turn. -Capture and status reads never call the runtime actor from the session actor. The runtime observes composition on boot slots; kernel teardown runs on separate monitored stop slots. The session answers with a closure (`Unobserved`, `session_namespace.kernel_observer`) that the caller finishes: a session without a held kernel learns what the runtime has loaded there, under the same 15 s budget as the composition observation. A read made while the runtime is busy waits for it instead of failing at the session's 5 s call deadline, and the session keeps answering everything else meanwhile. A session's first observation walks its skill and instruction files for the retained-discovery key and once more to confirm they did not change; discovery itself does not walk them a third time (`session_catalog.inspect_with` takes the inputs already read), and one walk looks each shared path component up once (`albedo_skills:with_link_memo`), since every lookup waits for the CPU on a loaded machine. +Capture and status reads never call the runtime actor from the session actor. The runtime observes composition on boot slots; kernel teardown runs on separate monitored stop slots. The session answers with a closure (`Unobserved`, `session_namespace.kernel_observer`) that the caller finishes: a session without a held kernel learns what the runtime has loaded there, under the same 15 s budget as the composition observation. A read made while the runtime is busy waits for it instead of failing at the session's 5 s call deadline, and the session keeps answering everything else meanwhile. A session's first observation walks its skill and instruction files for the retained-discovery key and once more to confirm they did not change; discovery itself does not walk them a third time (`session_catalog.inspect_with` takes the inputs already read), and one walk or one discovery looks each shared path component up once (`albedo_skills:with_link_memo`), since every lookup waits for the CPU on a loaded machine. Writer callbacks held for at least one second are logged once with their duration, caller label, and generated callback module/function name. Only function metadata is logged, never closure environments or SQL parameter values. diff --git a/src/albedo/harness/extensions/skills/albedo_skills.erl b/src/albedo/harness/extensions/skills/albedo_skills.erl index 23f09a58c..eb8c4f09c 100644 --- a/src/albedo/harness/extensions/skills/albedo_skills.erl +++ b/src/albedo/harness/extensions/skills/albedo_skills.erl @@ -48,6 +48,9 @@ builtin_root() -> %% Built-in skills rank below every workspace and user skill, so a same-named %% skill there replaces one silently instead of reporting a duplicate. catalog(Workspace, Home, Builtin) -> + with_link_memo(fun() -> catalog_scan(Workspace, Home, Builtin) end). + +catalog_scan(Workspace, Home, Builtin) -> try case scan(Workspace, Home, Builtin) of {ok, {Candidates, Diagnostics, _Truncated}} -> Skills = [selected_metadata(Name, Description, Lexical, Source) @@ -75,13 +78,11 @@ inputs(Workspace, Home, Builtin) -> %% per skill: on a machine starved of CPU every look is a wait, so the same %% facts are read in far fewer of them. with_link_memo(Fun) -> - Outer = put(?LINK_MEMO, #{}), - try Fun() - after - case Outer of - undefined -> erase(?LINK_MEMO); - _ -> put(?LINK_MEMO, Outer) - end + case get(?LINK_MEMO) of + undefined -> + put(?LINK_MEMO, #{}), + try Fun() after erase(?LINK_MEMO) end; + _ -> Fun() end. link_info(Path) -> @@ -127,6 +128,9 @@ input_entries([Entry | Rest], Root, Sources, Count) -> end. discover(Workspace, Home, Builtin) -> + with_link_memo(fun() -> discover_scan(Workspace, Home, Builtin) end). + +discover_scan(Workspace, Home, Builtin) -> case scan(Workspace, Home, Builtin) of {ok, {Candidates, Diagnostics, Limited}} -> Fingerprints = [bounded_fingerprint(text_list(Source)) @@ -386,7 +390,7 @@ scan_entries([Entry | Rest], Root, {Selected, Candidates} = State, end. candidate(Candidate, Entry) -> - case file:read_link_info(Candidate) of + case link_info(Candidate) of {ok, #file_info{type = Type}} when Type =:= directory; Type =:= symlink -> case realpath(Candidate) of {ok, Directory} -> diff --git a/test/e2e/observation_walk_test.py b/test/e2e/observation_walk_test.py index 2b931c898..735406c3b 100644 --- a/test/e2e/observation_walk_test.py +++ b/test/e2e/observation_walk_test.py @@ -6,7 +6,7 @@ while it discovered (two walks); a later observation of the same session re-checks the retained discovery with one. Discovery also used to walk once more inside, a fourth. A walk resolves every skill's directory and file one path component at a time, which cost over a thousand link lookups for one new -session before a walk looked each shared component up once. On a loaded +session (walk and discovery) before each looked a shared component up once. On a loaded machine each lookup waits for the CPU, so the extra walk and the repeated lookups pushed session writes past the observation's deadline (503). Only the daemon's real runtime shows how many times it walked, so this runs through an @@ -35,7 +35,7 @@ class ObservationWalkTests(unittest.TestCase): report = probe.call_json("trace_stop") self.assertGreaterEqual(report["walks"], 1, report) self.assertLessEqual(report["walks"], 3, report) - self.assertLessEqual(report["link_lookups"], 750, report) + self.assertLessEqual(report["link_lookups"], 300, report) if __name__ == "__main__": -- knotmirror 0.0.1 From 58a24279e6f7e80338e97b4e9019bdb84237bd98 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 16:33:57 -0400 Subject: [PATCH 63/72] Ask stalled endpoints once, together: single-flight /models fetch and concurrent profile listing --- src/albedo/daemon/child_models.gleam | 89 ++++++++++++-- .../extensions/openai/albedo_openai.erl | 57 ++++++++- test/e2e/stalled_endpoints_test.py | 113 ++++++++++++++++++ 3 files changed, 245 insertions(+), 14 deletions(-) create mode 100644 test/e2e/stalled_endpoints_test.py diff --git a/src/albedo/daemon/child_models.gleam b/src/albedo/daemon/child_models.gleam index d422e6db3..1a69b0107 100644 --- a/src/albedo/daemon/child_models.gleam +++ b/src/albedo/daemon/child_models.gleam @@ -6,11 +6,15 @@ //// answers every request in the daemon, and an endpoint that never answers //// once held it for seconds per spawn, failing every request meanwhile. +import albedo/clock import albedo/daemon/configuration import albedo/daemon/conversation import albedo/daemon/session_provider import albedo/harness/runtime import albedo/text_scalars +import gleam/dict +import gleam/erlang/process +import gleam/int import gleam/list import gleam/result import gleam/string @@ -57,11 +61,7 @@ pub fn resolve( case offers(host, home, current, model) { True -> Ok(#(current, model)) False -> - case - list.filter(profiles, fn(profile) { - profile.name != current.name && offers(host, home, profile, model) - }) - { + case other_offers(host, home, profiles, current, model) { [profile] -> Ok(#(profile, model)) [] -> Ok(#(current, model)) _ -> @@ -96,17 +96,86 @@ pub fn available( info: conversation.Info, ) -> List(String) { let profiles = configuration.providers(home) |> result.unwrap([]) + let listings = + concurrently(profiles, fn(profile) { listed(host, home, profile) }, []) + |> list.zip(profiles, _) let #(same, other) = - list.partition(profiles, fn(profile) { profile.name == info.provider }) - let same_models = list.flat_map(same, listed(host, home, _)) + list.partition(listings, fn(listing) { { listing.0 }.name == info.provider }) + let same_models = list.flat_map(same, fn(listing) { listing.1 }) let other_models = - list.flat_map(other, fn(profile) { - listed(host, home, profile) - |> list.map(fn(model) { profile.name <> "/" <> model }) + list.flat_map(other, fn(listing) { + list.map(listing.1, fn(model) { { listing.0 }.name <> "/" <> model }) }) list.unique([info.model, ..list.append(same_models, other_models)]) } +/// The profiles other than `current` that offer `model`, in profile order. Each +/// is asked at once, so stalled endpoints cost one wait together. +fn other_offers( + host: runtime.Runtime, + home: String, + profiles: List(configuration.Provider), + current: configuration.Provider, + model: String, +) -> List(configuration.Provider) { + let others = + list.filter(profiles, fn(profile) { profile.name != current.name }) + concurrently( + others, + fn(profile) { offers(host, home, profile, model) }, + False, + ) + |> list.zip(others, _) + |> list.filter_map(fn(asked) { + case asked.1 { + True -> Ok(asked.0) + False -> Error(Nil) + } + }) +} + +/// How long one profile's endpoint may take before it counts as offering +/// nothing: its own fetch gives up sooner, this bounds a fetch that never does. +const listing_timeout_ms = 15_000 + +/// `work` on every item at once, in item order; `fallback` for one that has not +/// answered by the deadline. +fn concurrently(items: List(a), work: fn(a) -> b, fallback: b) -> List(b) { + let answers = process.new_subject() + list.index_map(items, fn(item, index) { + process.spawn_unlinked(fn() { process.send(answers, #(index, work(item))) }) + }) + let deadline = clock.monotonic_ms() + listing_timeout_ms + let received = collect(answers, list.length(items), deadline, dict.new()) + list.index_map(items, fn(_, index) { + dict.get(received, index) |> result.unwrap(fallback) + }) +} + +fn collect( + answers: process.Subject(#(Int, b)), + remaining: Int, + deadline: Int, + received: dict.Dict(Int, b), +) -> dict.Dict(Int, b) { + case remaining { + 0 -> received + _ -> + case + process.receive(answers, int.max(0, deadline - clock.monotonic_ms())) + { + Ok(#(index, value)) -> + collect( + answers, + remaining - 1, + deadline, + dict.insert(received, index, value), + ) + Error(Nil) -> received + } + } +} + fn offers( host: runtime.Runtime, home: String, diff --git a/src/albedo/harness/extensions/openai/albedo_openai.erl b/src/albedo/harness/extensions/openai/albedo_openai.erl index aa6fccf39..402b79f06 100644 --- a/src/albedo/harness/extensions/openai/albedo_openai.erl +++ b/src/albedo/harness/extensions/openai/albedo_openai.erl @@ -22,19 +22,68 @@ models(Home0, Endpoint0) -> end. %% A changed key (a new login) is a different entry, so it is asked at once. +%% One fetcher asks per entry: callers that arrive while it waits share its wait +%% and its answer, a failure included, instead of each opening a connection. remembered(Endpoint, Key) -> Entry = {Endpoint, erlang:phash2(Key)}, + case fresh(Entry) of + {ok, Result} -> Result; + none -> + Fetcher = fetcher(Entry, Endpoint, Key), + Monitor = monitor(process, Fetcher), + receive {'DOWN', Monitor, process, Fetcher, _} -> ok + after ?FETCH_TIMEOUT_MS + ?CONNECT_TIMEOUT_MS + 1000 -> + demonitor(Monitor, [flush]) + end, + case fresh(Entry) of + {ok, Result} -> Result; + none -> {error, <<"could not reach endpoint: timeout">>} + end + end. + +fresh(Entry) -> Now = erlang:monotonic_time(millisecond), case albedo_registry:lookup(albedo_openai_models, Entry) of - {ok, {Until, Result}} when Until > Now -> Result; - _ -> + {ok, {Until, Result}} when Until > Now -> {ok, Result}; + _ -> none + end. + +%% The process asking this entry's endpoint: the one already asking, or a new one +%% that records its answer, clears the claim and exits. +fetcher(Entry, Endpoint, Key) -> + Claim = {asking, Entry}, + albedo_registry:register(albedo_openai_models, table_ready, true), + case ets:lookup(albedo_openai_models, Claim) of + [{_, Asking}] -> + case is_process_alive(Asking) of + true -> Asking; + false -> + ets:delete_object(albedo_openai_models, {Claim, Asking}), + fetcher(Entry, Endpoint, Key) + end; + [] -> start_fetcher(Claim, Entry, Endpoint, Key) + end. + +start_fetcher(Claim, Entry, Endpoint, Key) -> + Parent = self(), + Fetcher = spawn(fun() -> + receive {Parent, go} -> ok end, + try Result = fetch(Endpoint, Key), Ttl = case Result of {ok, _} -> ?LISTED_TTL_MS; _ -> ?FAILED_TTL_MS end, Fetched = erlang:monotonic_time(millisecond), albedo_registry:register(albedo_openai_models, Entry, {Fetched + Ttl, Result}), ets:select_delete(albedo_openai_models, - [{{'_', {'$1', '_'}}, [{'=<', '$1', Fetched}], [true]}]), - Result + [{{'_', {'$1', '_'}}, [{'=<', '$1', Fetched}], [true]}]) + after + ets:delete(albedo_openai_models, Claim) + end + end), + case ets:insert_new(albedo_openai_models, {Claim, Fetcher}) of + true -> Fetcher ! {Parent, go}, Fetcher; + false -> + exit(Fetcher, kill), + fetcher(Entry, Endpoint, Key) end. curated(Endpoint) -> diff --git a/test/e2e/stalled_endpoints_test.py b/test/e2e/stalled_endpoints_test.py new file mode 100644 index 000000000..39d721555 --- /dev/null +++ b/test/e2e/stalled_endpoints_test.py @@ -0,0 +1,113 @@ +"""Spawning a child asks endpoints that never answer once, together. + +A bare model the parent's provider does not list is looked up on every other +profile, and a generic profile asks its endpoint's `/models`. An endpoint that +accepts connections and never answers costs one fetch timeout: asked one after +another, three of them held a spawn for three timeouts, and two spawns that +arrived together each opened their own connection and waited their own +timeout. The wait is the daemon's, so this runs through the real daemon. +""" + +import json +import socket +import threading +import time +import unittest + +from harness import Albedo, Provider, operation_id, text + +STALLED = 3 +# One fetch timeout is 5 s; asked in sequence, three took at least 15. +TOGETHER_SECONDS = 12 + + +class StalledEndpointsTests(unittest.TestCase): + def setUp(self): + self.provider = Provider(lambda _request: text("ok")) + self.addCleanup(self.provider.close) + self.held = [] + profiles = {} + for name in ("alpha", "beta"): + profiles[f"{name}-{self.provider.route}"] = self.profile( + self.provider.url + f"/{name}/v1", + f"fixture-{name}-{self.provider.route}", + ) + for number in range(STALLED): + profiles[f"stalled{number}-{self.provider.route}"] = self.profile( + self.stall(), f"fixture-stalled{number}-{self.provider.route}" + ) + self.alpha = f"alpha-{self.provider.route}" + self.beta = f"beta-{self.provider.route}" + self.model = f"fixture-beta-{self.provider.route}" + self.app = Albedo(self.provider, providers=profiles).__enter__() + self.addCleanup(self.app.__exit__, None, None, None) + + def profile(self, url, model): + return { + "extension": "openai", + "baseUrl": url, + "apiKey": "key", + "model": model, + "protocol": "chat_completions", + } + + def stall(self): + """An endpoint url whose server accepts connections and never answers.""" + server = socket.create_server(("127.0.0.1", 0)) + connections = [] + + def hold(): + while True: + try: + connections.append(server.accept()[0]) + except OSError: + return + + threading.Thread(target=hold, daemon=True).start() + self.held.append(connections) + self.addCleanup(lambda: [c.close() for c in connections]) + self.addCleanup(server.close) + return f"http://127.0.0.1:{server.getsockname()[1]}/v1" + + def spawn(self, parent, name): + session = operation_id() + body = { + "kind": "child", + "parent_id": parent, + "address": name, + "name": name, + "initial_input_id": operation_id(), + "task": "scan", + "model": self.model, + } + with self.app.api( + f"/sessions/{session}", body, method="PUT", headers={"If-None-Match": "*"} + ) as response: + return json.load(response) + + def test_stalled_endpoints_are_asked_together_not_in_sequence(self): + parent = self.app.session() + began = time.monotonic() + made = self.spawn(parent, "scout") + elapsed = time.monotonic() - began + self.assertEqual(made["provider_profile"], self.beta) + self.assertLess(elapsed, TOGETHER_SECONDS) + self.assertEqual([len(c) for c in self.held], [1] * STALLED) + + def test_spawns_that_arrive_together_share_one_connection_per_endpoint(self): + parent = self.app.session() + made = [] + threads = [ + threading.Thread(target=lambda n=n: made.append(self.spawn(parent, n))) + for n in ("scout-1", "scout-2") + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + self.assertEqual(len(made), 2) + self.assertEqual([len(c) for c in self.held], [1] * STALLED) + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1 From cf499ec597a5bd49ea68f93a17453ff953bbf33a Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 12:29:38 -0400 Subject: [PATCH 64/72] Spare pool, early release, lazy kernels and rest release on by default --- robot-docs/kernel.md | 4 ++-- robot-docs/runtime.md | 9 +++++---- src/albedo/daemon/session.gleam | 13 ++++++++----- src/albedo/harness/runtime.gleam | 5 +++-- 4 files changed, 18 insertions(+), 13 deletions(-) diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index d8d9cb1fa..f90b6496a 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -559,13 +559,13 @@ still for it, `generation_over` ends it and replays what waited. ### fresh spare kernels -The runtime keeps a bounded pool of fresh local Python processes. `ALBEDO_KERNEL_SPARES` sets the target from 0 to 32; the default 0 disables the pool until the density measurements justify a default. A spare imports the kernel core without an agent namespace, workspace, plugin setup, or session environment. A spare is consumed once. Released kernels exit instead of returning to the pool. +The runtime keeps a bounded pool of fresh local Python processes. `ALBEDO_KERNEL_SPARES` sets the target from 0 to 32; the default is 2, and 0 disables the pool. A spare imports the kernel core without an agent namespace, workspace, plugin setup, or session environment. A spare is consumed once. Released kernels exit instead of returning to the pool. `boot_next` admits warmup and cleanup requests through the existing worker budget. Warmups wait behind session work and leave one admission slot free. The runtime holds one ticket per queued or running warmup. Admission removes a spare from the ready list before starting an open worker, so concurrent sessions cannot adopt the same process. An empty pool uses the ordinary cold open. Adoption consumes the spare even when an existing kernel reattaches or a remote workspace uses another launch path. The Python owner checks the source bundle before adoption. A stale spare stops before a cold replacement starts. Explicit reloads and upgrades retire ready spares and invalidate in-flight warmups. Failed cleanup retains its resource in the bounded pool accounting. Warmup failures retry after one second and mark the pool unhealthy until the retry. Shutdown drains admitted workers, stops all remaining spares, then closes the ledger. A spare also monitors the runtime actor and stops when that owner dies; spares never survive a daemon restart. -A completed turn asks, without waiting on the runtime actor, whether the pool is healthy: enabled, not shutting down or detaching, and not in a warmup-failure retry. If it is healthy and the session has no attached client, the session runs the ordinary release path and saves its namespace. Release does not wait for a ready spare, so a drained pool costs the next open a cold boot (about 147 ms more on macOS) instead of leaving the kernel resident. The release handler rechecks that the session is resting and has no live cell or job. Unknown live-work observations and snapshots that report unsaved names retain the kernel. Maintenance applies the same early-release policy to idle sessions and unowned kernels, using the 30 s detached grace. `ALBEDO_KERNEL_RELEASE_WITH_SPARE=1` enables this early release (off by default, which keeps kernels resident); the existing idle and memory-budget limits still apply. +A completed turn asks, without waiting on the runtime actor, whether the pool is healthy: enabled, not shutting down or detaching, and not in a warmup-failure retry. If it is healthy and the session has no attached client, the session runs the ordinary release path and saves its namespace. Release does not wait for a ready spare, so a drained pool costs the next open a cold boot (about 147 ms more on macOS) instead of leaving the kernel resident. The release handler rechecks that the session is resting and has no live cell or job. Unknown live-work observations and snapshots that report unsaved names retain the kernel. Maintenance applies the same early-release policy to idle sessions and unowned kernels, using the 30 s detached grace. This early release is the default; `ALBEDO_KERNEL_RELEASE_WITH_SPARE=0` turns it off and keeps kernels resident. The existing idle and memory-budget limits still apply. ## drops diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index 2a02c7da6..bdb2b7645 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -181,7 +181,7 @@ wakes it immediately; the timer never delays handling a message. Existing ## turns without a kernel -With `ALBEDO_KERNEL_LAZY=1` a turn starts from the session's composition +A turn starts from the session's composition (`session_state.composition`: the held kernel's, else the released one's, else `runtime.prepare_session_async`) and holds no Python kernel. The worker's `acquire` sends `AcquireKernel` before each tool call; the session answers with @@ -189,10 +189,11 @@ its live kernel or parks the request behind `kernel_or_park`, and refuses it onc the run is cancelled. The adoption notice (restored or lost namespace) reaches the model as a user note after that call's result. A turn whose transcript ends in unanswered calls still waits for the kernel, which alone can recover them. +`ALBEDO_KERNEL_LAZY=0` restores opening the kernel before the first request. -With the spare pool on (`ALBEDO_KERNEL_RELEASE_WITH_SPARE=1`), each model -request arms a rest timer: once the wait passes `ALBEDO_KERNEL_REST_MS` (3 s) -with no tool call, the kernel is released through the resting release's guards +While early release is on (the default; see kernel.md), each model request +arms a rest timer: once the wait passes `ALBEDO_KERNEL_REST_MS` (3 s; 0 keeps +the kernel for the whole turn) with no tool call, the kernel is released through the resting release's guards (no live work, no watcher, no transition, pool healthy), rechecked every second while they fail. Releasing at once cost 132 ms per step of a fast tool loop; at 3 s a fast loop never releases. diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 835dbd6f0..7db2d6dd6 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -2804,10 +2804,10 @@ fn prepare_submission( @external(erlang, "albedo_daemon", "env") fn env(name: String) -> String -/// ALBEDO_KERNEL_LAZY=1: a turn starts from the session's composition and -/// acquires its kernel at its first tool call. +/// A turn starts from the session's composition and acquires its kernel at +/// its first tool call, unless ALBEDO_KERNEL_LAZY is "0". fn lazy_kernel() -> Bool { - env("ALBEDO_KERNEL_LAZY") == "1" + env("ALBEDO_KERNEL_LAZY") != "0" } /// Whether a turn can start now. With lazy kernels it needs only the @@ -2934,7 +2934,7 @@ fn hand_kernel( const acquire_refused = "the turn ended before its python kernel was ready" /// ALBEDO_KERNEL_REST_MS, else 3 s: how long a turn waits on its model before -/// its idle kernel is released. +/// its idle kernel is released; 0 keeps it for the whole turn. fn rest_ms() -> Int { case int.parse(env("ALBEDO_KERNEL_REST_MS")) { Ok(ms) if ms >= 0 -> ms @@ -2946,7 +2946,10 @@ fn rest_ms() -> Int { /// `rest_ms`; its next tool call reacquires one. A tool call or the next /// request makes the timer stale. fn arm_rest(state: State, id: String) -> State { - case lazy_kernel() && runtime.release_with_spare(), state.kernel { + case + lazy_kernel() && runtime.release_with_spare() && rest_ms() > 0, + state.kernel + { True, Some(_) -> { let token = state.rest_token + 1 let _ = clock.send_after(state.self, rest_ms(), RestKernel(id, token)) diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index 3fa809b89..5231d8d8c 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -1841,15 +1841,16 @@ pub fn when_pool_healthy(runtime: Runtime, answer: fn(Bool) -> Nil) -> Nil { process.send(runtime.subject, runtime_state.WhenPoolHealthy(answer)) } +/// On unless ALBEDO_KERNEL_RELEASE_WITH_SPARE is "0". pub fn release_with_spare() -> Bool { - env("ALBEDO_KERNEL_RELEASE_WITH_SPARE") == "1" + env("ALBEDO_KERNEL_RELEASE_WITH_SPARE") != "0" } fn spare_target() -> Int { env("ALBEDO_KERNEL_SPARES") |> int.parse |> result.map(int.clamp(_, 0, 32)) - |> result.unwrap(0) + |> result.unwrap(2) } @external(erlang, "albedo_daemon", "env") -- knotmirror 0.0.1 From a3ad2e8bb7017db8e7b86eaa18b10170486eb62d Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 14:49:56 -0400 Subject: [PATCH 65/72] Say nothing for a lossless restore of a namespace saved with no variables --- src/albedo/daemon/session_namespace.gleam | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/albedo/daemon/session_namespace.gleam b/src/albedo/daemon/session_namespace.gleam index f22e25435..1b9985511 100644 --- a/src/albedo/daemon/session_namespace.gleam +++ b/src/albedo/daemon/session_namespace.gleam @@ -698,8 +698,10 @@ fn revive_saved( Some(path) -> runtime.load_state(kernel, path, state_timeout) None -> Error(python.Invalid("session has no state file")) } + // A namespace saved with no variables came back whole too: only a state + // that could not be read means the variables are lost. case revived { - Ok(python.Saved([_, ..], _, _, _, _, _) as saved) -> + Ok(saved) -> adopted( state, kernel, -- knotmirror 0.0.1 From be7345ec0ab8f4f2fe77f70d7919c9ab995e3f80 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 14:49:56 -0400 Subject: [PATCH 66/72] Report variables a save skipped when the state is restored from disk --- priv/python/albedo_state.py | 3 ++ .../harness/extensions/python/kernel.gleam | 3 +- test/e2e/kernel_lazy_test.py | 29 +++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/priv/python/albedo_state.py b/priv/python/albedo_state.py index d5e17392a..a7b98e0f3 100644 --- a/priv/python/albedo_state.py +++ b/priv/python/albedo_state.py @@ -148,6 +148,7 @@ def save_state( "names": payload, "definitions": saved_definitions, "kernel": kernel, + "skipped": skipped, }, file, ) @@ -254,6 +255,8 @@ def load_state( "restored": sorted(set(restored)), "defs": defs, "failed": failed, + # What the save could not keep is as lost as what fails to load. + "skipped": saved.get("skipped", []), "engine": kind, } if output_lost is not None: diff --git a/src/albedo/harness/extensions/python/kernel.gleam b/src/albedo/harness/extensions/python/kernel.gleam index cf8b84b78..006921b0a 100644 --- a/src/albedo/harness/extensions/python/kernel.gleam +++ b/src/albedo/harness/extensions/python/kernel.gleam @@ -924,7 +924,8 @@ pub fn upgrade( |> result.map(fn(restored) { Saved( ..restored, - missed: list.append(snapshot.missed, restored.missed), + // The restore reports the save's skips again. + missed: list.unique(list.append(snapshot.missed, restored.missed)), largest: snapshot.largest, ) }) diff --git a/test/e2e/kernel_lazy_test.py b/test/e2e/kernel_lazy_test.py index ac84c71da..1ef55af9c 100644 --- a/test/e2e/kernel_lazy_test.py +++ b/test/e2e/kernel_lazy_test.py @@ -174,6 +174,35 @@ class KernelLazyTests(unittest.TestCase): ] self.assertEqual(notices, [], after) + def test_a_restore_with_no_variables_says_nothing_unless_it_lost_one(self): + app = self.start() + existing = set(kernels(app.home)) + session = app.session() + + def released_then(prompt, code): + self.assertTrue( + wait_until(lambda: not set(kernels(app.home)) - existing), + "idle kernel outlived its limit", + ) + self.cells[prompt] = code + self.turn(app, session, prompt) + return [ + str(item.get("content")) + for item in inputs(self.provider.requests[-1]) + if is_note(item) + ] + + self.cells["print only"] = "print('nothing to keep')" + self.turn(app, session, "print only") + # Saved with no variables and nothing missed: a lossless restore. + self.assertEqual(released_then("again", "print('again')"), []) + # Saved with no variables but one it could not keep: still a loss. + self.cells["unpicklable"] = "import threading\nlock = threading.Lock()" + self.turn(app, session, "unpicklable") + notes = released_then("after the lock", "print('after')") + self.assertEqual(len(notes), 1, notes) + self.assertIn("lock", notes[0]) + def test_interrupt_while_the_kernel_starts_runs_no_cell(self): slow = Path("/tmp") / f"albedo-slow-{time.monotonic_ns()}" self.addCleanup(lambda: slow.unlink(missing_ok=True)) -- knotmirror 0.0.1 From 9179409e191a996f1b264b3f579d9bbe20565072 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 14:49:56 -0400 Subject: [PATCH 67/72] Show instruction file warnings when a lazy turn's composition is prepared --- src/albedo/daemon/session.gleam | 14 ++++++++++---- src/albedo/harness/runtime.gleam | 4 ++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 7db2d6dd6..d2025958b 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -2874,6 +2874,7 @@ fn prepared_opened( Some(#(_, parked)), Ok(prepared) -> session_state.State(..state, prepared: Some(prepared), booting: None) |> session_prompt.reconcile_prompt + |> warn(runtime.prepared_warnings(prepared)) |> run_parked(parked) } } @@ -3151,6 +3152,13 @@ fn prepared(state: State, head: Int) -> State { } } +/// Shows what preparing the session's composition warned about. +fn warn(state: State, warnings: List(String)) -> State { + list.fold(warnings, state, fn(state, warning) { + session_state.emit(state, view.note("daemon", "Warning: " <> warning)) + }) +} + fn kernel_opened( state: State, result: Result(runtime.Session, python.Error), @@ -3177,10 +3185,8 @@ fn kernel_opened( session_state.State(..state, booting: Some(#(attempts + 1, parked))) } Some(#(_, parked)), Ok(kernel) -> { - let state = adopt(session_state.State(..state, booting: None), kernel) - list.fold(runtime.warnings(kernel), state, fn(state, warning) { - session_state.emit(state, view.note("daemon", "Warning: " <> warning)) - }) + adopt(session_state.State(..state, booting: None), kernel) + |> warn(runtime.warnings(kernel)) |> run_parked(parked) } Some(#(_, parked)), Error(error) -> { diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index 5231d8d8c..823b844d0 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -555,6 +555,10 @@ pub fn warnings(session: Session) -> List(String) { composition.warnings(session.composition) } +pub fn prepared_warnings(prepared: Prepared) -> List(String) { + composition.warnings(prepared.composition) +} + pub fn kernel_pid(session: Session) -> Result(Int, Nil) { python.os_pid(session.kernel) } -- knotmirror 0.0.1 From ee61fd96c23f0b64684311e9de1552c016a4b7e1 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 15:16:38 -0400 Subject: [PATCH 68/72] Fix adopted kernel module identity and unused spare retirement --- priv/python/albedo_spare.py | 4 ++ priv/python/albedo_zygote.py | 2 +- robot-docs/kernel.md | 3 ++ test/harness/spare_protocol_test.py | 65 +++++++++++++++++++++++++++++ 4 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 test/harness/spare_protocol_test.py diff --git a/priv/python/albedo_spare.py b/priv/python/albedo_spare.py index b9c207364..213670323 100644 --- a/priv/python/albedo_spare.py +++ b/priv/python/albedo_spare.py @@ -46,6 +46,8 @@ def main(bundle: str | None = None) -> None: flush=True, ) line = sys.stdin.buffer.readline(1024 * 1024 + 1) + if not line: + return if len(line) > 1024 * 1024 or not line.endswith(b"\n"): raise ValueError("invalid spare adoption frame") spec = json.loads(line) @@ -68,6 +70,8 @@ def main(bundle: str | None = None) -> None: # The ordinary detached handshake still reads the secret from stdin. sys.stdin = io.TextIOWrapper(io.BytesIO((spec["token"] + "\n").encode())) sys.argv = [sys.argv[0], "--run", spec["run_dir"], spec["modules"]] + # Match cold kernels for imports of __main__ and pickled cell definitions. + sys.modules["__main__"] = albedo_cells albedo_cells.main() diff --git a/priv/python/albedo_zygote.py b/priv/python/albedo_zygote.py index 4a7add232..fca71ac28 100644 --- a/priv/python/albedo_zygote.py +++ b/priv/python/albedo_zygote.py @@ -81,8 +81,8 @@ def main(path: str) -> None: child(connection, bundle) except BaseException: traceback.print_exc() - finally: os._exit(1) + os._exit(0) connection.close() diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index f90b6496a..cdc87d688 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -393,6 +393,9 @@ private stdin adoption frame. Adoption installs the session's cwd, sanitized launcher environment (sent by the custodian), module list, run directory, and token, then starts the ordinary kernel. The kernel closes its stdout once its socket listens; the custodian confirms that socket before reporting adoption. +Adoption exposes `albedo_cells` as `__main__`, as a cold launch does. Closing +the adoption channel before sending any bytes retires an unused spare cleanly; +a partial or malformed adoption frame remains an error. On Linux (or anywhere with `ALBEDO_KERNEL_ZYGOTE=1`; `0` turns it off) spares are forked rather than started. `albedo_zygote.py` imports what a spare imports, diff --git a/test/harness/spare_protocol_test.py b/test/harness/spare_protocol_test.py new file mode 100644 index 000000000..4f60f98e4 --- /dev/null +++ b/test/harness/spare_protocol_test.py @@ -0,0 +1,65 @@ +"""Retiring an unadopted spare must not log an invalid-adoption traceback. + +The daemon discards unused spares by closing their private adoption channel. +E2E teardown does not expose the launcher's inherited stderr or exit status. +""" + +import json +import os +from pathlib import Path +import socket +import subprocess +import sys +import tempfile +import unittest + +PYTHON = Path(__file__).resolve().parents[2] / "priv/python" + + +class SpareProtocolTest(unittest.TestCase): + def test_unused_spare_exits_cleanly_on_eof(self): + result = subprocess.run( + [sys.executable, str(PYTHON / "albedo_spare.py")], + input=b"", + capture_output=True, + timeout=30, + ) + self.assertIn("ready", json.loads(result.stdout)) + self.assertEqual(result.returncode, 0, result.stderr.decode()) + self.assertEqual(result.stderr, b"") + + def test_partial_adoption_is_still_an_error(self): + result = subprocess.run( + [sys.executable, str(PYTHON / "albedo_spare.py")], + input=b"{", + capture_output=True, + timeout=30, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn(b"invalid spare adoption frame", result.stderr) + + @unittest.skipUnless(hasattr(os, "fork"), "requires fork") + def test_unused_forked_spare_exits_cleanly_on_eof(self): + with tempfile.TemporaryDirectory(prefix="spare-") as directory: + path = str(Path(directory) / "zygote.sock") + with subprocess.Popen( + [sys.executable, str(PYTHON / "albedo_zygote.py"), path], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) as zygote: + try: + assert zygote.stdout is not None + self.assertIn("ready", json.loads(zygote.stdout.readline())) + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as channel: + channel.settimeout(30) + channel.connect(path) + with channel.makefile("rb") as reader: + self.assertIn("ready", json.loads(reader.readline())) + channel.shutdown(socket.SHUT_WR) + self.assertEqual(reader.read(), b"") + _, errors = zygote.communicate(timeout=30) + self.assertEqual(zygote.returncode, 0, errors.decode()) + self.assertEqual(errors, b"") + finally: + zygote.kill() -- knotmirror 0.0.1 From 703f4a71d6edfcf4fd4bc43763bc9fe8a3ae4b55 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 14:49:56 -0400 Subject: [PATCH 69/72] One kernel behaviour: a kernel opens at the first tool call and releases always run --- cli/test/e2e/tui_folders_test.go | 19 ++-- robot-docs/kernel.md | 4 +- robot-docs/runtime.md | 15 ++- src/albedo/daemon/maintenance.gleam | 8 +- src/albedo/daemon/session.gleam | 59 ++++-------- src/albedo/harness/runtime.gleam | 5 - test/e2e/agents_swarm_test.py | 132 -------------------------- test/e2e/context_retention_test.py | 7 +- test/e2e/daemon_test.py | 6 +- test/e2e/extensions_test.py | 13 +-- test/e2e/harness.py | 49 ++++++++-- test/e2e/idle_reap_test.py | 11 ++- test/e2e/kernel_detach_test.py | 24 +++-- test/e2e/kernel_lazy_test.py | 9 +- test/e2e/kernel_pool_test.py | 37 ++++---- test/e2e/kernel_reset_test.py | 83 +++++++++------- test/e2e/kernel_state_test.py | 7 +- test/e2e/kernel_stop_test.py | 6 +- test/e2e/kernel_support.py | 7 +- test/e2e/kernel_swap_wakes_test.py | 14 +-- test/e2e/kernel_upgrade_test.py | 47 ++++----- test/e2e/mcp_test.py | 6 +- test/e2e/operations_retention_test.py | 7 +- test/e2e/operations_test.py | 102 -------------------- test/e2e/python_test.py | 8 +- test/e2e/release_request_test.py | 1 - test/e2e/remote_kernels_test.py | 24 +++-- test/e2e/run.py | 6 +- test/e2e/session_actor_test.py | 5 +- test/e2e/session_configure_test.py | 55 +---------- test/e2e/session_status_test.py | 16 +++- test/e2e/state_expiry_test.py | 13 ++- test/e2e/traces_test.py | 9 +- test/e2e/warm_test.py | 20 ++-- 34 files changed, 302 insertions(+), 532 deletions(-) diff --git a/cli/test/e2e/tui_folders_test.go b/cli/test/e2e/tui_folders_test.go index 260ec13d8..495d0755c 100644 --- a/cli/test/e2e/tui_folders_test.go +++ b/cli/test/e2e/tui_folders_test.go @@ -7,6 +7,7 @@ package e2e import ( "context" + "encoding/json" "errors" "fmt" "os" @@ -307,7 +308,12 @@ func mustEval(t *testing.T, p string) string { // // The TUI starts the session on the active profile, so this runs alone. func TestTUIStartsASessionOnAHostPickedLikeAFolder(t *testing.T) { - profile := providerRoute(t, echoReply) + profile := providerRoute(t, func(request map[string]any) string { + if toolAnswered(request) { + return "done" + } + return pythonCall("import os\nprint('cwd', os.getcwd())") + }) picked := filepath.Join(suite.remoteHome, "proj", fmt.Sprintf("picked-%d", os.Getpid())) if err := os.MkdirAll(picked, 0o755); err != nil { t.Fatal(err) @@ -337,14 +343,15 @@ func TestTUIStartsASessionOnAHostPickedLikeAFolder(t *testing.T) { t.Fatalf("the session's location did not decode: %+v", l) } - // its kernel boots on the host, and the status says it is attached + // its first cell boots the kernel on the host and runs in the picked folder if _, err := daemon.NewChatClient(conn(t), session.ID).Send(context.Background(), "hello there", nil); err != nil { t.Fatal(err) } - waitIdle(t, session.ID, profile, 1) - status, err := daemon.NewChatClient(conn(t), session.ID).GetStatus(context.Background()) - if err != nil || status.KernelLink != "attached" { - t.Fatalf("after a turn the kernel status is %+v (%v)", status, err) + waitIdle(t, session.ID, profile, 2) + requests := suite.provider.requests(profile) + answered, _ := json.Marshal(requests[len(requests)-1]) + if !strings.Contains(string(answered), "cwd "+picked) { + t.Fatalf("the cell did not run in gohost:%s: %s", picked, answered) } // a host ssh cannot reach says why and is never picked diff --git a/robot-docs/kernel.md b/robot-docs/kernel.md index cdc87d688..91f2d1e7d 100644 --- a/robot-docs/kernel.md +++ b/robot-docs/kernel.md @@ -562,13 +562,13 @@ still for it, `generation_over` ends it and replays what waited. ### fresh spare kernels -The runtime keeps a bounded pool of fresh local Python processes. `ALBEDO_KERNEL_SPARES` sets the target from 0 to 32; the default is 2, and 0 disables the pool. A spare imports the kernel core without an agent namespace, workspace, plugin setup, or session environment. A spare is consumed once. Released kernels exit instead of returning to the pool. +The runtime keeps a bounded pool of fresh local Python processes. `ALBEDO_KERNEL_SPARES` sets the target from 0 to 32 for the machine's size; the default is 2. A spare imports the kernel core without an agent namespace, workspace, plugin setup, or session environment. A spare is consumed once. Released kernels exit instead of returning to the pool. `boot_next` admits warmup and cleanup requests through the existing worker budget. Warmups wait behind session work and leave one admission slot free. The runtime holds one ticket per queued or running warmup. Admission removes a spare from the ready list before starting an open worker, so concurrent sessions cannot adopt the same process. An empty pool uses the ordinary cold open. Adoption consumes the spare even when an existing kernel reattaches or a remote workspace uses another launch path. The Python owner checks the source bundle before adoption. A stale spare stops before a cold replacement starts. Explicit reloads and upgrades retire ready spares and invalidate in-flight warmups. Failed cleanup retains its resource in the bounded pool accounting. Warmup failures retry after one second and mark the pool unhealthy until the retry. Shutdown drains admitted workers, stops all remaining spares, then closes the ledger. A spare also monitors the runtime actor and stops when that owner dies; spares never survive a daemon restart. -A completed turn asks, without waiting on the runtime actor, whether the pool is healthy: enabled, not shutting down or detaching, and not in a warmup-failure retry. If it is healthy and the session has no attached client, the session runs the ordinary release path and saves its namespace. Release does not wait for a ready spare, so a drained pool costs the next open a cold boot (about 147 ms more on macOS) instead of leaving the kernel resident. The release handler rechecks that the session is resting and has no live cell or job. Unknown live-work observations and snapshots that report unsaved names retain the kernel. Maintenance applies the same early-release policy to idle sessions and unowned kernels, using the 30 s detached grace. This early release is the default; `ALBEDO_KERNEL_RELEASE_WITH_SPARE=0` turns it off and keeps kernels resident. The existing idle and memory-budget limits still apply. +A completed turn asks, without waiting on the runtime actor, whether the pool is healthy: enabled, not shutting down or detaching, and not in a warmup-failure retry. If it is healthy and the session has no attached client, the session runs the ordinary release path and saves its namespace. Release does not wait for a ready spare, so a drained pool costs the next open a cold boot (about 147 ms more on macOS) instead of leaving the kernel resident. The release handler rechecks that the session is resting and has no live cell or job. Unknown live-work observations and snapshots that report unsaved names retain the kernel. Maintenance applies the same early-release policy to idle sessions and unowned kernels, using the 30 s detached grace. A pool of 0 spares is never healthy, so with `ALBEDO_KERNEL_SPARES=0` kernels stay resident until the idle and memory-budget limits release them, as they still do with a pool. A test that needs a kernel to stay up holds it the way a person would, with a running cell or a live job. ## drops diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index bdb2b7645..c28b335ba 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -189,14 +189,13 @@ its live kernel or parks the request behind `kernel_or_park`, and refuses it onc the run is cancelled. The adoption notice (restored or lost namespace) reaches the model as a user note after that call's result. A turn whose transcript ends in unanswered calls still waits for the kernel, which alone can recover them. -`ALBEDO_KERNEL_LAZY=0` restores opening the kernel before the first request. - -While early release is on (the default; see kernel.md), each model request -arms a rest timer: once the wait passes `ALBEDO_KERNEL_REST_MS` (3 s; 0 keeps -the kernel for the whole turn) with no tool call, the kernel is released through the resting release's guards -(no live work, no watcher, no transition, pool healthy), rechecked every second -while they fail. Releasing at once cost 132 ms per step of a fast tool loop; at -3 s a fast loop never releases. + +Each model request arms a rest timer: once the wait passes `rest_ms` (3 s) with +no tool call, the kernel is released through the resting release's guards (no +live work, no watcher, no transition, pool healthy; see kernel.md), rechecked +every second while they fail. Releasing at once cost 132 ms per step of a fast +tool loop; at 3 s a fast loop never releases. A test shortens the wait with +`ALBEDO_TEST_TIME_SCALE`. ## finite actor calls diff --git a/src/albedo/daemon/maintenance.gleam b/src/albedo/daemon/maintenance.gleam index bd24ff08a..6046acad0 100644 --- a/src/albedo/daemon/maintenance.gleam +++ b/src/albedo/daemon/maintenance.gleam @@ -90,9 +90,7 @@ fn release_idle( ) }) let workers = list.map(held, fn(entry) { #(entry.0, entry.1) }) - let idle_ms = case - runtime.release_with_spare() && runtime.pool_healthy(sweep.host) - { + let idle_ms = case runtime.pool_healthy(sweep.host) { True -> sweep.detached_ms False -> sweep.idle_ms } @@ -163,9 +161,7 @@ fn unload_quiet( /// A restarted daemon reattaches every recorded kernel, and only actors are /// swept above, so without this those kernels stay up for good. fn release_unowned(activity: List(#(String, Int)), sweep: Sweep) -> Nil { - let idle_ms = case - runtime.release_with_spare() && runtime.pool_healthy(sweep.host) - { + let idle_ms = case runtime.pool_healthy(sweep.host) { True -> sweep.detached_ms False -> sweep.idle_ms } diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index d2025958b..c8cdf24b7 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -2801,34 +2801,20 @@ fn prepare_submission( } } -@external(erlang, "albedo_daemon", "env") -fn env(name: String) -> String - -/// A turn starts from the session's composition and acquires its kernel at -/// its first tool call, unless ALBEDO_KERNEL_LAZY is "0". -fn lazy_kernel() -> Bool { - env("ALBEDO_KERNEL_LAZY") != "0" -} - -/// Whether a turn can start now. With lazy kernels it needs only the -/// composition, unless it owes results for calls a crash interrupted, which -/// only the kernel can recover. +/// Whether a turn can start now. It needs only the composition, since it +/// acquires its kernel at its first tool call, unless it owes results for calls +/// a crash interrupted, which only the kernel can recover. fn turn_ready(state: State) -> #(State, Bool) { let #(state, kernel) = session_namespace.ready(state) - case lazy_kernel() { - False -> #(state, kernel != None) - True -> { - let state = session_history.ensure_history(state) |> result.unwrap(state) - case session_history.needs_kernel(state.history) { - True -> #(state, kernel != None) - False -> #(state, session_state.composition(state) != None) - } - } + let state = session_history.ensure_history(state) |> result.unwrap(state) + case session_history.needs_kernel(state.history) { + True -> #(state, kernel != None) + False -> #(state, session_state.composition(state) != None) } } /// `kernel_or_park` for a turn: the state when it can start now, else `work` -/// parked until the kernel, or with lazy kernels just the composition, is here. +/// parked until the composition, or the kernel a turn owes results to, is here. fn turn_or_park(state: State, work: Message) -> Result(State, State) { case state.closing, uses_kernel_transition(state) { True, _ -> Error(state) @@ -2838,8 +2824,7 @@ fn turn_or_park(state: State, work: Message) -> Result(State, State) { #(state, True) -> Ok(state) #(state, False) -> case - lazy_kernel() - && option.is_none(state.booting) + option.is_none(state.booting) && !session_history.needs_kernel(state.history) { True -> Error(request_composition(state, work)) @@ -2934,29 +2919,22 @@ fn hand_kernel( const acquire_refused = "the turn ended before its python kernel was ready" -/// ALBEDO_KERNEL_REST_MS, else 3 s: how long a turn waits on its model before -/// its idle kernel is released; 0 keeps it for the whole turn. -fn rest_ms() -> Int { - case int.parse(env("ALBEDO_KERNEL_REST_MS")) { - Ok(ms) if ms >= 0 -> ms - _ -> 3000 - } -} +/// How long a turn waits on its model before its idle kernel is released. +/// Releasing at once cost a fast tool loop 132 ms per step; at 3 s a fast loop +/// never releases. +const rest_ms = 3000 /// A turn about to wait on its model releases its kernel if the wait outlasts /// `rest_ms`; its next tool call reacquires one. A tool call or the next /// request makes the timer stale. fn arm_rest(state: State, id: String) -> State { - case - lazy_kernel() && runtime.release_with_spare() && rest_ms() > 0, - state.kernel - { - True, Some(_) -> { + case state.kernel { + Some(_) -> { let token = state.rest_token + 1 - let _ = clock.send_after(state.self, rest_ms(), RestKernel(id, token)) + let _ = clock.send_after(state.self, rest_ms, RestKernel(id, token)) session_state.State(..state, rest_token: token) } - _, _ -> state + None -> state } } @@ -3907,8 +3885,7 @@ fn request_resting_release(state: State) -> Nil { case state.kernel, turn.running(state.activity), - runtime.release_with_spare() - && state.watchers == [] + state.watchers == [] && state.releasing == None && option.map(state.kernel, runtime.live_work) == Some(Ok(0)) { diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index 823b844d0..50bb01eab 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -1845,11 +1845,6 @@ pub fn when_pool_healthy(runtime: Runtime, answer: fn(Bool) -> Nil) -> Nil { process.send(runtime.subject, runtime_state.WhenPoolHealthy(answer)) } -/// On unless ALBEDO_KERNEL_RELEASE_WITH_SPARE is "0". -pub fn release_with_spare() -> Bool { - env("ALBEDO_KERNEL_RELEASE_WITH_SPARE") != "0" -} - fn spare_target() -> Int { env("ALBEDO_KERNEL_SPARES") |> int.parse diff --git a/test/e2e/agents_swarm_test.py b/test/e2e/agents_swarm_test.py index 809265f91..c218870c6 100644 --- a/test/e2e/agents_swarm_test.py +++ b/test/e2e/agents_swarm_test.py @@ -2,23 +2,17 @@ import json import os -import sqlite3 -import sys import time import unittest import urllib.error from harness import ( - resident_kernel, Albedo, Provider, - exclusive, latest_user, operation_id, python, - release_fifo, text, - wait_until, ) HEAVY = os.environ.get("ALBEDO_E2E_HEAVY") == "1" @@ -99,132 +93,6 @@ class AgentsSwarmTests(unittest.TestCase): finally: provider.close() - @exclusive - @resident_kernel - def test_closed_child_does_not_start_when_its_kernel_finishes_booting(self): - def script(request): - if request["messages"][-1].get("role") != "user": - return text("done") - if latest_user(request) == "spawn held child": - return python( - "models = await agents.models()\n" - "child = await agents.self.spawn('held task', name='held', model=models[0])\n" - "print(child.id)" - ) - if latest_user(request) == "close held child": - return python( - "await child.close()\nprint((await mail.submit(child, 'late task')).status)" - ) - return text("done") - - def prepare(app): - # The parent boots normally; creating this FIFO holds later launches. - wrapper = app.home / "bin" / "python3" - wrapper.parent.mkdir() - gate = app.workspace / "boot-gate" - wrapper.write_text( - f"#!{sys.executable}\n" - "import os, sys\n" - "from pathlib import Path\n" - f"gate = Path({str(gate)!r})\n" - "if ('--run' in sys.argv or 'start' in sys.argv) and gate.exists():\n" - f" Path({str(app.workspace / 'boot-ready')!r}).touch()\n" - " with gate.open('rb') as reader: reader.read(1)\n" - f"os.execv({sys.executable!r}, [{sys.executable!r}, *sys.argv[1:]])\n" - ) - wrapper.chmod(0o700) - app.env["PATH"] = str(wrapper.parent) + os.pathsep + app.env["PATH"] - - provider = Provider(script) - self.addCleanup(provider.close) - with Albedo(provider, prepare=prepare) as app: - parent = app.session() - app.prompt(parent, "prime parent kernel").close() - app.idle(parent) - gate = app.workspace / "boot-gate" - os.mkfifo(gate) - app.prompt(parent, "spawn held child").close() - app.idle(parent) - with app.api(f"/sessions?scope=all&family_id={parent}") as response: - child = next( - item["id"] - for item in json.load(response)["items"] - if item["parent_id"] == parent - ) - with sqlite3.connect(app.home / "albedo.sqlite") as database: - self.assertEqual( - database.execute( - "SELECT count(*) FROM mail WHERE recipient=? AND delivered_at IS NULL", - (child,), - ).fetchone()[0], - 1, - ) - self.assertEqual(app.history(child)["items"], []) - wait_until( - (app.workspace / "boot-ready").exists, 10, "child did not start booting" - ) - app.prompt(parent, "close held child").close() - app.idle(parent) - wait_until( - lambda: release_fifo(gate), 10, "child did not reach its boot gate" - ) - gate.unlink() - # Wait for the child's preparation to finish, not an arbitrary sleep. - app.idle(child) - self.assertEqual(app.history(child)["items"], []) - with sqlite3.connect(app.home / "albedo.sqlite") as database: - self.assertIsNotNone( - database.execute( - "SELECT closed_at FROM session_family WHERE session=?", - (child,), - ).fetchone()[0] - ) - self.assertEqual( - database.execute( - "SELECT count(*) FROM mail WHERE recipient=? AND delivered_at IS NULL", - (child,), - ).fetchone()[0], - 2, - ) - self.assertFalse( - any( - "held task" in latest_user(record["request"]) - for record in provider.requests - ) - ) - # A manual chat can still visit a closed child without consuming its letters. - app.prompt(child, "manual visit").close() - app.idle(child) - self.assertTrue( - any( - latest_user(record["request"]) == "manual visit" - for record in provider.requests - ) - ) - # Closing one child must not prevent a later sibling from starting. - sibling = operation_id() - with app.api( - f"/sessions/{sibling}", - { - "kind": "child", - "parent_id": parent, - "address": "sibling", - "name": "sibling", - "initial_input_id": operation_id(), - "task": "normal task", - }, - method="PUT", - headers={"If-None-Match": "*"}, - ) as response: - self.assertEqual(json.load(response)["id"], sibling) - app.idle(sibling) - self.assertTrue( - any( - "normal task" in latest_user(record["request"]) - for record in provider.requests - ) - ) - def test_explicit_session_provider_binds_and_unknown_profile_is_rejected(self): provider = Provider(lambda _request: text("ok")) try: diff --git a/test/e2e/context_retention_test.py b/test/e2e/context_retention_test.py index 8fd3e9b49..e73613df5 100644 --- a/test/e2e/context_retention_test.py +++ b/test/e2e/context_retention_test.py @@ -6,13 +6,13 @@ from pathlib import Path import unittest from inspect_support import Inspection -from harness import Albedo, Provider, Reply, ROOT, exclusive, resident_kernel +from harness import Albedo, Provider, Reply, ROOT, exclusive # exclusive: enables daemon inspection and global rolling settings @exclusive class ContextRetentionTest(unittest.TestCase): - @resident_kernel + @exclusive def test_eviction_releases_replay_while_inspection_survives(self): payload = "REPLAY_SENTINEL:" + "x" * (256 * 1024) reply = Reply( @@ -90,9 +90,10 @@ class ContextRetentionTest(unittest.TestCase): self.assertTrue(measured["history_unloaded"]) self.assertFalse(measured["replay_reachable"]) self.assertLess(measured["actor_binary_bytes"], len(payload)) + # Text turns never open a kernel, so there is none to release. + self.assertFalse(measured["kernel_released"]) for key in ( "history_readable", - "kernel_released", "context_cleared", "actor_stopped", "workers_terminated", diff --git a/test/e2e/daemon_test.py b/test/e2e/daemon_test.py index 1200569d0..4f1fc5ec1 100644 --- a/test/e2e/daemon_test.py +++ b/test/e2e/daemon_test.py @@ -21,7 +21,7 @@ import urllib.parse from inspect_support import Inspection from harness import ( - resident_kernel, + no_spares, Albedo, Provider, Reply, @@ -567,8 +567,8 @@ class DaemonTest(unittest.TestCase): self.assertEqual(response.status, 200) # exclusive: holds the daemon's store locked while it shuts down - @exclusive - @resident_kernel + # no spares: shutdown must find a session still holding its kernel + @no_spares def test_a_shutdown_stopped_by_a_stalled_step_still_ends_by_its_deadline(self): # A drain step that cannot finish (here a session that cannot reach the # store) once left the daemon serving forever: the stop request's diff --git a/test/e2e/extensions_test.py b/test/e2e/extensions_test.py index e5ad84ab4..880400bec 100644 --- a/test/e2e/extensions_test.py +++ b/test/e2e/extensions_test.py @@ -9,8 +9,7 @@ import unittest import urllib.error import urllib.parse -from harness import resident_kernel -from harness import Albedo, Provider, exclusive, operation_id, python, text +from harness import no_spares, Albedo, Provider, exclusive, operation_id, python, text SKILL = "---\nname: demo\ndescription: catalog-only fixture description\n---\nBODY_MUST_NOT_AUTOLOAD\n" @@ -644,8 +643,8 @@ class ExtensionTests(unittest.TestCase): self.assertNotIn("duplicate skill", json.dumps(request["input"])) # exclusive: restarts the daemon - @exclusive - @resident_kernel + # no spares: a release would prepare the composition again and announce it twice + @no_spares def test_reload_pins_system_prompt_until_compaction(self): self.turn("first turn") catalog_route = f"/sessions/{self.sid}/catalog" @@ -870,7 +869,8 @@ class ExtensionTests(unittest.TestCase): ) self.assertIn("older conversation summary", json.dumps(requests[-1]["input"])) - @resident_kernel + # no spares: the test needs the kernel whose snapshot fails to stay up + @no_spares def test_failed_snapshot_retains_kernel_and_saved_choice_for_retry(self): self.turn("hot probe before reload", expected=2) before = self.snapshot()["kernel"]["instance_id"] @@ -893,7 +893,8 @@ class ExtensionTests(unittest.TestCase): self.assertNotEqual(self.snapshot()["kernel"]["instance_id"], before) self.assertNotIn("/demo", [entry["slash_name"] for entry in self.commands()]) - @resident_kernel + # no spares: the test checks the same kernel survives a compaction change + @no_spares def test_compaction_applies_saved_strategy_and_keeps_matching_kernel(self): self.turn("first turn") self.turn("second turn") diff --git a/test/e2e/harness.py b/test/e2e/harness.py index 6f6f6d060..d01424be4 100644 --- a/test/e2e/harness.py +++ b/test/e2e/harness.py @@ -160,11 +160,12 @@ def exclusive(target): return target -def resident_kernel(target): - """Like `exclusive`, and the daemon keeps every kernel resident: the test - observes a kernel's pid, link row or reattachment, which a released kernel - has none of. A test that only reads a kernel's results does not need this.""" - target._e2e_resident = True +def no_spares(target): + """Like `exclusive`, on a daemon with no spare pool: nothing is released + early, so an idle kernel stays up between turns as on a machine configured + with `ALBEDO_KERNEL_SPARES=0`. For a test whose subject is something else + that reads one kernel across turns; say why at the use.""" + target._e2e_no_spares = True return exclusive(target) @@ -703,8 +704,42 @@ def latest_user(request): def prompt_text(request): """The last user's text without a trailing ``: a daemon note (a restore after a kernel release, a switch) rides on the user turn, and a - scripted provider keyed on the prompt must still match it.""" - return latest_user(request).split("")[0] + scripted provider keyed on the prompt must still match it. A note sent on + its own, after a cell's result, is not the prompt.""" + messages = request.get("messages", request.get("input", [])) + return next( + ( + str(item.get("content", "")).split("")[0] + for item in reversed(messages) + if item.get("role") == "user" and not is_note(item) + ), + "", + ) + + +def is_note(item): + """Whether a request item is a daemon note sent on its own.""" + return item.get("role") == "user" and str(item.get("content", "")).startswith( + "" + ) + + +def turn_notes(request): + """The daemon notes since the last prompt: those riding on it, and those + sent after a cell's result, such as the one a kernel's arrival leaves.""" + messages = request.get("messages", request.get("input", [])) + users = [ + str(item.get("content", "")) for item in messages if item.get("role") == "user" + ] + prompts = [ + i for i, text in enumerate(users) if not text.startswith("") + ] + since = users[prompts[-1] :] if prompts else users + return [ + "" + part + for text in since + for part in text.split("")[1:] + ] def wait_until(condition, seconds, message): diff --git a/test/e2e/idle_reap_test.py b/test/e2e/idle_reap_test.py index a6b2e8734..9b001d49a 100644 --- a/test/e2e/idle_reap_test.py +++ b/test/e2e/idle_reap_test.py @@ -7,8 +7,7 @@ import time import unittest from pathlib import Path -from harness import resident_kernel -from harness import alive, latest_user +from harness import no_spares, alive, latest_user from harness import Albedo, Provider, exclusive, python, text from stream_support import StreamProbe @@ -88,7 +87,9 @@ class IdleReapTests(unittest.TestCase): self.app.prompt(session, prompt).close() self.app.idle(session) - @resident_kernel + # no spares: the idle limit releases kernels only on a machine without spares; + # with a pool they go when the turn ends + @no_spares def test_idle_kernel_reaps_and_restores_variables_with_notices(self): app = self.app existing = set(kernels(app.home)) @@ -148,7 +149,9 @@ class IdleReapTests(unittest.TestCase): outputs, ) - @resident_kernel + # no spares: a kernel left idle across a crash exists only without spares; with + # a pool it is released when the turn ends + @no_spares def test_reattached_kernel_without_a_loaded_session_is_released(self): app = self.app app.restart(prepare=lambda a: a.env.update(ALBEDO_IDLE_SECONDS="600")) diff --git a/test/e2e/kernel_detach_test.py b/test/e2e/kernel_detach_test.py index 7e424a1cb..e023e231d 100644 --- a/test/e2e/kernel_detach_test.py +++ b/test/e2e/kernel_detach_test.py @@ -17,9 +17,8 @@ import time import unittest import harness -from harness import resident_kernel from harness import alive -from harness import Albedo, Provider, exclusive, python, text +from harness import Albedo, Provider, exclusive, no_spares, python, text def bridges(home): @@ -34,6 +33,11 @@ def bridges(home): ] +# A live job keeps an idle kernel from being released between turns, as a +# user's running work does. +HOLD = "hold = run('sleep', '120')\n" + + # exclusive: restarts the daemon @exclusive class KernelDetachTests(unittest.TestCase): @@ -74,9 +78,9 @@ class KernelDetachTests(unittest.TestCase): ] return results[-1] - @resident_kernel + @exclusive def test_variables_survive_graceful_and_crash_restarts(self): - first = self.cell("import os\nsurvivor = 41\nos.getpid()") + first = self.cell(HOLD + "import os\nsurvivor = 41\nos.getpid()") self.app.restart() after_stop = self.cell("survivor += 1\n(survivor, os.getpid())") self.assertEqual(after_stop["value"], f"(42, {first['value']})") @@ -105,11 +109,11 @@ class KernelDetachTests(unittest.TestCase): self.assertEqual(survivor, 42) self.assertNotEqual(pid, kernel) - @resident_kernel + @exclusive def test_a_daemon_booted_on_a_copy_of_the_database_leaves_its_kernels_alone(self): """The copy carries this daemon's kernel records (socket, token, process group); its daemon forgets them instead of attaching.""" - first = self.cell("import os\nsurvivor = 41\nos.getpid()") + first = self.cell(HOLD + "import os\nsurvivor = 41\nos.getpid()") copy = harness.Daemon("copy") with ( closing(sqlite3.connect(self.app.home / "albedo.sqlite")) as source, @@ -128,9 +132,9 @@ class KernelDetachTests(unittest.TestCase): after = self.cell("survivor += 1\n(survivor, os.getpid())") self.assertEqual(after["value"], f"(42, {first['value']})") - @resident_kernel + @exclusive def test_a_connection_dropped_mid_cell_still_delivers_the_result(self): - first = self.cell("import os\nos.getpid()") + first = self.cell(HOLD + "import os\nos.getpid()") self.assertEqual(bridges(self.app.home), [], "a local kernel kept a bridge") # The kernel drops the daemon's connection from its side a second in. slept = self.cell( @@ -247,7 +251,9 @@ class KernelDetachTests(unittest.TestCase): self.assertIn("The python kernel restarted", prompt) self.assertIn(f"Jobs stopped by the restart: {handle} (sleep 300)", prompt) - @resident_kernel + # no spares: with a pool, an idle kernel with nothing running is released + # before the restart, so only a machine without spares reattaches one + @no_spares def test_a_restart_tells_the_model_when_nothing_was_running(self): self.cell("survivor = 1") self.app.restart() diff --git a/test/e2e/kernel_lazy_test.py b/test/e2e/kernel_lazy_test.py index 1ef55af9c..6b063a0eb 100644 --- a/test/e2e/kernel_lazy_test.py +++ b/test/e2e/kernel_lazy_test.py @@ -100,11 +100,9 @@ class KernelLazyTests(unittest.TestCase): # idle reap counts kernel processes. app.env.update( { - "ALBEDO_KERNEL_LAZY": "1", "ALBEDO_TEST_TIME_SCALE": "100", "ALBEDO_IDLE_SECONDS": str(IDLE_SECONDS), "ALBEDO_KERNEL_SPARES": "0", - "ALBEDO_KERNEL_RELEASE_WITH_SPARE": "0", **env, } ) @@ -251,11 +249,8 @@ class KernelLazyTests(unittest.TestCase): ) def test_a_long_model_wait_mid_turn_releases_and_restores_the_kernel(self): - app = self.start( - ALBEDO_KERNEL_SPARES="1", - ALBEDO_KERNEL_RELEASE_WITH_SPARE="1", - ALBEDO_KERNEL_REST_MS="50", - ) + # The time scale makes the 3 s rest threshold 30 ms. + app = self.start(ALBEDO_KERNEL_SPARES="1") session = app.session() place = app.workspace / "place" place.mkdir() diff --git a/test/e2e/kernel_pool_test.py b/test/e2e/kernel_pool_test.py index abd00ad4a..b33932b96 100644 --- a/test/e2e/kernel_pool_test.py +++ b/test/e2e/kernel_pool_test.py @@ -37,7 +37,7 @@ exec env -i HOME={home} PATH="$path" SHELL={old}/loginsh /bin/sh -c "$*" class KernelPoolTests(ModelCells, unittest.TestCase): bundle: Path - def boot(self, *, spares=1, release=False, ssh=False, zygote=None): + def boot(self, *, spares=1, ssh=False, zygote=None): self.cells = [] def script(request): @@ -51,7 +51,6 @@ class KernelPoolTests(ModelCells, unittest.TestCase): ALBEDO_DAEMON=str(launcher), ALBEDO_INSPECT="1", ALBEDO_KERNEL_SPARES=str(spares), - ALBEDO_KERNEL_RELEASE_WITH_SPARE="1" if release else "0", ) if zygote is not None: app.env["ALBEDO_KERNEL_ZYGOTE"] = zygote @@ -119,7 +118,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): return ast.literal_eval(result["value"]) def test_changed_environment_keeps_its_kernel_without_saving_secrets(self): - self.boot(release=True) + self.boot() self.ready() pid = self.value( "import os\nos.environ['DENSITY_EPHEMERAL_SECRET']='private'\nos.getpid()" @@ -138,7 +137,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): ) def test_user_thread_survives_turn_end(self): - self.boot(release=True) + self.boot() self.ready() pid = self.value( "import os, threading\n_gate=threading.Event()\n_worker=threading.Thread(target=_gate.wait, daemon=True)\n_worker.start()\nos.getpid()" @@ -152,7 +151,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): ) def test_listening_socket_survives_turn_end(self): - self.boot(release=True) + self.boot() self.ready() pid, port = self.value( "import os, socket\n_server=socket.socket()\n_server.bind(('127.0.0.1', 0))\n_server.listen()\n(os.getpid(), _server.getsockname()[1])" @@ -166,7 +165,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): wait_until(lambda: not alive(pid), 15, "a closed server pinned its kernel") def test_user_timer_survives_turn_end(self): - self.boot(release=True) + self.boot() self.ready() pid = self.value( "import os\n_timer=asyncio.get_running_loop().call_later(300, lambda: None)\nos.getpid()" @@ -180,7 +179,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): ) def test_user_async_task_survives_turn_end(self): - self.boot(release=True) + self.boot() self.ready() pid = self.value( "import os\n_task=asyncio.create_task(asyncio.sleep(300))\nos.getpid()" @@ -196,7 +195,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): def test_owned_cua_driver_survives_turn_end(self): from cua_test import FAKE_DRIVER - self.boot(release=True) + self.boot() route = f"/sessions/{self.session}?view=configuration" with self.app.api(route) as response: response.read() @@ -224,7 +223,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): ) def test_owned_browser_survives_turn_end(self): - self.boot(release=True) + self.boot() self.ready() pid = self.value( "_browser=await browser.spawn()\n_page=await _browser.new_page()\nos.getpid()" @@ -236,7 +235,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): wait_until(lambda: not alive(pid), 15, "a closed browser pinned its kernel") def test_open_remote_connection_survives_turn_end(self): - self.boot(release=True, ssh=True) + self.boot(ssh=True) self.ready() pid = self.value( "_rem = await remote.connect('oldhost')\nassert _rem._stdin is None\nos.getpid()" @@ -258,7 +257,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): return json.load(response) def test_release_keeps_retained_output_and_the_job_book(self): - self.boot(release=True) + self.boot() self.ready() # A cell whose output spills past the preview (its result is stored # by reference, so it is not read back here), then one naming it. @@ -292,7 +291,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): self.assertEqual(restored, ("ééééé" + "end\n", "second\n", 0, text)) def test_spare_is_adopted_released_once_and_refilled(self): - self.boot(release=True) + self.boot() before = self.ready() first = self.value("import os\nsentinel = 41\nos.getpid()") self.assertIn(first, before, "the first cell did not adopt a spare") @@ -309,7 +308,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): self.assertTrue(self.ready().isdisjoint({first, second})) def test_live_background_work_keeps_the_adopted_kernel(self): - self.boot(release=True) + self.boot() self.ready() gate = self.app.workspace / "background-gate" program = f"import pathlib, time; p = pathlib.Path({str(gate)!r}); exec('while not p.exists(): time.sleep(0.01)')" @@ -355,7 +354,9 @@ class KernelPoolTests(ModelCells, unittest.TestCase): zygote = self.zygote_of(spare) sessions = [self.app.session() for _ in range(3)] for session in sessions: - self.cells.append("import os\nos.getpid()") + # The kernel may be released once its turn ends, so it names its + # parent itself. + self.cells.append("import os\nos.getppid()") self.app.prompt(session, "run it").close() pids = [] for session in sessions: @@ -369,7 +370,7 @@ class KernelPoolTests(ModelCells, unittest.TestCase): if part["kind"] == "json" and part["field"] == "result" ] pids.append(ast.literal_eval(result["value"])) - self.assertEqual({self.zygote_of(pid) for pid in pids}, {zygote}) + self.assertEqual(set(pids), {zygote}) def test_an_empty_pool_uses_a_cold_kernel(self): self.boot(spares=0) @@ -396,7 +397,11 @@ class KernelPoolTests(ModelCells, unittest.TestCase): def test_shutdown_stops_spares_but_detaches_an_adopted_kernel(self): self.boot() self.ready() - adopted = self.value("import os\nsentinel = 41\nos.getpid()") + # A live job keeps the adopted kernel from being released before the + # restart, as a user's running work does. + adopted = self.value( + "import os\nsentinel = 41\nhold = run('sleep', '120')\nos.getpid()" + ) ready = self.ready(excluding={adopted}) self.app.restart() wait_until( diff --git a/test/e2e/kernel_reset_test.py b/test/e2e/kernel_reset_test.py index e092672bd..27aff0240 100644 --- a/test/e2e/kernel_reset_test.py +++ b/test/e2e/kernel_reset_test.py @@ -1,21 +1,27 @@ """A Python crash injects exactly one reset notice without corrupting history; a -daemon crash leaves the detached kernel alive, so it injects only the line that -says nothing was lost.""" +daemon crash leaves a kernel with live work alive, so its next cell is told the +kernel reattached and the work carried on.""" import json import urllib.error import unittest -from harness import resident_kernel -from harness import latest_user -from harness import Albedo, Provider, exclusive, python, text +from harness import ( + Albedo, + Provider, + exclusive, + is_note, + prompt_text, + python, + text, + turn_notes, +) NOTICE = ( "The python kernel got reset and all variables are lost" ) REATTACHED = ( - "The python kernel reattached; its variables and jobs carried on." - " Nothing was running." + "The python kernel reattached; its variables and jobs carried on" ) @@ -23,13 +29,20 @@ REATTACHED = ( @exclusive class KernelResetTests(unittest.TestCase): def setUp(self): + cells = { + # A live job holds the kernel through the crash, as a user's would. + "first prompt": "job = run('sleep', '60')\nanswer = 7", + "after restart": "print(answer, job.exit_code)", + "lose kernel": "await job.stop()\nimport os; os._exit(1)", + "recover kernel": "print('kernel-ready')", + } + def script(request): - if request["input"][-1].get("role") == "user": - prompt = latest_user(request) - if prompt == "lose kernel": - return python("import os; os._exit(1)") - if prompt == "recover kernel" + NOTICE: - return python("print('kernel-ready')") + last = request["input"][-1] + if last.get("role") == "user" and not is_note(last): + code = cells.get(prompt_text(request)) + if code is not None: + return python(code) return text("ok") self.provider = Provider(script) @@ -39,39 +52,37 @@ class KernelResetTests(unittest.TestCase): self.addCleanup(self.app.__exit__, None, None, None) def turn(self, session, prompt): + """The notes the model saw in this turn.""" self.app.prompt(session, prompt).close() self.app.idle(session) - return latest_user(self.provider.requests[-1]["request"]) + return turn_notes(self.provider.requests[-1]["request"]) + + def outputs(self): + return [ + item.get("output", "") + for item in self.provider.requests[-1]["request"]["input"] + if item.get("type") == "function_call_output" + ] - @resident_kernel - def test_kernel_crash_emits_one_shot_reset_notice_and_daemon_crash_none(self): + def test_kernel_crash_emits_one_shot_reset_notice_and_daemon_crash_reattaches(self): app = self.app session = app.session() - self.assertEqual(self.turn(session, "first prompt"), "first prompt") + self.assertEqual(self.turn(session, "first prompt"), []) unused = app.session() app.restart(crash=True) - self.assertEqual( - self.turn(unused, "unused session's first prompt"), - "unused session's first prompt", - ) + self.assertEqual(self.turn(unused, "unused session's first prompt"), []) with self.assertRaises(urllib.error.HTTPError) as rejected: app.prompt(session, " ").close() self.assertEqual(rejected.exception.code, 400) - self.assertEqual( - self.turn(session, "after restart"), "after restart" + REATTACHED - ) - self.assertEqual(self.turn(session, "ordinary turn"), "ordinary turn") - self.assertEqual(self.turn(session, "lose kernel"), "lose kernel") - self.assertEqual( - self.turn(session, "recover kernel"), "recover kernel" + NOTICE - ) - self.assertTrue( - any( - "kernel-ready" in item.get("output", "") - for item in self.provider.requests[-1]["request"]["input"] - ) - ) - self.assertEqual(self.turn(session, "still alive"), "still alive") + [reattached] = self.turn(session, "after restart") + self.assertTrue(reattached.startswith(REATTACHED), reattached) + self.assertIn("Jobs still running", reattached) + self.assertIn("7 None", self.outputs()[-1]) + self.assertEqual(self.turn(session, "ordinary turn"), []) + self.assertEqual(self.turn(session, "lose kernel"), []) + self.assertEqual(self.turn(session, "recover kernel"), [NOTICE]) + self.assertIn("kernel-ready", self.outputs()[-1]) + self.assertEqual(self.turn(session, "still alive"), []) users = [ part["text"] for entry in app.history(session)["items"] diff --git a/test/e2e/kernel_state_test.py b/test/e2e/kernel_state_test.py index 9f43d8736..ddaf5bc6f 100644 --- a/test/e2e/kernel_state_test.py +++ b/test/e2e/kernel_state_test.py @@ -7,9 +7,8 @@ restore path lives in the kernel and the notice in the daemon. import unittest -from harness import resident_kernel from harness import latest_user, wait_until -from harness import Albedo, Provider, exclusive, python, text +from harness import Albedo, Provider, exclusive, no_spares, python, text IDLE_SECONDS = 1 BIG_DEFINITION = "def big():\n return '" + "x" * 40000 + "'\n" @@ -84,7 +83,9 @@ class KernelStateTests(unittest.TestCase): for item in self.provider.requests[-1]["request"]["input"] ) - @resident_kernel + # no spares: the idle limit releases a kernel holding values too big to + # save only without spares; with a pool the detached grace keeps it longer + @no_spares def test_helpers_classes_imports_and_failed_cells_survive_a_restart(self): session = self.app.session() self.turn(session, "define") diff --git a/test/e2e/kernel_stop_test.py b/test/e2e/kernel_stop_test.py index 6d7baff09..0f15ca369 100644 --- a/test/e2e/kernel_stop_test.py +++ b/test/e2e/kernel_stop_test.py @@ -3,14 +3,14 @@ import json import unittest -from harness import resident_kernel -from harness import ROOT, Albedo, Provider, exclusive, python, text +from harness import no_spares, ROOT, Albedo, Provider, exclusive, python, text from inspect_support import Inspection @exclusive class KernelStopTests(unittest.TestCase): - @resident_kernel + # no spares: the test stops a kernel it keeps open across turns + @no_spares def test_runtime_serves_reads_and_other_boots_while_stopping(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" diff --git a/test/e2e/kernel_support.py b/test/e2e/kernel_support.py index 38f33271d..d96d50764 100644 --- a/test/e2e/kernel_support.py +++ b/test/e2e/kernel_support.py @@ -6,7 +6,7 @@ import shutil import tempfile import harness -from harness import Albedo, Provider, latest_user +from harness import Albedo, Provider, prompt_text, turn_notes MARKER = '\nMARKER = "new bundle"\n' @@ -51,7 +51,8 @@ class ModelCells: session: str def cell(self, code): - """Run one cell through a model turn; its result and the turn's prompt.""" + """Run one cell through a model turn; its result, and the turn's prompt + followed by the notes the model saw with it or after the cell.""" self.cells.append(code) self.app.prompt(self.session, "run it").close() self.app.idle(self.session) @@ -67,5 +68,5 @@ class ModelCells: for r in reversed(self.provider.requests) if any(i.get("role") == "user" for i in r["request"]["input"]) ) - prompt = latest_user(request) + prompt = prompt_text(request) + "".join(turn_notes(request)) return results[-1], prompt diff --git a/test/e2e/kernel_swap_wakes_test.py b/test/e2e/kernel_swap_wakes_test.py index dee7c720f..823188e6b 100644 --- a/test/e2e/kernel_swap_wakes_test.py +++ b/test/e2e/kernel_swap_wakes_test.py @@ -88,6 +88,7 @@ class SwapWakeTests(ModelCells, unittest.TestCase): time.sleep(0.1) self.fail("the cell completion wake never reached the model") + @exclusive def test_a_pending_cell_wake_survives_the_idle_kernel_swap(self): gate, code = self.held_cell() first, _ = self.cell(code) @@ -116,17 +117,18 @@ class SwapWakeTests(ModelCells, unittest.TestCase): ) self.app.idle(self.session) - wake = self.wait_for_wake() + self.wait_for_wake() self.app.idle(self.session) - # The wake was admitted before the swap, so it rides the swapped - # kernel's turn together with the upgrade notice. - self.assertIn("The python kernel was upgraded to the new python bundle", wake) - self.assertRegex(wake, r"Restored: [^.]*\bsurvivor\b") - swapped, _ = self.cell( + # The wake was admitted before the swap and survived it; the upgrade + # notice reaches the model with the next cell, which runs on the + # swapped kernel. + swapped, prompt = self.cell( "import albedo_bundle, os\n" "(survivor, getattr(albedo_bundle, 'MARKER', None), os.getpid())" ) + self.assertIn("The python kernel was upgraded to the new python bundle", prompt) + self.assertRegex(prompt, r"Restored: [^.]*\bsurvivor\b") self.assertEqual(swapped.get("status"), "ok", swapped) survivor, marker, _pid = swapped["value"].strip("()").split(", ") self.assertEqual((survivor, marker), ("41", "'new bundle'"), swapped) diff --git a/test/e2e/kernel_upgrade_test.py b/test/e2e/kernel_upgrade_test.py index ef95e596b..3906d694c 100644 --- a/test/e2e/kernel_upgrade_test.py +++ b/test/e2e/kernel_upgrade_test.py @@ -18,9 +18,8 @@ import unittest import urllib.error import harness -from harness import resident_kernel from harness import alive -from harness import Albedo, Provider, exclusive, python, text +from harness import Albedo, Provider, exclusive, no_spares, python, text from kernel_support import MARKER, ModelCells, editable_daemon @@ -96,7 +95,9 @@ class KernelUpgradeTests(Swaps): "import albedo_bundle, os\n(survivor, getattr(albedo_bundle, 'MARKER', None), os.getpid())" ) - @resident_kernel + # no spares: with a pool the idle kernel is released before the restart, so + # only a machine without spares reattaches an idle stale kernel to swap + @no_spares def test_restart_onto_a_new_bundle_swaps_the_kernel_and_keeps_variables(self): first, _ = self.cell("import os\nsurvivor = 41\nos.getpid()") self.edit_bundle() @@ -180,7 +181,9 @@ class ModuleSkewTests(Swaps): def probe(self): return self.cell("import os\n(survivor, 'skills' in globals(), os.getpid())") - @resident_kernel + # no spares: with a pool the idle kernel is released before the restart, so + # only a machine without spares reattaches an idle stale kernel to swap + @no_spares def test_a_changed_module_set_swaps_the_kernel_and_keeps_variables(self): first, _ = self.cell( "import os\nsurvivor = 41\n('skills' in globals(), os.getpid())" @@ -298,10 +301,13 @@ class ProtocolSkewTests(Swaps): self.assertFalse(self.stale()) self.assert_gone(marker, kernel, job) + @exclusive + @exclusive def test_a_bundle_out_of_step_with_the_daemon_refuses_to_boot(self): """A python bundle on another protocol than the daemon's own makes - every fresh kernel stale at birth: the boot fails and says why, - instead of swapping one fresh kernel for another forever.""" + every fresh kernel stale at birth: the boot fails and says why, to the + cell that needed it, instead of swapping one fresh kernel for another + forever.""" def prepare(app): launcher, bundle = editable_daemon(app.root) @@ -310,23 +316,18 @@ class ProtocolSkewTests(Swaps): link.write_text(link.read_text().replace("PROTOCOL = 1", "PROTOCOL = 2", 1)) self.app.restart(prepare=prepare) - started = time.monotonic() - with self.app.prompt(self.session, "run it") as response: - input_id = json.load(response)["id"] - deadline = started + 10 - while time.monotonic() < deadline: - with self.app.api( - f"/sessions/{self.session}/inputs/{input_id}" - ) as response: - receipt = json.load(response) - if receipt["blocking_reason"]: - break - time.sleep(0.05) - else: - self.fail("incompatible kernel did not expose a blocked input") - self.assertEqual(receipt["delivery"], "pending") - self.assertIn("out of step", receipt["blocking_reason"]["detail"], receipt) - self.assertIn("protocol", receipt["blocking_reason"]["detail"]) + self.cells.append("print('ran')") + self.app.prompt(self.session, "run it").close() + self.app.idle(self.session, timeout=30) + outputs = [ + item.get("output", "") + for item in self.provider.requests[-1]["request"]["input"] + if item.get("type") == "function_call_output" + ] + self.assertTrue(outputs, "the cell got no result") + self.assertIn("out of step", outputs[-1]) + self.assertIn("protocol", outputs[-1]) + self.assertNotIn("ran", outputs[-1]) with self.app.api(f"/sessions/{self.session}?tail=0") as response: self.assertEqual(json.load(response)["kernel"]["state"], "none") diff --git a/test/e2e/mcp_test.py b/test/e2e/mcp_test.py index 0ff05a968..920d4a268 100644 --- a/test/e2e/mcp_test.py +++ b/test/e2e/mcp_test.py @@ -11,8 +11,7 @@ import time import unittest from pathlib import Path -from harness import resident_kernel -from harness import Albedo, Provider, exclusive, operation_id, Reply, text +from harness import no_spares, Albedo, Provider, exclusive, operation_id, Reply, text SERVER = Path(__file__).with_name("fake_mcp_server.py") @@ -141,7 +140,8 @@ class McpTests(unittest.TestCase): self.app.idle(session, timeout=60) return [entry["request"] for entry in self.provider.requests[before:]] - @resident_kernel + # no spares: the test reads the session's kernel between turns + @no_spares def test_cold_command_and_recorded_recovery_do_not_block_another_session(self): other = self.app.session() for session, enabled in ((self.session, True), (other, False)): diff --git a/test/e2e/operations_retention_test.py b/test/e2e/operations_retention_test.py index ea4cbb097..08ebbff28 100644 --- a/test/e2e/operations_retention_test.py +++ b/test/e2e/operations_retention_test.py @@ -7,7 +7,6 @@ import threading import time import urllib.error -from harness import resident_kernel from harness import Albedo, Provider, exclusive, operation_id, text from operations_test import InputScenario @@ -233,7 +232,7 @@ class OperationRetentionTests(InputScenario): database.execute("SELECT count(*) FROM pending_inputs").fetchone()[0], 0 ) - @resident_kernel + @exclusive def test_continuation_marker_survives_receipt_pruning_and_restart(self): session = self.app.session() self.app.prompt(session, "start").close() @@ -263,7 +262,9 @@ class OperationRetentionTests(InputScenario): while time.monotonic() < deadline: with self.app.api(f"/sessions/{session}?tail=0") as response: kernel = json.load(response)["kernel"] - if kernel["state"] == "attached": + # Text turns never open a kernel; one that had a kernel waits for it + # to reattach. + if kernel["state"] in ("attached", "none"): break time.sleep(0.05) else: diff --git a/test/e2e/operations_test.py b/test/e2e/operations_test.py index 060bd151e..89f24844c 100644 --- a/test/e2e/operations_test.py +++ b/test/e2e/operations_test.py @@ -4,17 +4,12 @@ from concurrent.futures import ThreadPoolExecutor from contextlib import closing import base64 import json -import os -from pathlib import Path -import shlex -import shutil import sqlite3 import threading import time import unittest import urllib.error -from harness import resident_kernel from harness import Albedo, Provider, exclusive, operation_id, python, text from image_limits_test import png @@ -535,100 +530,3 @@ class BlockedOperationsTests(InputScenario): self.put_input(session, rejected_id, rejected) self.assertEqual(replay.exception.code, 429) self.assertEqual(json.load(replay.exception), rejection) - - -# exclusive: changes daemon PATH to gate kernel startup; also tests restart -@exclusive -class PreparingOperationsTests(InputScenario): - opened: Path - release: Path - - def setUp(self): - provider = Provider(lambda request: text("done")) - self.addCleanup(provider.close) - - def prepare(app): - self.opened = app.root / "kernel-opening" - self.release = app.root / "kernel-release" - commands = app.root / "kernel-commands" - commands.mkdir() - executable = shutil.which("python3") - self.assertIsNotNone(executable) - wrapper = commands / "python3" - wrapper.write_text( - "#!/bin/sh\n" - # a detached kernel opens through its bridge's start or launch - + 'case "$*" in *albedo_kernel.py*|*"albedo_bridge.py start"*|*"albedo_bridge.py launch"*)\n' - + "touch " - + shlex.quote(str(self.opened)) - + "\n" - + "while [ ! -e " - + shlex.quote(str(self.release)) - + " ]; do sleep 0.05; done\n" - + ";; esac\nexec " - + shlex.quote(str(executable)) - + ' "$@"\n' - ) - wrapper.chmod(0o755) - app.env["PATH"] = str(commands) + os.pathsep + app.env["PATH"] - - self.app = Albedo(provider, protocol="responses", prepare=prepare) - self.app.__enter__() - self.addCleanup(self.app.__exit__, None, None, None) - - @resident_kernel - def test_kernel_preparation_admission_survives_restart(self): - session = self.app.session() - input_id = operation_id() - intent = {"kind": "message", "text": "stored while kernel opens"} - accepted = self.put_input(session, input_id, intent) - deadline = time.monotonic() + 10 - while not self.opened.exists() and time.monotonic() < deadline: - time.sleep(0.03) - self.assertTrue(self.opened.exists()) - self.assertEqual(self.receipt(session, input_id)["delivery"], "pending") - self.app.restart(crash=True, prepare=lambda _: self.release.touch()) - self.assertEqual( - self.put_input(session, input_id, intent)["acceptance_order"], - accepted["acceptance_order"], - ) - self.committed(session, input_id) - self.app.idle(session) - self.assertEqual( - [entry["input_id"] for entry in self.users(session)], [input_id] - ) - - @resident_kernel - def test_full_kernel_opening_queue_delivers_once_and_replays_rejection(self): - session = self.app.session() - inputs = [ - (operation_id(), {"kind": "message", "text": f"opening {index}"}) - for index in range(32) - ] - results = [ - self.put_input(session, input_id, intent) for input_id, intent in inputs - ] - deadline = time.monotonic() + 10 - while not self.opened.exists() and time.monotonic() < deadline: - time.sleep(0.03) - self.assertTrue(self.opened.exists()) - self.assertEqual( - self.put_input(session, *inputs[0])["acceptance_order"], - results[0]["acceptance_order"], - ) - rejected_id = operation_id() - intent = {"kind": "continue"} - with self.assertRaises(urllib.error.HTTPError) as failure: - self.put_input(session, rejected_id, intent) - self.assertEqual(failure.exception.code, 429) - rejection = json.load(failure.exception) - self.assertEqual(self.receipt(session, rejected_id)["admission"], "rejected") - self.release.touch() - for input_id, _ in inputs: - self.committed(session, input_id) - self.app.idle(session) - self.assert_user_order(session, inputs) - with self.assertRaises(urllib.error.HTTPError) as replay: - self.put_input(session, rejected_id, intent) - self.assertEqual(replay.exception.code, 429) - self.assertEqual(json.load(replay.exception), rejection) diff --git a/test/e2e/python_test.py b/test/e2e/python_test.py index 86d0beab7..d6e5e24ca 100644 --- a/test/e2e/python_test.py +++ b/test/e2e/python_test.py @@ -3,8 +3,7 @@ import json import unittest -from harness import resident_kernel -from harness import Albedo, Provider, Reply, python, text +from harness import no_spares, exclusive, Albedo, Provider, Reply, python, text class PythonToolsTests(unittest.TestCase): @@ -45,7 +44,7 @@ class PythonToolsTests(unittest.TestCase): def execute(self, code): return self.run_cell(code, self.app.session())["output"] - @resident_kernel + @exclusive def test_host_replies_preserve_escaped_call_ids_and_argument_errors(self): output = self.execute( "kernel = sys.modules['__main__']\n" @@ -66,7 +65,8 @@ class PythonToolsTests(unittest.TestCase): }, ) - @resident_kernel + # no spares: the tools kept in a variable must be the same objects in the next turn + @no_spares def test_deleting_shadowed_tools_recovers_the_original_bindings(self): (self.app.workspace / "note.txt").write_text("recovered\n") session = self.app.session() diff --git a/test/e2e/release_request_test.py b/test/e2e/release_request_test.py index 373574f7e..e279d87fb 100644 --- a/test/e2e/release_request_test.py +++ b/test/e2e/release_request_test.py @@ -28,7 +28,6 @@ class ReleaseRequestTests(unittest.TestCase): app.env.update( ALBEDO_IDLE_SECONDS="1", ALBEDO_KERNEL_SPARES="2", - ALBEDO_KERNEL_RELEASE_WITH_SPARE="1", ) with Albedo(provider, protocol="responses", prepare=prepare) as app: diff --git a/test/e2e/remote_kernels_test.py b/test/e2e/remote_kernels_test.py index 2b227def7..5b80835ef 100644 --- a/test/e2e/remote_kernels_test.py +++ b/test/e2e/remote_kernels_test.py @@ -22,8 +22,7 @@ import urllib.error import urllib.parse from pathlib import Path -from harness import resident_kernel -from harness import Albedo, Provider, exclusive, operation_id, python, text +from harness import Albedo, Provider, exclusive, no_spares, operation_id, python, text FAKE_SSH = """#!/bin/sh printf '%s\\n' "$*" >> {log} @@ -143,6 +142,11 @@ def wait_for(predicate, timeout=15, message="condition not met"): raise AssertionError(message) +# A live job keeps an idle kernel from being released between turns, as a +# user's running work does. +HOLD = "hold = run('sleep', '120')\n" + + # exclusive: sets daemon PATH for loopback SSH and local Python wrappers @exclusive class RemoteKernelTests(unittest.TestCase): @@ -596,10 +600,10 @@ print('live spill pages, disk failures, atomic saves, and pruning verified') self.assertEqual(result["status"], "ok", result) self.assertIn("staging", seen) - @resident_kernel + @exclusive def test_a_bridge_killed_mid_cell_reattaches_over_ssh(self): session = self.create(f"fakehost:{self.project}")["id"] - first = self.cell(session, "import os\nos.getpid()") + first = self.cell(session, HOLD + "import os\nos.getpid()") (bridge,) = processes( f"{self.remote_home}/.albedo-remote/", script="albedo_bridge.py" ) @@ -623,18 +627,18 @@ print('live spill pages, disk failures, atomic saves, and pruning verified') ] self.assertGreaterEqual(len(bridges), 2, "the reattach did not go over ssh") - @resident_kernel + @exclusive def test_a_remote_kernel_outlives_a_daemon_restart(self): session = self.create(f"fakehost:{self.project}")["id"] - first = self.cell(session, "import os\nsurvivor = 41\nos.getpid()") + first = self.cell(session, HOLD + "import os\nsurvivor = 41\nos.getpid()") self.app.restart(crash=True) after = self.cell(session, "survivor += 1\n(survivor, os.getpid())") self.assertEqual(after["value"], f"(42, {first['value']})") - @resident_kernel + @exclusive def test_a_kernel_survives_ssh_being_down_while_the_daemon_restarts(self): session = self.create(f"fakehost:{self.project}")["id"] - first = self.cell(session, "import os\nsurvivor = 41\nos.getpid()") + first = self.cell(session, HOLD + "import os\nsurvivor = 41\nos.getpid()") self.down.touch() self.app.restart(crash=True) # Back shortly after the turn starts, while the startup attach and @@ -815,7 +819,9 @@ print('live spill pages, disk failures, atomic saves, and pruning verified') self.assertEqual(host["state"], "needs_auth", host) self.assertTrue(host["authentication"]["control_path"].endswith("/%C"), host) - @resident_kernel + # no spares: a local spare starts the local stop helper this test checks a + # remote kernel's end never uses + @no_spares def test_a_remote_kernel_is_ended_on_its_host_never_here(self): session = self.create(f"fakehost:{self.project}")["id"] started = self.cell( diff --git a/test/e2e/run.py b/test/e2e/run.py index b1e2e8aca..cd0f57aef 100644 --- a/test/e2e/run.py +++ b/test/e2e/run.py @@ -63,10 +63,8 @@ def execute(test, daemon): def execute_alone(test): daemon = harness.Daemon("exclusive") - if marked(test, "_e2e_resident"): - daemon.env.update( - ALBEDO_KERNEL_SPARES="0", ALBEDO_KERNEL_RELEASE_WITH_SPARE="0" - ) + if marked(test, "_e2e_no_spares"): + daemon.env.update(ALBEDO_KERNEL_SPARES="0") try: return execute(test, daemon) finally: diff --git a/test/e2e/session_actor_test.py b/test/e2e/session_actor_test.py index 370c6f2f5..1f73709b1 100644 --- a/test/e2e/session_actor_test.py +++ b/test/e2e/session_actor_test.py @@ -6,7 +6,7 @@ import threading import unittest from harness import ( - resident_kernel, + no_spares, ROOT, Albedo, Provider, @@ -62,7 +62,8 @@ class SessionActorStallTests(unittest.TestCase): storage.call("release") self.assertTrue(self.wait_file(marker).startswith("{ok,")) - @resident_kernel + # no spares: the test stalls the runtime and releases a kernel it opened itself + @no_spares def test_release_does_not_wait_for_runtime_and_reset_precedes_next_open(self): def script(request): if request["messages"][-1].get("role") == "tool": diff --git a/test/e2e/session_configure_test.py b/test/e2e/session_configure_test.py index 285ccda36..66cbf2172 100644 --- a/test/e2e/session_configure_test.py +++ b/test/e2e/session_configure_test.py @@ -1,27 +1,20 @@ """Command mutations share conditional edits' checks, persistence, and context reset.""" import json -import os -from pathlib import Path import threading import unittest -from harness import resident_kernel -from harness import Albedo, Provider, ROOT, exclusive, release_fifo, text, wait_until +from harness import Albedo, Provider, ROOT, exclusive, text from inspect_support import Inspection -from kernel_support import editable_daemon @exclusive class SessionConfigureTest(unittest.TestCase): - """Isolated global defaults, catalog, inspection, and copied kernel startup.""" - - marker: Path + """Isolated global defaults, catalog, and inspection.""" def setUp(self): self.provider = Provider(lambda _request: text("done")) self.addCleanup(self.provider.close) - self.gate = None def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" @@ -45,24 +38,6 @@ class SessionConfigureTest(unittest.TestCase): } (app.home / "models.json").write_text(json.dumps(catalog)) app.write_extensions({"models": {"refreshHours": 0}}) - if ( - self._testMethodName - == "test_commands_reject_changes_during_kernel_boot" - ): - launcher, bundle = editable_daemon(app.root) - app.env["ALBEDO_DAEMON"] = str(launcher) - self.gate = app.workspace / "kernel-gate" - self.marker = app.workspace / "kernel-started" - os.mkfifo(self.gate) - gate = self.gate - self.addCleanup(lambda: gate.exists() and release_fifo(gate)) - (bundle / "albedo_kernel.py").write_text( - "from pathlib import Path\n" - f"Path({str(self.marker)!r}).touch()\n" - f"open({str(self.gate)!r}, 'rb').read(1) if Path({str(self.gate)!r}).exists() else None\n" - "import runpy\n" - "runpy.run_module('albedo_cells', run_name='__main__', alter_sys=True)\n" - ) self.app = Albedo( self.provider, @@ -207,32 +182,6 @@ class SessionConfigureTest(unittest.TestCase): release.set() self.app.idle(self.session) - @resident_kernel - def test_commands_reject_changes_during_kernel_boot(self): - self.app.prompt(self.session, "wait for the kernel").close() - wait_until( - lambda: self.marker.exists(), 10, "kernel startup did not reach its gate" - ) - before, defaults = self.configuration(), self.defaults() - try: - self.assertEqual( - self.model("second")["error"], "model must be nonempty and session idle" - ) - self.assertEqual( - self.invoke("effort", "low")["error"], - "switching effort requires an idle session", - ) - self.assertEqual(self.configuration(), before) - self.assertEqual(self.defaults(), defaults) - finally: - assert self.gate is not None - wait_until( - lambda: release_fifo(self.gate), 10, "kernel did not open its gate" - ) - self.gate.unlink() - self.app.idle(self.session) - self.assertEqual(self.provider.requests[-1]["request"]["model"], "first") - if __name__ == "__main__": unittest.main() diff --git a/test/e2e/session_status_test.py b/test/e2e/session_status_test.py index 1b355885b..314ef6340 100644 --- a/test/e2e/session_status_test.py +++ b/test/e2e/session_status_test.py @@ -11,8 +11,16 @@ import urllib.error import urllib.parse import uuid -from harness import resident_kernel -from harness import ROOT, Albedo, Provider, exclusive, latest_user, python, text +from harness import ( + no_spares, + ROOT, + Albedo, + Provider, + exclusive, + latest_user, + python, + text, +) from inspect_support import Inspection # Long enough for the daemon's sidebar pace plus a loaded test host. @@ -139,8 +147,8 @@ class SessionStatusPushTests(unittest.TestCase): "second turn", latest_user(self.provider.requests[-1]["request"]) ) - @exclusive - @resident_kernel + # no spares: the test inspects notifications from a kernel that stays attached + @no_spares def test_kernel_notifications_do_not_retain_session_state(self): def prepare(app): app.daemon.env["ALBEDO_INSPECT"] = "1" diff --git a/test/e2e/state_expiry_test.py b/test/e2e/state_expiry_test.py index 5c30d2060..c438b2f4e 100644 --- a/test/e2e/state_expiry_test.py +++ b/test/e2e/state_expiry_test.py @@ -12,7 +12,7 @@ import tempfile import time import unittest -from harness import latest_user, wait_until +from harness import is_note, latest_user, prompt_text, turn_notes, wait_until from harness import Albedo, Provider, exclusive, python, text IDLE_SECONDS = 1 @@ -27,12 +27,15 @@ LOST = ( class StateExpiryTests(unittest.TestCase): def setUp(self): def script(request): - if request["input"][-1].get("role") == "user": - prompt = latest_user(request) + last = request["input"][-1] + if last.get("role") == "user" and not is_note(last): + prompt = prompt_text(request) if prompt.startswith("remember"): return python("answer = 7") if prompt.startswith("pin"): return python("job = run('sleep', '25')\nanswer = 8") + if prompt.startswith("recall"): + return python("answer") return text("ok") self.provider = Provider(script) @@ -67,6 +70,7 @@ class StateExpiryTests(unittest.TestCase): self.app.idle(session) return latest_user(self.provider.requests[-1]["request"]) + @exclusive def test_an_idle_session_loses_its_state_and_a_live_kernel_keeps_it(self): idle, live = self.app.session(), self.app.session() # A saved state lasts from its idle save to its expiry, a few wall @@ -86,7 +90,8 @@ class StateExpiryTests(unittest.TestCase): 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) + self.turn(idle, "recall it") + self.assertEqual(turn_notes(self.provider.requests[-1]["request"]), [LOST]) def test_old_orphan_state_goes_at_startup_and_a_young_one_stays(self): kernels = self.app.home / "kernels" diff --git a/test/e2e/traces_test.py b/test/e2e/traces_test.py index 0cc566c91..3503df0ec 100644 --- a/test/e2e/traces_test.py +++ b/test/e2e/traces_test.py @@ -4,8 +4,7 @@ import json import unittest import urllib.parse -from harness import resident_kernel -from harness import Albedo, Provider, python, text +from harness import no_spares, Albedo, Provider, python, text class TracesTests(unittest.TestCase): @@ -129,7 +128,8 @@ open('binary.dat', 'wb').write(b'\\0binary') ) ) - @resident_kernel + # no spares: the last cell reads the kernel's archive of the earlier cells + @no_spares def test_many_edit_heavy_cells_release_buffers_and_keep_old_traces(self): oldest = None oldest_trace = None @@ -152,7 +152,8 @@ print('released') self.assertIn("released", result["output"]) self.assertEqual(self.read_trace(oldest), oldest_trace) - @resident_kernel + # no spares: the second cell reads the kernel's archive of the first + @no_spares def test_late_background_edits_execute_without_changing_finalized_trace(self): result, trace = self.run_cell(""" import asyncio diff --git a/test/e2e/warm_test.py b/test/e2e/warm_test.py index f3982ce96..1a03c36c4 100644 --- a/test/e2e/warm_test.py +++ b/test/e2e/warm_test.py @@ -23,10 +23,8 @@ import time import unittest from harness import ( - resident_kernel, LOOPBACK_REMOTE, Albedo, - alive, Provider, exclusive, operation_id, @@ -567,7 +565,6 @@ job.id""" # exclusive: shortens the daemon's idle and unload limits, restarts @exclusive - @resident_kernel def test_a_parent_waiting_on_its_child_keeps_warming_once_released(self): (self.app.home / "cache-ttl.json").write_text(json.dumps(RESTART_TTL)) self.app.restart( @@ -578,13 +575,16 @@ job.id""" ) ) parent, child = self.swarm() - with sqlite3.connect(self.app.home / "albedo.sqlite") as database: - (kernel,) = database.execute( - "SELECT pid FROM kernel_links WHERE session=?", (parent,) - ).fetchone() - # The idle sweep takes the kernel long before the first ping is due, - # and the unload sweep would stop the session with its warmer. - wait_for(lambda: not alive(kernel)) + + def released(): + with sqlite3.connect(self.app.home / "albedo.sqlite") as database: + return not database.execute( + "SELECT pid FROM kernel_links WHERE session=?", (parent,) + ).fetchone() + + # The kernel is released long before the first ping is due, and the + # unload sweep would stop the session with its warmer. + wait_for(released) self.assertEqual(self.pings(self.requests("/parent/")), []) wait_for(lambda: self.pings(self.requests("/parent/")), timeout=40) self.gate.set() -- knotmirror 0.0.1 From 3c9616cec4b698f8d8bf17f2fcd3ed51b3210475 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 16:46:22 -0400 Subject: [PATCH 70/72] Job routes read the saved job book once a released kernel stops under them --- .../harness/extensions/run/service.gleam | 47 ++++++++++++------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/src/albedo/harness/extensions/run/service.gleam b/src/albedo/harness/extensions/run/service.gleam index f89586022..5173cfd89 100644 --- a/src/albedo/harness/extensions/run/service.gleam +++ b/src/albedo/harness/extensions/run/service.gleam @@ -71,6 +71,23 @@ fn refusal(failure: job_book.Failure) -> String { } } +/// `live`, or the saved book once the kernel it asked stopped under it: a +/// release saves the book before it stops the kernel. +fn from_book( + attached: kernel.Kernel, + live: fn() -> Result(a, job_book.Failure), + saved: fn() -> Result(a, job_book.Failure), +) -> Result(a, job_book.Failure) { + case live() { + Error(job_book.Unavailable(_)) as failed -> + case kernel.alive(attached) { + True -> failed + False -> saved() + } + answered -> answered + } +} + fn dispatch( home: String, path: List(String), @@ -122,19 +139,14 @@ fn dispatch( command.KernelRead(fn(attached) { case attached { Some(kernel) -> - job_book.list(kernel) - |> result.map(fn(jobs) { - json.array(jobs, job_book.record_json) + from_book(kernel, fn() { job_book.list(kernel) }, fn() { + job_book.saved_list(home, id) }) - |> result.map_error(refusal) // A released kernel's book, read from disk: viewing never boots one. - None -> - job_book.saved_list(home, id) - |> result.map(fn(jobs) { - json.array(jobs, job_book.record_json) - }) - |> result.map_error(refusal) + None -> job_book.saved_list(home, id) } + |> result.map(fn(jobs) { json.array(jobs, job_book.record_json) }) + |> result.map_error(refusal) }), ) |> result.map_error(failure), @@ -163,14 +175,15 @@ fn dispatch( command.KernelRead(fn(attached) { case attached { Some(kernel) -> - job_book.read(kernel, job, offset, limit) - |> result.map(job_book.page_json) - |> result.map_error(refusal) - None -> - job_book.saved_read(home, id, job, offset, limit) - |> result.map(job_book.page_json) - |> result.map_error(refusal) + from_book( + kernel, + fn() { job_book.read(kernel, job, offset, limit) }, + fn() { job_book.saved_read(home, id, job, offset, limit) }, + ) + None -> job_book.saved_read(home, id, job, offset, limit) } + |> result.map(job_book.page_json) + |> result.map_error(refusal) }), ) |> result.map_error(failure), -- knotmirror 0.0.1 From 19fc4990680fa77bb9fad15a8d470f34adea4280 Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 16:46:22 -0400 Subject: [PATCH 71/72] Compaction, rewind summaries, releases and job stops need no kernel --- src/albedo/daemon/session.gleam | 57 +++++++++++++++++++++++++-------- test/e2e/daemon_test.py | 11 ++++++- test/e2e/extensions_test.py | 11 ++++++- test/e2e/session_status_test.py | 3 +- 4 files changed, 65 insertions(+), 17 deletions(-) diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index c8cdf24b7..f2a0b0bbc 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -1751,7 +1751,8 @@ fn handle( case busy(state) { True -> answer(state, reply, Error("session must be idle to compact")) False -> - case kernel_or_park(state, Compact(strategy, reply)) { + // Compaction needs the composition, not a kernel. + case turn_or_park(state, Compact(strategy, reply)) { Error(state) -> actor.continue(state) Ok(state) -> compact(state, strategy, reply) } @@ -1759,8 +1760,8 @@ fn handle( StopJob(id, reply) -> case state.kernel { Some(kernel) -> answer(state, reply, runtime.stop_job(kernel, id)) - None -> - answer(state, reply, Error("no kernel attached to this session")) + // A kernel is released only with no live job, so none runs now. + None -> answer(state, reply, Error("job not found")) } Watch(owner, key, notify) -> { let watchers = case @@ -2419,8 +2420,9 @@ fn finish_idle_work( case children_busy || occupied(state) { True -> answer(state, ack, Error("session must be idle to rewind")) False -> + // A summary needs the composition, not a kernel. case - kernel_or_park( + turn_or_park( state, StartSummary(checkpoint, instructions, out, ack), ) @@ -3512,6 +3514,7 @@ fn compact( True -> #(state, Error("session must be idle to compact")) False -> select_strategy(state, strategy) } + let state = recompose(state) let report = turn.CompactionReport( selection_applied: strategy != None && result.is_ok(selected), @@ -3579,6 +3582,29 @@ fn compact( } } +/// The session's composition, prepared again when a selection change dropped +/// it and no kernel carries one. The change itself already waited on the +/// runtime, so waiting for the composition it built adds little. +fn recompose(state: State) -> State { + case session_state.composition(state) { + Some(_) -> state + None -> { + let ready = process.new_subject() + runtime.prepare_session_async( + state.host, + state.info.id, + state.info.cwd, + process.send(ready, _), + ) + case process.receive(ready, 60_000) { + Ok(Ok(prepared)) -> + session_state.State(..state, prepared: Some(prepared)) + _ -> state + } + } + } +} + /// A named strategy becomes the session's own compaction extension, so the /// projection it saves is the one every later request reads. fn select_strategy( @@ -4812,17 +4838,20 @@ fn begin_release( state: State, reply: Option(Subject(Bool)), ) -> actor.Next(State, Message) { - case - state.kernel, - turn.running(state.activity), + let settled = !uses_kernel_transition(state) && state.booting == None + case state.kernel, turn.running(state.activity) { // Only published facts: unknown work retains the kernel without calling its owner. - uses_kernel_transition(state) - || state.booting != None - || option.map(state.kernel, runtime.live_work) != Some(Ok(0)) - { - Some(kernel), None, False -> - actor.continue(release_kernel(state, kernel, reply)) - _, _, _ -> release_answer(state, reply, False) + Some(kernel), None -> + case settled && runtime.live_work(kernel) == Ok(0) { + True -> actor.continue(release_kernel(state, kernel, reply)) + False -> release_answer(state, reply, False) + } + // A resting session that never opened a kernel still drops the request + // it prepared, as a release would. + None, None if settled -> + session_state.State(..state, context: session_state.unprepared()) + |> release_answer(reply, False) + _, _ -> release_answer(state, reply, False) } } diff --git a/test/e2e/daemon_test.py b/test/e2e/daemon_test.py index 4f1fc5ec1..d5631f0c1 100644 --- a/test/e2e/daemon_test.py +++ b/test/e2e/daemon_test.py @@ -573,7 +573,16 @@ class DaemonTest(unittest.TestCase): # A drain step that cannot finish (here a session that cannot reach the # store) once left the daemon serving forever: the stop request's # timeout was checked and then never used. - with Albedo() as app: + # A cell leaves the session a kernel whose namespace closing saves. + provider = Provider( + lambda request: ( + python("answer = 7") + if request["messages"][-1].get("role") == "user" + else text("ok") + ) + ) + self.addCleanup(provider.close) + with Albedo(provider) as app: session = app.session() app.prompt(session, "hello").close() app.idle(session) diff --git a/test/e2e/extensions_test.py b/test/e2e/extensions_test.py index 880400bec..4f33de8e9 100644 --- a/test/e2e/extensions_test.py +++ b/test/e2e/extensions_test.py @@ -893,11 +893,20 @@ class ExtensionTests(unittest.TestCase): self.assertNotEqual(self.snapshot()["kernel"]["instance_id"], before) self.assertNotIn("/demo", [entry["slash_name"] for entry in self.commands()]) + def test_compacting_a_session_that_never_ran_a_cell_opens_no_kernel(self): + self.turn("first turn") + self.turn("second turn") + self.change({"selection": {"extensions": {"lcm": True}}}) + report = self.compact("lcm") + self.assertEqual(report["state"], "compacted", report) + self.assertEqual(self.snapshot()["kernel"]["state"], "none") + # no spares: the test checks the same kernel survives a compaction change @no_spares def test_compaction_applies_saved_strategy_and_keeps_matching_kernel(self): self.turn("first turn") - self.turn("second turn") + # A cell opens the kernel the compaction must keep. + self.turn("hot probe before reload", expected=2) before = self.snapshot()["kernel"]["instance_id"] self.change({"selection": {"extensions": {"lcm": True}}}) # Saving is separate from applying. Named compaction must compare with diff --git a/test/e2e/session_status_test.py b/test/e2e/session_status_test.py index 314ef6340..c58d76525 100644 --- a/test/e2e/session_status_test.py +++ b/test/e2e/session_status_test.py @@ -155,7 +155,8 @@ class SessionStatusPushTests(unittest.TestCase): with Albedo(self.provider, prepare=prepare) as app: session = app.session() - app.prompt(session, "warm kernel").close() + # A job's cell opens a kernel, which the daemon then watches. + app.prompt(session, "start job").close() app.idle(session) sizes = json.loads( Inspection(app).evaluate( -- knotmirror 0.0.1 From 2f3b2cd3222f35e4cd029141966953edb42983fd Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Thu, 29 Oct 2026 18:38:37 -0400 Subject: [PATCH 72/72] Admit the sessions an invalidation names into every collection filter as it is published --- src/albedo/daemon/albedo_bus.erl | 36 ++++++++++++++++++++++++- src/albedo/daemon/bus.gleam | 9 ++++--- test/e2e/albedo_bus_filter_probe.erl | 14 ++++++++++ test/e2e/bus_filter_test.py | 39 ++++++++++++++++++++++++++++ 4 files changed, 93 insertions(+), 5 deletions(-) create mode 100644 test/e2e/albedo_bus_filter_probe.erl create mode 100644 test/e2e/bus_filter_test.py diff --git a/src/albedo/daemon/albedo_bus.erl b/src/albedo/daemon/albedo_bus.erl index a98592393..2334c834f 100644 --- a/src/albedo/daemon/albedo_bus.erl +++ b/src/albedo/daemon/albedo_bus.erl @@ -1,7 +1,7 @@ %% Bounded subscriber queues. Publishers admit directly into ETS; subscriber %% mailboxes carry only a coalesced wake, never event payloads. -module(albedo_bus). --export([subscribe_filtered/3, unsubscribe/1, set_filter/2, drain/1, rearm/2, publish/1, publish_activity/2, publish_mail/3, has_subscribers/0, +-export([subscribe_filtered/3, unsubscribe/1, set_filter/2, drain/1, rearm/2, publish/1, publish_invalidate/2, publish_activity/2, publish_mail/3, has_subscribers/0, mark_running/2, running/1, forget/2, register_progress/3, progress/2]). -define(TABLE, albedo_bus). @@ -57,6 +57,40 @@ publish(Event) -> nil end. +%% An invalidation names sessions whose next events a subscriber must not miss +%% while its own refresh is still reading the database: they join every filter +%% as the invalidation is published, and the refresh later replaces the filter +%% with the collection's exact members. +publish_invalidate(Event, Sessions) -> + case ets:whereis(?TABLE) of + undefined -> nil; + _ -> + lists:foreach( + fun({Ref, {_Owner, Notify, Control, _Filter}}) -> + widen_filter(Ref, Sessions, ?CAS_ATTEMPTS), + admit(Ref, Event, byte_size(Event), true, Notify, Control, ?CAS_ATTEMPTS) + end, + ets:tab2list(?TABLE)), + nil + end. + +widen_filter(_Ref, [], _Attempts) -> ok; +widen_filter(_Ref, _Sessions, 0) -> ok; +widen_filter(Ref, Sessions, Attempts) -> + case ets:lookup(?TABLE, Ref) of + [{Ref, {Owner, Notify, Control, Filter} = Previous}] -> + Wider = lists:foldl(fun(Session, Kept) -> Kept#{Session => true} end, Filter, Sessions), + Next = {Owner, Notify, Control, Wider}, + Replaced = ets:select_replace(?TABLE, [ + {{Ref, '$1'}, [{'=:=', '$1', {const, Previous}}], [{const, {Ref, Next}}]} + ]), + case Replaced of + 1 -> ok; + _ -> widen_filter(Ref, Sessions, Attempts - 1) + end; + [] -> ok + end. + %% Selection changes cannot recreate a dead or overflowed queue. set_filter({Ref, _Watcher}, Sessions) -> case ets:whereis(?TABLE) of diff --git a/src/albedo/daemon/bus.gleam b/src/albedo/daemon/bus.gleam index b7177c739..1f9fa2a71 100644 --- a/src/albedo/daemon/bus.gleam +++ b/src/albedo/daemon/bus.gleam @@ -20,7 +20,7 @@ pub fn invalidate( False -> Nil True -> { let truncated = list.length(urls) > 200 || list.length(session_ids) > 200 - publish( + publish_invalidate( json.object([ #("type", json.string("invalidate")), #( @@ -35,7 +35,8 @@ pub fn invalidate( ]), ), ]) - |> json.to_string, + |> json.to_string, + list.take(session_ids, 200), ) } } @@ -160,8 +161,8 @@ pub fn rearm(subscription: Subscription, wake_consumed: Bool) -> Nil @external(erlang, "albedo_bus", "publish_activity") fn publish_activity(session: String, event: String) -> Nil -@external(erlang, "albedo_bus", "publish") -fn publish(event: String) -> Nil +@external(erlang, "albedo_bus", "publish_invalidate") +fn publish_invalidate(event: String, session_ids: List(String)) -> Nil @external(erlang, "albedo_bus", "has_subscribers") fn has_subscribers() -> Bool diff --git a/test/e2e/albedo_bus_filter_probe.erl b/test/e2e/albedo_bus_filter_probe.erl new file mode 100644 index 000000000..abc2d9e96 --- /dev/null +++ b/test/e2e/albedo_bus_filter_probe.erl @@ -0,0 +1,14 @@ +%% Which events a fresh subscriber is admitted after an invalidation names a session. +-module(albedo_bus_filter_probe). +-export([invalidated_session_events/0]). + +invalidated_session_events() -> + Subscription = albedo_bus:subscribe_filtered(self(), fun() -> ok end, []), + albedo_bus:publish_invalidate(<<"invalidate child">>, [<<"child">>]), + albedo_bus:publish_activity(<<"child">>, <<"child activity">>), + albedo_bus:publish_activity(<<"stranger">>, <<"stranger activity">>), + albedo_bus:publish_mail({some, <<"stranger">>}, <<"child">>, <<"mail to child">>), + albedo_bus:publish_mail({some, <<"stranger">>}, <<"other">>, <<"mail elsewhere">>), + {batch, Events, Invalidated} = albedo_bus:drain(Subscription), + albedo_bus:unsubscribe(Subscription), + json:encode(#{events => Events, invalidated => Invalidated}). diff --git a/test/e2e/bus_filter_test.py b/test/e2e/bus_filter_test.py new file mode 100644 index 000000000..76ea29315 --- /dev/null +++ b/test/e2e/bus_filter_test.py @@ -0,0 +1,39 @@ +"""A session an invalidation names is heard from the moment it is published. + +A collection stream learns which sessions it follows from a database listing it +runs after each invalidation. A child's first activity or mail, published +before that listing finished, matched no filter and was dropped, and nothing +replayed it: under load a client following every session missed the new +child's first events (a suite failed on one of roughly twenty runs). The bus +admits the named sessions into every filter as it publishes the invalidation. +Only the daemon's real bus shows what a subscriber is admitted, so this runs +through an inspected daemon. +""" + +import unittest + +from harness import ROOT, Albedo, Provider, exclusive, text +from inspect_support import Inspection + + +@exclusive +class BusFilterTests(unittest.TestCase): + def test_an_invalidated_session_is_admitted_before_the_filter_refreshes(self): + provider = Provider(lambda request: text("ok")) + self.addCleanup(provider.close) + + def prepare(app): + app.daemon.env["ALBEDO_INSPECT"] = "1" + + with Albedo(provider, prepare=prepare) as app: + probe = Inspection(app, ROOT / "test/e2e/albedo_bus_filter_probe.erl") + report = probe.call_json("invalidated_session_events") + self.assertEqual( + report["events"], + ["invalidate child", "child activity", "mail to child"], + ) + self.assertTrue(report["invalidated"]) + + +if __name__ == "__main__": + unittest.main()