diff --git a/apps/albedo/test/albedo/session/agents_control_test.gleam b/apps/albedo/test/albedo/session/agents_control_test.gleam index 23e84a05f..77414ad01 100644 --- a/apps/albedo/test/albedo/session/agents_control_test.gleam +++ b/apps/albedo/test/albedo/session/agents_control_test.gleam @@ -1,6 +1,22 @@ -//// The agents tool's session controls (`albedo_ext_agents`), run in -//// process over a real family store with a coordinator that records what -//// it is asked. +//// Who may switch, close and cancel which session through the agents tool, +//// and what a cancel stops (`albedo_ext_agents`, robot-docs/agent-sessions.md +//// and the `agents` binding's docs in python/albedo_plugins/agents.py). +//// +//// The contract: a session may switch, close or cancel its own children +//// and the peers it started, and no one else, not even a grandchild or +//// itself; a refused call reaches the coordinator with nothing. A cancel +//// stops the session's turn, and with `tree` the turns of everything +//// beneath it, parents first; it answers the sessions that were running, +//// so the handle reads True when a turn ran. `cancel_all` does that for +//// every child of the caller. +//// +//// Defects: a stranger, a grandparent, a sibling or the session itself +//// allowed to stop or close one; a refused call that still reaches the +//// coordinator; a cancel with `tree` that misses a descendant, stops one +//// before its parent, or answers sessions that were not running. The tool +//// runs in process over a real family store with a coordinator that +//// records what it is asked; families of up to seven roots, children and +//// peers are generated, and every caller and target pair is tried. import albedo/composition/extensions import albedo/history/conversation @@ -28,6 +44,11 @@ import gleam/list import gleam/option.{None} import sqlight +import albedo_property +import gleam/int +import gleam/string +import qcheck.{type Generator} + /// A cancel on a peer stopped only the peer and answered no sessions, so /// `cancel()` read False while its turn ran, and `tree=True` left what ran /// beneath it running. It answers like a child's: what was running, the @@ -84,6 +105,297 @@ type World { ) } +type Kind { + Root + /// A child of an earlier session. + ChildOf(Int) + /// A root peer an earlier session started. + PeerOf(Int) +} + +type Node { + Node(kind: Kind, running: Bool) +} + +fn node(index: Int) -> Generator(Node) { + let kind = case index { + 0 -> qcheck.return(Root) + _ -> + // Often under the session just made, so chains three deep, where a + // cancel with the tree must reach a grandchild, are common. + qcheck.from_weighted_generators(#(1, qcheck.return(Root)), [ + #(3, qcheck.return(ChildOf(index - 1))), + #(2, qcheck.map(qcheck.bounded_int(0, index - 1), ChildOf)), + #(2, qcheck.map(qcheck.bounded_int(0, index - 1), PeerOf)), + ]) + } + qcheck.map2(kind, qcheck.bool(), Node) +} + +fn generated() -> Generator(List(Node)) { + use size <- qcheck.bind(qcheck.bounded_int(2, 7)) + int.range(from: 0, to: size, with: [], run: fn(drawn, index) { + [index, ..drawn] + }) + |> list.reverse + |> list.fold(qcheck.return([]), fn(drawn, index) { + qcheck.map2(drawn, node(index), fn(nodes, node) { + list.append(nodes, [node]) + }) + }) +} + +/// A generated family over the shared family. +type Family { + Family(world: World, ids: List(String), nodes: List(Node)) +} + +pub fn only_a_parent_or_starter_acts_and_a_cancel_stops_what_is_beneath_test_() -> albedo_property.Timed { + use <- albedo_property.within(120) + let home = scratch.directory("agents-control-") + let assert Ok(host) = + runtime.start_with_config(home <> "/albedo.db", extensions.Config([], [])) + session_fixture.initialise(host) + albedo_property.run(40, generated(), fn(nodes) { + let family = build(host, home, nodes) + let pairs = + list.flat_map(family.ids, fn(caller) { + list.map(family.ids, fn(target) { #(caller, target) }) + }) + list.each(pairs, fn(pair) { check_pair(family, pair.0, pair.1) }) + list.each(family.ids, fn(caller) { check_cancel_all(family, caller) }) + }) + runtime.stop(host) +} + +fn check_pair(family: Family, caller: String, target: String) -> Nil { + let allowed = owns(family, caller, target) + let what = fn(op) { + op + <> " by " + <> caller + <> " on " + <> target + <> " in " + <> string.inspect(family.nodes) + } + // switch + let got = + call(family.world, caller, "agents.switch", [ + #("id", json.string(target)), + #("model", json.string("m")), + ]) + let asked = drain(family.world) + case allowed { + True -> { + let assert Ok(_) = got as what("switch") + assert asked == [control.Switch(caller, target, "m")] as what("switch") + } + False -> { + let assert Error(_) = got as what("switch") + assert asked == [] as what("switch") + } + } + // cancel, alone and with the tree + list.each([False, True], fn(tree) { + let got = + call(family.world, caller, "agents.cancel", [ + #("id", json.string(target)), + #("tree", json.bool(tree)), + ]) + let asked = drain(family.world) + let name = what("cancel tree=" <> string.inspect(tree)) + case allowed { + True -> { + let stopped = stops(asked) + assert list.length(stopped) == list.length(asked) as name + let expected = case tree { + False -> [target] + True -> [target, ..beneath(family, target)] + } + assert list.sort(stopped, string.compare) + == list.sort(expected, string.compare) + as name + assert parents_first(family, stopped) as name + let assert Ok(answer) = got as name + assert json.to_string(answer) == running_in(family, stopped) as name + } + False -> { + let assert Error(_) = got as name + assert asked == [] as name + } + } + }) + // close + let got = + call(family.world, caller, "agents.close", [#("id", json.string(target))]) + let asked = drain(family.world) + case allowed { + True -> { + let assert Ok(_) = got as what("close") + assert asked == [control.Close(target)] as what("close") + } + False -> { + let assert Error(_) = got as what("close") + assert asked == [] as what("close") + } + } +} + +fn check_cancel_all(family: Family, caller: String) -> Nil { + list.each([False, True], fn(tree) { + let got = + call(family.world, caller, "agents.cancel_all", [ + #("tree", json.bool(tree)), + ]) + let asked = drain(family.world) + let name = + "cancel_all tree=" + <> string.inspect(tree) + <> " by " + <> caller + <> " in " + <> string.inspect(family.nodes) + let children = children_of(family, caller) + let expected = case tree { + False -> children + True -> + list.flat_map(children, fn(child) { [child, ..beneath(family, child)] }) + } + let stopped = stops(asked) + assert list.sort(stopped, string.compare) + == list.sort(expected, string.compare) + as name + assert parents_first(family, stopped) as name + let assert Ok(answer) = got as name + assert json.to_string(answer) == running_in(family, stopped) as name + }) +} + +// ---- the oracle ------------------------------------------------------------- + +fn index_of(family: Family, id: String) -> Int { + let assert Ok(index) = + list.index_map(family.ids, fn(each, index) { #(each, index) }) + |> list.key_find(id) + index +} + +fn node_of(family: Family, id: String) -> Node { + let assert Ok(node) = + list.drop(family.nodes, index_of(family, id)) |> list.first + node +} + +fn id_of(family: Family, index: Int) -> String { + let assert Ok(id) = list.drop(family.ids, index) |> list.first + id +} + +fn owns(family: Family, caller: String, target: String) -> Bool { + case node_of(family, target).kind { + ChildOf(parent) | PeerOf(parent) -> id_of(family, parent) == caller + Root -> False + } +} + +fn children_of(family: Family, parent: String) -> List(String) { + family.ids + |> list.filter(fn(id) { + case node_of(family, id).kind { + ChildOf(index) -> id_of(family, index) == parent + _ -> False + } + }) +} + +/// Every session beneath `id` through children (not peers it started). +fn beneath(family: Family, id: String) -> List(String) { + list.flat_map(children_of(family, id), fn(child) { + [child, ..beneath(family, child)] + }) +} + +/// No session is stopped before its parent, when both are stopped. +fn parents_first(family: Family, stopped: List(String)) -> Bool { + let at = + list.index_map(stopped, fn(id, index) { #(id, index) }) |> dict.from_list + list.all(stopped, fn(id) { + case node_of(family, id).kind { + ChildOf(parent) -> + case dict.get(at, id_of(family, parent)), dict.get(at, id) { + Ok(before), Ok(after) -> before < after + _, _ -> True + } + _ -> True + } + }) +} + +fn running_in(family: Family, stopped: List(String)) -> String { + stopped + |> list.filter(fn(id) { node_of(family, id).running }) + |> json.array(json.string) + |> json.to_string +} + +fn stops(asked: List(control.Op)) -> List(String) { + list.filter_map(asked, fn(op) { + case op { + control.Stop(session) -> Ok(session) + _ -> Error(Nil) + } + }) +} + +// ---- the world -------------------------------------------------------------- + +fn build(host: runtime.Runtime, home: String, nodes: List(Node)) -> Family { + let ledger = runtime.ledger(host) + let run = int.to_string(int.random(1_000_000_000)) + let ids = + list.index_fold(nodes, [], fn(ids, node, index) { + let id = "agents-" <> run <> "-" <> int.to_string(index) + let info = info(id, home) + case node.kind { + Root | PeerOf(_) -> { + let assert Ok(_) = conversation.create(ledger, info) + Nil + } + ChildOf(parent) -> { + let assert Ok(parent) = list.drop(ids, parent) |> list.first + let assert Ok(_) = + conversation.create_child( + ledger, + info, + parent, + "kid" <> int.to_string(index), + "", + ) + Nil + } + } + case node.kind { + PeerOf(starter) -> { + let assert Ok(starter) = list.drop(ids, starter) |> list.first + let assert Ok(_) = + store.write(ledger, "UPDATE sessions SET started_by=? WHERE id=?", [ + sqlight.text(starter), + sqlight.text(id), + ]) + Nil + } + _ -> Nil + } + list.append(ids, [id]) + }) + let running = + list.zip(ids, nodes) + |> list.map(fn(pair) { #(pair.0, { pair.1 }.running) }) + |> dict.from_list + Family(World(host, process.new_subject(), running), ids, nodes) +} + fn info(id: String, workspace: String) -> session_info.Info { session_info.Info( id, diff --git a/e2e/agents_test.py b/e2e/agents_test.py index bc286b3e5..9b3ddfe72 100644 --- a/e2e/agents_test.py +++ b/e2e/agents_test.py @@ -1294,43 +1294,6 @@ for target, model in [({child!r}, 'no-such-switch-model'), self.assertIsNone(snapshot["workspace_change"]) self.assertFalse((self.app.workspace / "restored-child-cwd").exists()) - def test_cancel_all_stops_every_running_turn_beneath_the_caller(self): - entered = {"mid": threading.Event(), "leaf": threading.Event()} - release = threading.Event() - self.addCleanup(release.set) - answer = self.provider.script - - def held(request): - user = latest_user(request) - for name, gate in entered.items(): - if f"hold {name}" in user: - gate.set() - release.wait(30) - return text("held turn ended") - if request["messages"][-1].get("role") == "user" and user == "stop all": - return python("print(sorted(await agents.cancel_all()))") - return answer(request) - - self.provider.script = held - parent = self.app.session() - mid = self.spawn(parent, "mid", "hold mid")["id"] - leaf = self.spawn(mid, "leaf", "hold leaf")["id"] - for gate in entered.values(): - self.assertTrue(gate.wait(30), "a held turn never reached the provider") - self.send(parent, "stop all") - for session in (parent, mid, leaf): - self.app.idle(session) - self.assertFalse(release.is_set()) - result = next( - json.loads(part["value"]) - for entry in reversed(self.app.history(parent)["items"]) - if entry["kind"] == "tool_result" - for part in entry["content"] - if part["kind"] == "json" and part["field"] == "result" - ) - self.assertEqual(result["status"], "ok", result) - self.assertEqual(result["output"].strip(), str(sorted([mid, leaf]))) - def test_a_closed_child_is_not_woken_by_a_job_that_finishes_later(self): calls = [] answer = self.provider.script @@ -1638,38 +1601,6 @@ for target, model in [({child!r}, 'no-such-switch-model'), finally: self.provider.script = answer - def test_only_starter_can_cancel_and_close_peer(self): - starter = self.app.session() - peer = self.execute( - starter, - "peer = await agents.start('authorization task', name='owned-peer', model=" - + repr(f"{self.alpha}/fixture-alpha-{self.provider.route}") - + ")\n" - "print(peer.id)", - ).strip() - self.app.idle(peer) - stranger = self.app.session() - output = self.execute( - stranger, - "target = await agents.get(" + repr(peer) + ")\n" - "errors = []\n" - "for action in (target.cancel, target.close):\n" - " try:\n" - " await action()\n" - " except Exception as error:\n" - " errors.append(str(error))\n" - "assert len(errors) == 2, errors\n" - "print('refused')", - ) - self.assertIn("refused", output) - self.execute( - starter, - "target = await agents.get(" + repr(peer) + ")\n" - "await target.cancel()\n" - "await target.close()", - ) - self.assertTrue(self.snapshot(peer)["closed"]) - @exclusive def test_close_saves_a_kernel_after_its_session_worker_dies(self) -> None: parent = self.app.session()