mind-launch: a Grant names its instance and its store, Persona runs take no claims, breaker bounds pinned
Grant carries the instance whose store was read; read_effective(root, instance) derives the store path itself and no caller supplies a path or a source. The launch refuses a Grant of another instance and a Persona request with claims, both typed refusals that name no input. Launcher drops its dead label: liveness is keyed by unit (instance, turn). Tests pin Persona step 0, the Operator-run exclusion, the fiftieth ended run and the same-batch boundary. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
35c5b7ac24
commit
663a844e76
7 changed files with 331 additions and 77 deletions
|
|
@ -49,7 +49,7 @@ pub fn run(args: &[String], root: &Path, set_by: &str, now: DateTime<Utc>, out:
|
|||
let path = control_path(root, &instance)?;
|
||||
let words: Vec<&str> = command.iter().map(String::as_str).collect();
|
||||
match words.as_slice() {
|
||||
["show"] => show(&path, &instance, out),
|
||||
["show"] => show(root, &instance, out),
|
||||
["brake", "hold"] => ControlWriter::open(&path)?.set_brake(false, now, set_by),
|
||||
["brake", "release"] => ControlWriter::open(&path)?.set_brake(true, now, set_by),
|
||||
["dial", "set", flags @ ..] => {
|
||||
|
|
@ -90,8 +90,8 @@ fn need<'a>(value: Option<&'a str>, name: &str) -> Result<&'a str> {
|
|||
value.ok_or_else(|| anyhow!("{name} is required"))
|
||||
}
|
||||
|
||||
fn show(path: &Path, instance: &Slug, out: &mut impl Write) -> Result<()> {
|
||||
let source = FileSource::new(path);
|
||||
fn show(root: &Path, instance: &Slug, out: &mut impl Write) -> Result<()> {
|
||||
let source = FileSource::new(control_path(root, instance)?);
|
||||
writeln!(out, "instance: {}", instance.0)?;
|
||||
match load_state(&source) {
|
||||
Ok(state) => {
|
||||
|
|
@ -120,6 +120,6 @@ fn show(path: &Path, instance: &Slug, out: &mut impl Write) -> Result<()> {
|
|||
}
|
||||
Err(error) => writeln!(out, "store: undecodable ({error:#})")?,
|
||||
}
|
||||
writeln!(out, "effective: {:?}", read_effective(&source))?;
|
||||
writeln!(out, "effective: {:?}", read_effective(root, instance))?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,10 @@
|
|||
//!
|
||||
//! `Released` carries a `Grant`, the only value that hands a run cap to the
|
||||
//! launch: it cannot be built outside this module, so a cap exists only as the
|
||||
//! reading of a released brake and an in-bounds dial.
|
||||
//! reading of a released brake and an in-bounds dial. The Grant names the
|
||||
//! instance whose store was read, and that store's path is derived from the
|
||||
//! instance here, by the one reader: no caller supplies a path or a source, so
|
||||
//! a Grant is the proof that this instance's own root-owned store released.
|
||||
//!
|
||||
//! State is a CultCache single-file store at
|
||||
//! `/etc/gamecult/minds/<instance>/control.cc`, root-owned and world-readable.
|
||||
|
|
@ -121,16 +124,24 @@ pub enum Effective {
|
|||
Released(Grant),
|
||||
}
|
||||
|
||||
/// The proof that the brake was released and the dial in bounds when read. Its
|
||||
/// fields are private and only `read_effective` makes one; `open_and_launch`
|
||||
/// takes it by value, so one reading opens at most one run.
|
||||
/// The proof that the brake was released and the dial in bounds when read, in
|
||||
/// the root-owned store 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.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Grant {
|
||||
instance: Slug,
|
||||
cadence: Duration,
|
||||
run_cap_usd: Decimal,
|
||||
}
|
||||
|
||||
impl Grant {
|
||||
/// The instance whose control store this was read from.
|
||||
pub fn instance(&self) -> &Slug {
|
||||
&self.instance
|
||||
}
|
||||
|
||||
/// How often she may wake.
|
||||
pub fn cadence(&self) -> Duration {
|
||||
self.cadence
|
||||
|
|
@ -141,9 +152,11 @@ impl Grant {
|
|||
self.run_cap_usd
|
||||
}
|
||||
|
||||
/// 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(cadence: Duration, run_cap_usd: Decimal) -> Self {
|
||||
Self { cadence, run_cap_usd }
|
||||
pub(crate) fn for_test(instance: Slug, cadence: Duration, run_cap_usd: Decimal) -> Self {
|
||||
Self { instance, cadence, run_cap_usd }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -157,7 +170,7 @@ pub struct ControlState {
|
|||
impl ControlState {
|
||||
/// The one derivation. Order: brake first, then dial; each failing rung is
|
||||
/// its own reason.
|
||||
fn effective(&self) -> Effective {
|
||||
fn effective(&self, instance: &Slug) -> Effective {
|
||||
let held = |reason| Effective::Held { reason };
|
||||
let Some(brake) = &self.brake else {
|
||||
return held(HeldReason::BrakeAbsent);
|
||||
|
|
@ -172,7 +185,7 @@ impl ControlState {
|
|||
return held(HeldReason::DialOutOfBounds);
|
||||
}
|
||||
match (dial.cadence(), dial.run_cap_usd()) {
|
||||
(Some(cadence), Some(run_cap_usd)) => Effective::Released(Grant { cadence, run_cap_usd }),
|
||||
(Some(cadence), Some(run_cap_usd)) => Effective::Released(Grant { instance: instance.clone(), cadence, run_cap_usd }),
|
||||
_ => held(HeldReason::DialOutOfBounds),
|
||||
}
|
||||
}
|
||||
|
|
@ -220,14 +233,46 @@ pub fn load_state(source: &impl ControlSource) -> Result<ControlState> {
|
|||
}
|
||||
|
||||
/// The only reader every organ uses (the waker now; the permit issuer and the
|
||||
/// Persona organ later).
|
||||
pub fn read_effective(source: &impl ControlSource) -> Effective {
|
||||
match load_state(source) {
|
||||
Ok(state) => state.effective(),
|
||||
/// Persona organ later). The store is `instance`'s own, at the path
|
||||
/// `control_path` derives under `root`; the caller supplies neither a path nor
|
||||
/// a source. An instance that is not a slug reads as held.
|
||||
pub fn read_effective(root: &Path, instance: &Slug) -> Effective {
|
||||
match control_path(root, instance) {
|
||||
Ok(path) => derive(&FileSource::new(path), instance),
|
||||
Err(_) => Effective::Held { reason: HeldReason::Undecodable },
|
||||
}
|
||||
}
|
||||
|
||||
fn derive(source: &impl ControlSource, instance: &Slug) -> Effective {
|
||||
match load_state(source) {
|
||||
Ok(state) => state.effective(instance),
|
||||
Err(_) => Effective::Held { reason: HeldReason::Undecodable },
|
||||
}
|
||||
}
|
||||
|
||||
/// The same derivation over a fake store, for tests of the reader; the Grant it
|
||||
/// makes names the instance given, and the launch judges that like any other.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn read_effective_from(source: &impl ControlSource, instance: &Slug) -> Effective {
|
||||
derive(source, instance)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_source_that_fails_reads_as_held() {
|
||||
struct Failing;
|
||||
impl ControlSource for Failing {
|
||||
fn snapshot(&self) -> Result<Vec<CultCacheEnvelope>> {
|
||||
Err(anyhow::anyhow!("disk gone"))
|
||||
}
|
||||
}
|
||||
assert_eq!(read_effective_from(&Failing, &Slug("eureka".into())), Effective::Held { reason: HeldReason::Undecodable });
|
||||
}
|
||||
}
|
||||
|
||||
/// The operator's writer over one control file. Each setter replaces its
|
||||
/// document whole; the other document is untouched. The file is created on the
|
||||
/// first write.
|
||||
|
|
|
|||
|
|
@ -10,7 +10,10 @@
|
|||
//! 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. The primitive
|
||||
//! 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: stopping her units is the operator's brake
|
||||
//! hold, which is another cut's.
|
||||
|
||||
|
|
@ -33,9 +36,10 @@ pub const START_GRACE_S: i64 = 120;
|
|||
/// Starts the unit that carries a run, and says whether it is still running.
|
||||
/// Nothing here stops a unit.
|
||||
pub trait Launcher {
|
||||
// The label names the run asked about; SystemdLauncher names its unit by instance and turn alone (ruling mind-unit-names).
|
||||
fn start(&self, instance: &Slug, turn: RunTurn, label: &Label) -> Result<()>;
|
||||
fn alive(&self, instance: &Slug, turn: RunTurn, label: &Label) -> bool;
|
||||
/// Units are named by instance and turn alone (ruling mind-unit-names), so
|
||||
/// liveness is keyed the same way.
|
||||
fn start(&self, instance: &Slug, turn: RunTurn) -> Result<()>;
|
||||
fn alive(&self, instance: &Slug, turn: RunTurn) -> bool;
|
||||
}
|
||||
|
||||
/// The time the primitive reads: run labels, dates and receipts.
|
||||
|
|
@ -110,12 +114,12 @@ pub(crate) fn unit(instance: &Slug, turn: RunTurn) -> Result<String> {
|
|||
}
|
||||
|
||||
impl Launcher for SystemdLauncher {
|
||||
fn start(&self, instance: &Slug, turn: RunTurn, _label: &Label) -> Result<()> {
|
||||
fn start(&self, instance: &Slug, turn: RunTurn) -> Result<()> {
|
||||
let reply = self.systemctl.run(&["start", "--no-block", &unit(instance, turn)?])?;
|
||||
if reply.success { Ok(()) } else { Err(anyhow!("systemctl did not start the unit")) }
|
||||
}
|
||||
|
||||
fn alive(&self, instance: &Slug, turn: RunTurn, _label: &Label) -> bool {
|
||||
fn alive(&self, instance: &Slug, turn: RunTurn) -> bool {
|
||||
let Ok(unit) = unit(instance, turn) else {
|
||||
return false;
|
||||
};
|
||||
|
|
@ -157,6 +161,10 @@ pub enum Declined {
|
|||
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)]
|
||||
|
|
@ -233,6 +241,12 @@ fn holders(mind: &dyn MindPort, instance: &Slug, turn: RunTurn) -> Result<Vec<Pi
|
|||
pub fn open_and_launch(ports: &Ports, request: LaunchRequest) -> Result<LaunchOutcome> {
|
||||
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::PersonaTurn && !claims.is_empty() {
|
||||
return Ok(LaunchOutcome::Refused(Declined::PersonaRunTakesNoClaims));
|
||||
}
|
||||
let now = ports.clock.now();
|
||||
let label = run_label(now);
|
||||
|
||||
|
|
@ -241,8 +255,7 @@ pub fn open_and_launch(ports: &Ports, request: LaunchRequest) -> Result<LaunchOu
|
|||
let mut batch: Vec<PipelineDocument> = Vec::new();
|
||||
let mut ending: Vec<PipelineRef> = Vec::new();
|
||||
for holder in holders(ports.mind, &instance, turn)? {
|
||||
let PipelineFacts::Run { label: held, .. } = &holder.facts else { continue };
|
||||
if ports.launcher.alive(&instance, turn, held) || !past_grace(&holder.admission.admitted_at, now) {
|
||||
if ports.launcher.alive(&instance, turn) || !past_grace(&holder.admission.admitted_at, now) {
|
||||
return Ok(LaunchOutcome::Busy { run: holder.id });
|
||||
}
|
||||
batch.push(close_dead(ports.mind, &holder.id, now)?);
|
||||
|
|
@ -303,7 +316,7 @@ pub fn open_and_launch(ports: &Ports, request: LaunchRequest) -> Result<LaunchOu
|
|||
}
|
||||
}
|
||||
}
|
||||
if ports.launcher.start(&instance, turn, &label).is_err() {
|
||||
if ports.launcher.start(&instance, turn).is_err() {
|
||||
let withdrawal = PipelineResolution {
|
||||
subject: opened,
|
||||
sequence: 1,
|
||||
|
|
@ -388,7 +401,7 @@ mod tests {
|
|||
|
||||
fn try_launch_through(&self, mind: &dyn MindPort, turn: RunTurn, claims: &[PipelineRef], cap: Decimal) -> Result<LaunchOutcome> {
|
||||
let ports = Ports { mind, launcher: &self.launcher, clock: &self.clock, host: "yggdrasil-host" };
|
||||
let grant = Grant::for_test(StdDuration::from_secs(60), cap);
|
||||
let grant = Grant::for_test(Slug(INSTANCE.into()), StdDuration::from_secs(60), cap);
|
||||
open_and_launch(&ports, LaunchRequest { turn, claims: claims.to_vec(), agent: "agent-x".into(), grant })
|
||||
}
|
||||
|
||||
|
|
@ -414,7 +427,7 @@ mod tests {
|
|||
/// 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(label);
|
||||
self.launcher.revive(turn);
|
||||
}
|
||||
|
||||
fn in_force(&self, run: &str) -> bool {
|
||||
|
|
@ -451,7 +464,7 @@ mod tests {
|
|||
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, label("mind-20261009T131500000Z"))]);
|
||||
assert_eq!(*rig.launcher.started.borrow(), vec![(Slug(INSTANCE.into()), RunTurn::SelfRun)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -751,7 +764,7 @@ mod tests {
|
|||
let first_label = first.id.0.rsplit(':').next().unwrap().to_string();
|
||||
rig.age(&first.id.0, 3600);
|
||||
assert_eq!(rig.launch(RunTurn::SelfRun, &[], five()), LaunchOutcome::Busy { run: first.clone() }, "its unit is still running");
|
||||
rig.launcher.kill(&first_label);
|
||||
rig.launcher.kill(RunTurn::SelfRun);
|
||||
assert!(matches!(rig.launch(RunTurn::SelfRun, &[], five()), LaunchOutcome::Launched { .. }));
|
||||
assert!(!rig.in_force(&first_label));
|
||||
assert_eq!(rig.started(), 2);
|
||||
|
|
@ -833,6 +846,58 @@ mod tests {
|
|||
assert_eq!((rig.runs(), rig.started()), (3, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grant_read_for_another_instance_opens_nothing_and_starts_nothing() {
|
||||
let rig = Rig::new();
|
||||
rig.mind.committed(vec![spec("x")]);
|
||||
for turn in [RunTurn::SelfRun, RunTurn::PersonaTurn] {
|
||||
let claims = if turn == RunTurn::SelfRun { vec![spec_ref("x")] } else { vec![] };
|
||||
let ports = Ports { mind: &rig.mind, launcher: &rig.launcher, clock: &rig.clock, host: "yggdrasil-host" };
|
||||
let grant = Grant::for_test(Slug("another-instance".into()), StdDuration::from_secs(60), five());
|
||||
let outcome = open_and_launch(&ports, LaunchRequest { turn, claims, agent: "agent-x".into(), grant }).unwrap();
|
||||
assert_eq!(outcome, LaunchOutcome::Refused(Declined::GrantForOtherInstance), "{turn:?}");
|
||||
}
|
||||
assert_eq!((rig.runs(), rig.started()), (0, 0));
|
||||
assert!(matches!(rig.launch(RunTurn::SelfRun, &[spec_ref("x")], five()), LaunchOutcome::Launched { .. }), "the mind's own Grant launches");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_persona_turn_with_claims_is_refused_and_opens_nothing() {
|
||||
let rig = Rig::new();
|
||||
rig.mind.committed(vec![spec("x"), spec("blocked")]);
|
||||
rig.mind.committed(vec![question_in("fork", &spec_ref("blocked"))]);
|
||||
// A queued claim and a blocked one: neither opens a Persona run.
|
||||
for item in ["x", "blocked"] {
|
||||
let outcome = rig.launch(RunTurn::PersonaTurn, &[spec_ref(item)], five());
|
||||
assert_eq!(outcome, LaunchOutcome::Refused(Declined::PersonaRunTakesNoClaims), "{item}");
|
||||
}
|
||||
assert_eq!((rig.runs(), rig.started()), (0, 0));
|
||||
assert!(matches!(rig.launch(RunTurn::PersonaTurn, &[], five()), LaunchOutcome::Launched { .. }));
|
||||
}
|
||||
|
||||
#[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, &[], five()), 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, &[], five()), 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_nor_does_a_dead_self_run_get_closed_by_it() {
|
||||
let rig = Rig::new();
|
||||
rig.seed("alive-self", RunTurn::SelfRun, &[]);
|
||||
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, &[], five()), LaunchOutcome::Launched { .. }));
|
||||
assert!(rig.in_force("alive-self") && rig.in_force("dead-self"), "a Persona launch reads and closes only Persona holders");
|
||||
}
|
||||
|
||||
struct Spy {
|
||||
calls: RefCell<Vec<Vec<String>>>,
|
||||
success: Cell<bool>,
|
||||
|
|
@ -858,11 +923,10 @@ mod tests {
|
|||
#[test]
|
||||
fn units_are_templated_by_instance_and_turn() {
|
||||
let (launcher, spy) = spied();
|
||||
let l = label("mind-20261009T131500123Z");
|
||||
assert_eq!(unit(&eureka(), RunTurn::PersonaTurn).unwrap(), "mind-persona@eureka.service");
|
||||
assert_eq!(unit(&eureka(), RunTurn::SelfRun).unwrap(), "mind-self@eureka.service");
|
||||
launcher.start(&eureka(), RunTurn::SelfRun, &l).unwrap();
|
||||
launcher.start(&Slug("eureka.test".into()), RunTurn::PersonaTurn, &l).unwrap();
|
||||
launcher.start(&eureka(), RunTurn::SelfRun).unwrap();
|
||||
launcher.start(&Slug("eureka.test".into()), RunTurn::PersonaTurn).unwrap();
|
||||
assert_eq!(
|
||||
*spy.calls.borrow(),
|
||||
vec![vec!["start", "--no-block", "mind-self@eureka.service"], vec!["start", "--no-block", "mind-persona@eureka.test.service"],]
|
||||
|
|
@ -872,21 +936,20 @@ mod tests {
|
|||
#[test]
|
||||
fn a_unit_is_alive_while_active_activating_or_reloading() {
|
||||
let (launcher, spy) = spied();
|
||||
let l = label("a");
|
||||
for (said, alive) in
|
||||
[("active\n", true), ("activating\n", true), ("reloading\n", true), ("inactive\n", false), ("failed\n", false), ("", false)]
|
||||
{
|
||||
*spy.stdout.borrow_mut() = said.to_string();
|
||||
assert_eq!(launcher.alive(&eureka(), RunTurn::SelfRun, &l), alive, "{said:?}");
|
||||
assert_eq!(launcher.alive(&eureka(), RunTurn::SelfRun), alive, "{said:?}");
|
||||
}
|
||||
assert_eq!(spy.calls.borrow()[0], vec!["is-active", "mind-self@eureka.service"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_start_names_neither_instance_nor_label() {
|
||||
fn a_failed_start_names_no_instance() {
|
||||
let (launcher, spy) = spied();
|
||||
spy.success.set(false);
|
||||
let error = launcher.start(&Slug("canary-instance-7f3a91".into()), RunTurn::SelfRun, &label("canary-label-2c8d04")).unwrap_err();
|
||||
let error = launcher.start(&Slug("canary-instance-7f3a91".into()), RunTurn::SelfRun).unwrap_err();
|
||||
let shown = format!("{error:#}");
|
||||
assert!(!shown.contains("canary"), "{shown}");
|
||||
}
|
||||
|
|
@ -914,9 +977,9 @@ b",
|
|||
"canary/9",
|
||||
] {
|
||||
let instance = Slug(hostile.into());
|
||||
let error = launcher.start(&instance, RunTurn::SelfRun, &label("ok")).unwrap_err();
|
||||
let error = launcher.start(&instance, RunTurn::SelfRun).unwrap_err();
|
||||
assert!(!format!("{error:#}").contains("canary"), "{error:#}");
|
||||
assert!(!launcher.alive(&instance, RunTurn::PersonaTurn, &label("ok")), "instance {hostile:?}");
|
||||
assert!(!launcher.alive(&instance, RunTurn::PersonaTurn), "instance {hostile:?}");
|
||||
}
|
||||
assert!(spy.calls.borrow().is_empty(), "no hostile name reached systemctl: {:?}", spy.calls.borrow());
|
||||
}
|
||||
|
|
@ -924,10 +987,10 @@ b",
|
|||
#[test]
|
||||
fn a_unit_is_named_by_instance_and_turn_alone() {
|
||||
let (launcher, spy) = spied();
|
||||
launcher.start(&eureka(), RunTurn::SelfRun, &label("mind-20261009T131500001Z")).unwrap();
|
||||
launcher.start(&eureka(), RunTurn::SelfRun, &label("mind-20261009T131500002Z")).unwrap();
|
||||
launcher.start(&eureka(), RunTurn::SelfRun).unwrap();
|
||||
launcher.start(&eureka(), RunTurn::SelfRun).unwrap();
|
||||
let calls = spy.calls.borrow();
|
||||
assert_eq!(calls[0], calls[1], "two runs of one turn share a unit name");
|
||||
assert!(!calls[0][2].contains("mind-2026"), "{:?}", calls[0]);
|
||||
assert_eq!(calls[0][2], "mind-self@eureka.service");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -285,6 +285,48 @@ mod tests {
|
|||
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_eq!(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] {
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use anyhow::{Result, anyhow};
|
|||
use chrono::{DateTime, Duration, TimeZone, Utc};
|
||||
use cultnet_rs::Selection;
|
||||
use eureka_pipeline::{
|
||||
CommitRange, CutVerification, Date, DocRef, Label, PipelineCampaign, PipelineCutReport, PipelineCutSpec, PipelineDocument, PipelineFollowUp,
|
||||
CommitRange, CutVerification, Date, DocRef, PipelineCampaign, PipelineCutReport, PipelineCutSpec, PipelineDocument, PipelineFollowUp,
|
||||
PipelineInstance, PipelineKind, PipelineQuestion, PipelineRef, PipelineResolution, PipelineRuling, PipelineRun, PipelineStewardship,
|
||||
PipelineTarget, QuestionOption, ResolutionOutcome, RulingAuthority, RunOperator, RunTurn, Sha, Slug, StructuralDelta, TargetInvariant,
|
||||
};
|
||||
|
|
@ -37,38 +37,39 @@ impl Clock for Fixed {
|
|||
}
|
||||
}
|
||||
|
||||
/// A launcher that records every start as (instance, turn, label), fails them
|
||||
/// on command, and answers `alive` from a set of labels: `start` fills it,
|
||||
/// `kill` empties it for a label and `revive` fills it for a seeded run.
|
||||
/// A launcher that records every start as (instance, turn), fails them on
|
||||
/// command, and answers `alive` per unit, which is what instance and turn name:
|
||||
/// `start` fills it, `kill` empties a turn's unit and `revive` fills it for a
|
||||
/// seeded run.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Recording {
|
||||
pub(crate) started: RefCell<Vec<(Slug, RunTurn, Label)>>,
|
||||
pub(crate) started: RefCell<Vec<(Slug, RunTurn)>>,
|
||||
pub(crate) fail: Cell<bool>,
|
||||
running: RefCell<Vec<Label>>,
|
||||
running: RefCell<Vec<(Slug, RunTurn)>>,
|
||||
}
|
||||
|
||||
impl Recording {
|
||||
pub(crate) fn kill(&self, run: &str) {
|
||||
self.running.borrow_mut().retain(|label| label.0 != run);
|
||||
pub(crate) fn kill(&self, turn: RunTurn) {
|
||||
self.running.borrow_mut().retain(|unit| *unit != (Slug(INSTANCE.into()), turn));
|
||||
}
|
||||
|
||||
pub(crate) fn revive(&self, run: &str) {
|
||||
self.running.borrow_mut().push(label(run));
|
||||
pub(crate) fn revive(&self, turn: RunTurn) {
|
||||
self.running.borrow_mut().push((Slug(INSTANCE.into()), turn));
|
||||
}
|
||||
}
|
||||
|
||||
impl Launcher for Recording {
|
||||
fn start(&self, instance: &Slug, turn: RunTurn, label: &Label) -> Result<()> {
|
||||
fn start(&self, instance: &Slug, turn: RunTurn) -> Result<()> {
|
||||
if self.fail.get() {
|
||||
return Err(anyhow!("refused"));
|
||||
}
|
||||
self.started.borrow_mut().push((instance.clone(), turn, label.clone()));
|
||||
self.running.borrow_mut().push(label.clone());
|
||||
self.started.borrow_mut().push((instance.clone(), turn));
|
||||
self.running.borrow_mut().push((instance.clone(), turn));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn alive(&self, _instance: &Slug, _turn: RunTurn, label: &Label) -> bool {
|
||||
self.running.borrow().contains(label)
|
||||
fn alive(&self, instance: &Slug, turn: RunTurn) -> bool {
|
||||
self.running.borrow().contains(&(instance.clone(), turn))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -381,10 +382,6 @@ pub(crate) fn history_as(mind: &TestMind, item: &PipelineRef, prefix: &str, runs
|
|||
}
|
||||
}
|
||||
|
||||
pub(crate) fn label(value: &str) -> Label {
|
||||
value.into()
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
|
|
|||
|
|
@ -12,12 +12,12 @@
|
|||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use cultcache_rs::{CultCache, CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use mind_body::control::{
|
||||
BRAKE_KEY, BurnRate, ControlSource, ControlWriter, Effective, FileSource, HeldReason, control_path, load_state, read_effective,
|
||||
BRAKE_KEY, BurnRate, ControlWriter, Effective, FileSource, HeldReason, control_path, load_state, read_effective,
|
||||
};
|
||||
use eureka_pipeline::Slug;
|
||||
use rust_decimal::Decimal;
|
||||
use std::str::FromStr;
|
||||
|
||||
|
|
@ -33,8 +33,9 @@ fn dial(heat: &str, cooldown: u32, run_usd: &str) -> BurnRate {
|
|||
BurnRate { heat: dec(heat), base_cooldown_s: cooldown, base_run_usd: dec(run_usd), set_at: at(0), set_by: "op".into() }
|
||||
}
|
||||
|
||||
/// The store of the instance `eureka` under the root `dir`.
|
||||
fn store_path(dir: &Path) -> PathBuf {
|
||||
dir.join("control.cc")
|
||||
dir.join("eureka").join("control.cc")
|
||||
}
|
||||
|
||||
fn held(reason: HeldReason) -> Effective {
|
||||
|
|
@ -50,8 +51,12 @@ fn released_store(dir: &Path, dial: BurnRate) -> PathBuf {
|
|||
path
|
||||
}
|
||||
|
||||
/// The reader's answer for the store at `<root>/<instance>/control.cc`: the
|
||||
/// reader derives that path itself from the root and the instance.
|
||||
fn effective(path: &Path) -> Effective {
|
||||
read_effective(&FileSource::new(path))
|
||||
let directory = path.parent().unwrap();
|
||||
let instance = Slug(directory.file_name().unwrap().to_str().unwrap().into());
|
||||
read_effective(directory.parent().unwrap(), &instance)
|
||||
}
|
||||
|
||||
/// A dial written around the writer's bounds check, so the reader's own check
|
||||
|
|
@ -104,21 +109,10 @@ fn a_path_that_cannot_be_read_as_a_file_reads_as_held() {
|
|||
let dir = tempfile::tempdir().unwrap();
|
||||
// A directory sits where the store should be: it exists and cannot be read as a file.
|
||||
let path = store_path(dir.path());
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
assert_eq!(effective(&path), held(HeldReason::Undecodable));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_that_fails_reads_as_held() {
|
||||
struct Failing;
|
||||
impl ControlSource for Failing {
|
||||
fn snapshot(&self) -> Result<Vec<CultCacheEnvelope>> {
|
||||
Err(anyhow!("disk gone"))
|
||||
}
|
||||
}
|
||||
assert_eq!(read_effective(&Failing), held(HeldReason::Undecodable));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_document_type_makes_the_store_undecodable() {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
|
|
@ -291,7 +285,6 @@ fn reading_writes_nothing_and_takes_no_lock_file() {
|
|||
|
||||
#[test]
|
||||
fn the_control_path_is_derived_from_a_valid_instance_only() {
|
||||
use eureka_pipeline::Slug;
|
||||
let root = Path::new(mind_body::control::CONTROL_ROOT);
|
||||
assert_eq!(control_path(root, &Slug("eureka".into())).unwrap(), root.join("eureka").join("control.cc"));
|
||||
for bad in ["", "../etc", "a/b", "A b", "eureka/.."] {
|
||||
|
|
|
|||
114
crates/mind-body/tests/grant.rs
Normal file
114
crates/mind-body/tests/grant.rs
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
//! A Grant is the proof that this instance's own control store released. The
|
||||
//! tests are an outside crate's view: the only reader takes a root and an
|
||||
//! instance and derives the store path itself, and a launch refuses a Grant
|
||||
//! read for another instance before it asks the mind anything.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use cultnet_rs::Selection;
|
||||
use eureka_pipeline::{PipelineDocument, RunTurn, Slug};
|
||||
use huginn_mind::{PipelineAdmissionOutcome, PipelineSelectionPage};
|
||||
use mind_body::control::{BurnRate, ControlWriter, Effective, HeldReason, control_path, read_effective};
|
||||
use mind_body::launch::{Clock, Declined, LaunchOutcome, LaunchRequest, Launcher, Ports, open_and_launch};
|
||||
use mind_body::queue::MindPort;
|
||||
use rust_decimal::Decimal;
|
||||
|
||||
fn slug(name: &str) -> Slug {
|
||||
Slug(name.into())
|
||||
}
|
||||
|
||||
fn release(root: &Path, instance: &Slug) {
|
||||
let mut writer = ControlWriter::open(control_path(root, instance).unwrap()).unwrap();
|
||||
let at = Utc.timestamp_opt(1_800_000_000, 0).unwrap();
|
||||
writer.set_brake(true, at, "op").unwrap();
|
||||
writer.set_dial(BurnRate { heat: Decimal::ONE, base_cooldown_s: 3600, base_run_usd: Decimal::new(5, 0), set_at: at, set_by: "op".into() }).unwrap();
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
Utc.timestamp_opt(1_800_000_100, 0).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn launch_as(mind_instance: &str, grant: mind_body::control::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 the_reader_makes_a_grant_for_the_instance_whose_store_it_read() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
release(root.path(), &slug("void"));
|
||||
let Effective::Released(grant) = read_effective(root.path(), &slug("void")) else { panic!("void's store is released") };
|
||||
assert_eq!(grant.instance(), &slug("void"));
|
||||
assert_eq!(grant.run_cap_usd(), Decimal::new(5, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_instances_released_store_yields_no_grant_for_this_one() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
release(root.path(), &slug("void"));
|
||||
// The operator holds eureka's brake: eureka has no released store under this root.
|
||||
assert_eq!(read_effective(root.path(), &slug("eureka")), Effective::Held { reason: HeldReason::BrakeAbsent });
|
||||
// A path-shaped instance cannot reach void's store by walking.
|
||||
for walk in ["../void", "void/..", "eureka/../void", "/void"] {
|
||||
assert_eq!(read_effective(root.path(), &slug(walk)), Effective::Held { reason: HeldReason::Undecodable }, "{walk}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grant_read_for_one_instance_cannot_launch_another() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
release(root.path(), &slug("void"));
|
||||
for turn in [RunTurn::SelfRun, RunTurn::PersonaTurn] {
|
||||
let Effective::Released(grant) = read_effective(root.path(), &slug("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(), &slug("void"));
|
||||
let Effective::Released(grant) = read_effective(root.path(), &slug("void")) else { panic!("void's store is released") };
|
||||
// Past the check the silent mind is asked, so the launch errors there.
|
||||
let error = launch_as("void", grant, RunTurn::SelfRun).unwrap_err();
|
||||
assert!(format!("{error:#}").contains("asked the mind"), "{error:#}");
|
||||
}
|
||||
Loading…
Reference in a new issue