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 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-19 22:30:50 +01:00
commit 6df3255330
6 changed files with 42 additions and 1835 deletions

View file

@ -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<ControlState> {
/// 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:
///
/// ```

View file

@ -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<PipelineSelectionPage> {
Err(anyhow!("the launch asked the mind"))
}
fn admit(&self, _agent: &str, _session: &str, _documents: Vec<PipelineDocument>) -> Result<PipelineAdmissionOutcome> {
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<Utc> {
at(100)
}
}
fn launch_as(mind_instance: &str, grant: Grant, turn: RunTurn) -> Result<LaunchOutcome> {
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();

File diff suppressed because it is too large Load diff

View file

@ -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

View file

@ -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<Vec<PipelineRef>> {
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<Vec<PipelineRef>> {
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<Vec<Hold>> {
@ -205,303 +174,16 @@ pub fn on_hold(mind: &dyn MindPort) -> Result<Held> {
))
}
/// 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<Vec<PipelineRef>> {
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<Breaker> {
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<usize> = (0..ran.len()).filter(|index| ran[*index].1).collect();
let considered: Vec<usize> = ended.iter().rev().take(WINDOW).copied().collect();
let admitted: Vec<u64> =
set.iter().filter(|header| !matches!(header.facts, PipelineFacts::Run { .. })).map(|header| header.admission.ordinal).collect();
// Newest first, like `considered`.
let empty: Vec<bool> = 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<Vec<PipelineRef>> {
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<bool> = [E, E, N].repeat(5);
assert!(tripped(&ten), "10 empty, never 3 in a row");
let mut nine: Vec<bool> = [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<bool> = [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<PipelineRef> = 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<PipelineRef> = ["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::<PipelineRef>::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}");

View file

@ -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<PipelineSelectionPage> {
self.inner.query(selection)
}
fn admit(&self, _agent: &str, _session: &str, _documents: Vec<PipelineDocument>) -> Result<PipelineAdmissionOutcome> {
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 `<prefix>0`, `<prefix>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 {