From 6e4267359996b3a27252347d77f0112802c986f9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:55:05 +0100 Subject: [PATCH] persona drain: a failed room cannot hold answered rooms; two failures set a line aside; the put is stamped at the put; keys without the clock Her trace records now carry the room and the event ids the turn held. A line a turn that did not fail held is decided and wakes no one again; a line two failed turns held is acked past with one set_aside record, told to her next turn. A turn decided is the turn that did not fail, so a trace that cannot be written no longer makes her answer again; the mouth's ack follows the turn. The put is stamped at the put and strictly later than the stored updatedAt (P5), and the fake store enforces P5 with stamps after the turn began. The turn key is the newest seq and her trace's length. The drain reads every page the heartbeat reads (read_pending, shared). Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/heartbeat.rs | 22 +-- crates/mind-body/src/persona.rs | 139 ++++++++++++----- crates/mind-body/src/persona/drain_tests.rs | 161 +++++++++++++++++++- 3 files changed, 271 insertions(+), 51 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index c64c126..4cb37d0 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -32,7 +32,7 @@ use eureka_pipeline::{OrgRepo, PipelineKind, RunTurn, Slug}; use huginn_mind::PipelineFacts; use crate::address::{Addressee, Name, is_for, project_names}; -use crate::chat_client::{Basis, Chat, ChatDelivery}; +use crate::chat_client::{Basis, Chat, ChatDelivery, ChatPending}; use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable}; use crate::launch::{Clock, Launcher}; use crate::queue::{MindPort, headers, in_force, of_kind}; @@ -572,19 +572,23 @@ pub(crate) fn pending_facts(pending: &[&ChatDelivery], her: &str, minds: &[Strin /// The mouth pages a pending answer, so fewer deliveries may come than wait. /// The heartbeat acks nothing: it asks again after the highest seq it has until /// the answer is empty. A mouth that never empties is cut off at `PENDING_PAGES`. -fn read_pending(chat: &dyn Chat) -> Result> { - let mut all: Vec = Vec::new(); - let mut after = 0; - for _ in 0..PENDING_PAGES { - let page = chat.pending(after)?.deliveries; - let Some(top) = page.iter().map(|delivery| delivery.seq).max() else { +/// The answer's first page is the one that carries the room tail, and every later page adds its deliveries to it. +pub(crate) fn read_pending(chat: &dyn Chat) -> Result { + let mut all = chat.pending(0)?; + let mut after = all.deliveries.iter().map(|delivery| delivery.seq).max().unwrap_or(0); + for _ in 1..PENDING_PAGES { + if after == 0 { + break; + } + let mut page = chat.pending(after)?; + let Some(top) = page.deliveries.iter().map(|delivery| delivery.seq).max() else { break; }; if top <= after { break; } after = top; - all.extend(page); + all.deliveries.append(&mut page.deliveries); } Ok(all) } @@ -665,7 +669,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { // Pending chat, read-only, for a released Mind. if row.released { match read_pending(seat.chat) { - Ok(deliveries) => row.pending = deliveries, + Ok(pending) => row.pending = pending.deliveries, Err(_) => { eventful = true; row.note = "chat: pending failed".into(); diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index ed1f32a..bd94560 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -2,13 +2,13 @@ //! `eureka-body:ruling:persona-turn-drains-deliveries`, map section 16.36.2). //! //! A start reads the instance brake and the swarm brake once. A held brake ends it `Dead` before anything else is -//! touched. A released one reads her persona state and her pending deliveries once, takes one turn in each room that +//! touched. A released one reads her persona state and every page of her pending deliveries (the depth the heartbeat reads) once, takes one turn in each room that //! holds a waking line (`heartbeat::wakes`, the one rule), oldest waking line first, at most `TURNS_PER_START` of them //! (a start the beat woke, with no waking line, takes one turn in the room of the newest pending line, else her first //! room), and acks after each turn. Each turn is `projection::take`, the simulator's turn: the Interpreter's decision through the //! mouth, the commit's application of her proposals, one put of her state, one record appended to her trace. //! -//! The put is `persona_put` under the `updatedAt` she was read at. A stale one (Self or Life put between) reads her +//! The put is `persona_put` under the `updatedAt` she was read at, stamped at the put and later than the stored one (P5). A stale one (Self or Life put between) reads her //! again, applies the same record again and puts once more; a second refusal is `put_refused` in the record and on //! stderr, and her lines have already gone out. The record is appended after the put, refused or not. //! @@ -16,12 +16,17 @@ //! record a decision (it failed, or was not taken); every line below it is acked, the ones that woke no one as ambient. //! A failed turn leaves its room's waking lines pending, so her next wake shows them again. The heartbeat never acks. //! +//! The trace is what bounds that. Each turn's record carries its `room` and the `held` event ids of the room's lines the +//! drain read for it. A line a turn that did not fail held is decided and wakes no one again, so a room stuck behind the ack +//! never has the answered rooms taken again; a line two failed turns held is set aside: one `set_aside` record, the line acked +//! past, and her next turn is told so (`outcome`). +//! //! What the module holds besides the drain is what a chat line is made of: her `Config`, who a sender is to her //! (`sender_role`), whom a message addresses (`addressees`, `addressing_of`), the framed `message` line, the tail of //! her rooms (`render_tail`) and the turn records' store (`FileTrace`). Items no start calls yet carry an //! `allow(dead_code)` that the first caller removes. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use std::path::PathBuf; @@ -35,7 +40,7 @@ use serde_json::{Value, json}; use crate::address::{Addressee, addresses, is_for, localpart}; use crate::chat_client::{Basis, Chat, ChatDelivery, TailLine}; use crate::control::{ControlSource, Effective, HeldReason, derive}; -use crate::heartbeat::{HeartbeatView, Speaker, own_rooms, pending_facts, wakes}; +use crate::heartbeat::{HeartbeatView, Speaker, own_rooms, pending_facts, read_pending, wakes}; use crate::projection::{DomainSource, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, history, own_addressee as heard_as, take}; /// The admitting agent's name on what her Persona admitted; `self_run::inbox` still reads her briefs by it. @@ -247,7 +252,7 @@ pub fn carry(control: &impl ControlSource, swarm: &impl ControlSource, } } -/// One turn's standing for the ack: the room it was in, whether she decided and it is in her trace, and whether the put +/// One turn's standing for the ack: the room it was in, whether she decided (the turn did not fail), and whether the put /// was refused twice. struct Turn { room: String, @@ -255,6 +260,32 @@ struct Turn { put_refused: bool, } +/// How many turns that held a waking line may fail before the line is set aside. +pub const STRIKES: usize = 2; + +/// A waking line: where it sits in the mouth's queue, and which room and event it is. +struct Waking<'a> { + seq: u64, + room: &'a str, + event: &'a str, +} + +/// The events her trace shows she is done with: every line a turn held that did not fail (`held`, the room's event ids +/// the drain read for it), and every line set aside (`set_aside`). +fn done_events(records: &[Value]) -> BTreeSet<&str> { + let mut done = BTreeSet::new(); + for record in records.iter().filter(|record| record.get("failed").is_none()) { + done.extend(record["held"].as_array().into_iter().flatten().filter_map(Value::as_str)); + done.extend(record["set_aside"].as_array().into_iter().flatten().filter_map(|aside| aside["event"].as_str())); + } + done +} + +/// How many of her turns that held `event` failed. +fn strikes(records: &[Value], event: &str) -> usize { + records.iter().filter(|record| record.get("failed").is_some() && record["held"].as_array().is_some_and(|held| held.iter().any(|id| id == event))).count() +} + fn drain(instance: &Slug, start: &Start) -> Outcome { let began = (start.clock)(); let began_ms = u64::try_from(began.timestamp_millis()).unwrap_or_default(); @@ -264,10 +295,15 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { Ok((state, _)) => state, Err(fault) => return failed("her persona state was not read", fault), }; - let pending = match start.chat.pending(0) { + // Every page of what is pending, as the heartbeat reads it: the wake rule and the ack must see the same queue. + let pending = match read_pending(&start.chat) { Ok(pending) => pending, Err(fault) => return failed("the mouth was not read", fault), }; + let trace = match start.trace.records() { + Ok(records) => records, + Err(fault) => return failed("her trace was not read", fault), + }; let mut deliveries: Vec<&ChatDelivery> = pending.deliveries.iter().collect(); deliveries.sort_by_key(|delivery| delivery.seq); // Her rooms and her addressee, as the heartbeat reads them: the rooms named for the repos she stewards (a failed read @@ -277,22 +313,38 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { 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); - let waking: Vec<(u64, &str)> = deliveries + let waking_all: Vec = deliveries .iter() .zip(&facts) .filter(|(delivery, facts)| wakes(&her, delivery, speaker(config, delivery), **facts).is_some()) - .map(|(delivery, _)| (delivery.seq, delivery.room_alias.as_str())) + .map(|(delivery, _)| Waking { seq: delivery.seq, room: delivery.room_alias.as_str(), event: delivery.event_id.as_str() }) .collect(); - // The rooms to take a turn in, oldest waking line first; a start with no waking line is the beat's. + let woken = !waking_all.is_empty(); + // A line her trace shows decided is not waking again, whatever else in the queue is still stuck; one whose turns failed + // twice is set aside, acked past with no third turn. + let done = done_events(&trace); + let (aside, waking): (Vec, Vec) = waking_all.into_iter().filter(|line| !done.contains(line.event)).partition(|line| strikes(&trace, line.event) >= STRIKES); + // The key of every record and send of this start: the newest seq the mouth holds and how long her trace is, so no clock + // names a turn. A start that leaves neither changed re-sends its turns under the same ids, which the mouth answers as the + // sends they already were. + let stem = format!("s{}-n{}", deliveries.last().map_or(0, |delivery| delivery.seq), trace.len()); + if !aside.is_empty() { + let lines: Vec = aside.iter().map(|line| json!({ "room": line.room, "event": line.event })).collect(); + eprintln!("mind-persona: {} waking line(s) failed {STRIKES} turns and were set aside: {lines:?}", lines.len()); + if let Err(fault) = start.trace.record(&format!("{stem}-a"), &json!({ "set_aside": lines, "at": began.to_rfc3339() })) { + eprintln!("mind-persona: the record of the lines set aside was not appended: {fault:#}"); + } + } + // The rooms to take a turn in, oldest waking line first; a start no line woke is the beat's. let mut rooms: Vec<&str> = Vec::new(); - for (_, room) in &waking { - if !rooms.contains(room) { - rooms.push(room); + for line in &waking { + if !rooms.contains(&line.room) { + rooms.push(line.room); } } rooms.truncate(TURNS_PER_START); - let kind = if rooms.is_empty() { TurnKind::Beat } else { TurnKind::Chat }; - if rooms.is_empty() { + let kind = if woken { TurnKind::Chat } else { TurnKind::Beat }; + if !woken { rooms.extend(deliveries.last().map(|delivery| delivery.room_alias.as_str()).or(config.rooms.first().map(String::as_str))); } // The newest event of each room her input held: a send is refused if another sender reached the room after it. @@ -308,8 +360,24 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { let organs = Organs { persona: None, chat: Some(&start.chat), addressing: start.addressing.as_deref(), model: Some(start.model.as_ref()), domain: start.domain.as_deref(), reads: start.reads.as_deref() }; let mut taken: Vec = Vec::new(); let mut acked: Option = None; + // The ack follows each turn's commit, so a start killed between turns does not replay a message she answered: through + // the highest seq below the first waking line whose room has no decision yet. A line set aside or already decided waits + // for no room. + let settle = |taken: &[Turn], acked: &mut Option| { + let blocked = waking.iter().find(|line| !taken.iter().any(|turn| turn.decided && turn.room == line.room)).map(|line| line.seq); + let through = deliveries.iter().map(|delivery| delivery.seq).filter(|seq| blocked.is_none_or(|limit| *seq < limit)).max().filter(|seq| acked.is_none_or(|held| *seq > held)); + if let Some(seq) = through { + match start.chat.ack(seq) { + Ok(()) => *acked = Some(seq), + Err(fault) => eprintln!("mind-persona: the ack through {seq} failed: {fault:#}"), + } + } + }; + if rooms.is_empty() { + settle(&taken, &mut acked); + } for (index, room) in rooms.iter().enumerate() { - let key = format!("{began_ms}-t{index}"); + let key = format!("{stem}-t{index}"); let now = (start.clock)(); let past = match start.trace.records() { Ok(records) => history(&records), @@ -336,9 +404,12 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { records: past.records, }; let mut turn = take(&organs, &request, &mouth, &key, now); + // What the turn held, for the starts after it to read: which lines she has decided, and which she has failed on. + turn.record["room"] = json!(room); + turn.record["held"] = json!(deliveries.iter().filter(|delivery| delivery.room_alias == **room).map(|delivery| delivery.event_id.as_str()).collect::>()); let mut put_refused = false; if turn.record.get("failed").is_none() && turn.state != state { - match put_applied(start.persona.as_ref(), &state, &turn, &key, now) { + match put_applied(start.persona.as_ref(), &state, &turn, &key, now, start.clock.as_ref()) { Ok(landed) => state = landed, Err((fresh, why)) => { put_refused = true; @@ -348,21 +419,13 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { } } } - let recorded = start.trace.record(&key, &turn.record); - if let Err(fault) = &recorded { + // Her lines went out when the record says so, whether or not the trace could keep it: the decision is the turn's and + // the ack follows it. A trace that cannot be written loses her memory of the turn, never the answer to her line. + if let Err(fault) = start.trace.record(&key, &turn.record) { eprintln!("mind-persona: the record of turn {key} was not appended: {fault:#}"); } - taken.push(Turn { room: (*room).to_owned(), decided: turn.record.get("failed").is_none() && recorded.is_ok(), put_refused }); - // The ack follows each turn's commit, so a start killed between turns does not replay a message she answered: through - // the highest seq below the first waking line whose room has no decision yet. - let blocked = waking.iter().find(|(_, room)| !taken.iter().any(|turn| turn.decided && turn.room == *room)).map(|(seq, _)| *seq); - let through = deliveries.iter().map(|delivery| delivery.seq).filter(|seq| blocked.is_none_or(|limit| *seq < limit)).max().filter(|seq| acked.is_none_or(|held| *seq > held)); - if let Some(seq) = through { - match start.chat.ack(seq) { - Ok(()) => acked = Some(seq), - Err(fault) => eprintln!("mind-persona: the ack through {seq} failed: {fault:#}"), - } - } + taken.push(Turn { room: (*room).to_owned(), decided: turn.record.get("failed").is_none(), put_refused }); + settle(&taken, &mut acked); } Outcome::Drained { turns: taken.len(), acked_through: acked, put_refused: taken.iter().filter(|turn| turn.put_refused).count() } } @@ -394,15 +457,23 @@ fn speaker(config: &Config, delivery: &ChatDelivery) -> Speaker { } } +/// The `updatedAt` a put carries: the time of the put, and strictly later than the one stored, which the daemon requires +/// (P5). A write by Self or Life during her turn is stamped after the turn began, so the turn's own start time would be +/// refused. +fn stamp_after(now: DateTime, stored: Option<&str>) -> String { + let floor = stored.and_then(|text| DateTime::parse_from_rfc3339(text).ok()).map(|at| at.with_timezone(&Utc) + chrono::Duration::milliseconds(1)); + floor.map_or(now, |floor| now.max(floor)).to_rfc3339() +} + /// `turn`'s state put under the `updatedAt` she was read at (`read`, the state the turn began from). A stale put reads /// her again, applies the same record to the state as it stands and puts once more. The state as stored is the answer; /// when the second put is refused too, the state as it then stands, and why. -fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str, now: DateTime) -> std::result::Result { - let stamped = |mut state: Value| { - state["updatedAt"] = json!(now.to_rfc3339()); +fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str, now: DateTime, clock: &dyn Fn() -> DateTime) -> std::result::Result { + let stamped = |mut state: Value, stored: &Value| { + state["updatedAt"] = json!(stamp_after(clock(), stored.get("updatedAt").and_then(Value::as_str))); state }; - let next = stamped(turn.state.clone()); + let next = stamped(turn.state.clone(), read); match store.put(&next, read.get("updatedAt").and_then(Value::as_str), key) { Ok(Put::Committed) => return Ok(next), Ok(Put::Stale) => {} @@ -411,7 +482,7 @@ fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str, } let (fresh, _) = store.persona().map_err(|fault| (read.clone(), format!("her state was not read again: {fault:#}")))?; let (applied, _) = apply_commit(&fresh, &turn.record, key, now); - let next = stamped(applied); + let next = stamped(applied, &fresh); match store.put(&next, fresh.get("updatedAt").and_then(Value::as_str), key) { Ok(Put::Committed) => Ok(next), Ok(Put::Stale) => Err((fresh, "stale again".to_owned())), diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 84be314..10c8ec1 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -54,13 +54,14 @@ struct FakeMouth { sent: RefCell>, acks: RefCell>, reads: Cell, + ack_fails: Cell, log: Log, } impl Chat for Rc { - fn pending(&self, _: u64) -> Result { + fn pending(&self, after: u64) -> Result { self.reads.set(self.reads.get() + 1); - Ok(ChatPending { persona: "eureka".into(), deliveries: self.held.borrow().clone(), tail: Some(vec![]), tail_gaps: vec![] }) + Ok(ChatPending { persona: "eureka".into(), deliveries: self.held.borrow().iter().filter(|delivery| delivery.seq > after).cloned().collect(), tail: Some(vec![]), tail_gaps: vec![] }) } fn send(&self, request: &ChatSendRequest) -> Result { self.sent.borrow_mut().push(request.clone()); @@ -74,6 +75,9 @@ impl Chat for Rc { bail!("a drain fetches nothing") } fn ack(&self, through_seq: u64) -> Result<()> { + if self.ack_fails.get() { + bail!("the mouth is unreachable"); + } self.log.borrow_mut().push("ack".into()); self.acks.borrow_mut().push(through_seq); self.held.borrow_mut().retain(|delivery| delivery.seq > through_seq); @@ -84,8 +88,10 @@ impl Chat for Rc { } } -/// Her persona document as the mind holds it: a put under the stored `updatedAt` commits, any other is stale. `outside` -/// is Self or Life's put landing between her read and her put: it edits the stored document once per put, as long as it lasts. +/// Her persona document as the mind holds it: a put under the stored `updatedAt` commits, any other is stale, and one not +/// stamped later than the stored `updatedAt` is refused (the daemon's P5). `outside` is Self or Life's put landing between +/// her read and her put, stamped 2.5 s after the rig's start (after her turn began, before she puts, as a real one is): it +/// edits the stored document once per put, as long as it lasts. struct FakeStore { stored: RefCell, puts: RefCell>, @@ -106,11 +112,15 @@ impl PersonaStore for Rc { self.outside.set(self.outside.get() - 1); let mut stored = self.stored.borrow_mut(); stored["outside"] = json!("kept"); - stored["updatedAt"] = json!(format!("2026-11-26T00:0{}:00Z", self.puts.borrow().len() + self.outside.get())); + stored["updatedAt"] = json!((Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap() + 2500 + i64::try_from(self.puts.borrow().len() + self.outside.get()).unwrap()).unwrap()).to_rfc3339()); } if self.stored.borrow().get("updatedAt").and_then(Value::as_str) != expected_updated_at { return Ok(Put::Stale); } + let stamp = |value: &Value| value.get("updatedAt").and_then(Value::as_str).and_then(|text| chrono::DateTime::parse_from_rfc3339(text).ok()); + if stamp(&self.stored.borrow()).is_some_and(|stored| stamp(state).is_none_or(|put| put <= stored)) { + return Ok(Put::Refused("updatedAt must be later than the stored one".into())); + } *self.stored.borrow_mut() = state.clone(); self.puts.borrow_mut().push(state.clone()); Ok(Put::Committed) @@ -119,11 +129,16 @@ impl PersonaStore for Rc { struct MemTrace { rows: RefCell>, + /// The trace cannot be written (the state directory is full). + fail: Cell, log: Log, } impl Trace for Rc { fn record(&self, key: &str, record: &Value) -> Result<()> { + if self.fail.get() { + bail!("no space left on device"); + } self.log.borrow_mut().push("trace".into()); self.rows.borrow_mut().push((key.to_owned(), record.clone())); Ok(()) @@ -173,9 +188,9 @@ impl Rig { let dir = TempDir::new().unwrap(); ControlWriter::open(dir.path().join("control.cc")).unwrap().set_brake(true, at(0), "op").unwrap(); SwarmWriter::open(dir.path().join("swarm.cc")).unwrap().set_brake(true, at(0), "op").unwrap(); - let mouth = Rc::new(FakeMouth { held: RefCell::new(deliveries), sent: RefCell::default(), acks: RefCell::default(), reads: Cell::new(0), log: log.clone() }); + let mouth = Rc::new(FakeMouth { held: RefCell::new(deliveries), sent: RefCell::default(), acks: RefCell::default(), reads: Cell::new(0), ack_fails: Cell::new(false), log: log.clone() }); let store = Rc::new(FakeStore { stored: RefCell::new(control()), puts: RefCell::default(), outside: Cell::new(0), log: log.clone() }); - let trace = Rc::new(MemTrace { rows: RefCell::default(), log: log.clone() }); + let trace = Rc::new(MemTrace { rows: RefCell::default(), fail: Cell::new(false), log: log.clone() }); Self { mouth, store, trace, log, dir } } @@ -266,7 +281,7 @@ fn t_l2_65_mentions_do_not_storm() { let lines = (1..=65).map(|seq| line(seq, &room(seq % 3), META, &format!("are you there {seq}"))).collect(); let rig = Rig::new(lines); assert_eq!(rig.run(scripted(false)), Outcome::Drained { turns: 3, acked_through: Some(65), put_refused: 0 }); - assert_eq!(rig.mouth.reads.get(), 4, "the drain read pending once, and each of its three turns read the room"); + assert_eq!(rig.mouth.reads.get(), 5, "the drain read pending to its empty second page, and each of its three turns read the room"); assert!(Chat::pending(&rig.mouth, 0).unwrap().deliveries.is_empty(), "a poll after the start finds nothing pending"); } @@ -277,6 +292,8 @@ fn t_l2_stale_put_reapplies_once() { assert_eq!(rig.run(scripted(true)), Outcome::Drained { turns: 1, acked_through: Some(1), put_refused: 0 }); let stored = rig.store.stored.borrow(); assert_eq!(stored["outside"], "kept", "the outside value survives"); + let landed = chrono::DateTime::parse_from_rfc3339(stored["updatedAt"].as_str().unwrap()).unwrap(); + assert!(landed.timestamp_millis() > i64::try_from(BASE_MS).unwrap() + 2500, "her put is stamped at the put, later than the outside write it merged over: {landed}"); let notes = stored["thoughtMemory"]["shortTerm"].as_array().unwrap(); assert!(notes.iter().any(|note| note["summary"].as_str().is_some_and(|text| text.contains("glad to hear from Meta"))), "the same record is applied again to the fresh state: {notes:?}"); assert_eq!(rig.log().iter().filter(|event| *event == "put").count(), 2, "one stale put, one retry"); @@ -334,3 +351,131 @@ fn t_l2_trace_print() { assert_eq!(std::fs::read(dir.path().join("persona-trace.cc")).unwrap(), before, "printing writes nothing"); assert_eq!(trace_lines(&trace, 10).unwrap().len(), 3); } + +/// A model that keeps every prompt it is asked. +struct Spy { + inner: Scripted, + prompts: Rc>>, +} + +impl Model for Spy { + fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { + self.prompts.borrow_mut().push(prompt.to_owned()); + self.inner.ask(request_id, model, prompt, schema) + } +} + +fn sends_to(rig: &Rig, room: &str) -> usize { + rig.mouth.sent.borrow().iter().filter(|request| request.room_alias == room).count() +} + +/// Soul's probe: one room whose turn fails every time must not hold the ack below lines she already answered in another room. +#[test] +fn t_l2_a_poison_room_does_not_take_the_answered_rooms_again_and_is_set_aside_after_two_failures() { + let rig = Rig::new(vec![line(1, &room(1), META, "alpha is fine"), line(2, &room(2), META, "FAILME bravo"), line(3, &room(1), META, "alpha again")]); + let failing = || Flaky { inner: scripted(false), marker: "FAILME" }; + rig.run(failing()); + assert_eq!(rig.held_seqs(), [2, 3], "start 1: room 1 answered, room 2 failed once"); + rig.run(failing()); + assert_eq!(sends_to(&rig, &room(1)), 1, "start 2 took room 2 only: the answered room's line 3 is decided, not waking"); + assert_eq!(rig.held_seqs(), [2, 3]); + let outcome = rig.run(failing()); + assert_eq!(outcome, Outcome::Drained { turns: 0, acked_through: Some(3), put_refused: 0 }, "start 3 takes no third turn on the line: it is set aside and acked past"); + assert_eq!(sends_to(&rig, &room(1)), 1, "room 1 was never taken again"); + assert!(rig.held_seqs().is_empty(), "the other rooms stop re-waking"); + let rows = rig.trace.rows.borrow(); + assert_eq!(rows.iter().filter(|(_, record)| record.get("failed").is_some()).count(), 2, "exactly two failed turns, never a third"); + let (_, aside) = rows.last().unwrap(); + assert_eq!(aside["set_aside"], json!([{ "room": room(2), "event": "$e2" }]), "the line set aside is in her trace: {aside}"); +} + +/// The line is not dropped silently: her next turn is told, in the outcome's own words, that it failed and was set aside. +#[test] +fn t_l2_she_is_told_the_next_wake_that_her_turn_on_the_line_failed_and_it_was_set_aside() { + let rig = Rig::new(vec![line(1, &room(2), META, "FAILME bravo")]); + for _ in 0..3 { + rig.run(Flaky { inner: scripted(false), marker: "FAILME" }); + } + assert!(rig.held_seqs().is_empty()); + rig.mouth.held.borrow_mut().push(line(2, &room(1), META, "hello again")); + let prompts = Rc::new(RefCell::new(Vec::new())); + rig.run(Spy { inner: scripted(false), prompts: prompts.clone() }); + let told = prompts.borrow().iter().any(|prompt| prompt.contains("failed twice, so the line was set aside")); + assert!(told, "her next wake says so: {:?}", prompts.borrow()); +} + +/// Her lines went out; the trace could not keep the record. The ack is the decision, and the line is not answered again. +#[test] +fn t_l2_a_trace_that_cannot_be_written_does_not_make_her_answer_the_line_again() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.trace.fail.set(true); + assert_eq!(rig.run(scripted(false)), Outcome::Drained { turns: 1, acked_through: Some(1), put_refused: 0 }); + assert_eq!(sends_to(&rig, &room(1)), 1); + assert!(rig.held_seqs().is_empty(), "the line is acked: the next start has nothing to answer"); +} + +#[test] +fn t_l2_a_refused_put_is_told_the_next_wake() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.store.outside.set(2); + assert_eq!(rig.run(scripted(true)), Outcome::Drained { turns: 1, acked_through: Some(1), put_refused: 1 }); + rig.mouth.held.borrow_mut().push(line(2, &room(1), META, "and again")); + let prompts = Rc::new(RefCell::new(Vec::new())); + rig.run(Spy { inner: scripted(false), prompts: prompts.clone() }); + let told = prompts.borrow().iter().any(|prompt| prompt.contains("meant to keep from that turn was not kept")); + assert!(told, "her next wake says her notes did not land: {:?}", prompts.borrow()); +} + +#[test] +fn t_l2_each_rooms_send_basis_is_its_newest_event() { + let rig = Rig::new(vec![line(1, &room(1), META, "first"), line(2, &room(2), META, "elsewhere"), line(3, &room(1), META, "second")]); + rig.run(scripted(false)); + let sent = rig.mouth.sent.borrow(); + let basis = |room: &str| sent.iter().find(|request| request.room_alias == room).and_then(|request| request.basis.as_ref()).and_then(|basis| basis.seen_event_id.clone()); + assert_eq!(basis(&room(1)).as_deref(), Some("$e3"), "the newest line of the room, not its first"); + assert_eq!(basis(&room(2)).as_deref(), Some("$e2"), "never another room's event"); +} + +#[test] +fn t_l2_a_beat_start_speaks_in_the_room_of_the_newest_pending_line() { + let ops = "#ops:gamecult.org"; + let rig = Rig::new(vec![line(1, MINDS, LIBBY, "the deploy went fine"), line(2, ops, LIBBY, "lunch anyone")]); + assert_eq!(rig.run(scripted(false)), Outcome::Drained { turns: 1, acked_through: Some(2), put_refused: 0 }); + let rooms: Vec = rig.mouth.sent.borrow().iter().map(|request| request.room_alias.clone()).collect(); + assert_eq!(rooms, [ops], "the beat's one turn is in the newest pending line's room"); +} + +#[test] +fn t_l2_a_turn_that_changed_nothing_puts_nothing_and_one_that_did_puts_once() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.run(scripted(false)); + assert!(rig.store.puts.borrow().is_empty() && !rig.log().contains(&"put".to_owned()), "no put for an unchanged state: {:?}", rig.log()); + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.run(scripted(true)); + assert_eq!(rig.store.puts.borrow().len(), 1); +} + +#[test] +fn t_l2_an_ack_goes_through_a_seq_once_and_a_failed_ack_is_not_reported_as_acked() { + let rig = Rig::new(vec![line(1, &room(1), META, "alpha is fine"), line(2, &room(2), META, "FAILME bravo")]); + rig.run(Flaky { inner: scripted(false), marker: "FAILME" }); + assert_eq!(*rig.mouth.acks.borrow(), [1], "the failed turn's settling does not ack through 1 a second time"); + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.mouth.ack_fails.set(true); + assert_eq!(rig.run(scripted(false)), Outcome::Drained { turns: 1, acked_through: None, put_refused: 0 }, "the ack did not happen, and the outcome says so"); + assert_eq!(rig.held_seqs(), [1]); +} + +/// Every turn of a start is its own key, and a start that finds her trace longer is under other keys: no wall clock names one. +#[test] +fn t_l2_a_turn_key_comes_from_the_mouth_and_her_trace_not_the_clock() { + let rig = Rig::new(vec![line(7, &room(1), META, "alpha"), line(9, &room(2), META, "bravo")]); + rig.run(scripted(false)); + let first: Vec = rig.trace.rows.borrow().iter().map(|(key, _)| key.clone()).collect(); + assert_eq!(first, ["s9-n0-t0", "s9-n0-t1"]); + rig.mouth.held.borrow_mut().push(line(9, &room(1), META, "again")); + rig.run(scripted(false)); + let keys: Vec = rig.trace.rows.borrow().iter().map(|(key, _)| key.clone()).collect(); + assert_eq!(keys.len(), 3); + assert_eq!(keys[2], "s9-n2-t0", "the same newest seq under a longer trace is another key"); +}