From b1c61830c16e3fd06b9779f453cbec2dcb3ee12e Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Tue, 17 Nov 2026 02:28:37 -0500 Subject: [PATCH] fix(links): guard linked summaries and key preparations on the link group Two defects in the per-recipient memory summary from 7b09235f: A hung LinkedSummaryPlugin blocked every later recipient. The host ran each summary in the calling process with no deadline, inside links' serial recipient loop. Daemon.linked_summaries now takes every recipient at once and answers by session. daemon/linked_summaries reads every recipient's plugins in one runtime observation, so a link change takes one admission slot whatever its size, then runs the plugins under one guardian per call. The caller starts the guardian unlinked and monitors it; the guardian traps exits, monitors the caller, and starts each plugin on a helper linked to itself. A plugin crash, or a linked child's exit that takes its helper down, reaches only the guardian and costs only that plugin's answer. The caller collects answers for two seconds, then kills the guardian, and its helpers die with it; a guardian whose caller stops kills itself and its helpers. Links posts every note after that one call. A link made while a session prepared could leave its memory out for good: the preparation published the snapshot memory took from the old group. The link group of the session's workspace now joins the inputs key that build_cached already reads before and after composing, so in nearly every case such a composition is refused, closed in its worker, and its waiters get the existing "composition inputs changed during preparation" error; the session's next preparation reads the new group. Each preparation stays one attempt and nothing new runs on the runtime actor. The key is read at two instants, so a link after the second read, or a link undone between them, can still publish the old group; that session reads the new group at its next open or reload, and the docs say so. linked_summaries_test covers a plugin that never returns beside one that crashes across eight recipients, a plugin whose linked child crashes, a caller killed while a summary hangs (no helper or guardian survives), the deadline killing the guardian and its helpers, and many link changes during one preparation with no summaries call. The new cases fail on the previous helper design and the preparation case without the key. --- .../albedo_sdk/src/albedo_sdk/extension.gleam | 34 +- robot-docs/plugins.md | 35 ++- robot-docs/runtime.md | 20 ++ robot-docs/workspaces.md | 10 +- src/albedo/daemon/linked_summaries.gleam | 229 ++++++++++++++ src/albedo/daemon/server.gleam | 42 +-- .../harness/extensions/links/service.gleam | 35 ++- src/albedo/harness/runtime.gleam | 47 +-- src/albedo/harness/runtime/catalog.gleam | 25 +- src/albedo/harness/runtime/state.gleam | 5 +- test/e2e/areas.toml | 1 + .../albedo_linked_summaries_test_support.erl | 8 + test/harness/extension_capability_test.gleam | 2 +- test/harness/linked_summaries_test.gleam | 297 ++++++++++++++++++ 14 files changed, 695 insertions(+), 95 deletions(-) create mode 100644 src/albedo/daemon/linked_summaries.gleam create mode 100644 test/harness/albedo_linked_summaries_test_support.erl create mode 100644 test/harness/linked_summaries_test.gleam diff --git a/packages/albedo_sdk/src/albedo_sdk/extension.gleam b/packages/albedo_sdk/src/albedo_sdk/extension.gleam index 205d79c0e..518ef424c 100644 --- a/packages/albedo_sdk/src/albedo_sdk/extension.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/extension.gleam @@ -942,21 +942,33 @@ pub type Daemon { hosts: hosts.Hosts, /// The worktree origins linked workspace groups read (`sdk/links`). origins: worktree.Origins, - /// What the session named first hears about the workspaces that just - /// joined its link group, from each `LinkedSummaryPlugin` active in its - /// loaded composition, in registry order. A session with no composition - /// loaded here hears nothing, since the composition it prepares reads the - /// group as it is then. So does one whose contributing extension is - /// disabled, or quarantined because it failed to load or prepare. A - /// contribution that crashes is left out and logged, and an empty one is - /// dropped. - linked_summaries: fn(String, List(String)) -> List(String), + /// What each recipient hears about the workspaces that just joined its + /// link group, by session: the `LinkedSummaryPlugin`s active in its loaded + /// composition, in registry order. The host reads every recipient's + /// plugins in one runtime call, then runs every plugin side by side under + /// a guardian, so a plugin that crashes, or whose linked process dies, + /// costs only its own answer. It collects answers for a few seconds + /// after the read and then stops the plugins still running; that is a + /// collection deadline, not a bound on the whole call. A plugin that fails + /// or misses it is left out and logged, and an empty answer is dropped. A + /// recipient hears nothing from an extension disabled there, or + /// quarantined because it failed to load or prepare, and nothing at all + /// when it has no composition loaded, whose next preparation reads the new + /// group, or when the runtime read is refused or times out. A recipient + /// missing from the answer hears nothing. + linked_summaries: fn(List(LinkedRecipient)) -> Dict(String, List(String)), /// The store scoped to the extension whose service handles the request. /// `service` sets it before calling the handler. storage: storage.Storage, ) } +/// A session the links extension tells that `joined` joined its +/// workspace's link group (`Daemon.linked_summaries`). +pub type LinkedRecipient { + LinkedRecipient(session: String, joined: List(String)) +} + pub type Extension { Extension( name: String, @@ -1352,9 +1364,9 @@ pub fn gate_daemon(daemon: Daemon, extension: Extension) -> Daemon { capability.Sessions, daemon.linked_summaries, ) - fn(_, _) { + fn(_) { let _ = refusal() - [] + dict.new() } }, ) diff --git a/robot-docs/plugins.md b/robot-docs/plugins.md index 47ebff2a1..d437d70bf 100644 --- a/robot-docs/plugins.md +++ b/robot-docs/plugins.md @@ -170,15 +170,32 @@ that just joined its workspace's [link group](workspaces.md#linked-workspaces). Its `summary` takes those workspaces and answers text that stands on its own after the links note's sentence, or `""` for nothing. Memory contributes the memory the session's next snapshot will hold for them. The links extension does -not call it: it asks the host through `Daemon.linked_summaries` for each session -it tells, under the `Sessions` -[capability](extensions.md#extension-capabilities). The host runs the plugins of -the extensions active in that session's loaded composition, in registry order, -outside the runtime actor. A disabled or quarantined extension adds nothing, and -neither does any extension of a session with no composition loaded, whose next -preparation reads the group as it is then. A summary that crashes is left out -and logged, and an unanswered runtime read leaves them all out; the note is -posted either way. +not call it: it asks the host once for every session it tells, through +`Daemon.linked_summaries` and under the `Sessions` +[capability](extensions.md#extension-capabilities), then posts each note. The +host's [`linked_summaries`](../src/albedo/daemon/linked_summaries.gleam) reads +every recipient's plugins in one runtime observation, from the extensions active +in each loaded composition, in registry order. It then runs every plugin of +every recipient side by side, outside the runtime actor, under one guardian +process per call. The guardian traps exits and starts each plugin on a helper +linked to itself, so a plugin that crashes, or whose linked child or port dies +and takes it down, costs only its own answer; the caller only monitors the +guardian. The caller collects answers for two seconds and then kills the +guardian, whose helpers die with it, and a guardian whose caller stops kills +itself and its helpers. The two seconds bound how long the caller waits for +answers once the runtime has said which plugins apply, not the whole call: +reading the plugins and starting the guardian come on top, and a busy scheduler +stretches all of it. A plugin that fails or misses the deadline is left out and +logged, and the notes are posted whatever the plugins did. A disabled or +quarantined extension adds nothing. Neither does any extension of a session with +no composition loaded, nor of any recipient when the runtime refuses or times +out the read, for instance when its observation slots are full. Such a session +learns of the joined workspaces from a composition prepared after the link. A +preparation running when the link commits is usually refused rather than +published, as [preparation and kernels](runtime.md#preparation-and-kernels) +describes, but one can still publish the group it read, and a composition +already loaded keeps its snapshot; both read the new group at the session's next +open or reload. `SchedulePlugin` contributes a `due` callback, given the extension's storage handle, that returns the scheduled prompts due at a given time as diff --git a/robot-docs/runtime.md b/robot-docs/runtime.md index cd06ecfbf..a5ed779e3 100644 --- a/robot-docs/runtime.md +++ b/robot-docs/runtime.md @@ -40,6 +40,26 @@ linked groups read. `preparation.build_cached` builds the `worktrees` capability over the selection's providers and every declared extension's followers, and the kernel's routes get one over the composed extensions' providers. +[`preparation.build_cached`](../src/albedo/harness/runtime/preparation.gleam) +keys the session's inputs before it composes and again after, with +[`catalog.inputs`](../src/albedo/harness/runtime/catalog.gleam): the saved +choices and settings, the skill and instruction files, and the link group of the +session's workspace, which extensions such as memory read while they prepare. +When the two keys differ, the preparation closes the composition in its worker +and fails with "composition inputs changed during preparation", so waiters for +it get that error, and the session's next preparation reads the inputs as they +are then. The runtime does not prepare it again by itself, so a run of changes +cannot keep an open waiting: each preparation is one attempt. + +The recheck compares the inputs at two instants, so it catches most changes +during a preparation, not all. A change after the second read but before the +runtime publishes the composition, or one undone between the two reads, such as +a link and an unlink, leaves the composition published with what it read. A +composition already published is not refreshed when an input changes either. +Either way the session reads the inputs as they are at its next open or reload; +see [linked workspaces](workspaces.md#linked-workspaces) for how a link change +reaches a loaded session. + `prepared` extracts the kernel-free composition, instructions, and context from an open session. The runtime can inspect commands from a prepared composition without opening a kernel. The [session actor](sessions.md) decides when to diff --git a/robot-docs/workspaces.md b/robot-docs/workspaces.md index 249c95bb5..8e95ea981 100644 --- a/robot-docs/workspaces.md +++ b/robot-docs/workspaces.md @@ -64,7 +64,15 @@ adds what each recipient's own active extensions say about them through `Daemon.linked_summaries` ([plugins](plugins.md#daemon-contributions)). A session with memory active hears the memory its next snapshot will hold for them; a session without memory, or whose memory is quarantined, hears only the -change. Links itself reads no memory. +change. A session preparing when the link commits usually has that preparation +refused, with "composition inputs changed during preparation", and its next +preparation holds the new group in its snapshot. In a narrow window it can still +publish the group it read; it then reads the new group at its next open or +reload. The host collects every recipient's summaries under one deadline of a +few seconds, so a slow or failing summary drops only itself. When the host +cannot read a session's composition, its note goes without summaries, and a +session already loaded then sees the joined memory only after it reloads. Links +itself reads no memory. ## Moving a session diff --git a/src/albedo/daemon/linked_summaries.gleam b/src/albedo/daemon/linked_summaries.gleam new file mode 100644 index 000000000..62ebcc33b --- /dev/null +++ b/src/albedo/daemon/linked_summaries.gleam @@ -0,0 +1,229 @@ +//// What each recipient of a links note hears about the workspaces that +//// joined its link group (`extension.Daemon.linked_summaries`). One runtime +//// read answers the `LinkedSummaryPlugin`s active in every recipient's +//// loaded composition, and they run here, outside the runtime actor. +//// +//// A plugin is extension code that may read a slow filesystem, start a +//// linked process, or crash, so the plugins of one batch run side by side +//// under a guardian. The caller starts the guardian unlinked and monitors +//// it. The guardian traps exits and starts each plugin on a helper linked +//// to itself, so a helper's crash, or a linked child's that takes the +//// helper down, reaches only the guardian, which records that plugin's +//// failure. The guardian forwards each answer as it arrives. When the +//// collection deadline passes, the caller kills the guardian, and its +//// helpers die with it through their links; the caller, which only +//// monitors it, is untouched. When the caller stops first, such as a +//// request handler whose client went away, the guardian sees it go and +//// kills itself, taking its helpers with it. No helper outlives the batch. +//// The links extension posts each note after this answers, whatever a +//// plugin did. + +import albedo/harness/runtime +import albedo_clock +import albedo_env/log +import albedo_sdk/extension.{type LinkedRecipient} +import gleam/dict.{type Dict} +import gleam/erlang/process.{type Pid, type Subject} +import gleam/int +import gleam/list +import gleam/option +import gleam/result +import gleam/string + +/// How long the daemon collects every recipient's answers, once the runtime +/// has said which plugins apply: a collection deadline, not a bound on the +/// whole call. +pub const deadline_ms = 2000 + +/// Each recipient's summaries, by session, collected for at most +/// `within_ms` after the runtime answers which plugins apply. A recipient +/// whose runtime read fails hears nothing, and a plugin that fails or +/// misses the deadline is logged and left out. An empty answer is dropped. +pub fn answer( + host: runtime.Runtime, + recipients: List(LinkedRecipient), + within_ms: Int, +) -> Dict(String, List(String)) { + let heard = + dict.from_list( + list.map(recipients, fn(recipient) { #(recipient.session, []) }), + ) + let ids = list.map(recipients, fn(recipient) { recipient.session }) + case runtime.linked_summaries(host, ids, within_ms) { + Error(reason) -> { + log.warning("linked summaries unavailable: " <> reason) + heard + } + Ok(found) -> { + let tasks = + list.flat_map(recipients, fn(recipient) { + list.key_find(found, recipient.session) + |> result.unwrap([]) + |> list.map(fn(summary) { + #(recipient.session, fn() { summary(recipient.joined) }) + }) + }) + run_all(tasks, within_ms) + |> list.fold(heard, fn(heard, answered) { + let #(session, text) = answered + dict.upsert(heard, session, append(_, text)) + }) + } + } +} + +fn append(texts: option.Option(List(String)), text: String) -> List(String) { + list.append(option.unwrap(texts, []), [text]) +} + +type Answer = + #(Int, Result(String, String)) + +/// Runs every task under one guardian and collects the non-empty answers, in +/// task order, until all have answered or failed, or `within_ms` passes. +fn run_all( + tasks: List(#(String, fn() -> String)), + within_ms: Int, +) -> List(#(String, String)) { + let deadline = albedo_clock.monotonic_ms() + within_ms + let answers: Subject(Answer) = process.new_subject() + let caller = process.self() + let runs = list.map(tasks, fn(task) { task.1 }) + let guardian = process.spawn_unlinked(fn() { guard(caller, runs, answers) }) + let watched = process.monitor(guardian) + let received = + collect(answers, watched, list.length(tasks), deadline, dict.new()) + // A guardian still running holds a helper past the deadline: killing it + // kills its linked helpers. One that already finished ignores the kill. + process.kill(guardian) + process.demonitor_process(watched) + list.index_map(tasks, fn(task, index) { #(index, task.0) }) + |> list.filter_map(fn(task) { + let #(index, session) = task + case dict.get(received, index) { + Ok(Ok("")) -> Error(Nil) + Ok(Ok(text)) -> Ok(#(session, text)) + Ok(Error(reason)) -> { + log.warning( + "a linked summary for session " + <> session + <> " failed, so its note goes without it: " + <> reason, + ) + Error(Nil) + } + Error(Nil) -> { + log.warning( + "a linked summary for session " + <> session + <> " did not answer within " + <> int.to_string(within_ms) + <> " ms, so its note goes without it", + ) + Error(Nil) + } + } + }) +} + +/// Answers until all `left` have arrived, the deadline passes, or the +/// guardian is gone. +fn collect( + answers: Subject(Answer), + watched: process.Monitor, + left: Int, + deadline: Int, + received: Dict(Int, Result(String, String)), +) -> Dict(Int, Result(String, String)) { + case left { + 0 -> received + _ -> { + let wait = int.max(0, deadline - albedo_clock.monotonic_ms()) + let next = + process.new_selector() + |> process.select_map(answers, Ok) + |> process.select_specific_monitor(watched, fn(_) { Error(Nil) }) + |> process.selector_receive(wait) + case next { + Ok(Ok(#(index, outcome))) -> + collect( + answers, + watched, + left - 1, + deadline, + dict.insert(received, index, outcome), + ) + _ -> received + } + } + } +} + +/// The guardian of one batch: starts each run on a helper linked to it, +/// forwards every answer or failure to the caller, and ends with the batch, +/// or kills itself, and so its helpers, when the caller stops. +fn guard( + caller: Pid, + runs: List(fn() -> String), + answers: Subject(Answer), +) -> Nil { + process.trap_exits(True) + let caller_gone = process.monitor(caller) + let results = process.new_subject() + let helpers = + list.index_map(runs, fn(run, index) { + #( + process.spawn(fn() { process.send(results, #(index, Ok(run()))) }), + index, + ) + }) + |> dict.from_list + let selector = + process.new_selector() + |> process.select_map(results, Answered) + |> process.select_trapped_exits(Exited) + |> process.select_specific_monitor(caller_gone, fn(_) { CallerGone }) + watch(selector, helpers, answers) +} + +type Event { + Answered(Answer) + Exited(process.ExitMessage) + CallerGone +} + +/// `helpers` are the ones that have not answered yet, by pid. A helper sends +/// its answer before it exits, so its normal exit always follows it. +fn watch( + selector: process.Selector(Event), + helpers: Dict(Pid, Int), + answers: Subject(Answer), +) -> Nil { + case dict.is_empty(helpers) { + True -> Nil + False -> + case process.selector_receive_forever(selector) { + Answered(#(index, outcome)) -> { + process.send(answers, #(index, outcome)) + watch( + selector, + dict.filter(helpers, fn(_, waiting) { waiting != index }), + answers, + ) + } + Exited(process.ExitMessage(pid, reason)) -> + case dict.get(helpers, pid), reason { + Ok(index), process.Abnormal(cause) -> { + process.send(answers, #(index, Error(string.inspect(cause)))) + watch(selector, dict.delete(helpers, pid), answers) + } + Ok(index), process.Killed -> { + process.send(answers, #(index, Error("killed"))) + watch(selector, dict.delete(helpers, pid), answers) + } + _, _ -> watch(selector, helpers, answers) + } + CallerGone -> process.kill(process.self()) + } + } +} diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index 33f6befbf..5954d8591 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -26,6 +26,7 @@ import albedo/daemon/http_transfers import albedo/daemon/http_wire import albedo/daemon/inspection import albedo/daemon/lifecycle +import albedo/daemon/linked_summaries import albedo/daemon/listener import albedo/daemon/mail import albedo/daemon/moves @@ -46,9 +47,7 @@ import albedo/harness/runtime import albedo/harness/worktree import albedo_clock import albedo_env -import albedo_env/log import albedo_process/within -import albedo_protect import albedo_sdk/credentials import albedo_sdk/extension import albedo_sdk/http_api as sdk_http_api @@ -742,46 +741,13 @@ fn daemon( jobs.capability(config.home), locations.capability(), worktree.origins(), - fn(session, joined) { linked_summaries(host, session, joined) }, + fn(recipients) { + linked_summaries.answer(host, recipients, linked_summaries.deadline_ms) + }, extension.unscoped(runtime.ledger(host)), ) } -/// What `session`'s active extensions tell it about the workspaces that -/// joined its link group (`extension.Daemon.linked_summaries`). The plugins -/// run here, outside the runtime actor. A crash leaves its contribution out, -/// and an unanswered runtime read leaves them all out: the note still goes. -fn linked_summaries( - host: runtime.Runtime, - session: String, - joined: List(String), -) -> List(String) { - case runtime.linked_summaries(host, session) { - Error(reason) -> { - log.warning( - "linked summaries for session " <> session <> " unavailable: " <> reason, - ) - [] - } - Ok(summaries) -> - list.filter_map(summaries, fn(summary) { - case albedo_protect.attempt(fn() { summary(joined) }) { - Ok("") -> Error(Nil) - Ok(text) -> Ok(text) - Error(reason) -> { - log.warning( - "a linked summary for session " - <> session - <> " crashed: " - <> reason, - ) - Error(Nil) - } - } - }) - } -} - fn daemon_route( config: Config, registry: Subject(Message), diff --git a/src/albedo/harness/extensions/links/service.gleam b/src/albedo/harness/extensions/links/service.gleam index 9f9a71b67..13d9b1f80 100644 --- a/src/albedo/harness/extensions/links/service.gleam +++ b/src/albedo/harness/extensions/links/service.gleam @@ -6,6 +6,7 @@ import albedo_sdk/http_api as api import albedo_sdk/input import albedo_sdk/location import albedo_web/etag +import gleam/dict import gleam/dynamic/decode import gleam/http.{Delete, Get, Post} import gleam/http/request @@ -273,13 +274,15 @@ fn joined(members: List(String), others: List(String)) -> List(Note) { } /// The note `session` reads: the change, then what its active extensions -/// say about the workspaces that joined. -fn told(daemon: extension.Daemon, session: String, note: Note) -> String { - let added = case note.joined { - [] -> [] - joined -> daemon.linked_summaries(session, joined) - } - list.fold(added, note.text, fn(text, summary) { text <> " " <> summary }) +/// say about the workspaces that joined (`summaries`, by session). +fn told( + summaries: dict.Dict(String, List(String)), + session: String, + note: Note, +) -> String { + dict.get(summaries, session) + |> result.unwrap([]) + |> list.fold(note.text, fn(text, summary) { text <> " " <> summary }) } fn change( @@ -298,6 +301,22 @@ fn change( list.find(notes, fn(note) { note.workspace == info.cwd }) |> result.map(fn(note) { #(info.id, note) }) }) + // One host call answers every recipient within its deadline, so a slow + // summary for one session holds back no other session's note. + let summaries = + targets + |> list.filter_map(fn(target) { + case { target.1 }.joined { + [] -> Error(Nil) + joined -> Ok(extension.LinkedRecipient(target.0, joined)) + } + }) + |> fn(recipients) { + case recipients { + [] -> dict.new() + _ -> daemon.linked_summaries(recipients) + } + } let #(outcomes, _) = list.fold(targets, #([], 0), fn(state, target) { let outcome = @@ -308,7 +327,7 @@ fn change( "links", "workspace links changed", "" - <> told(daemon, target.0, target.1) + <> told(summaries, target.0, target.1) <> "", ), ) diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index 5e4bd22bb..50c00c3be 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -674,19 +674,22 @@ pub fn extension_summaries( ) } -/// The `LinkedSummaryPlugin`s active in the session's loaded composition, -/// for the host to run outside the runtime actor; none when no composition -/// is loaded for it. +/// The `LinkedSummaryPlugin`s active in each named session's loaded +/// composition, for the host to run outside the runtime actor: none for a +/// session with no composition loaded. One read for every session, so a +/// link change takes one observation slot whatever its size. Waits at most +/// `timeout` ms. pub fn linked_summaries( runtime: Runtime, - id: String, -) -> Result(List(fn(List(String)) -> String), String) { + ids: List(String), + timeout: Int, +) -> Result(List(#(String, List(fn(List(String)) -> String))), String) { call( runtime, admission.Observation, "", - runtime_state.LinkedSummaries(id, _), - 10_000, + runtime_state.LinkedSummaries(ids, _), + timeout, Error, ) } @@ -1648,22 +1651,20 @@ fn serve( ) continue(state) } - runtime_state.LinkedSummaries(id, reply) -> { - let composed = case - dict.get(state.sessions, id), - dict.get(state.compositions, id) - { - Ok(session), _ -> Ok(session.composition) - _, Ok(cached) -> Ok(cached.composition) - _, _ -> Error(Nil) - } - process.send( - reply, - Ok(case composed { - Ok(composed) -> selection.linked_summaries(composed) - Error(Nil) -> [] - }), - ) + runtime_state.LinkedSummaries(ids, reply) -> { + let found = + list.map(ids, fn(id) { + let composed = case + dict.get(state.sessions, id), + dict.get(state.compositions, id) + { + Ok(session), _ -> [session.composition] + _, Ok(cached) -> [cached.composition] + _, _ -> [] + } + #(id, list.flat_map(composed, selection.linked_summaries)) + }) + process.send(reply, Ok(found)) continue(state) } runtime_state.Peek(id, cwd, reply) -> diff --git a/src/albedo/harness/runtime/catalog.gleam b/src/albedo/harness/runtime/catalog.gleam index 4ef264e95..ebfce0075 100644 --- a/src/albedo/harness/runtime/catalog.gleam +++ b/src/albedo/harness/runtime/catalog.gleam @@ -8,12 +8,14 @@ import albedo/harness/extension/selection import albedo/harness/instruction_files import albedo/harness/project_files import albedo/harness/settings/composition +import albedo/harness/worktree import albedo_bytes/digest import albedo_bytes/term_codec import albedo_protect import albedo_sdk/capabilities import albedo_sdk/extension import albedo_sdk/follow +import albedo_sdk/links import albedo_sdk/settings_store import albedo_sdk/skills/catalog as skills import albedo_sdk/skills/files as skill_files @@ -117,7 +119,8 @@ fn failed(result: Result(a, String)) -> Result(a, Failure) { pub type Inputs { /// `saved` keys the stored choices and settings alone; `key` adds the - /// contents of every discovered source file. + /// contents of every discovered source file and the session workspace's + /// link group. Inputs(key: String, basis: String, saved: String) } @@ -129,6 +132,7 @@ pub fn inputs( id: String, ) -> Result(Inputs, Failure) { use choices <- result.try(saved_choices(inventory, id)) + use group <- result.try(link_group(inventory, choices.0)) use saved <- result.try(native_saved(home) |> failed) use sources <- result.try( walk_sources( @@ -140,7 +144,7 @@ pub fn inputs( |> failed, ) Ok(Inputs( - fingerprint(string.inspect(#(choices, sources.0))), + fingerprint(string.inspect(#(choices, group, sources.0))), sources.1, fingerprint(string.inspect(#(choices, saved))), )) @@ -158,6 +162,23 @@ pub fn saved_key( Ok(fingerprint(string.inspect(#(choices, saved)))) } +/// The workspaces linked with `workspace`, with their worktrees, as +/// extensions read the group while they prepare (memory's snapshot holds +/// each member's memory). A link made while a session prepares usually +/// changes the key between `preparation.build_cached`'s two reads, so the +/// recheck refuses the composition that read the old group. One made after +/// the second read, or undone between the two, is not seen +/// (robot-docs/runtime.md, "Preparation and kernels"). +fn link_group( + inventory: Inventory, + workspace: String, +) -> Result(List(String), Failure) { + store.snapshot(inventory.ledger, fn(db) { + Ok(links.members(db, worktree.origins(), workspace)) + }) + |> failed +} + fn saved_choices( inventory: Inventory, id: String, diff --git a/src/albedo/harness/runtime/state.gleam b/src/albedo/harness/runtime/state.gleam index dd61a5b4e..e648a1f6d 100644 --- a/src/albedo/harness/runtime/state.gleam +++ b/src/albedo/harness/runtime/state.gleam @@ -485,9 +485,10 @@ pub type Message { /// A reported application outcome; worker death uses the same settlement. ReloadFinished(String, Reference, ReloadApplication, ReloadOutcome) Summaries(String, Subject(Result(List(extension.Summary), String))) + /// The `LinkedSummaryPlugin`s of each named session's loaded composition. LinkedSummaries( - String, - Subject(Result(List(fn(List(String)) -> String), String)), + List(String), + Subject(Result(List(#(String, List(fn(List(String)) -> String))), String)), ) ObserveComposition( String, diff --git a/test/e2e/areas.toml b/test/e2e/areas.toml index ad3acfde7..6fc1011da 100644 --- a/test/e2e/areas.toml +++ b/test/e2e/areas.toml @@ -225,6 +225,7 @@ "prompt_test.py", "worktrees_test.py", ] +"src/albedo/daemon/linked_summaries.gleam" = ["links_test.py", "memory_test.py"] "src/albedo/harness/extensions/links/**" = ["links_test.py", "memory_test.py"] "src/albedo/harness/extensions/memory/**" = ["memory_test.py", "links_test.py"] "src/albedo/harness/extensions/agents/**" = [ diff --git a/test/harness/albedo_linked_summaries_test_support.erl b/test/harness/albedo_linked_summaries_test_support.erl new file mode 100644 index 000000000..dc2e1d894 --- /dev/null +++ b/test/harness/albedo_linked_summaries_test_support.erl @@ -0,0 +1,8 @@ +%% The processes `Pid` is linked to, for linked_summaries_test to find a +%% summary helper's guardian. Gleam has no binding for process_info/2. +-module(albedo_linked_summaries_test_support). +-export([links/1]). + +links(Pid) -> + {links, Links} = erlang:process_info(Pid, links), + [Linked || Linked <- Links, is_pid(Linked)]. diff --git a/test/harness/extension_capability_test.gleam b/test/harness/extension_capability_test.gleam index 801ca15c8..1a7c69cb6 100644 --- a/test/harness/extension_capability_test.gleam +++ b/test/harness/extension_capability_test.gleam @@ -287,7 +287,7 @@ fn daemon(ledger: store.Store) -> extension.Daemon { jobs.capability("/tmp"), locations.capability(), worktree.origins(), - fn(_, _) { ["linked"] }, + fn(_) { dict.from_list([#("s", ["linked"])]) }, extension.unscoped(ledger), ) } diff --git a/test/harness/linked_summaries_test.gleam b/test/harness/linked_summaries_test.gleam new file mode 100644 index 000000000..b9b37b50d --- /dev/null +++ b/test/harness/linked_summaries_test.gleam @@ -0,0 +1,297 @@ +//// What a links note adds for each recipient comes from extension code the +//// host runs (`extension.Daemon.linked_summaries`), and what a session's +//// snapshot holds comes from the group an extension read while the session +//// prepared. The daemon only installs albedo's own registry, whose memory +//// plugin answers at once, so the ways that can go wrong are checked here +//// against fixture extensions: a plugin that hangs must not hold back any +//// recipient or outlive its caller, and a link made while a session +//// prepares must never leave it publishing the group it read before. + +import albedo/daemon/linked_summaries +import albedo/harness/extensions +import albedo/harness/runtime +import albedo_clock +import albedo_sdk/context_block +import albedo_sdk/extension +import albedo_sdk/links +import albedo_sdk/store +import gleam/dict +import gleam/erlang/process +import gleam/list +import gleam/string +import gleeunit/should +import harness/session_fixture +import sqlight + +fn plugin_only(name: String, plugin: extension.Plugin) -> extension.Extension { + extension.Extension( + name, + "one plugin", + [], + [plugin], + extension.no_initialise, + tables: [], + uses: [], + ) +} + +fn start(installed: List(extension.Extension)) -> runtime.Runtime { + let assert Ok(host) = + runtime.start_with_config( + ":memory:", + extensions.Config( + installed, + list.map(installed, fn(extension) { extension.name }), + ), + ) + session_fixture.initialise(host) + let assert Ok(_) = store.query(runtime.ledger(host), links.apply) + host +} + +fn prepared(host: runtime.Runtime, id: String) -> Nil { + session_fixture.create(host, id, "/tmp") + let assert Ok(_) = runtime.prepare_session(host, id, "/tmp") + Nil +} + +/// Every recipient hears from the plugins that answer, although another +/// plugin active in each never returns and a third crashes. The call takes +/// one deadline for everyone: eight recipients waited on one after another +/// would take eight. +pub fn a_hung_linked_summary_holds_back_no_recipient_test() -> Nil { + let host = + start([ + plugin_only( + "hangs", + extension.LinkedSummaryPlugin(fn(_) { + process.sleep_forever() + "never" + }), + ), + plugin_only("crashes", extension.LinkedSummaryPlugin(fn(_) { panic })), + plugin_only( + "answers", + extension.LinkedSummaryPlugin(fn(joined) { + "joined " <> string.join(joined, ",") + }), + ), + ]) + let ids = ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8"] + list.each(ids, prepared(host, _)) + let recipients = + list.map(["unprepared", ..ids], fn(id) { + extension.LinkedRecipient(id, ["/elsewhere"]) + }) + let started = albedo_clock.monotonic_ms() + let answered = linked_summaries.answer(host, recipients, 1000) + let took = albedo_clock.monotonic_ms() - started + // Waiting on the recipients one after another would take at least eight + // deadlines; this bound leaves a loaded scheduler several of them. + { took < 6000 } |> should.be_true + answered + |> should.equal( + dict.from_list([ + #("unprepared", []), + ..list.map(ids, fn(id) { #(id, ["joined /elsewhere"]) }) + ]), + ) + runtime.stop(host) +} + +/// A plugin that hangs after reporting its helper, and the helper's +/// guardian, the one process the helper is linked to. +fn reporting_hang( + helpers: process.Subject(#(process.Pid, process.Pid)), +) -> extension.Extension { + plugin_only( + "hangs", + extension.LinkedSummaryPlugin(fn(_) { + let assert [guardian] = links_of(process.self()) + process.send(helpers, #(process.self(), guardian)) + process.sleep_forever() + "never" + }), + ) +} + +/// Whether `pid` stops within a bound generous enough for a loaded +/// scheduler; it is checked for liveness, not for how fast it went. +fn stops(pid: process.Pid) -> Bool { + let gone = process.monitor(pid) + process.new_selector() + |> process.select_specific_monitor(gone, fn(_) { Nil }) + |> process.selector_receive(30_000) + == Ok(Nil) +} + +/// A caller that stops while a summary hangs, such as a request handler +/// whose client went away, leaves neither the helper nor its guardian +/// behind, long before the deadline would have. +pub fn a_stopped_caller_leaves_no_helper_or_guardian_test() -> Nil { + let helpers = process.new_subject() + let host = start([reporting_hang(helpers)]) + prepared(host, "hung") + let caller = + process.spawn_unlinked(fn() { + linked_summaries.answer( + host, + [extension.LinkedRecipient("hung", ["/elsewhere"])], + 600_000, + ) + }) + let assert Ok(#(helper, guardian)) = process.receive(helpers, 30_000) + process.kill(caller) + stops(helper) |> should.be_true + stops(guardian) |> should.be_true + runtime.stop(host) +} + +/// The collection deadline kills the guardian and so its helpers, and the +/// caller goes on with the answers it has. +pub fn the_deadline_kills_the_guardian_and_its_helpers_test() -> Nil { + let helpers = process.new_subject() + let host = start([reporting_hang(helpers)]) + prepared(host, "hung") + linked_summaries.answer( + host, + [extension.LinkedRecipient("hung", ["/elsewhere"])], + 200, + ) + |> should.equal(dict.from_list([#("hung", [])])) + let assert Ok(#(helper, guardian)) = process.receive(helpers, 0) + stops(helper) |> should.be_true + stops(guardian) |> should.be_true + runtime.stop(host) +} + +/// A plugin whose linked child crashes is taken down with it, which no +/// catch inside the plugin can stop. Only its answer is lost: the caller +/// survives and the other plugin's answer arrives. +pub fn a_crashing_linked_child_costs_only_its_plugin_test() -> Nil { + let host = + start([ + plugin_only( + "spawns", + extension.LinkedSummaryPlugin(fn(_) { + process.spawn(fn() { panic as "linked child failed" }) + process.sleep_forever() + "never" + }), + ), + plugin_only( + "answers", + extension.LinkedSummaryPlugin(fn(_) { "answered" }), + ), + ]) + prepared(host, "linked") + // A failed plugin counts as answered, so the call ends long before this + // deadline unless the failure went unseen. + linked_summaries.answer( + host, + [extension.LinkedRecipient("linked", ["/elsewhere"])], + 600_000, + ) + |> should.equal(dict.from_list([#("linked", ["answered"])])) + runtime.stop(host) +} + +@external(erlang, "albedo_linked_summaries_test_support", "links") +fn links_of(pid: process.Pid) -> List(process.Pid) + +/// A memory-like extension reads the link group while the session +/// prepares, another extension holds the preparation open, and the group +/// changes many times in between. No summaries call reaches the runtime, as +/// when observation admission refuses it. The open is still answered once +/// the preparation ends, it never publishes the group read before the +/// links, and the session's next preparation reads the group as it is. +pub fn a_link_during_preparation_never_publishes_the_old_group_test() -> Nil { + let reads = process.new_subject() + let entered = process.new_subject() + let host = + start([ + extension.Extension( + "remembers", + "reads the group as memory does", + [], + [ + extension.ManagedPlugin(fn(preparation) { + let group = + links.group( + preparation.storage, + preparation.origins, + preparation.workspace, + ) + |> string.join(",") + process.send(reads, group) + Ok( + extension.Managed(..extension.empty(), context: "group " <> group), + ) + }), + extension.LinkedSummaryPlugin(fn(_) { "remembered" }), + ], + extension.no_initialise, + tables: [], + uses: [], + ), + plugin_only( + "slow", + extension.ManagedPlugin(fn(_) { + let go = process.new_subject() + process.send(entered, go) + let _ = process.receive(go, 60_000) + Ok(extension.empty()) + }), + ), + ]) + let ledger = runtime.ledger(host) + let link = fn(sql) { + let assert Ok(_) = + store.query(ledger, fn(db) { + sqlight.exec(sql, db) |> should.be_ok + Ok(Nil) + }) + Nil + } + session_fixture.create(host, "raced", "/tmp") + let opened = process.new_subject() + process.spawn(fn() { + process.send(opened, runtime.prepare_session(host, "raced", "/tmp")) + }) + process.receive(reads, 10_000) |> should.equal(Ok("/tmp")) + let assert Ok(held) = process.receive(entered, 10_000) + list.each(list.repeat(Nil, 10), fn(_) { + link( + "INSERT INTO workspace_links(workspace, grp) VALUES('/tmp', 1), ('/elsewhere', 1)", + ) + link("DELETE FROM workspace_links") + }) + link( + "INSERT INTO workspace_links(workspace, grp) VALUES('/tmp', 1), ('/elsewhere', 1)", + ) + process.send(held, Nil) + + // One attempt, answered: the composition that read the old group is + // refused, not published and not prepared again behind the open. + let assert Ok(Error(_)) = process.receive(opened, 60_000) + process.receive(reads, 0) |> should.equal(Error(Nil)) + let assert Ok(found) = runtime.linked_summaries(host, ["raced"], 10_000) + found |> should.equal([#("raced", [])]) + + // The next preparation reads the group as it is now. + process.spawn(fn() { + process.send(opened, runtime.prepare_session(host, "raced", "/tmp")) + }) + process.receive(reads, 10_000) |> should.equal(Ok("/tmp,/elsewhere")) + let assert Ok(again) = process.receive(entered, 10_000) + process.send(again, Nil) + let assert Ok(Ok(session)) = process.receive(opened, 60_000) + runtime.context(session) + |> list.any(fn(block: context_block.ContextBlock) { + string.contains(block.body, "group /tmp,/elsewhere") + }) + |> should.be_true + let assert Ok([#("raced", [_])]) = + runtime.linked_summaries(host, ["raced"], 10_000) + runtime.stop(host) +} -- knotmirror 0.0.1