diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index e370f4e..df6dc6a 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -9,10 +9,14 @@ //! //! Her trace alone says whether a line is decided (`projection::decided`, the reader the heartbeat's poll uses too): a line is done when a //! completed wake held it, or it is set aside. The mouth's pending list and its ack cursor are transport and decide nothing; the ack is cleanup, -//! through the highest seq below the first waking line her trace does not yet hold decided. A failed wake acks nothing. +//! through the highest seq below the first line of a waking room that her trace does not yet hold decided. A wake holds the lines she was +//! shown: every line of the turn's room and, of the other waking rooms, those the Persona's page had room for (`Waked::elsewhere_shown`) and +//! her own, and what is no message (a notice, an edit), which nothing shows. A failed wake acks nothing. //! -//! A failed wake is in her trace and decides nothing; a failure that is no outage strikes the oldest line it was waking on, and a line two -//! such wakes held is set aside: one `set_aside` record, the line acked past, and her next wake is told so (`outcome`). The heartbeat never acks. +//! A failed wake is in her trace and decides nothing. The wake after one that failed for a reason that is no outage takes only the oldest +//! waking room. A failure that is no outage, in a wake over one room, strikes that room's oldest waking line; a line two such wakes held is set +//! aside: one `set_aside` record, the line acked past, and her next wake is told so (`outcome`). A wake over several rooms strikes nothing. +//! The heartbeat never acks. //! //! The put (`put_applied`) is the Interpreter's, when it attaches: under the `updatedAt` she was read at, stamped at the put and later than the stored one (P5). //! @@ -21,7 +25,7 @@ //! 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; @@ -33,7 +37,7 @@ use huginn_mind::{Faculty, HuginnMindResponse, MindRefusal, PersonaPutOutcome, P use serde_json::{Value, json}; use crate::address::{Addressee, addresses, is_for, localpart}; -use crate::chat_client::{Basis, Chat, ChatDelivery, TailLine}; +use crate::chat_client::{Basis, Chat, ChatDelivery, Form, TailLine}; use crate::control::{ControlSource, Effective, HeldReason, derive}; use crate::heartbeat::{HeartbeatView, Speaker, own_rooms, pending_facts, read_pending, wakes}; use crate::projection::{DomainSource, HuginnPersonaSource, Model, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, decided, history, wake, own_addressee as heard_as}; @@ -343,13 +347,18 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { .map(|(delivery, _)| Waking { seq: delivery.seq, room: delivery.room_alias.as_str(), event: delivery.event_id.as_str(), sender: if delivery.sender_display.is_empty() { delivery.sender.as_str() } else { delivery.sender_display.as_str() }, text: delivery.text.as_str() }) .collect(); let woken = !waking_all.is_empty(); - // A line her trace shows decided is not waking again, whatever else in the queue is still stuck. The oldest line of a - // room with two strikes is set aside and acked past, that line only: the room's later lines are tried without it. - let done = decided(&trace); // A line her trace shows decided is not waking again, whatever else in the queue is still stuck. The oldest waking line, once // it has two strikes, is set aside and acked past, that line only: the others are woken for without it. + let done = decided(&trace); let mut first = true; - let (aside, waking): (Vec, Vec) = waking_all.into_iter().filter(|line| !done.contains(line.event)).partition(|line| std::mem::take(&mut first) && strikes(&trace, line.event) >= STRIKES); + let (aside, due): (Vec, Vec) = waking_all.into_iter().filter(|line| !done.contains(line.event)).partition(|line| std::mem::take(&mut first) && strikes(&trace, line.event) >= STRIKES); + // The rooms of every line this start owes a wake or a set-aside: the ack never passes an undecided line of theirs, shown or not. + let watched: BTreeSet<&str> = aside.iter().chain(&due).map(|line| line.room).collect(); + // The wake after one that failed for a reason that is no outage takes only the oldest waking room: a failure the blend of rooms hid is + // found in one room alone, where it strikes that room's oldest line and no innocent room's. + let retreating = trace.iter().rev().find(|record| record.get("set_aside").is_none()).is_some_and(|record| record.get("failed").is_some() && record.get("outage").is_none()); + let oldest_room = due.first().map(|line| line.room); + let waking: Vec = due.into_iter().filter(|line| !retreating || Some(line.room) == oldest_room).collect(); // The key of this start's records in her trace: how long it is, so a record that landed is never written over. let stem = format!("n{}", trace.len()); // The waking rooms, oldest waking line first: the first is the wake's room and every other an arrival in it. A start no line woke is @@ -365,8 +374,8 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { rooms.extend(deliveries.last().map(|delivery| delivery.room_alias.as_str()).or(config.rooms.first().map(String::as_str))); } let mut acked: Option = None; - // The ack is cleanup behind her trace and decides nothing: through the highest seq below the first line this start was to answer or set - // aside that her trace does not yet hold as decided. A start killed before its wake record landed does not ack past a line it did not + // The ack is cleanup behind her trace and decides nothing: through the highest seq below the first undecided line of a room this start owes + // a wake or a set-aside (taken in this wake or not). A start killed before its wake record landed does not ack past a line it did not // answer, and a line whose record did not land is never acked past. let settle = |acked: &mut Option| { let records = match start.trace.records() { @@ -374,7 +383,7 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { Err(fault) => return eprintln!("mind-persona: her trace was not read, so nothing is acked: {fault:#}"), }; let done = decided(&records); - let blocked = aside.iter().chain(&waking).filter(|line| !done.contains(line.event)).map(|line| line.seq).min(); + let blocked = deliveries.iter().filter(|delivery| watched.contains(delivery.room_alias.as_str()) && !done.contains(delivery.event_id.as_str())).map(|delivery| delivery.seq).min(); 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) { @@ -435,10 +444,15 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { // completed, and the ids her projection selected. let key = waking.first().map_or_else(|| format!("b{began_ms}"), |line| format!("l{}", line.event)); let record_key = format!("{stem}-w"); - let held: Vec<&str> = deliveries.iter().filter(|delivery| rooms.contains(&delivery.room_alias.as_str())).map(|delivery| delivery.event_id.as_str()).collect(); + let held: Vec<&str> = deliveries + .iter() + .filter(|delivery| delivery.room_alias == rooms[0] || rooms.contains(&delivery.room_alias.as_str()) && (delivery.sender == config.own_sender || delivery.form != Form::Message || waked.elsewhere_shown.contains(&delivery.event_id))) + .map(|delivery| delivery.event_id.as_str()) + .collect(); let mut record = json!({ "key": record_key, "seq": records.len(), + "kind": kind, "room": rooms[0], "rooms": rooms, "held": held, @@ -451,18 +465,23 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { }); if let Some(fault) = &waked.failed { record["failed"] = json!(fault.reason); - // A failure that is no outage is a strike against the oldest line this wake was waking on, and no other. + // A failure that is no outage, in a wake over one room, is a strike against that room's oldest waking line and no other. A wake over + // several rooms cannot say which one failed it: it strikes nothing, and the next wake takes one room. if fault.outage { record["outage"] = json!(true); - } else if let Some(line) = waking.first() { + } else if rooms.len() == 1 + && let Some(line) = waking.first() + { record["strike"] = json!(line.event); } } // The Interpreter reads (narration, prose, the lines held) here and its deltas are put through `put_applied`; the agent's turn follows it // (map 16.38.2, items 5): neither is built yet, so a wake changes no state and posts nothing. // The record is durable before anything is acked, and a record that cannot be written acks nothing: the lines are woken for again. + // A failed wake acks nothing: the lines it was over are woken for again, in one room if it was a blend. match start.trace.record(&record_key, &record) { - Ok(()) => settle(&mut acked), + Ok(()) if waked.failed.is_none() => settle(&mut acked), + Ok(()) => {} Err(fault) => eprintln!("mind-persona: the record of wake {key} was not appended, so nothing is acked: {fault:#}"), } Outcome::Drained { wakes: 1, acked_through: acked } diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 964b9a2..274eab1 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -1,8 +1,7 @@ -//! The drain (map 16.36.2, cut L2): one start through fake organs, each recording into one shared log so the order of -//! put, trace append and ack can be read. +//! The drain (map 16.38.2): one start through fake organs. The mouth holds deliveries until they are acked and keeps what was acked; the +//! trace is a list the test reads; the model is recorded. use std::cell::{Cell, RefCell}; -use std::collections::BTreeMap; use std::rc::Rc; use anyhow::{Result, bail}; @@ -19,17 +18,18 @@ use crate::testkit::at; const META: &str = "@meta:gamecult.org"; const LIBBY: &str = "@libby:gamecult.org"; -const MINDS: &str = "#minds:gamecult.org"; const BASE_MS: u64 = 1_795_867_200_000; -type Log = Rc>>; - fn room(n: u64) -> String { format!("!dm-{n}:gamecult.org") } /// A line the mouth holds, the `seq`th: in a direct message from the operator unless `room` is a public one. fn line(seq: u64, room: &str, sender: &str, text: &str) -> ChatDelivery { + line_at(seq, room, sender, text, BASE_MS - 120_000 + seq * 1000) +} + +fn line_at(seq: u64, room: &str, sender: &str, text: &str, at_unix_ms: u64) -> ChatDelivery { ChatDelivery { seq, room_alias: room.into(), @@ -38,7 +38,7 @@ fn line(seq: u64, room: &str, sender: &str, text: &str) -> ChatDelivery { sender: sender.into(), sender_display: String::new(), text: text.into(), - at_unix_ms: BASE_MS - 120_000 + seq * 1000, + at_unix_ms, context: vec![], mentions: vec![], is_direct: room.starts_with('!'), @@ -49,70 +49,21 @@ fn line(seq: u64, room: &str, sender: &str, text: &str) -> ChatDelivery { } } -/// The mouth: it holds deliveries until they are acked, records its sends and acks, and counts reads. +/// The mouth: it holds deliveries until they are acked, and records its sends and acks. struct FakeMouth { held: RefCell>, sent: RefCell>, acks: RefCell>, - reads: Cell, ack_fails: Cell, - /// How many deliveries one page of `pending` holds. - page: Cell, - /// The room tail: every line she sent, as the mouth would show it. - tail: RefCell>, - /// The transactions the homeserver remembers, by id, and the event each made; `forgot` is its memory expiring. - txn: RefCell>, - forgot: Cell, - /// The rooms whose sends fail on the way, as a homeserver that is down does. - down: RefCell>, - /// The next send lands and its answer is lost on the way back. - answer_lost: Cell, - /// The mouth answers every resend `ResendUnknown`: it does not remember the id. - resend_unknown: Cell, - /// The mouth vouches only for a resend of an id it was sent before, as the real one does (it remembers what it reached the PUT with). - vouches_attempted: Cell, - /// Rooms where the homeserver is down before every PUT: the mouth answers `NotSent` for a send into them. - not_sent_rooms: RefCell>, - /// The mouth answers every send with this refusal. - refuse: Cell>, - /// Every id a send came under, retries and deduped ones included. - attempts: RefCell>, - log: Log, } impl Chat for Rc { fn pending(&self, after: u64) -> Result { - self.reads.set(self.reads.get() + 1); - Ok(ChatPending { persona: "eureka".into(), deliveries: self.held.borrow().iter().filter(|delivery| delivery.seq > after).take(self.page.get()).cloned().collect(), tail: Some(self.tail.borrow().clone()), 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 { - if self.not_sent_rooms.borrow().contains(&request.room_alias) { - return Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: None, refusal: Some(crate::chat_client::Refusal::NotSent), newer: vec![] }); - } - let attempted = self.attempts.borrow().contains(&request.request_id); - self.attempts.borrow_mut().push(request.request_id.clone()); - if let Some(refusal) = self.refuse.get() { - return Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: None, refusal: Some(refusal), newer: vec![] }); - } - if request.resend && (self.resend_unknown.get() || self.vouches_attempted.get() && !attempted) { - return Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: None, refusal: Some(crate::chat_client::Refusal::ResendUnknown), newer: vec![] }); - } - if self.down.borrow().contains(&request.room_alias) { - bail!("the homeserver did not answer"); - } - let remembered = self.txn.borrow().get(&request.request_id).cloned(); - if let Some(event) = remembered.filter(|_| !self.forgot.get()) { - return Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: Some(event), refusal: None, newer: vec![] }); - } self.sent.borrow_mut().push(request.clone()); - self.log.borrow_mut().push("send".into()); - let event = format!("$sent-{}", self.sent.borrow().len()); - self.tail.borrow_mut().push(crate::chat_client::TailLine { room: request.room_alias.clone(), event_id: event, at_unix_ms: BASE_MS + 500 * self.sent.borrow().len() as u64, sender: "@eureka:gamecult.org".into(), form: Form::Message, basis: None, body: request.text.clone(), reply_to: Default::default() }); - self.txn.borrow_mut().insert(request.request_id.clone(), format!("$sent-{}", self.sent.borrow().len())); - if self.answer_lost.replace(false) { - bail!("the answer did not come"); - } - Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: Some(format!("$sent-{}", self.sent.borrow().len())), refusal: None, newer: vec![] }) + Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: Some("$sent".into()), refusal: None, newer: vec![] }) } fn open_direct(&self, _: &ChatOpenDirectRequest) -> Result { bail!("a drain opens no conversation") @@ -124,7 +75,6 @@ impl Chat for Rc { 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); Ok(()) @@ -134,63 +84,32 @@ impl Chat for Rc { } } -/// 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>, - outside: Cell, - log: Log, -} +/// Her persona document as the mind holds it. A wake puts nothing yet. +struct FakeStore(Value); impl PersonaSource for Rc { fn persona(&self) -> Result<(Value, String)> { - Ok((self.stored.borrow().clone(), "receipt".into())) + Ok((self.0.clone(), "receipt".into())) } } impl PersonaStore for Rc { - fn put(&self, state: &Value, expected_updated_at: Option<&str>, _session: &str) -> Result { - self.log.borrow_mut().push("put".into()); - if self.outside.get() > 0 { - self.outside.set(self.outside.get() - 1); - let mut stored = self.stored.borrow_mut(); - stored["outside"] = json!("kept"); - 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) + fn put(&self, _: &Value, _: Option<&str>, _: &str) -> Result { + bail!("a wake puts nothing yet") } } struct MemTrace { rows: RefCell>, - /// The one record key that cannot be written, as a file that is gone read-only would be. - fail_key: RefCell>, /// The trace cannot be written (the state directory is full). fail: Cell, - /// How many more writes land before the trace stops taking them. - allow: Cell, - log: Log, } impl Trace for Rc { fn record(&self, key: &str, record: &Value) -> Result<()> { - if self.fail.get() || self.allow.get() == 0 || self.fail_key.borrow().as_deref() == Some(key) { + if self.fail.get() { bail!("no space left on device"); } - self.allow.set(self.allow.get() - 1); - self.log.borrow_mut().push("trace".into()); let mut rows = self.rows.borrow_mut(); match rows.iter_mut().find(|(held, _)| held == key) { Some(row) => row.1 = record.clone(), @@ -227,82 +146,16 @@ impl Model for Flaky { } } -/// 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()) - } +/// A model that fails the calls whose prompt carries `marker`. +fn poisoned(marker: &'static str, reason: &'static str) -> Flaky { + Flaky { inner: Scripted::new(|_| "He thinks of them.".into()), marker, reason } } -struct Rig { - mouth: Rc, - store: Rc, - trace: Rc, - log: Log, - dir: TempDir, - /// The clock's ticks, kept across starts as a real clock is. - ticks: Rc>, +/// A model that fails every call: the line's own failure (`REFUSED`) or the body's (`OUTAGE`). +fn failing(reason: &'static str) -> Flaky { + poisoned("", reason) } -impl Rig { - fn new(deliveries: Vec) -> Self { - let log = Log::default(); - 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), down: RefCell::default(), sent: RefCell::default(), acks: RefCell::default(), reads: Cell::new(0), ack_fails: Cell::new(false), page: Cell::new(usize::MAX), tail: RefCell::default(), txn: RefCell::default(), forgot: Cell::new(false), answer_lost: Cell::new(false), resend_unknown: Cell::new(false), vouches_attempted: Cell::new(false), refuse: Cell::new(None), attempts: RefCell::default(), not_sent_rooms: RefCell::default(), 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(), fail_key: RefCell::default(), fail: Cell::new(false), allow: Cell::new(usize::MAX), log: log.clone() }); - Self { mouth, store, trace, log, dir, ticks: Rc::default() } - } - - 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 { - config: Config { rooms: vec![MINDS.into()], operators: vec![META.into()], minds: vec!["@eureka:gamecult.org".into(), LIBBY.into()], own_sender: "@eureka:gamecult.org".into(), model: "test-model".into() }, - persona: Box::new(self.store.clone()), - chat: self.mouth.clone(), - trace: Box::new(self.trace.clone()), - addressing, - model: Box::new(model), - domain: None, - reads: None, - tuning: self.dir.path().join("persona-tuning.toml"), - clock: Box::new(move || { - ticks.set(ticks.get() + 1); - Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap() + Duration::seconds(ticks.get()) - }), - }) - }; - carry(&FileSource::new(self.dir.path().join("control.cc")), &FileSource::new(self.dir.path().join("swarm.cc")), &Slug("eureka".into()), start) - } - - fn log(&self) -> Vec { - self.log.borrow().clone() - } - - fn held_seqs(&self) -> Vec { - self.mouth.held.borrow().iter().map(|delivery| delivery.seq).collect() - } -} - - /// A recorded model that keeps every prompt: the Projector narrates a fixed line and the Persona answers in her inner voice. #[derive(Clone, Default)] struct Tally(Rc>>); @@ -315,16 +168,59 @@ impl Model for Tally { } } -/// A model that fails every call: the line's own failure (`REFUSED`) or the body's (`OUTAGE`). -fn failing(reason: &'static str) -> Flaky { - Flaky { inner: Scripted::new(|_| String::new()), marker: "", reason } +struct Rig { + mouth: Rc, + trace: Rc, + store: Rc, + dir: TempDir, + /// The clock's ticks, kept across starts as a real clock is. + ticks: Rc>, } -const ANN: &str = "@ann:gamecult.org"; -const BO: &str = "@bo:gamecult.org"; +impl Rig { + fn new(deliveries: Vec) -> Self { + 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(), ack_fails: Cell::new(false) }); + let trace = Rc::new(MemTrace { rows: RefCell::default(), fail: Cell::new(false) }); + Self { mouth, trace, store: Rc::new(FakeStore(control())), dir, ticks: Rc::default() } + } + fn run(&self, model: impl Model + 'static) -> Outcome { + let ticks = self.ticks.clone(); + let start = || { + Ok(Start { + config: Config { rooms: vec!["#minds:gamecult.org".into()], operators: vec![META.into()], minds: vec!["@eureka:gamecult.org".into(), LIBBY.into()], own_sender: "@eureka:gamecult.org".into(), model: "test-model".into() }, + persona: Box::new(self.store.clone()), + chat: self.mouth.clone(), + trace: Box::new(self.trace.clone()), + addressing: None, + model: Box::new(model), + domain: None, + reads: None, + tuning: self.dir.path().join("persona-tuning.toml"), + clock: Box::new(move || { + ticks.set(ticks.get() + 1); + Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap() + Duration::seconds(ticks.get()) + }), + }) + }; + carry(&FileSource::new(self.dir.path().join("control.cc")), &FileSource::new(self.dir.path().join("swarm.cc")), &Slug("eureka".into()), start) + } + + fn records(&self) -> Vec { + self.trace.rows.borrow().iter().map(|(_, record)| record.clone()).collect() + } + + fn acks(&self) -> Vec { + self.mouth.acks.borrow().clone() + } +} + +/// Three direct messages from the operator: every line wakes her, in three rooms. fn three_rooms() -> Rig { - Rig::new(vec![line(1, &room(1), META, "morning, are you there"), line(2, &room(2), ANN, "evening, a question for you"), line(3, &room(3), BO, "night, one more thing")]) + Rig::new(vec![line(1, &room(1), META, "morning, are you there"), line(2, &room(2), META, "evening, a question for you"), line(3, &room(3), META, "night, one more thing")]) } #[test] @@ -335,9 +231,9 @@ fn t_p1_one_projector_one_persona() { let prompts = tally.0.borrow(); assert_eq!(prompts.len(), 2, "a wake with waking lines in three rooms makes exactly two model calls"); assert!(prompts[0].starts_with("You are a private Projector.")); - let rows = rig.trace.rows.borrow(); - assert_eq!(rows.len(), 1, "one wake record"); - assert_eq!((rows[0].1["status"].as_str(), rows[0].1["held"].clone()), (Some("completed"), json!(["$e1", "$e2", "$e3"]))); + let records = rig.records(); + assert_eq!(records.len(), 1, "one wake record"); + assert_eq!((records[0]["status"].as_str(), records[0]["kind"].as_str(), records[0]["held"].clone()), (Some("completed"), Some("chat"), json!(["$e1", "$e2", "$e3"]))); assert!(rig.mouth.sent.borrow().is_empty(), "nothing is posted until the agent is wired"); } @@ -364,16 +260,42 @@ fn t_p1_no_drafts_in_prompt() { assert!(tally.0.borrow().iter().all(|prompt| !prompt.contains("typed>")), "no draft markup and no speech form reaches either call"); } +/// A wake over several rooms that fails cannot say which room failed it: no strike, no ack, and the next wake takes the oldest waking room only. #[test] -fn t_p1_ack_after_completed_wake() { +fn t_p1_a_failed_blended_wake_strikes_nothing_and_acks_nothing() { let rig = three_rooms(); assert_eq!(rig.run(failing(REFUSED)), Outcome::Drained { wakes: 1, acked_through: None }, "a failed wake acks nothing"); - assert!(rig.mouth.acks.borrow().is_empty()); - let rows = rig.trace.rows.borrow(); - assert_eq!((rows[0].1["status"].as_str(), rows[0].1["strike"].as_str()), (Some("failed"), Some("$e1")), "the strike is the oldest waking line's"); - drop(rows); - assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(3) }, "the next completed wake acks through the highest held seq"); - assert_eq!(*rig.mouth.acks.borrow(), [3]); + assert!(rig.acks().is_empty()); + let records = rig.records(); + assert_eq!(records[0]["status"], "failed"); + assert!(records[0].get("strike").is_none(), "{:?}", records[0]); + let tally = Tally::default(); + assert_eq!(rig.run(tally.clone()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "the next wake takes room 1 alone, and acks through its lines"); + let prompts = tally.0.borrow(); + assert!(prompts[1].contains("morning, are you there") && !prompts[1].contains("evening, a question") && !prompts[1].contains("night, one more"), "{}", prompts[1]); + assert_eq!(rig.records()[1]["rooms"], json!([room(1)])); + assert_eq!(rig.records()[1]["held"], json!(["$e1"]), "the rooms it did not take are not held"); + drop(prompts); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(3) }, "the rooms after it, when it did not fail, are blended again"); +} + +/// Self's rule: a poison line in room B with an innocent older line in room A. The blend fails and strikes nothing; then A is taken alone and +/// completes; B alone fails twice and is set aside. A is never set aside. +#[test] +fn t_p1_a_poison_line_in_one_room_never_sets_an_innocent_room_aside() { + let rig = Rig::new(vec![line(1, &room(1), META, "an ordinary hello"), line(2, &room(2), META, "POISON arrives")]); + let model = || poisoned("POISON", REFUSED); + assert_eq!(rig.run(model()), Outcome::Drained { wakes: 1, acked_through: None }, "the blend fails"); + assert_eq!(rig.run(model()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "room A alone completes, and is acked; room B's line is not"); + assert_eq!(rig.run(model()), Outcome::Drained { wakes: 1, acked_through: None }, "room B alone fails: the first strike"); + assert_eq!(rig.run(model()), Outcome::Drained { wakes: 1, acked_through: None }, "the second strike"); + assert_eq!(rig.run(model()), Outcome::Drained { wakes: 0, acked_through: Some(2) }, "the poison line is set aside and acked past"); + let records = rig.records(); + let strikes: Vec<&Value> = records.iter().filter_map(|record| record.get("strike")).collect(); + assert_eq!(strikes, [&json!("$e2"), &json!("$e2")], "{records:?}"); + let aside: Vec<&Value> = records.iter().flat_map(|record| record["set_aside"].as_array().into_iter().flatten()).map(|line| &line["event"]).collect(); + assert_eq!(aside, [&json!("$e2")], "only the poison line is set aside"); + assert_eq!(rig.acks(), [1, 2]); } #[test] @@ -381,9 +303,21 @@ fn t_p1_strike_then_set_aside() { let rig = Rig::new(vec![line(1, &room(1), META, "a line the model refuses")]); rig.run(failing(REFUSED)); rig.run(failing(REFUSED)); - assert!(rig.mouth.acks.borrow().is_empty(), "two failed wakes ack nothing"); + assert!(rig.acks().is_empty(), "two failed wakes ack nothing"); + assert_eq!(rig.records().iter().map(|record| record["strike"].clone()).collect::>(), [json!("$e1"), json!("$e1")], "a failure in a wake over one room strikes its oldest line"); assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 0, acked_through: Some(1) }, "the third start sets the line aside and acks past it, with no wake"); - assert!(rig.trace.rows.borrow().iter().any(|(_, record)| record["set_aside"][0]["event"] == "$e1")); + assert!(rig.records().iter().any(|record| record["set_aside"][0]["event"] == "$e1")); +} + +/// A line set aside is acked past before the wake, so the wake reads its room without it: the later line of the room is answered in the same start. +#[test] +fn t_p1_a_set_aside_line_is_acked_before_the_wake_reads_the_room() { + let rig = Rig::new(vec![line(1, &room(1), META, "POISON in the first line"), line(2, &room(1), META, "a fine second line")]); + rig.run(poisoned("POISON", REFUSED)); + rig.run(poisoned("POISON", REFUSED)); + assert_eq!(rig.run(poisoned("POISON", REFUSED)), Outcome::Drained { wakes: 1, acked_through: Some(2) }); + assert_eq!(rig.acks(), [1, 2], "past the set-aside line first, then the wake's"); + assert_eq!(rig.records().last().unwrap()["status"], "completed"); } #[test] @@ -391,5 +325,88 @@ fn t_p1_an_outage_charges_no_strike() { let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); rig.run(failing(OUTAGE)); rig.run(failing(OUTAGE)); + let records = rig.records(); + assert!(records.iter().all(|record| record["outage"] == true && record.get("strike").is_none()), "{records:?}"); assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "the body's failures never set a line aside"); } + +/// A failed wake acks nothing, not even the lines of rooms nobody is waiting in that sit below the line it was waking on. +#[test] +fn t_p1_a_failed_wake_acks_no_line_below_the_waking_one() { + let rig = Rig::new(vec![line(1, "#minds:gamecult.org", LIBBY, "status: green"), line(2, &room(1), META, "a line the model refuses")]); + assert_eq!(rig.run(failing(REFUSED)), Outcome::Drained { wakes: 1, acked_through: None }); + assert!(rig.acks().is_empty()); +} + +/// A line her trace holds decided is not woken for again though the mouth still holds it (the ack failed): the next start only acks. +#[test] +fn t_p1_a_decided_line_is_not_woken_for_again() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello"), line(2, &room(2), META, "and hello")]); + rig.mouth.ack_fails.set(true); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: None }, "the wake completed, its ack did not"); + rig.mouth.ack_fails.set(false); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 0, acked_through: Some(2) }, "no second wake for lines held by a completed one"); + assert_eq!(rig.records().len(), 1); +} + +/// Two lines in one room and one in another: the wake's rooms are the two, once each, oldest waking line first. +#[test] +fn t_p1_each_waking_room_is_named_once() { + let rig = Rig::new(vec![line(1, &room(1), META, "first"), line(2, &room(1), META, "second"), line(3, &room(2), META, "third")]); + rig.run(Tally::default()); + assert_eq!(rig.records()[0]["rooms"], json!([room(1), room(2)])); +} + +/// The record holds the lines of the wake's rooms, and no line of a room that did not wake her. +#[test] +fn t_p1_a_wake_holds_only_its_own_rooms_lines() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello"), line(2, "#minds:gamecult.org", LIBBY, "status: green")]); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(2) }, "the other room's line is cleaned up behind her"); + assert_eq!(rig.records()[0]["held"], json!(["$e1"])); +} + +/// A start no line woke is the beat's, and says so; a record it cannot write acks nothing. +#[test] +fn t_p1_a_start_no_line_woke_is_a_beat() { + let rig = Rig::new(vec![line(1, "#minds:gamecult.org", LIBBY, "status: green")]); + rig.trace.fail.set(true); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: None }, "the record did not land, so nothing is acked"); + assert!(rig.acks().is_empty()); + rig.trace.fail.set(false); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) }); + assert_eq!(rig.records()[0]["kind"], "beat"); +} + +/// What she was not shown is neither held nor acked: of a long room elsewhere, the oldest lines the page had no room for stay in the mouth, and +/// the start after this one wakes for them. +#[test] +fn t_p1_lines_the_page_had_no_room_for_are_not_held_or_acked() { + let mut lines = vec![line(1, &room(1), META, "the turn's room")]; + lines.extend((2..=61).map(|seq| line(seq, &room(2), META, &format!("line {seq} of a long talk elsewhere, said at some length so that the page fills")))); + let rig = Rig::new(lines); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "acked only below the oldest line she was not shown"); + let held: Vec = rig.records()[0]["held"].as_array().unwrap().iter().map(|event| event.as_str().unwrap().to_owned()).collect(); + assert!(held.contains(&"$e1".to_owned()) && held.contains(&"$e61".to_owned()), "{held:?}"); + assert!(!held.contains(&"$e2".to_owned()) && held.len() < 61, "the oldest of the long room were not shown, so not held: {held:?}"); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(61) }, "the lines left in the mouth wake her again, now in the turn's room"); +} + +/// The other rooms' lines are read in the order they were said, whatever order the mouth delivered them in. +#[test] +fn t_p1_other_rooms_are_read_in_the_order_they_were_said() { + let rig = Rig::new(vec![line(1, &room(1), META, "the turn's room"), line_at(2, &room(2), META, "SAID-LAST", BASE_MS - 30_000), line_at(3, &room(3), META, "SAID-FIRST", BASE_MS - 100_000)]); + let tally = Tally::default(); + rig.run(tally.clone()); + let prompt = tally.0.borrow()[1].clone(); + let (first, last) = (prompt.find("SAID-FIRST").unwrap(), prompt.find("SAID-LAST").unwrap()); + assert!(prompt.contains("Also, in other rooms:") && first < last, "{prompt}"); +} + +/// A notice in another waking room is no line that is shown to her: it does not hold the ack behind it. +#[test] +fn t_p1_a_notice_in_another_room_does_not_hold_the_ack() { + let mut notice = line(3, &room(2), META, "a notice"); + notice.form = Form::Notice; + let rig = Rig::new(vec![line(1, &room(1), META, "hello"), line(2, &room(2), META, "and hello"), notice, line(4, &room(1), META, "once more")]); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(4) }); +} diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 113a6d7..98b4a7e 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -349,6 +349,7 @@ fn packet_json(packet: &Packet) -> Value { "arrival": packet.arrival, "speaking": packet.speaking, "heard": packet.heard, + "elsewhere_shown": packet.elsewhere_shown, }) } diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index 011ef84..73801cd 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -303,6 +303,8 @@ pub(crate) struct Packet { pub bridged: String, /// What the other waking rooms said, verbatim, rendered for the Persona after the room: who, where and when, then the words. Empty with no other waking room. pub elsewhere: String, + /// The event of each line `elsewhere` shows: the other waking rooms' lines that fit `heard_bytes`, which are the ones she was shown. + pub elsewhere_shown: Vec, /// Bytes the messages to her took past the stimulus and heard caps: verbatim beats the cap. pub overflow: Overflow, pub present: Vec, @@ -1324,15 +1326,16 @@ fn turned_to_her(inputs: &Inputs) -> Vec<(String, String)> { } /// What the other waking rooms said, as the Persona reads it after the room: the speaker, the room and when, then the words verbatim, -/// newest kept within `heard_bytes`. The Projector's packet holds none of it (`turned_to_her` names who and where). -fn elsewhere_heard(inputs: &Inputs, tuning: &Tuning) -> String { +/// newest kept within `heard_bytes`, with the lines it shows. The Projector's packet holds none of it (`turned_to_her` names who and where). +fn elsewhere_heard<'a>(inputs: &'a Inputs, tuning: &Tuning) -> (String, Vec<&'a RoomLine>) { let mut lines: Vec<&RoomLine> = inputs.room.elsewhere.iter().filter(|line| line.sender != inputs.people.own_sender).collect(); lines.sort_by_key(|line| line.at_ms); let rendered: Vec = lines.iter().map(|line| format!("{}, in {}, {}: {}", name_of(line, inputs), line.room, coarse_ms(inputs.now, line.at_ms), spoken(&line.text))).collect(); - let (kept, _) = newest_that_fit(&rendered, tuning.select.heard_bytes); - if kept.is_empty() { String::new() } else { format!("Also, in other rooms: + let (kept, dropped) = newest_that_fit(&rendered, tuning.select.heard_bytes); + let text = if kept.is_empty() { String::new() } else { format!("Also, in other rooms: {}", kept.join(" -")) } +")) }; + (text, lines[dropped..].to_vec()) } /// The tail lines a beat's stimulus quotes: the newest `beat_tail_lines` of others'. @@ -2062,7 +2065,8 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { // reading, so the two never disagree (map 16.21). let present = present_people(inputs, tuning); let turned = turned_to_her(inputs); - let elsewhere = elsewhere_heard(inputs, tuning); + let (elsewhere, elsewhere_lines) = elsewhere_heard(inputs, tuning); + let elsewhere_shown: Vec = elsewhere_lines.iter().map(|line| line.event.clone()).collect(); let (stimulus, heard, bridged, overflow, earlier_shown) = match inputs.kind { TurnKind::Chat => chat_stimulus(inputs, tuning, &present, &turned), TurnKind::Beat => { @@ -2283,5 +2287,5 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { sections.domain = domain_view.len(); let now_ms = u64::try_from(inputs.now.timestamp_millis()).unwrap_or_default(); let readers = here.filter(|room| room_kind(inputs, room) == RoomKind::Direct).map(|room| readers(inputs, room)).unwrap_or_default(); - Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), sections, stimulus, heard, bridged, elsewhere, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning).iter().map(|line| (name_of(line, inputs), line.sender.clone())).collect(), affordances: inputs.affordances.to_vec(), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), readers, bodies, private, clipped, amendable, quotable, domain, domain_shown, in_view, now_ms, own_sender: inputs.people.own_sender.to_owned(), already_read, refused_reads, arrival, speaking: conversation.speaking.unwrap_or_default(), unshown, memories } + Packet { kind: inputs.kind, seed: inputs.seed, lens, name, voice, context: context.render(), sections, stimulus, heard, bridged, elsewhere, elsewhere_shown, overflow, present: present_names, ids, selected, forms: her, people: people_in_view(inputs, tuning).iter().map(|line| (name_of(line, inputs), line.sender.clone())).collect(), affordances: inputs.affordances.to_vec(), room: turn_room(inputs).map(str::to_owned), room_kind: turn_room(inputs).map_or(RoomKind::Public, |room| room_kind(inputs, room)), readers, bodies, private, clipped, amendable, quotable, domain, domain_shown, in_view, now_ms, own_sender: inputs.people.own_sender.to_owned(), already_read, refused_reads, arrival, speaking: conversation.speaking.unwrap_or_default(), unshown, memories } } diff --git a/crates/mind-body/src/projection/wake.rs b/crates/mind-body/src/projection/wake.rs index 0265388..07aa2f3 100644 --- a/crates/mind-body/src/projection/wake.rs +++ b/crates/mind-body/src/projection/wake.rs @@ -30,6 +30,9 @@ pub(crate) struct Waked { /// What each call cost: `{projector, persona}`, as the connector reported it. pub usage: Value, pub failed: Option, + /// The event of each line of the other waking rooms the Persona was shown (what fit `heard_bytes`): the lines of those rooms she did not see are not + /// held by this wake. + pub elsewhere_shown: Vec, /// The whole report of the render, the packet included. pub report: Value, } @@ -47,6 +50,7 @@ pub(crate) fn wake(organs: &Organs, request: &Request, now: DateTime) -> Re prose: persona["prose"].as_str().map(str::to_owned), usage: json!({ "projector": render["usage"], "persona": persona["usage"] }), failed, + elsewhere_shown: report["packet"]["elsewhere_shown"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(), report, }) }