diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 4da8c0b..13a5b78 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -221,6 +221,19 @@ pub trait Store { fn save_addressing(&self, addressing: &Addressing) -> Result<()>; } +/// The lines a wake of one Mind is for: the line that woke her (none for the beat's) and the open-floor lines she took. The +/// one derivation: the poll records them as her handled keys, `woken_for` reads them back for her packet, and the simulator +/// hands her packet the same, so the simulator measures what live does. +pub(crate) fn claimed(waking: Option<&str>, floor: &[String]) -> Vec { + let mut events: Vec = Vec::new(); + for event in waking.into_iter().chain(floor.iter().map(String::as_str)) { + if !events.iter().any(|held| held == event) { + events.push(event.to_owned()); + } + } + events +} + /// The lines the heartbeat woke `slug` for, as her handled keys name them (`slug:event`): what her packet reads as said to /// her, so the wake and the packet cannot disagree about whose line it was. pub fn woken_for(state: &HeartbeatState, slug: &str) -> Vec { @@ -234,6 +247,11 @@ pub trait HeartbeatView { fn written_at(&self) -> Option> { None } + /// The lines the heartbeat woke `slug` for (`woken_for`): the poll records them before it starts her unit, so a start finds + /// them. A view with no heartbeat behind it names none. + fn woken_for(&self, _slug: &str) -> Result> { + Ok(Vec::new()) + } } /// The store as a CultCache single-file store under the unit's state directory. @@ -333,6 +351,10 @@ impl HeartbeatView for FileStore { fn written_at(&self) -> Option> { std::fs::metadata(&self.path).and_then(|meta| meta.modified()).ok().map(DateTime::::from) } + + fn woken_for(&self, slug: &str) -> Result> { + Ok(self.load()?.map(|state| woken_for(&state, slug)).unwrap_or_default()) + } } /// What the operator stores allow: the swarm brake, and each instance's own @@ -860,29 +882,32 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { .into_iter() .zip(facts) .filter(|(delivery, facts)| wakes(&row.addressee, delivery, config.speaker(&row.addressee, delivery), *facts).is_some()) - .map(|(delivery, _)| format!("{}:{}", slug.0, delivery.event_id)) - .find(|key| !state.handled_mentions.contains(key)) + .map(|(delivery, _)| delivery.event_id.clone()) + .find(|event| !state.handled_mentions.contains(&format!("{}:{event}", slug.0))) }; - let Some(key) = mentioned else { continue }; + let Some(event) = mentioned else { continue }; tried.push(index); + // The wake's lines are recorded before her unit starts, so the start reads them; a start that fails gives them back. + let before = state.clone(); + for event in claimed(Some(&event), &floor[index]) { + let key = format!("{}:{event}", slug.0); + if !state.handled_mentions.contains(&key) { + state.handled_mentions.push(key); + } + } + let excess = state.handled_mentions.len().saturating_sub(MENTIONS_KEPT); + state.handled_mentions.drain(..excess); + state.last_turn_at.insert(slug.0.clone(), now); + organs.store.save(&state)?; match wake(organs, row) { Woke::Started => { - state.handled_mentions.push(key); - // The floor lines she took are taken: no other Mind is picked for them. - for event in &floor[index] { - let taken = format!("{}:{event}", slug.0); - if !state.handled_mentions.contains(&taken) { - state.handled_mentions.push(taken); - } - } - let excess = state.handled_mentions.len().saturating_sub(MENTIONS_KEPT); - state.handled_mentions.drain(..excess); - state.last_turn_at.insert(slug.0.clone(), now); row.busy = true; launches.push(slug.0.clone()); launched.push(slug); } refused => { + state = before; + organs.store.save(&state)?; match refused { Woke::Refused(why) => row.note = why, _ => row.busy = true, diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 1be3834..4c1d900 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -117,6 +117,8 @@ struct MemStore { traces: RefCell>, addressing: RefCell>, addressing_saves: Cell, + /// `save` into the order a launcher's `start` logs into. + log: std::rc::Rc>>, } impl Store for MemStore { @@ -125,6 +127,7 @@ impl Store for MemStore { } fn save(&self, state: &HeartbeatState) -> Result<()> { + self.log.borrow_mut().push("save"); *self.state.borrow_mut() = Some(state.clone()); Ok(()) } @@ -867,6 +870,32 @@ mod wake_rule { assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "once per line: the Mind who took it is not woken again and no other is picked for it"); } + #[test] + fn the_lines_a_wake_is_for_are_recorded_before_her_unit_starts_and_given_back_when_it_does_not_start() { + let mut rig = quiet_rig(); + rig.launcher.log = rig.store.log.clone(); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + rig.store.log.borrow_mut().clear(); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); + let log = rig.store.log.borrow().clone(); + assert_eq!(log.iter().position(|step| *step == "start").and_then(|start| log[..start].iter().position(|step| *step == "save")), Some(0), "her state held the claim when her unit started: {log:?}"); + let state = rig.store.state.borrow().clone().unwrap(); + assert_eq!(woken_for(&state, "ann"), vec![state.handled_mentions[0].split_once(':').unwrap().1.to_owned()], "the line is hers"); + let rig = quiet_rig(); + rig.launcher.fail.set(true); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }); + let state = rig.store.state.borrow().clone().unwrap(); + assert!(woken_for(&state, "ann").is_empty() && woken_for(&state, "bob").is_empty(), "a start that failed claims nothing: {:?}", state.handled_mentions); + } + + #[test] + fn a_wake_is_for_the_line_that_woke_her_and_the_floor_lines_she_took_and_for_nothing_twice() { + assert_eq!(claimed(Some("$a"), &["$b".into(), "$a".into()]), vec!["$a".to_owned(), "$b".to_owned()]); + assert_eq!(claimed(None, &["$b".into()]), vec!["$b".to_owned()], "the beat's wake names no line of its own"); + assert!(claimed(None, &[]).is_empty()); + } + #[test] fn a_second_hello_after_that_mind_answered_wakes_no_extra_mind() { let rig = quiet_rig(); diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index ee28e7e..17cb6a7 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -316,7 +316,16 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { let own = own_rooms(repos.iter().map(String::as_str), deliveries.iter().map(|delivery| delivery.room_alias.as_str())); let public_name = state.get("publicName").and_then(Value::as_str).unwrap_or_default().to_owned(); let (her, _) = heard_as(start.addressing.as_deref(), &config.own_sender, &public_name, began); - let facts = pending_facts(&deliveries, &config.own_sender, &config.minds, &own); + // The lines the heartbeat woke her for, recorded before it started this unit: the open floor is hers only on those, as the + // poll judged it, so a start the beat made does not answer a hello another Mind took. + let claimed = match start.addressing.as_ref().map(|view| view.woken_for(&instance.0)).transpose() { + Ok(lines) => lines.unwrap_or_default(), + Err(fault) => return failed("the heartbeat state was not read", fault), + }; + let mut facts = pending_facts(&deliveries, &config.own_sender, &config.minds, &own); + for (delivery, facts) in deliveries.iter().zip(&mut facts) { + facts.open_floor &= claimed.contains(&delivery.event_id); + } let waking_all: Vec = deliveries .iter() .zip(&facts) @@ -407,7 +416,7 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { last_heard: vec![], recent: past.recent, own_rooms: own.clone(), - woken_for: vec![], + woken_for: claimed.clone(), last_outcome: past.last_outcome, last_wake: past.last_wake, records: past.records, diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index f97c83e..7a237fd 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -182,6 +182,19 @@ fn scripted(remembering: bool) -> Scripted { }) } +/// The heartbeat as a start reads it: no table, and these lines recorded as the ones it woke her for. +struct Woken(Vec); + +impl HeartbeatView for Woken { + fn addressing(&self) -> Result> { + Ok(None) + } + + fn woken_for(&self, _: &str) -> Result> { + Ok(self.0.clone()) + } +} + struct Rig { mouth: Rc, store: Rc, @@ -205,6 +218,15 @@ impl Rig { } fn run(&self, model: impl Model + 'static) -> Outcome { + self.run_as(model, None) + } + + /// A start whose heartbeat state holds `woken` as the lines it woke her for. + fn run_woken(&self, model: impl Model + 'static, woken: &[&str]) -> Outcome { + self.run_as(model, Some(Box::new(Woken(woken.iter().map(|event| (*event).to_owned()).collect())))) + } + + fn run_as(&self, model: impl Model + 'static, addressing: Option>) -> Outcome { let ticks = self.ticks.clone(); let start = || { Ok(Start { @@ -212,7 +234,7 @@ impl Rig { persona: Box::new(self.store.clone()), chat: self.mouth.clone(), trace: Box::new(self.trace.clone()), - addressing: None, + addressing, model: Box::new(model), domain: None, reads: None, @@ -696,3 +718,16 @@ fn t_l2_her_put_is_stamped_after_a_stored_updated_at_that_is_ahead_of_the_clock( let landed = chrono::DateTime::parse_from_rfc3339(rig.store.stored.borrow()["updatedAt"].as_str().unwrap()).unwrap(); assert!(landed.timestamp_millis() > i64::try_from(BASE_MS).unwrap() + 3_600_000, "later than the stored stamp: {landed}"); } + +/// The open floor is hers only on the lines the heartbeat woke her for, which it recorded before it started her unit: a beat's +/// start does not answer a hello the poll gave to another Mind, and one the poll gave her it does. +#[test] +fn t_l2_the_open_floor_is_hers_only_on_the_lines_the_heartbeat_woke_her_for() { + let hello = || vec![line(1, MINDS, "@newcomer:gamecult.org", "hello everyone!")]; + let rig = Rig::new(hello()); + assert_eq!(rig.run_woken(scripted(false), &[]), Outcome::Drained { turns: 1, acked_through: Some(1), put_refused: 0 }); + assert!(rig.mouth.sent.borrow().iter().all(|request| request.request_id.starts_with('b')), "no line woke her: the beat's turn, answering none"); + let rig = Rig::new(hello()); + assert_eq!(rig.run_woken(scripted(false), &["$e1"]), Outcome::Drained { turns: 1, acked_through: Some(1), put_refused: 0 }); + assert_eq!(rig.mouth.sent.borrow().iter().map(|request| request.request_id.clone()).collect::>(), ["l$e1:s0"], "the heartbeat woke her for the hello: she answers it"); +} diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index dd4b249..dd4e614 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -43,7 +43,7 @@ use super::turn::{self, Actuator, Edited, Sent, history, last_wake}; use super::{DomainFacts, DomainSource, MouthReader, Organs, ReadFixture, ReadSource, Request, Through, TurnKind}; use crate::address::{Addressee, is_for, localpart}; use crate::chat_client::ChatPending; -use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, EXCHANGE_MINUTES, FactLine, FileStore, Hearer, HeartbeatView, LineFacts, Speaker, WakeCause, addressed_by_member, floor_to, line_facts, wakes}; +use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, EXCHANGE_MINUTES, FactLine, FileStore, Hearer, HeartbeatView, LineFacts, Speaker, WakeCause, addressed_by_member, claimed, floor_to, line_facts, wakes}; use crate::tempo::{Standing, pick}; /// The most personas a simulation holds: the swarm. @@ -496,7 +496,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) last_heard: vec![], recent: past.recent, own_rooms: member.entry.own_rooms.clone(), - woken_for: won[at].iter().map(|line| lines[*line].delivery(*line, &id, &lines).event_id).collect(), + woken_for: claimed(why.as_ref().map(|why| lines[why.line].delivery(why.line, &id, &lines).event_id).as_deref(), &won[at].iter().map(|line| lines[*line].delivery(*line, &id, &lines).event_id).collect::>()), last_outcome: past.last_outcome, last_wake: past.last_wake, records: past.records, diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 673ec42..73a82db 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -1171,3 +1171,18 @@ fn an_open_hello_wakes_one_persona_and_a_second_after_her_answer_wakes_no_extra_ let first = run["transcript"].as_array().unwrap().iter().find(|line| line["woke"] == "human").unwrap(); assert_eq!(first["from"], TOBIAH, "{first}"); } + +/// The simulator's packet reads what live reads: every line the wake was for is said to her, the floor's and the one that woke +/// her through her exchange alike (`heartbeat::claimed`, the one derivation, which live records as her handled keys). +#[test] +fn a_line_that_woke_her_is_said_to_her_in_the_packet_as_live_reads_it() { + let dir = tempfile::tempdir().unwrap(); + let path = bare_plan(dir.path(), 3, ""); + hello(&path, 0); + hello(&path, 2); + let (_, run) = run_plan(&path, &chatty()); + let round_two = run["turns"].as_array().unwrap().iter().find(|turn| turn["round"] == 2).expect("the second hello woke her"); + let stimulus = round_two["report"]["packet"]["stimulus"].as_str().unwrap(); + let said = stimulus.split("Said to ").nth(1).unwrap_or_default().split("Also in the room").next().unwrap_or_default(); + assert!(said.contains("hello everyone!"), "her exchange woke her; the line is said to her: {stimulus}"); +} diff --git a/crates/mind-body/src/testkit.rs b/crates/mind-body/src/testkit.rs index 11cb3b8..af5e261 100644 --- a/crates/mind-body/src/testkit.rs +++ b/crates/mind-body/src/testkit.rs @@ -56,6 +56,8 @@ pub(crate) struct Recording { /// One named instance whose unit never starts. pub(crate) fail_for: RefCell>, running: RefCell>, + /// A shared order of events: a start puts `start` here, so a store that logs into the same list shows what came first. + pub(crate) log: std::rc::Rc>>, } impl Recording { @@ -75,6 +77,7 @@ impl Launcher for Recording { if self.fail.get() || self.fail_for.borrow().as_ref() == Some(instance) { return Err(anyhow!("refused")); } + self.log.borrow_mut().push("start"); self.started.borrow_mut().push((instance.clone(), turn)); self.running.borrow_mut().push((instance.clone(), turn.slot())); Ok(()) diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 4bbfa9b..31b973d 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -169,7 +169,7 @@ mind_body::heartbeat: impl Store for FileStore mind_body::heartbeat: impl fmt :: Display for Outcome mind_body::heartbeat: impl fmt :: Display for PollTrace mind_body::heartbeat: pub trait Control { fn envelope (& self) -> SwarmEffective ; fn effective (& self , instance : & Slug) -> Effective ; } -mind_body::heartbeat: pub trait HeartbeatView { fn addressing (& self) -> Result < Option < Addressing > > ; fn written_at (& self) -> Option < DateTime < Utc > > { None } } +mind_body::heartbeat: pub trait HeartbeatView { fn addressing (& self) -> Result < Option < Addressing > > ; fn written_at (& self) -> Option < DateTime < Utc > > { None } fn woken_for (& self , _slug : & str) -> Result < Vec < String > > { Ok (Vec :: new ()) } } mind_body::heartbeat: pub trait Store { fn load (& self) -> Result < Option < HeartbeatState > > ; fn save (& self , state : & HeartbeatState) -> Result < () > ; fn record (& self , trace : & PollTrace) -> Result < () > ; fn load_addressing (& self) -> Result < Option < Addressing > > ; fn save_addressing (& self , addressing : & Addressing) -> Result < () > ; } mind_body::heartbeat: struct Addressing # [derive (Clone , Debug , Default , PartialEq , Eq , DatabaseEntry)] pub-fields[minds: Vec < Addressee >] mind_body::heartbeat: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[personas: Vec < PersonaId >, operators: Vec < String >, beat_s: u32]