From 6df32553307a0ed50feb1c3a6c424c412927f7ff Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 19 Nov 2026 22:30:50 +0100 Subject: [PATCH] Delete the run opener, the work queue and the breaker (C2 follow-up, Soul F3) Map section 7 keeps no dormant switch in main: Self-run launching is parked at parked/self-run-launch. open_and_launch was the only code that opened a SelfRun run and nothing called it in production. launch.rs keeps the systemd door (Launcher, SystemdLauncher, unit names, the brake's stop) and the two reads self_run uses, holders and closure. Deleted: open_and_launch, Ports, LaunchRequest, LaunchOutcome, Declined, slot, START_GRACE_S, run_label, the dead-run closer and the breaker question, with their tests. queue.rs keeps MindPort, HuginnMind, the paged reads and on_hold, which self_run's inbox reads. Deleted: queue, breaker, Breaker, CONSECUTIVE, WINDOW, EMPTY_SHARE, live_claims, claims_of, with their tests. control: Grant::for_test and the launch-gate tests went with the gate. testkit: the helpers only those tests used. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/control.rs | 24 +- crates/mind-body/src/control/tests.rs | 96 -- crates/mind-body/src/launch.rs | 1211 +------------------------ crates/mind-body/src/lib.rs | 5 +- crates/mind-body/src/queue.rs | 461 +--------- crates/mind-body/src/testkit.rs | 80 +- 6 files changed, 42 insertions(+), 1835 deletions(-) diff --git a/crates/mind-body/src/control.rs b/crates/mind-body/src/control.rs index 64de05d..7a37f50 100644 --- a/crates/mind-body/src/control.rs +++ b/crates/mind-body/src/control.rs @@ -1,8 +1,8 @@ //! The operator's brakes, and the one reader of them. //! -//! `Released` carries a `Grant`, the only value that opens a launch: it cannot -//! be built outside this module, so a launch exists only as the reading of a -//! released instance brake and a released swarm brake. The Grant names the +//! `Released` carries a `Grant`: it cannot be built outside this module, so it +//! exists only as the reading of a released instance brake and a released +//! swarm brake. The Grant names the //! instance whose store was read and carries nothing else: no money, no cap. The store is at a fixed place, `CONTROL_ROOT`, //! and the one reader takes the instance only: no function, argument, variable //! or flag lets a caller choose a root, a path or a source, so a Grant is the @@ -92,9 +92,7 @@ pub enum Effective { /// The proof that the instance brake and the swarm brake were released when /// read, in the root-owned stores of `instance`. Its fields are private and only -/// `read_effective` makes one; `open_and_launch` takes it by value and refuses -/// one read for another instance, so one reading opens at most one run, of the -/// instance it was read for. +/// `read_effective` makes one. /// /// Outside this crate the type system leaves no way to make one: the fields are /// private, there is no public constructor, and the derives give no path (no @@ -113,7 +111,7 @@ pub enum Effective { /// ``` /// /// ```compile_fail,E0599 -/// // not Clone, so a reading cannot be copied into a second run +/// // not Clone, so a reading cannot be copied /// fn copy(grant: &mind_body::control::Grant) -> mind_body::control::Grant { /// grant.clone() /// } @@ -140,13 +138,6 @@ impl Grant { pub fn instance(&self) -> &Slug { &self.instance } - - /// A Grant for a launch test that has no store. It names its instance like - /// any other, so the launch's instance check judges it. - #[cfg(test)] - pub(crate) fn for_test(instance: Slug) -> Self { - Self { instance } - } } /// The instance store's contents, decoded and not yet judged. @@ -237,11 +228,6 @@ pub fn load_state(source: &impl ControlSource) -> Result { /// let _ = mind_body::control::read_effective_from; /// ``` /// -/// ```compile_fail -/// // and the test constructor is not in the library build -/// let _ = mind_body::control::Grant::for_test; -/// ``` -/// /// The same preamble with the real call compiles: /// /// ``` diff --git a/crates/mind-body/src/control/tests.rs b/crates/mind-body/src/control/tests.rs index 83d9719..c8d8be0 100644 --- a/crates/mind-body/src/control/tests.rs +++ b/crates/mind-body/src/control/tests.rs @@ -67,96 +67,6 @@ fn a_brake_payload_that_does_not_decode_makes_the_store_undecodable() { assert_eq!(effective(&path), held(HeldReason::Undecodable)); } - - -mod grant { - //! A Grant is the proof that this instance's own control store released: the - //! reader derives the path from the instance, and a launch refuses a Grant - //! read for another instance before it asks the mind anything. - - use anyhow::{Result, anyhow}; - use cultnet_rs::Selection; - use eureka_pipeline::{PipelineDocument, RunTurn}; - use huginn_mind::{PipelineAdmissionOutcome, PipelineSelectionPage}; - - use super::*; - use crate::launch::{Clock, Declined, LaunchOutcome, LaunchRequest, Launcher, Ports, open_and_launch}; - use crate::queue::MindPort; - - fn slug(name: &str) -> Slug { - Slug(name.into()) - } - - fn read(root: &Path, instance: &str) -> Effective { - with_root(root, || read_effective(&slug(instance))) - } - - /// A mind that answers nothing: a launch that reaches it has gone past the - /// instance check. - struct SilentMind(Slug); - - impl MindPort for SilentMind { - fn instance(&self) -> &Slug { - &self.0 - } - - fn query(&self, _selection: &Selection) -> Result { - Err(anyhow!("the launch asked the mind")) - } - - fn admit(&self, _agent: &str, _session: &str, _documents: Vec) -> Result { - Err(anyhow!("the launch admitted")) - } - } - - struct NoUnits; - - impl Launcher for NoUnits { - fn start(&self, _instance: &Slug, _turn: RunTurn) -> Result<()> { - Err(anyhow!("the launch started a unit")) - } - - fn alive(&self, _instance: &Slug, _turn: RunTurn) -> bool { - false - } - } - - struct Now; - - impl Clock for Now { - fn now(&self) -> DateTime { - at(100) - } - } - - fn launch_as(mind_instance: &str, grant: Grant, turn: RunTurn) -> Result { - let mind = SilentMind(slug(mind_instance)); - let ports = Ports { mind: &mind, launcher: &NoUnits, clock: &Now, host: "host" }; - open_and_launch(&ports, LaunchRequest { turn, claims: vec![], agent: "agent".into(), grant }) - } - - #[test] - fn a_grant_read_for_one_instance_cannot_launch_another() { - let root = tempfile::tempdir().unwrap(); - release(root.path(), "void"); - for turn in [RunTurn::SelfRun, RunTurn::PersonaTurn] { - let Effective::Released(grant) = read(root.path(), "void") else { panic!("void's store is released") }; - // The mind is eureka's; the silent mind and the unit-less launcher fail loudly if the launch goes on. - let outcome = launch_as("eureka", grant, turn).unwrap(); - assert_eq!(outcome, LaunchOutcome::Refused(Declined::GrantForOtherInstance), "{turn:?}"); - } - } - - #[test] - fn the_matching_grant_is_not_stopped_by_the_instance_check() { - let root = tempfile::tempdir().unwrap(); - release(root.path(), "void"); - let Effective::Released(grant) = read(root.path(), "void") else { panic!("void's store is released") }; - let error = launch_as("void", grant, RunTurn::SelfRun).unwrap_err(); - assert!(format!("{error:#}").contains("asked the mind"), "{error:#}"); - } -} - /// The swarm store with its brake released, and nothing else in it. fn release_swarm(root: &Path) { SwarmWriter::open(swarm_path(root)).unwrap().set_brake(true, at(0), "op").unwrap(); @@ -250,12 +160,6 @@ fn the_stores_are_written_world_readable_and_root_only_writable() { let _ = path; } -/// A named instance store with its brake released, and a released swarm. -fn release(root: &Path, name: &str) { - ControlWriter::open(root.join(name).join("control.cc")).unwrap().set_brake(true, at(0), "op").unwrap(); - release_swarm(root); -} - #[test] fn a_writer_refuses_to_open_over_a_store_holding_a_record_it_does_not_read() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/mind-body/src/launch.rs b/crates/mind-body/src/launch.rs index f43afd4..2662879 100644 --- a/crates/mind-body/src/launch.rs +++ b/crates/mind-body/src/launch.rs @@ -1,45 +1,19 @@ -//! The one way her organs open a run and start its unit. +//! Her units under systemd, and the reads of the runs a Self run holds. //! -//! `open_and_launch` is the whole path, in this order: (0) the in-force runs of -//! hers of the request's turn are read through `slot`, which tells a live one -//! (its unit active, or admitted within `START_GRACE_S`: it answers Busy) from a -//! dead one (to be closed Recorded); (1) every cut-spec claim must be in the queue; (2) no claim may be held by an open question (the gate reads the hold itself, once, after the breaker reads and just before the admission, and takes no caller's word for it), and none may -//! trip the repetition breaker (a trip raises one question in the run whose end -//! tripped it, which holds that run's claims); (3) the run is admitted, in the one batch that -//! closes the dead holders, so liveness is decided by the in-force record alone -//! and the unit table is only the evidence for a close; (4) the unit is started, -//! only after that batch commits. The run is the grant (target invariant -//! run-is-the-grant), so there is no pressure file, lease or breaker state -//! beside it, and a unit never starts without a committed run. A run opens -//! only against a `Grant`, which `read_effective` alone makes and which names -//! the instance it was read for: a Grant of another instance is refused. A -//! Persona turn's run opens with no claims, so a request that carries any is -//! refused. The primitive -//! owns no file and stops no unit through the `Launcher` port: stopping her -//! units is either brake's hold (one Mind's, or the swarm's for every Mind), -//! through `SystemdLauncher::stop`. - +//! `Launcher` starts a turn's unit and says whether it lives; `SystemdLauncher` +//! is it over `systemctl`, and its `stop` is the one stop a brake hold calls. +//! `holders` reads the in-force runs of hers of one slot, and `closure` builds +//! the closing resolution of a run that ended without its own flush; `self_run` +//! uses both. Nothing here opens a run: Self-run launching is parked at tag +//! `parked/self-run-launch` (ruling `eureka-body:ruling:persona-only-heartbeat`). use anyhow::{Result, anyhow}; -use chrono::{DateTime, Duration, Utc}; +use chrono::{DateTime, Utc}; use cultnet_rs::Selection; -use eureka_pipeline::{ - Date, Label, PipelineDocument, PipelineKind, PipelineQuestion, PipelineRef, PipelineResolution, PipelineRun, QuestionOption, ResolutionOutcome, - RunOperator, RunSlot, RunTurn, Slug, pipeline_key, -}; -use huginn_mind::{ - MindRefusal, PipelineAdmissionOutcome, PipelineDocumentSummary, PipelineFacts, -}; +use eureka_pipeline::{Date, PipelineDocument, PipelineKind, PipelineRef, PipelineResolution, ResolutionOutcome, RunOperator, RunSlot, RunTurn, Slug}; +use huginn_mind::{PipelineDocumentSummary, PipelineFacts}; -use crate::control::Grant; -use crate::queue::{ - Breaker, MindPort, any_of, breaker, citing, claims_of, headers, in_force, of_kind, on_hold, queue, -}; -use eureka_state::hold::RETIRE; - -/// How long a run just admitted may have no active unit before its slot is -/// treated as dead: `systemctl start --no-block` returns before the unit runs. -pub const START_GRACE_S: i64 = 120; +use crate::queue::{MindPort, any_of, citing, headers, in_force, of_kind}; /// Starts the unit that carries a run, and says whether it is still running. /// Nothing here stops a unit. @@ -50,7 +24,7 @@ pub trait Launcher { fn alive(&self, instance: &Slug, turn: RunTurn) -> bool; } -/// The time the primitive reads: run labels, dates and receipts. +/// The time her organs read: dates and receipts. pub trait Clock { fn now(&self) -> DateTime; } @@ -93,8 +67,7 @@ impl Systemctl for RealSystemctl { /// `mind-persona@.service` and /// `mind-self@.service` (ruling mind-unit-names: one live run per /// instance and turn, so the run label names no unit). The launcher holds no instance: the -/// caller names it on every call, and `open_and_launch` always names the -/// mind's own. +/// caller names it on every call. pub struct SystemdLauncher { systemctl: Box, } @@ -234,95 +207,13 @@ impl Launcher for SystemdLauncher { } } -/// A run's label from the instant it opens: UTC, to the millisecond. Two -/// launches in one millisecond collide on the run's key, admission answers -/// Conflict, and nothing launches. -pub fn run_label(now: DateTime) -> Label { - Label(now.format("mind-%Y%m%dT%H%M%S%3fZ").to_string()) -} - -pub struct Ports<'a> { - pub mind: &'a dyn MindPort, - pub launcher: &'a dyn Launcher, - pub clock: &'a dyn Clock, - /// The `host` the run records. - pub host: &'a str, -} - -pub struct LaunchRequest { - pub turn: RunTurn, - pub claims: Vec, - /// The admitting agent's name on the receipt. - pub agent: String, - /// The reading of a released instance brake and a released swarm brake. - /// Taken by value, so one reading opens at most one run. - pub grant: Grant, -} - -/// Why admission did not open the run: its own refusal, or one of the two -/// answers that mean the run's key is taken. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Declined { - Admission(MindRefusal), - Conflict, - AlreadyAdmitted, - /// The run committed, its unit did not start, and the run was withdrawn. - StartFailed, - /// The Grant was read for another instance than the mind's own. - GrantForOtherInstance, - /// A Persona turn's run opens with no claims (ruling wake-target). - PersonaRunTakesNoClaims, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum LaunchOutcome { - Launched { - run: PipelineRef, - }, - NotQueued { - item: PipelineRef, - }, - /// The trip belongs to `run`, the run whose end tripped it; `question` is raised in it. - Tripped { - run: PipelineRef, - question: PipelineRef, - }, - /// The live holder of the request's turn, from step 0 or from admission. - Busy { - run: PipelineRef, - }, - Refused(Declined), -} - fn date(now: DateTime) -> Date { Date(now.format("%Y-%m-%d").to_string()) } -/// The root of a full pipeline id: the campaign slug of a campaign's document. -fn root_of(item: &PipelineRef) -> &str { - item.id.0.split(':').next().unwrap_or_default() -} - -fn key_of(document: &PipelineDocument) -> Result { - pipeline_key(document).map_err(|_| anyhow!("the document could not be keyed")) -} - -/// Whether a run admitted at `admitted_at` has had `START_GRACE_S` to start -/// its unit. A stamp that does not parse has not. -fn past_grace(admitted_at: &str, now: DateTime) -> bool { - DateTime::parse_from_rfc3339(admitted_at).is_ok_and(|at| now.signed_duration_since(at) >= Duration::seconds(START_GRACE_S)) -} - -/// The resolution that closes a dead run of hers: Recorded, not Withdrawn, so -/// a unit that keeps dying counts as an empty run and trips the breaker. -fn close_dead(mind: &dyn MindPort, run: &PipelineRef, now: DateTime) -> Result { - closure(mind, run, now, ResolutionOutcome::Recorded { reason: "unit not active".into() }, "The run's unit was not active when its turn's slot was next wanted.") -} - /// The closing resolution of `run` with `outcome`. Its sequence is the run's /// next, counting a closure that was itself withdrawn. The one builder of a -/// closure for a run that ended without its own flush: a dead unit -/// (`close_dead`, Recorded: it counts as an empty run) and a Self run whose +/// closure for a run that ended without its own flush: a Self run whose /// credential lease was refused (`self_run`, Recorded for a refusal, Withdrawn /// for a misconfigured length: no run happened and none is counted). pub(crate) fn closure(mind: &dyn MindPort, run: &PipelineRef, now: DateTime, outcome: ResolutionOutcome, rationale: &str) -> Result { @@ -345,9 +236,8 @@ pub(crate) fn closure(mind: &dyn MindPort, run: &PipelineRef, now: DateTime } /// The in-force runs of hers (operated by the mind) of `turn` on `instance`, -/// read from typed facts: the holders of that turn's slot. The one reader of -/// the slot, for step 0 and for checking a holder admission names. `self_run` -/// reads her open Self run through it too. +/// read from typed facts: the holders of that turn's slot. `self_run` reads +/// her open Self run through it. pub(crate) fn holders(mind: &dyn MindPort, instance: &Slug, turn: RunTurn) -> Result> { let runs = headers(mind, &in_force(any_of(of_kind(PipelineKind::Run), "root", &[&instance.0])))?; Ok(runs @@ -356,1080 +246,11 @@ pub(crate) fn holders(mind: &dyn MindPort, instance: &Slug, turn: RunTurn) -> Re .collect()) } -/// The holders of a turn's slot, told apart: the live one, if any (its unit -/// active, or admitted within `START_GRACE_S`), and the dead, which the next -/// launch closes. The one reader of whether a holder lives: step 0 and the -/// heartbeat's claim of briefs both ask here. -pub(crate) struct Slot { - pub live: Option, - pub dead: Vec, -} - -pub(crate) fn slot( - ports: &Ports, - instance: &Slug, - turn: RunTurn, - now: DateTime, -) -> Result { - let mut found = Slot { - live: None, - dead: Vec::new(), - }; - for holder in holders(ports.mind, instance, turn)? { - if ports.launcher.alive(instance, turn) || !past_grace(&holder.admission.admitted_at, now) { - found.live = Some(holder.id); - return Ok(found); - } - found.dead.push(holder.id); - } - Ok(found) -} - -pub fn open_and_launch(ports: &Ports, request: LaunchRequest) -> Result { - let LaunchRequest { - turn, - claims, - agent, - grant, - } = request; - let instance = ports.mind.instance().clone(); - if grant.instance() != &instance { - return Ok(LaunchOutcome::Refused(Declined::GrantForOtherInstance)); - } - if turn != RunTurn::SelfRun && !claims.is_empty() { - return Ok(LaunchOutcome::Refused(Declined::PersonaRunTakesNoClaims)); - } - let now = ports.clock.now(); - let label = run_label(now); - - // Step 0: a live holder of this turn's slot answers Busy; a dead one is closed - // in the batch that admits whatever comes next. - let mut batch: Vec = Vec::new(); - let mut ending: Vec = Vec::new(); - let found = slot(ports, &instance, turn, now)?; - if let Some(run) = found.live { - return Ok(LaunchOutcome::Busy { run }); - } - for dead in found.dead { - batch.push(close_dead(ports.mind, &dead, now)?); - ending.push(dead); - } - - if turn == RunTurn::SelfRun { - // Every read of the breaker comes first, so the hold snapshot below is the - // last read of the mind before the admission; a refusal by a hold still - // outranks a trip. - let mut tripped: Option<(&PipelineRef, PipelineRef)> = None; - for item in &claims { - if let Breaker::Trip { run } = breaker(ports.mind, item, &ending)? { - tripped = Some((item, run)); - break; - } - } - let held = on_hold(ports.mind)?; - let open = queue(ports.mind, &instance, &ending, &held)?; - if let Some(item) = claims.iter().find(|claim| { - held.contains(claim) || (claim.kind == PipelineKind::CutSpec && !open.contains(claim)) - }) { - return Ok(LaunchOutcome::NotQueued { item: item.clone() }); - } - if let Some((item, run)) = tripped { - let count = claims_of(ports.mind, &run)?.len(); - let question = - PipelineDocument::Question(breaker_question(item, &run, count, &label, now)); - let id = PipelineRef { - kind: PipelineKind::Question, - id: key_of(&question)?.as_str().into(), - }; - batch.push(question); - return Ok(match committed(ports.mind.admit(&agent, &label.0, batch)?) { - Ok(()) => LaunchOutcome::Tripped { run, question: id }, - Err(declined) => LaunchOutcome::Refused(declined), - }); - } - } - - let mut campaigns: Vec = Vec::new(); - for claim in &claims { - let root = Slug(root_of(claim).to_string()); - if !campaigns.contains(&root) { - campaigns.push(root); - } - } - let run = PipelineDocument::Run(PipelineRun { - instance: instance.clone(), - label: label.clone(), - operated_by: RunOperator::Mind, - turn, - host: ports.host.into(), - started_on: date(now), - // The field is dead record: nothing reads it, and the schema revision that drops it is a follow-up. - budget_usd: "0".into(), - claims, - campaigns, - }); - let opened = PipelineRef { kind: PipelineKind::Run, id: key_of(&run)?.as_str().into() }; - batch.push(run); - match ports.mind.admit(&agent, &label.0, batch)? { - // The holder is a claim until the mind shows it: a run of this instance's own, of this turn, in force. - PipelineAdmissionOutcome::Refused(MindRefusal::AlreadyLive { run: named }) => { - let held = named.to_ref(); - return Ok(if holders(ports.mind, &instance, turn)?.iter().any(|holder| holder.id == held) { - LaunchOutcome::Busy { run: held } - } else { - LaunchOutcome::Refused(Declined::Admission(MindRefusal::AlreadyLive { run: named })) - }); - } - answer => { - if let Err(declined) = committed(answer) { - return Ok(LaunchOutcome::Refused(declined)); - } - } - } - if ports.launcher.start(&instance, turn).is_err() { - let withdrawal = PipelineResolution { - subject: opened, - sequence: 1, - outcome: ResolutionOutcome::Withdrawn { reason: "the unit failed to start".into() }, - rationale: "The run committed and its unit did not start, so it holds no work.".into(), - resolved_on: date(now), - }; - return match committed(ports.mind.admit(&agent, &label.0, vec![PipelineDocument::Resolution(withdrawal)])?) { - Ok(()) => Ok(LaunchOutcome::Refused(Declined::StartFailed)), - Err(_) => Err(anyhow!("the run could not be withdrawn after its unit failed to start")), - }; - } - Ok(LaunchOutcome::Launched { run: opened }) -} - -/// Whether admission landed the batch; if not, why. -fn committed(outcome: PipelineAdmissionOutcome) -> Result<(), Declined> { - match outcome { - PipelineAdmissionOutcome::Committed { .. } => Ok(()), - PipelineAdmissionOutcome::Refused(refusal) => Err(Declined::Admission(refusal)), - PipelineAdmissionOutcome::Conflict { .. } => Err(Declined::Conflict), - PipelineAdmissionOutcome::AlreadyAdmitted { .. } => Err(Declined::AlreadyAdmitted), - } -} - -/// `breaker-`: one question per trip, since each trip is a launch -/// with a label of its own. -fn breaker_label(label: &Label) -> Label { - Label(format!("breaker-{}", label.0)) -} - -/// The question a trip raises, in the campaign of the claim that tripped: one -/// per trip, raised in `run` and holding the `held` claims it claimed. -fn breaker_question(claim: &PipelineRef, run: &PipelineRef, held: usize, label: &Label, now: DateTime) -> PipelineQuestion { - PipelineQuestion { - campaign: Slug(root_of(claim).to_string()), - label: breaker_label(label), - title: "Repeated runs on the same work admitted nothing".into(), - question: format!( - "Run {} and the runs before it left nothing that cites the work it held (claims held: {held}), so none of it launches again. Answering with reopen, or withdrawing this, reopens every claim of that run with a fresh count. To stop working them, resolve the claims, then answer with retire.", - run.id.0 - ) - .as_str() - .into(), - options: vec![ - QuestionOption { label: "reopen".into(), text: "Answer to reopen every claim of the run with a fresh count.".into() }, - QuestionOption { label: RETIRE.into(), text: "Resolve the claims so they are no longer worked, and answer with this option.".into() }, - ], - recommended: "reopen".into(), - depends: vec![], - raised_in: Some(run.clone()), - asked_on: date(now), - } -} - #[cfg(test)] mod tests { use std::cell::{Cell, RefCell}; - use eureka_pipeline::PipelineKind as K; - use huginn_mind::{PipelineAdmissionOutcome as Outcome, PipelineSelectionPage, PipelineStatus}; - use super::*; - use crate::testkit::*; - - struct Rig { - mind: TestMind, - launcher: Recording, - clock: Fixed, - } - - impl Rig { - fn new() -> Self { - Self { mind: TestMind::seeded(), launcher: Recording::default(), clock: Fixed(Cell::new(at(0))) } - } - - fn launch(&self, turn: RunTurn, claims: &[PipelineRef]) -> LaunchOutcome { - self.launch_through(&self.mind, turn, claims) - } - - fn launch_through(&self, mind: &dyn MindPort, turn: RunTurn, claims: &[PipelineRef]) -> LaunchOutcome { - self.try_launch_through(mind, turn, claims).unwrap() - } - - fn try_launch_through(&self, mind: &dyn MindPort, turn: RunTurn, claims: &[PipelineRef]) -> Result { - let ports = Ports { mind, launcher: &self.launcher, clock: &self.clock, host: "yggdrasil-host" }; - let grant = Grant::for_test(Slug(INSTANCE.into())); - open_and_launch( - &ports, - LaunchRequest { - turn, - claims: claims.to_vec(), - agent: "agent-x".into(), - grant, - }, - ) - } - - fn at(&self, milliseconds: i64) { - self.clock.0.set(at(milliseconds)); - } - - /// The clock `seconds` after the run with this id was admitted. - fn age(&self, run: &str, seconds: i64) { - let admitted = self.mind.view(K::Run, run).unwrap().admission.admitted_at; - let admitted = DateTime::parse_from_rfc3339(&admitted).unwrap().with_timezone(&Utc); - self.clock.0.set(admitted + Duration::seconds(seconds)); - } - - fn started(&self) -> usize { - self.launcher.started.borrow().len() - } - - fn runs(&self) -> usize { - self.mind.ids(K::Run).len() - } - - /// A run of hers in force, with a unit that is running. - fn seed(&self, label: &str, turn: RunTurn, claims: &[PipelineRef]) { - self.mind.committed(vec![run(label, turn, RunOperator::Mind, claims)]); - self.launcher.revive(turn); - } - - fn in_force(&self, run: &str) -> bool { - self.mind.view(K::Run, &run_ref(run).id.0).unwrap().status == PipelineStatus::InForce - } - } - - fn the_run(view: &huginn_mind::PipelineDocumentView) -> &PipelineRun { - let PipelineDocument::Run(run) = &view.document else { panic!("not a run") }; - run - } - - fn the_closure(rig: &Rig, run: &str, sequence: u32) -> (PipelineResolution, String) { - let view = rig.mind.view(K::Resolution, &format!("{INSTANCE}:resolution:run.{run}.n{sequence}")).expect("the closure"); - let PipelineDocument::Resolution(closure) = view.document else { panic!("not a resolution") }; - (closure, view.admission.receipt_id) - } - - #[test] - fn a_queued_spec_opens_a_run_that_records_its_launch_and_then_its_unit_starts() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x")]); - let LaunchOutcome::Launched { run } = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]) else { panic!("not launched") }; - assert_eq!(run.id.0, "yggdrasil:run:mind-20261009T131500000Z"); - let view = rig.mind.view(K::Run, &run.id.0).unwrap(); - let held = the_run(&view); - assert_eq!((held.operated_by, held.turn), (RunOperator::Mind, RunTurn::SelfRun)); - assert_eq!((held.host.0.as_str(), held.started_on.0.as_str(), held.budget_usd.0.as_str()), ("yggdrasil-host", "2026-10-09", "0")); - assert_eq!(held.claims, vec![spec_ref("x")]); - assert_eq!(held.campaigns, vec![Slug(CAMPAIGN.into())]); - assert_eq!(view.admission.provenance.agent.0, "agent-x"); - assert_eq!(view.admission.provenance.session.0, "mind-20261009T131500000Z"); - assert_eq!(*rig.launcher.started.borrow(), vec![(Slug(INSTANCE.into()), RunTurn::SelfRun)]); - } - - /// A Sleep run and a Persona session are one slot of hers: one unit, one live holder, in either order. - #[test] - fn a_sleep_run_and_a_persona_run_share_one_slot() { - let rig = Rig::new(); - let LaunchOutcome::Launched { run } = rig.launch(RunTurn::Sleep, &[]) else { panic!("not launched") }; - rig.at(1); - assert_eq!(rig.launch(RunTurn::PersonaTurn, &[]), LaunchOutcome::Busy { run: run.clone() }, "a live Sleep holds the Persona slot"); - assert_eq!(rig.launch(RunTurn::Sleep, &[]), LaunchOutcome::Busy { run: run.clone() }); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[]), LaunchOutcome::Launched { .. }), "a Self run is the other slot"); - let ports = Ports { mind: &rig.mind, launcher: &rig.launcher, clock: &rig.clock, host: "yggdrasil-host" }; - assert!(slot(&ports, rig.mind.instance(), RunTurn::PersonaTurn, rig.clock.now()).unwrap().live.is_some()); - assert_eq!(unit(&eureka(), RunTurn::Sleep).unwrap(), "mind-persona@eureka.service", "the night runs in the Persona unit"); - rig.mind.committed(vec![close(run, recorded())]); - rig.at(2); - let LaunchOutcome::Launched { run: persona } = rig.launch(RunTurn::PersonaTurn, &[]) else { panic!("not launched") }; - rig.at(3); - assert_eq!(rig.launch(RunTurn::Sleep, &[]), LaunchOutcome::Busy { run: persona }, "a live Persona session holds the slot a night needs"); - } - - #[test] - fn a_sleep_run_takes_no_claims() { - let rig = Rig::new(); - assert_eq!(rig.launch(RunTurn::Sleep, &[spec_ref("x")]), LaunchOutcome::Refused(Declined::PersonaRunTakesNoClaims)); - assert_eq!(rig.runs(), 0); - } - - #[test] - fn the_unit_started_names_the_minds_instance() { - let rig = Rig::new(); - rig.launch(RunTurn::PersonaTurn, &[]); - let started = rig.launcher.started.borrow(); - assert_eq!(started[0].0, *rig.mind.instance()); - } - - #[test] - fn a_run_carries_no_budget_and_each_persona_turn_opens_after_the_last_ended() { - let rig = Rig::new(); - for n in 0..3 { - rig.at(n); - let LaunchOutcome::Launched { run } = rig.launch(RunTurn::PersonaTurn, &[]) else { panic!("not launched") }; - let view = rig.mind.view(K::Run, &run.id.0).unwrap(); - assert_eq!(the_run(&view).budget_usd.0, "0", "the dead record field is written zero"); - assert_eq!(the_run(&view).turn, RunTurn::PersonaTurn); - assert!(the_run(&view).claims.is_empty() && the_run(&view).campaigns.is_empty()); - // One live Persona turn of hers at a time: end this one. - rig.mind.committed(vec![close(run, recorded())]); - } - assert_eq!(rig.started(), 3, "each Persona turn ended before the next opened, so none was refused"); - } - - #[test] - fn a_live_persona_turn_is_busy_to_a_persona_launch_and_does_not_block_a_self_run() { - let rig = Rig::new(); - let LaunchOutcome::Launched { run } = rig.launch(RunTurn::PersonaTurn, &[]) else { panic!("not launched") }; - rig.at(1); - assert_eq!(rig.launch(RunTurn::PersonaTurn, &[]), LaunchOutcome::Busy { run }); - assert_eq!((rig.runs(), rig.started()), (1, 1), "Busy admits and starts nothing"); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[]), LaunchOutcome::Launched { .. })); - } - - #[test] - fn run_labels_are_utc_to_the_millisecond() { - assert_eq!(run_label(at(123)).0, "mind-20261009T131500123Z"); - assert_ne!(run_label(at(123)), run_label(at(124))); - } - - #[test] - fn two_launches_in_one_millisecond_open_one_run() { - let rig = Rig::new(); - assert!(matches!(rig.launch(RunTurn::PersonaTurn, &[]), LaunchOutcome::Launched { .. })); - // A Self run holds another slot, so only the key (instance and label) collides. - let second = rig.launch(RunTurn::SelfRun, &[]); - assert!(matches!(second, LaunchOutcome::Refused(_)), "{second:?}"); - assert_eq!((rig.runs(), rig.started()), (1, 1)); - } - - #[test] - fn a_refused_run_never_starts_a_unit() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x"), follow_up("later", &spec_ref("x"))]); - let later = reference(K::FollowUp, &id("follow_up", "later")); - rig.mind.committed(vec![run("op", RunTurn::SelfRun, RunOperator::Operator, std::slice::from_ref(&later))]); - let outcome = rig.launch(RunTurn::SelfRun, std::slice::from_ref(&later)); - assert!(matches!(outcome, LaunchOutcome::Refused(Declined::Admission(MindRefusal::AlreadyClaimed { .. }))), "{outcome:?}"); - for (answer, declined) in [ - (Outcome::Conflict { identities: vec![] }, Declined::Conflict), - (Outcome::AlreadyAdmitted { receipt_id: "r".into() }, Declined::AlreadyAdmitted), - ] { - let mind = Answering { inner: &rig.mind, outcome: answer }; - assert_eq!(rig.launch_through(&mind, RunTurn::SelfRun, &[spec_ref("x")]), LaunchOutcome::Refused(declined)); - } - assert_eq!((rig.runs(), rig.started()), (1, 0)); - } - - #[test] - fn a_start_failure_withdraws_the_run_it_opened_and_only_that_run() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x"), spec("y")]); - rig.mind.committed(vec![run("other", RunTurn::SelfRun, RunOperator::Operator, &[spec_ref("y")])]); - rig.launcher.fail.set(true); - let outcome = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]); - assert_eq!(outcome, LaunchOutcome::Refused(Declined::StartFailed)); - let opened = format!("{INSTANCE}:run:mind-20261009T131500000Z"); - let status = |id: &str| rig.mind.view(K::Run, id).unwrap().status; - assert!(matches!(status(&opened), PipelineStatus::Resolved { record, .. } if matches!(record.outcome, ResolutionOutcome::Withdrawn { .. }))); - assert_eq!(status(&run_ref("other").id.0), PipelineStatus::InForce); - // The spec is free again. - rig.launcher.fail.set(false); - rig.at(1); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[spec_ref("x")]), LaunchOutcome::Launched { .. })); - } - - #[test] - fn a_spec_that_is_reported_blocked_or_claimed_is_not_queued_and_admits_nothing() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("done"), spec("blocked"), spec("held"), spec("free")]); - rig.mind.committed(vec![report("done")]); - rig.mind.committed(vec![question_in("fork", &spec_ref("blocked"))]); - rig.mind.committed(vec![run("op", RunTurn::SelfRun, RunOperator::Operator, &[spec_ref("held")])]); - for item in ["done", "blocked", "held"] { - let outcome = rig.launch(RunTurn::SelfRun, &[spec_ref(item)]); - assert_eq!(outcome, LaunchOutcome::NotQueued { item: spec_ref(item) }); - } - let mixed = rig.launch(RunTurn::SelfRun, &[spec_ref("free"), spec_ref("done")]); - assert_eq!(mixed, LaunchOutcome::NotQueued { item: spec_ref("done") }, "one unqueued claim refuses the whole request"); - assert_eq!((rig.runs(), rig.started()), (1, 0)); - } - - #[test] - fn a_second_live_self_run_of_hers_is_busy_and_other_runs_do_not_count() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x"), spec("y")]); - // None of these is a live Self run of hers. - rig.mind.committed(vec![run("op", RunTurn::SelfRun, RunOperator::Operator, &[])]); - rig.mind.committed(vec![run("gone", RunTurn::SelfRun, RunOperator::Mind, &[])]); - rig.mind.committed(vec![close(run_ref("gone"), withdrawn())]); - rig.seed("persona", RunTurn::PersonaTurn, &[]); - rig.at(1); - let LaunchOutcome::Launched { run: first } = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]) else { - panic!("blocked by a run that is not hers") - }; - let (runs, started) = (rig.runs(), rig.started()); - rig.at(2); - assert_eq!(rig.launch(RunTurn::SelfRun, &[spec_ref("y")]), LaunchOutcome::Busy { run: first.clone() }); - assert_eq!((rig.runs(), rig.started()), (runs, started), "Busy admits and starts nothing"); - // Ending her run frees the slot. - rig.mind.committed(vec![close(first, recorded())]); - rig.at(3); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[spec_ref("y")]), LaunchOutcome::Launched { .. })); - } - - #[test] - fn an_alive_run_is_busy_however_old_and_is_not_closed() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x")]); - rig.seed("old", RunTurn::SelfRun, &[spec_ref("x")]); - rig.age(&run_ref("old").id.0, 24 * 3600); - assert_eq!(rig.launch(RunTurn::SelfRun, &[]), LaunchOutcome::Busy { run: run_ref("old") }); - assert!(rig.in_force("old")); - assert_eq!((rig.runs(), rig.started()), (1, 0)); - } - - #[test] - fn a_claimless_alive_run_is_busy() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x")]); - rig.seed("bare", RunTurn::SelfRun, &[]); - rig.age(&run_ref("bare").id.0, 3600); - assert_eq!(rig.launch(RunTurn::SelfRun, &[spec_ref("x")]), LaunchOutcome::Busy { run: run_ref("bare") }); - assert!(rig.in_force("bare")); - } - - #[test] - fn a_dead_run_is_closed_past_the_grace_in_the_batch_that_opens_the_next() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x")]); - // Her run on x, admitted, and its unit never ran. - rig.mind.committed(vec![run("dead", RunTurn::SelfRun, RunOperator::Mind, &[spec_ref("x")])]); - let dead = run_ref("dead").id.0; - rig.age(&dead, START_GRACE_S - 1); - assert_eq!( - rig.launch(RunTurn::SelfRun, &[]), - LaunchOutcome::Busy { run: run_ref("dead") }, - "inside the grace the unit may still be starting" - ); - assert!(rig.in_force("dead")); - assert_eq!((rig.runs(), rig.started()), (1, 0)); - - rig.age(&dead, START_GRACE_S); - let LaunchOutcome::Launched { run: next } = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]) else { - panic!("the dead run's claim stayed held") - }; - assert!(!rig.in_force("dead")); - let (closure, closed_in) = the_closure(&rig, "dead", 1); - assert_eq!(closure.outcome, ResolutionOutcome::Recorded { reason: "unit not active".into() }); - assert_eq!(closure.subject, run_ref("dead")); - assert_eq!( - closed_in, - rig.mind.view(K::Run, &next.id.0).unwrap().admission.receipt_id, - "one admission closes the dead run and opens the next" - ); - assert_eq!(rig.started(), 1); - } - - #[test] - fn a_dead_runs_closure_takes_the_next_sequence_of_its_subject() { - let rig = Rig::new(); - rig.mind.committed(vec![run("dead", RunTurn::SelfRun, RunOperator::Mind, &[])]); - rig.mind.committed(vec![close(run_ref("dead"), recorded())]); - // Withdrawing that closure puts the run back in force. - let first = reference(K::Resolution, &format!("{INSTANCE}:resolution:run.dead.n1")); - rig.mind.committed(vec![close(first, withdrawn())]); - assert!(rig.in_force("dead")); - rig.age(&run_ref("dead").id.0, 600); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[]), LaunchOutcome::Launched { .. })); - assert!(!rig.in_force("dead")); - assert_eq!(the_closure(&rig, "dead", 2).0.sequence, 2); - } - - #[test] - fn only_a_dead_holder_of_the_requests_turn_is_closed() { - let rig = Rig::new(); - rig.mind.committed(vec![run("op", RunTurn::SelfRun, RunOperator::Operator, &[])]); - rig.mind.committed(vec![run("persona", RunTurn::PersonaTurn, RunOperator::Mind, &[])]); - rig.mind.committed(vec![run("dead", RunTurn::SelfRun, RunOperator::Mind, &[])]); - rig.age(&run_ref("dead").id.0, 3600); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[]), LaunchOutcome::Launched { .. })); - assert!(!rig.in_force("dead")); - assert!(rig.in_force("op") && rig.in_force("persona"), "an Operator run and a run of the other turn are never closed by this launch"); - } - - #[test] - fn a_run_whose_admit_answer_was_lost_is_closed_by_the_next_launch_of_its_turn() { - struct LosesAnswer<'a>(&'a TestMind); - impl MindPort for LosesAnswer<'_> { - fn instance(&self) -> &Slug { - self.0.instance() - } - - fn query(&self, selection: &Selection) -> Result { - self.0.query(selection) - } - - fn admit(&self, agent: &str, session: &str, documents: Vec) -> Result { - self.0.admit(agent, session, documents)?; - Err(anyhow!("the answer was lost")) - } - } - let rig = Rig::new(); - assert!(rig.try_launch_through(&LosesAnswer(&rig.mind), RunTurn::SelfRun, &[]).is_err()); - assert_eq!((rig.runs(), rig.started()), (1, 0), "committed, and no unit was started"); - let lost = rig.mind.ids(K::Run).remove(0); - rig.age(&lost, START_GRACE_S); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[]), LaunchOutcome::Launched { .. })); - assert_eq!((rig.runs(), rig.started()), (2, 1)); - let lost_label = lost.rsplit(':').next().unwrap().to_string(); - assert!(!rig.in_force(&lost_label)); - } - - #[test] - fn a_port_that_admits_a_rival_live_run_between_step_0_and_the_admission_is_busy_and_starts_nothing() { - struct Racing<'a> { - inner: &'a TestMind, - raced: Cell, - } - impl MindPort for Racing<'_> { - fn instance(&self) -> &Slug { - self.inner.instance() - } - - fn query(&self, selection: &Selection) -> Result { - self.inner.query(selection) - } - - fn admit(&self, agent: &str, session: &str, documents: Vec) -> Result { - if !self.raced.replace(true) { - self.inner.committed(vec![run("rival", RunTurn::SelfRun, RunOperator::Mind, &[])]); - } - self.inner.admit(agent, session, documents) - } - } - let rig = Rig::new(); - let racing = Racing { inner: &rig.mind, raced: Cell::new(false) }; - assert_eq!(rig.launch_through(&racing, RunTurn::SelfRun, &[]), LaunchOutcome::Busy { run: run_ref("rival") }); - assert_eq!((rig.runs(), rig.started()), (1, 0)); - } - - #[test] - fn an_already_live_holder_the_mind_does_not_show_as_hers_is_refused_not_trusted() { - struct Forged<'a>(&'a TestMind, &'a str); - impl MindPort for Forged<'_> { - fn instance(&self) -> &Slug { - self.0.instance() - } - - fn query(&self, selection: &Selection) -> Result { - self.0.query(selection) - } - - fn admit(&self, _agent: &str, _session: &str, _documents: Vec) -> Result { - let run = huginn_mind::RunId::try_from(self.1.to_string()).unwrap(); - Ok(Outcome::Refused(MindRefusal::AlreadyLive { run })) - } - } - let rig = Rig::new(); - // A Persona turn of hers is live, and a Self run of hers is not: a real Self holder named by admission is the race test's Busy. - rig.seed("persona", RunTurn::PersonaTurn, &[]); - for foreign in - ["other:run:mind-20261010T010203004Z", "eureka-body:run:mind-20261010T010203004Z", "yggdrasil:run:nobody", "yggdrasil:run:persona"] - { - let outcome = rig.launch_through(&Forged(&rig.mind, foreign), RunTurn::SelfRun, &[]); - assert!(matches!(outcome, LaunchOutcome::Refused(Declined::Admission(MindRefusal::AlreadyLive { .. }))), "{foreign}: {outcome:?}"); - } - assert_eq!(rig.started(), 0); - } - - #[test] - fn a_run_whose_unit_died_is_closed_by_the_next_launch_of_its_turn() { - let rig = Rig::new(); - let LaunchOutcome::Launched { run: first } = rig.launch(RunTurn::SelfRun, &[]) else { panic!("not launched") }; - let first_label = first.id.0.rsplit(':').next().unwrap().to_string(); - rig.age(&first.id.0, 3600); - assert_eq!(rig.launch(RunTurn::SelfRun, &[]), LaunchOutcome::Busy { run: first.clone() }, "its unit is still running"); - rig.launcher.kill(RunTurn::SelfRun); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[]), LaunchOutcome::Launched { .. })); - assert!(!rig.in_force(&first_label)); - assert_eq!(rig.started(), 2); - } - - #[test] - fn a_tripped_item_raises_one_question_launches_nothing_and_a_ruling_reopens_it() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x")]); - history(&rig.mind, &spec_ref("x"), &[false, false, false]); - let before = rig.runs(); - let outcome = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]); - let question = id("question", "breaker-mind-20261009T131500000Z"); - assert_eq!(outcome, LaunchOutcome::Tripped { run: run_ref("h2"), question: reference(K::Question, &question) }); - assert_eq!((rig.runs(), rig.started()), (before, 0)); - assert_eq!(rig.mind.ids(K::Question), vec![question.clone()]); - let view = rig.mind.view(K::Question, &question).unwrap(); - let PipelineDocument::Question(asked) = &view.document else { panic!("not a question") }; - assert_eq!((asked.raised_in.clone(), asked.campaign.0.as_str()), (Some(run_ref("h2")), CAMPAIGN), "raised in the run whose end tripped it"); - assert!(asked.question.0.contains(&run_ref("h2").id.0) && asked.question.0.contains("claims held: 1"), "{}", asked.question.0); - let texts: Vec<(&str, &str)> = asked.options.iter().map(|option| (option.label.0.as_str(), option.text.0.as_str())).collect(); - assert_eq!( - texts, - [ - ("reopen", "Answer to reopen every claim of the run with a fresh count."), - ("retire", "Resolve the claims so they are no longer worked, and answer with this option.") - ], - "retire is resolved by its answerer: no option promises the machine will" - ); - assert_eq!(view.admission.provenance.session.0, "mind-20261009T131500000Z"); - // Open, the question blocks the item. - assert_eq!(rig.launch(RunTurn::SelfRun, &[spec_ref("x")]), LaunchOutcome::NotQueued { item: spec_ref("x") }); - // The ruling that answers it opens the item, and the count starts afresh. - rig.mind.committed(vec![ruling("reopen-x", Some((&question, "reopen")))]); - rig.at(1); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[spec_ref("x")]), LaunchOutcome::Launched { .. })); - } - - #[test] - fn launching_a_tripped_item_with_another_queued_trips_and_launches_nothing() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x"), spec("y")]); - history_as(&rig.mind, &spec_ref("x"), "x", &[false, false, false]); - let outcome = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]); - assert!(matches!(outcome, LaunchOutcome::Tripped { .. }), "{outcome:?}"); - assert_eq!(rig.started(), 0); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[spec_ref("y")]), LaunchOutcome::Launched { .. }), "the other item still launches"); - } - - #[test] - fn a_second_trip_raises_a_second_question_with_its_own_key() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x")]); - history(&rig.mind, &spec_ref("x"), &[false, false, false]); - let LaunchOutcome::Tripped { question: first, .. } = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]) else { panic!("no first trip") }; - rig.mind.committed(vec![ruling("reopen", Some((&first.id.0, "reopen")))]); - history_as(&rig.mind, &spec_ref("x"), "g", &[false, false, false]); - rig.at(1); - let LaunchOutcome::Tripped { question: second, .. } = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]) else { - panic!("no second trip") - }; - assert_ne!(first, second); - assert_eq!(rig.mind.ids(K::Question).len(), 2); - assert_eq!(rig.started(), 0); - } - - #[test] - fn nine_empty_runs_of_fifty_before_the_answer_do_not_trip_after_it() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x")]); - let item = spec_ref("x"); - history(&rig.mind, &item, &[false, false, true, false, false, true, false, false, true, false, false, true, false]); - rig.mind.committed(vec![question_in("fork", &item)]); - rig.mind.committed(vec![ruling("answer", Some((&id("question", "fork"), "A")))]); - history_as(&rig.mind, &item, "g", &[false]); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[item]), LaunchOutcome::Launched { .. })); - } - - #[test] - fn a_dead_run_is_an_ended_empty_run_for_the_breaker_and_its_claim_is_free() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x")]); - history(&rig.mind, &spec_ref("x"), &[false, false]); - rig.mind.committed(vec![run("dead", RunTurn::SelfRun, RunOperator::Mind, &[spec_ref("x")])]); - rig.age(&run_ref("dead").id.0, 600); - let outcome = rig.launch(RunTurn::SelfRun, &[spec_ref("x")]); - assert!(matches!(outcome, LaunchOutcome::Tripped { .. }), "{outcome:?}"); - assert!(!rig.in_force("dead"), "the trip's batch closes the dead run too"); - let question = rig.mind.ids(K::Question).pop().expect("the trip asked"); - let PipelineDocument::Question(asked) = rig.mind.view(K::Question, &question).unwrap().document else { panic!("not a question") }; - assert_eq!(asked.raised_in, Some(run_ref("dead")), "the dead holder, closed in the same batch, is the run the question is raised in"); - assert_eq!((rig.runs(), rig.started()), (3, 0)); - } - - /// A caller's earlier read of the hold (the heartbeat's, choosing its claims) - /// is advisory: a question that lands after it and before the gate is seen. - #[test] - fn a_question_landing_before_the_gate_reads_is_seen_by_the_run_it_would_have_opened() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x"), follow_up("brief", &spec_ref("x"))]); - let brief = reference(K::FollowUp, &id("follow_up", "brief")); - let landing = Landing { - inner: &rig.mind, - question: RefCell::new(Some(vec![question_in("fork", &brief)])), - hold_reads: Cell::new(0), - lands_on: reads_anything, - }; - let outcome = rig.launch_through(&landing, RunTurn::SelfRun, std::slice::from_ref(&brief)); - assert_eq!(outcome, LaunchOutcome::NotQueued { item: brief }); - assert_eq!((landing.hold_reads.get(), rig.runs(), rig.started()), (1, 0, 0), "one read, nothing admitted"); - } - - #[test] - fn a_brief_an_open_question_is_raised_in_cannot_be_launched_on() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x"), follow_up("brief", &spec_ref("x"))]); - let brief = reference(K::FollowUp, &id("follow_up", "brief")); - rig.mind.committed(vec![question_in("fork", &brief)]); - assert_eq!(rig.launch(RunTurn::SelfRun, std::slice::from_ref(&brief)), LaunchOutcome::NotQueued { item: brief }); - assert_eq!((rig.runs(), rig.started()), (0, 0)); - } - - #[test] - fn the_gate_refuses_a_claim_an_open_question_holds_whatever_its_kind() { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x"), follow_up("brief", &spec_ref("x"))]); - let brief = reference(K::FollowUp, &id("follow_up", "brief")); - // A question raised in a run holds the follow-up that run claimed, though the follow-up is no cut spec. - rig.mind.committed(vec![run("failed", RunTurn::SelfRun, RunOperator::Mind, &[brief.clone(), spec_ref("x")])]); - rig.mind.committed(vec![close(run_ref("failed"), recorded())]); - rig.mind.committed(vec![question_in("fork", &run_ref("failed"))]); - let runs = rig.runs(); - assert_eq!(rig.launch(RunTurn::SelfRun, std::slice::from_ref(&brief)), LaunchOutcome::NotQueued { item: brief.clone() }); - assert_eq!(rig.launch(RunTurn::SelfRun, &[spec_ref("x")]), LaunchOutcome::NotQueued { item: spec_ref("x") }, "a cut spec held by a run-raised question"); - assert_eq!((rig.runs(), rig.started()), (runs, 0), "nothing admitted, nothing started"); - rig.mind.committed(vec![close(reference(K::Question, &id("question", "fork")), withdrawn())]); - assert!(matches!(rig.launch(RunTurn::SelfRun, &[brief]), LaunchOutcome::Launched { .. }), "withdrawn, the hold lifts"); - } - - /// A mind where a question lands the moment `lands_on` reads a selection. - struct Landing<'a> { - inner: &'a TestMind, - question: RefCell>>, - hold_reads: Cell, - lands_on: fn(&Selection) -> bool, - } - - fn reads_the_hold(selection: &Selection) -> bool { - selection.schemas.as_deref() == Some(&[K::Question.type_id().to_string()][..]) - && selection.fields.iter().flatten().any(|predicate| predicate.index == "in_force") - } - - fn reads_anything(_: &Selection) -> bool { - true - } - - impl MindPort for Landing<'_> { - fn instance(&self) -> &Slug { - self.inner.instance() - } - - fn query(&self, selection: &Selection) -> Result { - let answer = self.inner.query(selection); - if reads_the_hold(selection) { - self.hold_reads.set(self.hold_reads.get() + 1); - } - if (self.lands_on)(selection) - && let Some(documents) = self.question.take() - { - self.inner.committed(documents); - } - answer - } - - fn admit( - &self, - agent: &str, - session: &str, - documents: Vec, - ) -> Result { - self.inner.admit(agent, session, documents) - } - } - - #[test] - fn a_launch_reads_the_hold_once_and_a_question_landing_after_it_changes_no_answer_within_the_launch() - { - let rig = Rig::new(); - rig.mind.committed(vec![spec("x")]); - let landing = Landing { - inner: &rig.mind, - question: RefCell::new(Some(vec![question_in("fork", &spec_ref("x"))])), - hold_reads: Cell::new(0), - lands_on: reads_the_hold, - }; - // The gate's own snapshot is read first (the question lands behind it); the queue and the gate use that one. - let outcome = rig.launch_through(&landing, RunTurn::SelfRun, &[spec_ref("x")]); - assert!( - matches!(outcome, LaunchOutcome::Launched { .. }), - "{outcome:?}: queue and gate answered from one snapshot" - ); - assert_eq!( - landing.hold_reads.get(), - 1, - "the hold was read once for the whole launch" - ); - assert_eq!( - crate::queue::on_hold(&rig.mind).unwrap().items(), - [spec_ref("x")], - "the question did land" - ); - } - - /// The one source of every drawn case: splitmix64 from a fixed seed, so a - /// failure names a case that runs again. - struct Draw(u64); - - impl Draw { - fn next(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - z ^ (z >> 31) - } - - fn below(&mut self, bound: usize) -> usize { - (self.next() % bound as u64) as usize - } - } - - const LENGTH_EDGES: [usize; 13] = [1, 2, 3, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64]; - const ALPHABETS: [&str; 6] = [ - "abcdefghijklmnopqrstuvwxyz", - "abcdefghijklmnopqrstuvwxyz0123456789", - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", - "ab-_", - "a-b_c-d_e0", - "abcdefghijklmnopqrstuvwxyz-_", - ]; - - /// A valid slug of `length` characters, over an alphabet the draw picks, with - /// both separators (`-`, `_`) mixed in at random positions. - fn slug_of(draw: &mut Draw, length: usize) -> String { - loop { - let alphabet: Vec = ALPHABETS[draw.below(ALPHABETS.len())].chars().collect(); - let name: String = (0..length) - .map(|_| match draw.below(6) { - 0 => '-', - 1 => '_', - _ => alphabet[draw.below(alphabet.len())], - }) - .collect(); - if Slug(name.clone()).validate_slug().is_ok() { - return name; - } - } - } - - /// Valid slugs that differ from `name`: edits of it at every position (a - /// drawn character, the other separator, the other case), its prefixes, the - /// same name with every separator swapped, and independent draws. - fn distinct_valid(name: &str, draw: &mut Draw) -> Vec { - let chars: Vec = name.chars().collect(); - let pool: Vec = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_".chars().collect(); - let swapped = |c: char| match c { - '-' => '_', - '_' => '-', - other => other, - }; - let mut out = Vec::new(); - for i in 0..chars.len() { - let mut edited = chars.clone(); - edited[i] = swapped(chars[i]); - out.push(edited.iter().collect::()); - let mut edited = chars.clone(); - edited[i] = if chars[i].is_ascii_uppercase() { chars[i].to_ascii_lowercase() } else { chars[i].to_ascii_uppercase() }; - out.push(edited.iter().collect::()); - for _ in 0..3 { - let mut edited = chars.clone(); - edited[i] = pool[draw.below(pool.len())]; - out.push(edited.iter().collect::()); - } - out.push(chars[..i].iter().collect::()); - } - out.push(chars.iter().map(|&c| swapped(c)).collect::()); - out.push(name.to_uppercase()); - out.push(name.to_lowercase()); - if chars.len() < 64 { - out.push(format!("{name}-")); - out.push(format!("{name}_")); - out.push(format!("{name}0")); - } - for _ in 0..8 { - let length = 1 + draw.below(64); - out.push(slug_of(draw, length)); - } - out.retain(|other| other != name && Slug(other.clone()).validate_slug().is_ok()); - out - } - - /// A mind that knows only its instance. Any read or write is an error that - /// says so and is counted, so a gate that lets a launch through is seen by - /// the error it gets back, and a gate that refuses is seen to have touched - /// nothing. - struct Named { - instance: Slug, - reads: Cell, - } - - impl Named { - fn new(instance: &str) -> Self { - Self { instance: Slug(instance.into()), reads: Cell::new(0) } - } - } - - impl MindPort for Named { - fn instance(&self) -> &Slug { - &self.instance - } - - fn query(&self, _: &Selection) -> Result { - self.reads.set(self.reads.get() + 1); - Err(anyhow!("reached the mind")) - } - - fn admit(&self, _: &str, _: &str, _: Vec) -> Result { - self.reads.set(self.reads.get() + 1); - Err(anyhow!("reached the mind")) - } - } - - /// One launch by `turn` on a mind named `mind`, holding a Grant read for `grant`. - fn gated(mind: &Named, grant: &str, turn: RunTurn, claims: Vec) -> Result { - let (launcher, clock) = (Recording::default(), Fixed(Cell::new(at(0)))); - let ports = Ports { mind, launcher: &launcher, clock: &clock, host: "yggdrasil-host" }; - let grant = Grant::for_test(Slug(grant.into())); - let outcome = open_and_launch( - &ports, - LaunchRequest { - turn, - claims, - agent: "agent-x".into(), - grant, - }, - ); - assert!(launcher.started.borrow().is_empty()); - outcome - } - - #[test] - fn a_grant_passes_for_exactly_the_minds_own_instance_and_for_no_other_valid_slug() { - let mut draw = Draw(0x6a09_e667_f3bc_c908); - let mut names: Vec = Vec::new(); - for i in 0..780 { - names.push(slug_of(&mut draw, LENGTH_EDGES[i % LENGTH_EDGES.len()])); - } - for _ in 0..220 { - let length = 1 + draw.below(64); - names.push(slug_of(&mut draw, length)); - } - let mut distinct = 0; - for name in &names { - for turn in [RunTurn::SelfRun, RunTurn::PersonaTurn] { - let claims = if turn == RunTurn::SelfRun { vec![spec_ref("x")] } else { vec![] }; - let mind = Named::new(name); - let through = gated(&mind, name, turn, claims.clone()).unwrap_err(); - assert_eq!(format!("{through:#}"), "reached the mind", "{name:?} {turn:?}: the mind's own Grant passes the gate"); - for other in distinct_valid(name, &mut draw) { - let mind = Named::new(name); - let outcome = gated(&mind, &other, turn, claims.clone()).unwrap(); - assert_eq!(outcome, LaunchOutcome::Refused(Declined::GrantForOtherInstance), "mind {name:?}, grant {other:?}, {turn:?}"); - assert_eq!(mind.reads.get(), 0, "a refused launch reads nothing"); - distinct += 1; - } - } - } - assert!(distinct > 100_000, "{distinct}"); - // The families the property exists for are in the draw: long names, and both separators. - assert!(names.iter().any(|n| n.len() > 32) && names.iter().any(|n| n.contains('-')) && names.iter().any(|n| n.contains('_'))); - } - - /// A claim id from the same generator as instance names: varied alphabets, - /// both separators and the edge lengths, so a refusal keyed on id text - /// cannot pass. - fn claim_id(draw: &mut Draw) -> String { - let length = LENGTH_EDGES[draw.below(LENGTH_EDGES.len())]; - slug_of(draw, length) - } - - #[test] - fn a_persona_turn_with_any_claims_at_all_is_refused_and_touches_nothing() { - let kinds = PipelineKind::ALL; - let mut draw = Draw(0xbb67_ae85_84ca_a73b); - let mut sets: Vec> = Vec::new(); - // Every rotation of the kinds, so no kind or position is the one that starts, at every small size. - for start in 0..kinds.len() { - for size in 1..=40 { - sets.push((0..size).map(|i| reference(kinds[(start + i) % kinds.len()], &claim_id(&mut draw))).collect()); - let one = claim_id(&mut draw); - sets.push((0..size).map(|i| reference(kinds[(start + i) % kinds.len()], &one)).collect()); - } - } - // Every kind alone, repeated. - for kind in kinds { - for size in 1..=40 { - let one = claim_id(&mut draw); - sets.push((0..size).map(|_| reference(*kind, &one)).collect()); - } - } - // Drawn: every position a kind and an id from a pool of any size (one id repeated, to all distinct), - // at sizes from one to well past any bound a refusal could be written with. - let sizes = [1, 2, 3, 4, 5, 12, 13, 14, 26, 27, 64, 65, 100, 255, 256, 300]; - for round in 0..3_000 { - let size = if round < 600 { sizes[round % sizes.len()] } else { 1 + draw.below(300) }; - let pool: Vec = (0..1 + draw.below(size)).map(|_| claim_id(&mut draw)).collect(); - sets.push((0..size).map(|_| reference(kinds[draw.below(kinds.len())], &pool[draw.below(pool.len())])).collect()); - } - for size in [1_000, 10_000, 100_000] { - sets.push((0..size).map(|_| reference(kinds[draw.below(kinds.len())], &claim_id(&mut draw))).collect()); - } - for claims in sets { - let length = LENGTH_EDGES[draw.below(LENGTH_EDGES.len())]; - let name = slug_of(&mut draw, length); - let mind = Named::new(&name); - let outcome = gated(&mind, &name, RunTurn::PersonaTurn, claims.clone()).unwrap(); - assert_eq!(outcome, LaunchOutcome::Refused(Declined::PersonaRunTakesNoClaims), "{} claims, first {:?}", claims.len(), claims.first()); - assert_eq!(mind.reads.get(), 0); - } - // Without claims the same launch goes on to the mind. - let mind = Named::new("yggdrasil"); - assert_eq!(format!("{:#}", gated(&mind, "yggdrasil", RunTurn::PersonaTurn, vec![]).unwrap_err()), "reached the mind"); - } - - #[test] - fn a_persona_launch_closes_a_dead_persona_holder_past_the_grace() { - let rig = Rig::new(); - rig.mind.committed(vec![run("pdead", RunTurn::PersonaTurn, RunOperator::Mind, &[])]); - rig.age(&run_ref("pdead").id.0, START_GRACE_S - 1); - assert_eq!(rig.launch(RunTurn::PersonaTurn, &[]), LaunchOutcome::Busy { run: run_ref("pdead") }, "inside the grace"); - rig.age(&run_ref("pdead").id.0, START_GRACE_S); - assert!(matches!(rig.launch(RunTurn::PersonaTurn, &[]), LaunchOutcome::Launched { .. })); - assert!(!rig.in_force("pdead")); - assert_eq!(the_closure(&rig, "pdead", 1).0.outcome, ResolutionOutcome::Recorded { reason: "unit not active".into() }); - assert_eq!((rig.runs(), rig.started()), (2, 1)); - } - - #[test] - fn a_live_self_run_does_not_make_a_persona_launch_busy() { - let rig = Rig::new(); - rig.seed("alive-self", RunTurn::SelfRun, &[]); - assert!(matches!(rig.launch(RunTurn::PersonaTurn, &[]), LaunchOutcome::Launched { .. })); - assert!(rig.in_force("alive-self")); - } - - #[test] - fn a_dead_self_run_is_not_closed_by_a_persona_launch() { - let rig = Rig::new(); - rig.mind.committed(vec![run("dead-self", RunTurn::SelfRun, RunOperator::Mind, &[])]); - rig.age(&run_ref("dead-self").id.0, 3600); - assert!(matches!(rig.launch(RunTurn::PersonaTurn, &[]), LaunchOutcome::Launched { .. })); - assert!(rig.in_force("dead-self"), "a Persona launch closes only Persona holders"); - } struct Spy { calls: RefCell>>, diff --git a/crates/mind-body/src/lib.rs b/crates/mind-body/src/lib.rs index f8a9626..72e5848 100644 --- a/crates/mind-body/src/lib.rs +++ b/crates/mind-body/src/lib.rs @@ -4,9 +4,8 @@ //! hand on them. The brakes are the operator's consent, not her body: the store //! is root-owned and no organ of hers writes it. //! -//! `launch` and `queue` are the launch primitive: the work queue, the -//! repetition breaker, the one-live-Self-run rule, and the single path that -//! opens a run in the mind and only then starts its unit. +//! `launch` holds her units under systemd and the reads of the runs a Self run +//! holds; `queue` is her port to her mind and what an open question holds. //! //! `heartbeat` runs the swarm's shared heartbeat: the one process, the //! `mind-heartbeat` binary, that decides which Persona wakes and when, on the diff --git a/crates/mind-body/src/queue.rs b/crates/mind-body/src/queue.rs index 45d41cb..10944e9 100644 --- a/crates/mind-body/src/queue.rs +++ b/crates/mind-body/src/queue.rs @@ -1,34 +1,24 @@ -//! The Persona's view of open work, and the guard on it: what may be worked -//! (`queue`) and whether an item has stopped paying for its runs (`breaker`). +//! Her organs' port to her mind (`MindPort`, and `HuginnMind` over a daemon), +//! the paged reads built on it, and what an open question holds (`on_hold`), +//! which her Self's inbox reads before it tells a brief. //! -//! Nothing here keeps state. Both answers are derived from the mind on every -//! call, through `MindPort`: the mind is the only store, so a breaker that -//! needed a file of its own would be a second owner of what the runs already -//! record (target invariant run-is-the-grant). +//! Nothing here keeps state: every answer is derived from the mind on every +//! call. The work queue and the repetition breaker that guarded Self-run +//! launches are parked with them at tag `parked/self-run-launch`. use anyhow::{Result, anyhow, bail}; -use cultnet_rs::{Incoming, Selection}; -use eureka_pipeline::{ - Line, OrgRepo, PipelineDocument, PipelineKind, PipelineRef, ResolutionOutcome, RunOperator, RunTurn, - Slug, -}; +use cultnet_rs::Selection; +use eureka_pipeline::{Line, OrgRepo, PipelineDocument, PipelineRef, Slug}; use eureka_state::hold::{self, Hold}; use eureka_state::{ClientError, HuginnClient}; use huginn_mind::{ Faculty, HuginnMindRequest, HuginnMindResponse, PipelineAdmissionBatch, - PipelineAdmissionOutcome, PipelineDocumentSummary, PipelineFacts, PipelineProvenance, - PipelineSelectionPage, PipelineStatusSummary, RepoActivity, RootTouched, SemanticQuery, + PipelineAdmissionOutcome, PipelineDocumentSummary, PipelineProvenance, + PipelineSelectionPage, RepoActivity, RootTouched, SemanticQuery, }; -/// The last `CONSECUTIVE` ended runs over an item, all empty, trip its breaker. -pub const CONSECUTIVE: usize = 3; -/// So do `EMPTY_SHARE` empty ones among the last `WINDOW` (Codex auto-review's -/// per-turn breaker, `docs/research/autonomous-harness-prior-art.md` section 0). -pub const WINDOW: usize = 50; -pub const EMPTY_SHARE: usize = 10; - -/// The two things her launch organs ask of the mind: a typed selection, and -/// an admission as herself. The impl for a daemon is `HuginnMind`; a test +/// What her organs ask of the mind: a typed selection, and an admission as +/// herself. The impl for a daemon is `HuginnMind`; a test /// hands in a mind opened over a temporary directory. pub trait MindPort { /// The instance this port acts for. @@ -152,27 +142,6 @@ pub(crate) fn headers( hold::headers(&|asking| mind.query(asking), selection) } -/// The claims of the runs of `instance` that are still in force and not in -/// `ending`: the work someone holds. -pub(crate) fn live_claims(mind: &dyn MindPort, instance: &Slug, ending: &[PipelineRef]) -> Result> { - let runs = in_force(any_of(of_kind(PipelineKind::Run), "root", &[&instance.0])); - let mut claims = Vec::new(); - for header in headers(mind, &runs)? { - if let PipelineFacts::Run { claims: held, .. } = header.facts - && !ending.contains(&header.id) - { - claims.extend(held); - } - } - Ok(claims) -} - -/// The claims of the run `run`, resolved or not (a citation outlives its -/// resolution). Empty when the mind has no such run. -pub(crate) fn claims_of(mind: &dyn MindPort, run: &PipelineRef) -> Result> { - hold::claims_of(&|asking| mind.query(asking), run) -} - /// Every question holding anything and what it holds: `eureka_state::hold`, /// the one decider, which `huginn blocked` reads too. pub(crate) fn holds(mind: &dyn MindPort) -> Result> { @@ -205,303 +174,16 @@ pub fn on_hold(mind: &dyn MindPort) -> Result { )) } -/// What may be worked, oldest first: the cut specs in force that no report -/// answers, that no open question holds, and that no live run claims. A run in -/// `ending` is one the caller closes in the same admission that opens the next, -/// so it claims nothing here. -pub fn queue( - mind: &dyn MindPort, - instance: &Slug, - ending: &[PipelineRef], - held: &Held, -) -> Result> { - let unreported = Selection { - cited: Some(Incoming { - role: "cut_spec".into(), - exists: false, - }), - ..in_force(of_kind(PipelineKind::CutSpec)) - }; - let claimed = live_claims(mind, instance, ending)?; - Ok(headers(mind, &unreported)? - .into_iter() - .map(|header| header.id) - .filter(|spec| !held.contains(spec) && !claimed.contains(spec)) - .collect()) -} - -/// Whether an item may still be launched on. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Breaker { - Clear, - /// Tripped, and the trip belongs to `run`: the newest ended counted run on - /// the item, the run whose end completed the streak or the share. - Trip { run: PipelineRef }, -} - -/// The repetition breaker, derived from the documents that cite the item. -/// -/// One role-less citation selection over every schema gives the set: the runs -/// that claim the item, and whatever else points at it (a follow-up sourced -/// from it, a report, a resolution, a question raised in it). The newest -/// question raised in the item is the boundary: only runs admitted after it -/// count, so answering a trip starts a fresh count. A counted run is a Self run -/// of hers (typed `turn` and `operated_by`) that was not withdrawn; a -/// withdrawn run never ran and is no run here. A counted run is ended when -/// resolved or listed in `ending`, and is empty when no document of the set -/// other than a run was admitted from its own admission up to the next counted -/// run's (or to now). Trip, naming the newest ended counted run, when the last `CONSECUTIVE` ended runs are empty, or -/// `EMPTY_SHARE` of the last `WINDOW`. What else the mind admitted, such as a -/// Persona turn's run or an unrelated ruling, cites nothing here and counts for -/// nothing. -pub fn breaker(mind: &dyn MindPort, item: &PipelineRef, ending: &[PipelineRef]) -> Result { - let mut set = headers(mind, &Selection { cites: Some(citing(item, None)), ..Selection::default() })?; - set.sort_by_key(|header| header.admission.ordinal); - let asked_in_item = set - .iter() - .filter(|header| matches!(&header.facts, PipelineFacts::Question { raised_in: Some(raised), .. } if raised == item)) - .map(|header| header.admission.ordinal); - let asked_in_run = Selection { - cites: Some(citing(item, Some("claims"))), - cited: Some(Incoming { role: "raised_in".into(), exists: true }), - ..of_kind(PipelineKind::Run) - }; - let boundary = asked_in_item.chain(headers(mind, &asked_in_run)?.into_iter().map(|run| run.admission.ordinal)).max(); - let after = |header: &&PipelineDocumentSummary| boundary.is_none_or(|boundary| header.admission.ordinal > boundary); - let withdrawn = - |run: &PipelineDocumentSummary| matches!(run.status, PipelineStatusSummary::Resolved { outcome: ResolutionOutcome::Withdrawn { .. }, .. }); - // (admission ordinal, ended, ref) of each counted run, oldest first. - let ran: Vec<(u64, bool, PipelineRef)> = set - .iter() - .filter(after) - .filter(|header| { - matches!(header.facts, PipelineFacts::Run { turn: RunTurn::SelfRun, operated_by: RunOperator::Mind, .. }) && !withdrawn(header) - }) - .map(|run| (run.admission.ordinal, matches!(run.status, PipelineStatusSummary::Resolved { .. }) || ending.contains(&run.id), run.id.clone())) - .collect(); - let ended: Vec = (0..ran.len()).filter(|index| ran[*index].1).collect(); - let considered: Vec = ended.iter().rev().take(WINDOW).copied().collect(); - let admitted: Vec = - set.iter().filter(|header| !matches!(header.facts, PipelineFacts::Run { .. })).map(|header| header.admission.ordinal).collect(); - - // Newest first, like `considered`. - let empty: Vec = considered - .iter() - .map(|index| { - let end = ran.get(index + 1).map_or(u64::MAX, |next| next.0); - !admitted.iter().any(|ordinal| *ordinal >= ran[*index].0 && *ordinal < end) - }) - .collect(); - let consecutive = empty.len() >= CONSECUTIVE && empty[..CONSECUTIVE].iter().all(|empty| *empty); - let share = empty.iter().filter(|empty| **empty).count() >= EMPTY_SHARE; - Ok(match ended.last() { - Some(newest) if consecutive || share => Breaker::Trip { run: ran[*newest].2.clone() }, - _ => Breaker::Clear, - }) -} - #[cfg(test)] mod tests { use std::net::SocketAddr; use std::time::Duration; - use eureka_pipeline::{RunOperator, RunTurn}; + use eureka_pipeline::{PipelineKind, RunOperator, RunTurn}; use super::*; - - /// `queue` against a hold read now. - fn queued( - mind: &dyn MindPort, - instance: &Slug, - ending: &[PipelineRef], - ) -> Result> { - queue(mind, instance, ending, &on_hold(mind)?) - } use crate::testkit::*; - /// A mind holding the spec `x` and a history of ended runs on it. - fn worked(runs: &[bool]) -> (TestMind, PipelineRef) { - let mind = TestMind::seeded(); - mind.committed(vec![spec("x")]); - let item = spec_ref("x"); - history(&mind, &item, runs); - (mind, item) - } - - const E: bool = false; - const N: bool = true; - - fn tripped(runs: &[bool]) -> bool { - let (mind, item) = worked(runs); - matches!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { .. }) - } - - #[test] - fn three_consecutive_empty_runs_trip_and_two_do_not() { - assert!(!tripped(&[])); - assert!(!tripped(&[E, E])); - assert!(tripped(&[E, E, E])); - assert!(tripped(&[N, E, E, E])); - } - - #[test] - fn a_document_in_a_runs_window_makes_that_run_not_empty() { - assert!(!tripped(&[E, E, N, E, E]), "one run with a document in its window breaks the streak"); - assert!(tripped(&[E, E, N, E, E, E])); - } - - #[test] - fn ten_empty_of_the_last_fifty_trip_with_gaps_and_nine_do_not() { - let ten: Vec = [E, E, N].repeat(5); - assert!(tripped(&ten), "10 empty, never 3 in a row"); - let mut nine: Vec = [E, E, N].repeat(4); - nine.push(E); - assert!(!tripped(&nine), "9 empty, never 3 in a row"); - } - - #[test] - fn only_the_last_fifty_ended_runs_are_counted() { - let mut runs = vec![E]; - for _ in 0..9 { - runs.extend([E, N]); - } - runs.extend([N].repeat(32)); - assert_eq!(runs.len(), 51); - assert!(!tripped(&runs), "the tenth empty run is the 51st newest"); - } - - #[test] - fn the_operators_self_runs_on_the_item_are_not_hers_to_count() { - let after_a_run_by = |operated_by: RunOperator| { - let (mind, item) = worked(&[E, E]); - mind.committed(vec![run("third", RunTurn::SelfRun, operated_by, std::slice::from_ref(&item))]); - mind.committed(vec![close(run_ref("third"), recorded())]); - breaker(&mind, &item, &[]).unwrap() - }; - assert!(matches!(after_a_run_by(RunOperator::Mind), Breaker::Trip { .. }), "hers, the third empty one"); - assert_eq!(after_a_run_by(RunOperator::Operator), Breaker::Clear, "his, counted for nothing"); - } - - #[test] - fn the_fiftieth_newest_ended_run_is_counted() { - // Ten empty of exactly fifty, the tenth the oldest, never three in a row. - let mut runs = vec![E]; - for _ in 0..9 { - runs.extend([E, N]); - } - runs.extend([N].repeat(31)); - assert_eq!(runs.len(), WINDOW); - assert!(tripped(&runs)); - } - - #[test] - fn runs_born_closed_in_the_questions_batch_are_before_the_count() { - // One batch holds the question raised in x and two runs of hers on x, each closed at birth. - let (mind, item) = worked(&[]); - mind.committed(vec![ - question_in("fork", &item), - run("pa", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item)), - close(run_ref("pa"), recorded()), - run("pb", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item)), - close(run_ref("pb"), recorded()), - ]); - // Then thirteen ended runs, nine of them empty and never three in a row. - let mut after: Vec = [E, E, N].repeat(4); - after.push(E); - history(&mind, &item, &after); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Clear, "the pair is not after the question, so the tenth empty run is not counted"); - } - - #[test] - fn three_empty_runs_trip_after_any_history_of_non_empty_ones() { - for before in [0usize, 1, 12, 20] { - let mut runs = vec![N; before]; - runs.extend([E, E, E]); - assert!(tripped(&runs), "{before} non-empty runs then three empty ones"); - assert!(!tripped(&[vec![N; before], vec![E, E]].concat()), "two empty ones never trip"); - } - } - - #[test] - fn only_documents_that_cite_the_item_make_a_run_non_empty() { - let (mind, item) = worked(&[]); - mind.committed(vec![spec("other")]); - for n in 0..3 { - // A Persona turn's run, a ruling and a follow-up of another item all land in the window. - mind.committed(vec![run(&format!("p{n}"), RunTurn::PersonaTurn, RunOperator::Mind, &[])]); - mind.committed(vec![ruling(&format!("r{n}"), None), follow_up(&format!("o{n}"), &spec_ref("other"))]); - ended_run(&mind, &item, "h", n, false); - mind.committed(vec![close(run_ref(&format!("p{n}")), recorded())]); - } - assert!(matches!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { .. })); - } - - #[test] - fn a_run_in_ending_is_an_ended_empty_run() { - let (mind, item) = worked(&[E, E]); - mind.committed(vec![run("dying", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item))]); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Clear, "open, it is not yet ended"); - assert!(matches!(breaker(&mind, &item, &[run_ref("dying")]).unwrap(), Breaker::Trip { .. })); - let instance = Slug(INSTANCE.into()); - assert!( - queued(&mind, &instance, &[]) - .unwrap() - .iter() - .all(|spec| *spec != item), - "it claims the item" - ); - assert!( - queued(&mind, &instance, &[run_ref("dying")]) - .unwrap() - .contains(&item), - "an ending run claims nothing" - ); - } - - #[test] - fn the_newest_question_in_the_item_starts_a_fresh_count() { - // Nine empty of the last fifty, then a question about the item is raised and answered. - let (mind, item) = worked(&[E, E, N, E, E, N, E, E, N, E, E, N, E]); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Clear); - mind.committed(vec![question_in("fork", &item)]); - mind.committed(vec![ruling("answer", Some((&id("question", "fork"), "A")))]); - ended_run(&mind, &item, "g", 0, false); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Clear, "the tenth empty run, but nine of them are before the question"); - ended_run(&mind, &item, "g", 1, false); - ended_run(&mind, &item, "g", 2, false); - assert!(matches!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { .. }), "three empty runs after it"); - } - - #[test] - fn a_withdrawn_run_never_ran_and_is_no_boundary() { - let withdrawn_between = |ruling_after: bool| { - let (mind, item) = worked(&[E]); - mind.committed(vec![run("w", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item))]); - mind.committed(vec![close(run_ref("w"), withdrawn())]); - if ruling_after { - mind.committed(vec![follow_up("after", &item)]); - } - ended_run(&mind, &item, "h", 1, false); - ended_run(&mind, &item, "h", 2, false); - breaker(&mind, &item, &[]).unwrap() - }; - assert!(matches!(withdrawn_between(false), Breaker::Trip { .. }), "the withdrawn run is neither counted nor does it break the streak"); - assert_eq!(withdrawn_between(true), Breaker::Clear, "a document after the withdrawn run still lands in the first run's window"); - } - - #[test] - fn a_runs_window_includes_its_own_batch_and_stops_before_the_next_runs() { - let (mind, item) = worked(&[E, E]); - // The third run opens with a ruling in its batch; it is still open. - mind.committed(vec![run("h2", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item)), follow_up("with-run", &item)]); - mind.committed(vec![close(run_ref("h2"), recorded())]); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Clear, "the ruling in its own batch is in its window"); - - let (mind, item) = worked(&[E, E, E]); - mind.committed(vec![run("live", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item)), follow_up("with-next", &item)]); - assert!(matches!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { .. }), "the next run's batch is not the previous run's window"); - } - /// The adapter over the wire vocabulary, answered by a real mind. #[test] fn the_daemon_port_asks_and_admits_in_the_wire_vocabulary() { @@ -509,10 +191,8 @@ mod tests { mind.committed(vec![spec("x")]); let port = HuginnMind::over(Slug(INSTANCE.into()), Box::new(|request| Ok(mind.answer(request)))); assert_eq!(port.instance().0, INSTANCE); - assert_eq!( - queued(&port, port.instance(), &[]).unwrap(), - vec![spec_ref("x")] - ); + let specs: Vec = headers(&port, &in_force(of_kind(PipelineKind::CutSpec))).unwrap().into_iter().map(|header| header.id).collect(); + assert_eq!(specs, vec![spec_ref("x")]); let outcome = port .admit( "agent-x", @@ -621,81 +301,6 @@ mod tests { assert!(format!("{down:#}").contains("could not be asked") && !format!("{down:#}").contains("canary"), "{down:#}"); } - #[test] - fn runs_of_another_item_are_not_this_items_runs() { - - let mind = TestMind::seeded(); - mind.committed(vec![spec("x"), spec("y")]); - history_as(&mind, &spec_ref("x"), "x", &[E, E]); - history_as(&mind, &spec_ref("y"), "y", &[E, E, E]); - assert_eq!(breaker(&mind, &spec_ref("x"), &[]).unwrap(), Breaker::Clear); - assert!(matches!(breaker(&mind, &spec_ref("y"), &[]).unwrap(), Breaker::Trip { .. })); - } - - #[test] - fn the_oldest_counted_runs_own_batch_is_in_its_window() { - let (mind, item) = worked(&[]); - mind.committed(vec![run("h0", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item)), follow_up("with-oldest", &item)]); - mind.committed(vec![close(run_ref("h0"), recorded())]); - ended_run(&mind, &item, "h", 1, false); - ended_run(&mind, &item, "h", 2, false); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Clear); - } - - #[test] - fn the_queue_is_the_unreported_unblocked_unclaimed_specs_oldest_first() { - let mind = TestMind::seeded(); - mind.committed(vec![spec("a"), spec("b"), spec("c"), spec("d"), spec("e")]); - let instance = Slug(INSTANCE.into()); - let all: Vec = ["a", "b", "c", "d", "e"] - .iter() - .map(|cut| spec_ref(cut)) - .collect(); - assert_eq!(queued(&mind, &instance, &[]).unwrap(), all); - - mind.committed(vec![report("b")]); - mind.committed(vec![question_in("fork", &spec_ref("c"))]); - mind.committed(vec![run( - "held", - RunTurn::SelfRun, - RunOperator::Operator, - &[spec_ref("d")], - )]); - assert_eq!( - queued(&mind, &instance, &[]).unwrap(), - vec![spec_ref("a"), spec_ref("e")] - ); - - mind.committed(vec![close(run_ref("held"), recorded())]); - assert_eq!( - queued(&mind, &instance, &[]).unwrap(), - vec![spec_ref("a"), spec_ref("d"), spec_ref("e")], - "a closed run claims nothing" - ); - let other = Slug("another-instance".into()); - mind.committed(vec![run( - "again", - RunTurn::SelfRun, - RunOperator::Operator, - &[spec_ref("a")], - )]); - assert_eq!( - queued(&mind, &other, &[]).unwrap().len(), - 3, - "claims are read for the instance asked" - ); - } - - #[test] - fn a_trip_names_the_newest_ended_counted_run() { - let (mind, item) = worked(&[E, E, E, E]); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { run: run_ref("h3") }); - mind.committed(vec![run("live", RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(&item))]); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { run: run_ref("h3") }, "a run still open is not ended"); - assert_eq!(breaker(&mind, &item, &[run_ref("live")]).unwrap(), Breaker::Trip { run: run_ref("live") }, "a run in ending is"); - } - - /// Two items claimed together by every run of a history; the last one ended empty. fn bundle() -> (TestMind, PipelineRef, PipelineRef) { let mind = TestMind::seeded(); mind.committed(vec![spec("a"), spec("b")]); @@ -718,11 +323,6 @@ mod tests { held.contains(&a) && held.contains(&b) && held.items().len() == 2, "{held:?}: the claims of the resolved run" ); - assert_eq!( - queued(&mind, &Slug(INSTANCE.into()), &[]).unwrap(), - Vec::::new(), - "queue reads the same hold" - ); let question = id("question", "fork"); if withdraw { mind.committed(vec![close(reference(PipelineKind::Question, &question), withdrawn())]); @@ -789,35 +389,6 @@ mod tests { assert!(!on_hold(&mind).unwrap().contains(&b)); } - #[test] - fn answering_a_question_in_the_run_gives_every_claim_of_it_a_fresh_count() { - let (mind, a, b) = bundle(); - assert_eq!(breaker(&mind, &a, &[]).unwrap(), Breaker::Trip { run: run_ref("f2") }); - assert_eq!(breaker(&mind, &b, &[]).unwrap(), Breaker::Trip { run: run_ref("f2") }); - mind.committed(vec![question_in("fork", &run_ref("f2"))]); - mind.committed(vec![ruling("answer", Some((&id("question", "fork"), "A")))]); - for item in [&a, &b] { - assert_eq!(breaker(&mind, item, &[]).unwrap(), Breaker::Clear, "counts only runs after f2"); - } - for n in 0..3 { - mind.committed(vec![run(&format!("g{n}"), RunTurn::SelfRun, RunOperator::Mind, &[a.clone(), b.clone()])]); - mind.committed(vec![close(run_ref(&format!("g{n}")), recorded())]); - let expected = if n == 2 { Breaker::Trip { run: run_ref("g2") } } else { Breaker::Clear }; - assert_eq!(breaker(&mind, &b, &[]).unwrap(), expected, "b has no question of its own and trips after three fresh empty runs, never before"); - } - } - - #[test] - fn a_question_in_a_run_that_did_not_claim_the_item_is_no_boundary() { - let (mind, item) = worked(&[E, E, E]); - mind.committed(vec![spec("y")]); - mind.committed(vec![run("other", RunTurn::SelfRun, RunOperator::Mind, &[spec_ref("y")])]); - mind.committed(vec![question_in("fork", &run_ref("other"))]); - assert_eq!(breaker(&mind, &item, &[]).unwrap(), Breaker::Trip { run: run_ref("h2") }, "the question holds y's run, not x's count"); - } - - /// A daemon that is not there: the failure names no input, endpoint or - /// instance. #[test] fn an_unreachable_mind_names_no_input() { let canary = "canary-instance-7f3a91"; @@ -827,7 +398,7 @@ mod tests { Slug(canary.into()), Duration::from_millis(300), )); - let error = queued(&port, &Slug(canary.into()), &[]).unwrap_err(); + let error = on_hold(&port).unwrap_err(); let shown = format!("{error:#}"); assert!(shown.contains("unavailable"), "{shown}"); assert!(!shown.contains(canary) && !shown.contains("127.0.0.1"), "{shown}"); diff --git a/crates/mind-body/src/testkit.rs b/crates/mind-body/src/testkit.rs index 4a127d7..16d504b 100644 --- a/crates/mind-body/src/testkit.rs +++ b/crates/mind-body/src/testkit.rs @@ -13,7 +13,7 @@ use model_connector::PlanQuota; use chrono::{DateTime, Duration, TimeZone, Utc}; use cultnet_rs::Selection; use eureka_pipeline::{ - CommitRange, CutVerification, Date, DocRef, MemoryOrigin, MemorySort, PipelineCampaign, PipelineCutReport, PipelineCutSpec, PipelineDocument, PipelineFollowUp, + CutVerification, Date, DocRef, MemoryOrigin, MemorySort, PipelineCampaign, PipelineCutSpec, PipelineDocument, PipelineFollowUp, PipelineInstance, PipelineKind, PipelineMemory, PipelineQuestion, PipelineRef, PipelineResolution, PipelineRuling, PipelineRun, PipelineStewardship, PipelineTarget, QuestionOption, ResolutionOutcome, RulingAuthority, RunOperator, RunTurn, Sha, Slug, StructuralDelta, TargetInvariant, }; @@ -59,20 +59,12 @@ pub(crate) struct Recording { } impl Recording { - pub(crate) fn kill(&self, turn: RunTurn) { - self.running.borrow_mut().retain(|unit| *unit != (Slug(INSTANCE.into()), turn.slot())); - } - - /// `kill` for a named instance. + /// Her unit of `turn`'s slot ends. pub(crate) fn kill_as(&self, instance: &Slug, turn: RunTurn) { self.running.borrow_mut().retain(|unit| *unit != (instance.clone(), turn.slot())); } - pub(crate) fn revive(&self, turn: RunTurn) { - self.revive_as(&Slug(INSTANCE.into()), turn); - } - - /// `revive` for a named instance. + /// Her unit of `turn`'s slot is active. pub(crate) fn revive_as(&self, instance: &Slug, turn: RunTurn) { self.running.borrow_mut().push((instance.clone(), turn.slot())); } @@ -229,26 +221,6 @@ impl MindPort for TestMind { } } -/// A mind whose admissions answer as told, over a real mind's reads. -pub(crate) struct Answering<'a> { - pub(crate) inner: &'a TestMind, - pub(crate) outcome: PipelineAdmissionOutcome, -} - -impl MindPort for Answering<'_> { - fn instance(&self) -> &Slug { - self.inner.instance() - } - - fn query(&self, selection: &Selection) -> Result { - self.inner.query(selection) - } - - fn admit(&self, _agent: &str, _session: &str, _documents: Vec) -> Result { - Ok(self.outcome.clone()) - } -} - /// One of her memories: `sort` and `text`, about `about`, learned in #swarm, salience 500. pub(crate) fn memory(label: &str, sort: MemorySort, text: &str, about: &[&str]) -> PipelineDocument { memory_from(label, sort, text, about, MemoryOrigin::Room { rooms: "swarm".into(), heard_from: vec![] }, 500) @@ -368,26 +340,6 @@ fn delta() -> StructuralDelta { } } -pub(crate) fn report(cut: &str) -> PipelineDocument { - PipelineDocument::CutReport(PipelineCutReport { - campaign: Slug(CAMPAIGN.into()), - cut_spec: id("cut_spec", &format!("cut-{cut}.r1")).as_str().into(), - attempt: 1, - repo: REPO.into(), - branch: "eureka-body/x".into(), - commits: vec![eureka_pipeline::ReportCommit { sha: Sha("df7507b".into()), subject: "Land the cut".into(), builds: true }], - range: CommitRange { base: Sha("df7507b".into()), head: Sha("df7507b".into()) }, - verification: vec![], - mutations: vec![], - deviations: vec![], - forks: vec![], - structural_delta: delta(), - landed_names: vec![], - undone: vec![], - promises: vec![], - }) -} - /// A question raised in `item`, which blocks it. pub(crate) fn question_in(label: &str, item: &PipelineRef) -> PipelineDocument { PipelineDocument::Question(PipelineQuestion { @@ -461,32 +413,6 @@ pub(crate) fn withdrawn() -> ResolutionOutcome { ResolutionOutcome::Withdrawn { reason: "never ran".into() } } -/// Her Self run on `item`, ended, as `n` in a history: opened, closed, and -/// followed by a follow-up sourced from `item` when `leaves_something` (the -/// document that cites the item, which makes the run non-empty). -pub(crate) fn ended_run(mind: &TestMind, item: &PipelineRef, prefix: &str, n: usize, leaves_something: bool) { - let label = format!("{prefix}{n}"); - mind.committed(vec![run(&label, RunTurn::SelfRun, RunOperator::Mind, std::slice::from_ref(item))]); - let mut closing = vec![close(run_ref(&label), recorded())]; - if leaves_something { - closing.push(follow_up(&format!("{prefix}left{n}"), item)); - } - mind.committed(closing); -} - -/// A history of ended runs on `item`, oldest first; `true` leaves a document. -pub(crate) fn history(mind: &TestMind, item: &PipelineRef, runs: &[bool]) { - history_as(mind, item, "h", runs); -} - -/// The same, with run labels `0`, `1`, and so on, for a mind -/// holding the histories of several items. -pub(crate) fn history_as(mind: &TestMind, item: &PipelineRef, prefix: &str, runs: &[bool]) { - for (n, leaves_something) in runs.iter().enumerate() { - ended_run(mind, item, prefix, n, *leaves_something); - } -} - /// A follow-up sourced from `source`: work a run may claim that the queue does /// not list. pub(crate) fn follow_up(label: &str, source: &PipelineRef) -> PipelineDocument {