From 219f165a8cd7b7d95f504514ecb1aaca6c866752 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 01:55:14 +0100 Subject: [PATCH] persona drain: her trace decides a line, and the decision is written before any of it is sent A turn is decide then deliver. The record of a decision carries each line's words and send id (owed) and is durable before the first send; a record that cannot be written sends nothing. The receipts rewrite the same record. A send whose answer never came stays owed and the next start sends the recorded words under the recorded id without asking the model; one owed past the homeserver's transaction memory is given up (owed_too_old). A line is decided when her trace holds a record of it that owes nothing, or sets it aside (projection::decided, the one reader); the ack is cleanup behind that and decides nothing. Deleted: the room-tail text receipt (Mouth.posted/counted/head), the digest in the send id (wire_id), the per-turn Turn decided flag the ack read, and done_events. Failed records stay in her trace but not in the window her packet reads. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/persona.rs | 145 +++++++------- crates/mind-body/src/persona/drain_tests.rs | 183 +++++++++++++----- crates/mind-body/src/projection.rs | 4 +- .../src/projection/simulate/tests.rs | 2 +- crates/mind-body/src/projection/turn.rs | 154 +++++++++------ crates/mind-body/src/projection/turn/tests.rs | 36 +++- 6 files changed, 338 insertions(+), 186 deletions(-) diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index 2c68592..1f2e514 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -5,21 +5,24 @@ //! 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. +//! room), and acks after each turn. Each turn is the simulator's turn in two steps, `projection::decide` and `deliver`: the +//! Interpreter's decision, the commit's application of her proposals, one put of her state, her record, and the lines through the mouth. +//! +//! Her trace alone says whether a line is decided (`projection::decided`, the reader the heartbeat's poll uses too): a line is done +//! when it holds a record that owes no send, or 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. +//! +//! Write ahead: the record of a decision, each line's words and send id (`owed`), is durable before any of it is sent, and a record +//! that cannot be written sends nothing. The receipts rewrite the same record. A send whose answer never came stays owed, and the next +//! start sends it again as recorded, under the recorded id, without asking the model; one owed longer than the homeserver remembers +//! a transaction (`OWED_WINDOW_S`) is given up instead of risking a second post. Her record is appended after the put, refused or not. //! //! 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. +//! again, applies the same record again and puts once more; a second refusal is `put_refused` in the record and on stderr. //! -//! The ack rule: after each turn (the unit has a runtime bound, and a start killed between turns must not replay an answered message), ack through the highest seq below the first waking delivery whose room's turn did not -//! 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`). +//! Each turn's record carries its `room` and the `held` event ids of the room's lines the drain read for it. A failed turn 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 turns held is +//! set aside: one `set_aside` record, the line acked past, and her next turn is told so (`outcome`). The heartbeat never acks. //! //! 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 @@ -41,7 +44,7 @@ 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, 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}; +use crate::projection::{DomainSource, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, decide, decided, deliver, history, own_addressee as heard_as}; /// The admitting agent's name on what her Persona admitted; `self_run::inbox` still reads her briefs by it. pub const AGENT: &str = "mind-persona"; @@ -252,21 +255,16 @@ pub fn carry(control: &impl ControlSource, swarm: &impl ControlSource, } } -/// 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, - decided: bool, - put_refused: bool, -} - /// How many turns that held a waking line may fail before the line is set aside. const STRIKES: usize = 2; +/// How long a recorded send stays owed, in seconds: the least a homeserver remembers a transaction (Synapse `HttpTransactionCache`). Past it the +/// same id is no longer the same send, so a repeat could post twice; the send is given up. +const OWED_WINDOW_S: i64 = 1800; + /// A waking line: where it sits in the mouth's queue, and which room and event it is. struct Waking<'a> { seq: u64, - at_unix_ms: u64, room: &'a str, event: &'a str, /// Who sent it, as the mouth names them, and what they said. @@ -274,17 +272,6 @@ struct Waking<'a> { text: &'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 strikes her trace charges `event`: a failed turn that was not an outage (the connector's typed kind, `Failed::outage`) charged one to the /// oldest line it was waking on, the room's held turn, and to no other line it happened to share the room with. fn strikes(records: &[Value], event: &str) -> usize { @@ -337,12 +324,12 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { .iter() .zip(&facts) .filter(|(delivery, facts)| claimed.contains(&delivery.event_id) || wakes(&her, delivery, speaker(config, delivery), **facts).is_some()) - .map(|(delivery, _)| Waking { seq: delivery.seq, at_unix_ms: delivery.at_unix_ms, 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() }) + .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 = done_events(&trace); + let done = decided(&trace); let mut oldest_of_room = BTreeSet::new(); let (aside, waking): (Vec, Vec) = waking_all.into_iter().filter(|line| !done.contains(line.event)).partition(|line| oldest_of_room.insert(line.room) && strikes(&trace, line.event) >= STRIKES); // The key of this start's records in her trace: how long it is, so a record that landed is never written over. @@ -368,22 +355,21 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { } } let seen = newest.into_iter().map(|(room, (_, event))| (room.to_owned(), event.to_owned())).collect(); - // Her own lines in the tail that follow the line a room's turn answers: what an earlier start of that turn already posted, whose - // record did not land. The mouth counts them as the sends they are, so a retry after the homeserver forgot the transaction posts nothing twice. - let posted: Vec = rooms - .iter() - .filter_map(|room| waking.iter().find(|line| line.room == *room).map(|line| (*room, line.at_unix_ms))) - .flat_map(|(room, since)| pending.tail.iter().flatten().filter(move |tail| tail.room == room && tail.sender == config.own_sender && tail.at_unix_ms >= since).cloned()) - .collect(); - let mouth = Mouth { chat: &start.chat, persona: instance.0.clone(), seen, since_unix_ms: began_ms, posted, counted: Default::default() }; + let mouth = Mouth { chat: &start.chat, persona: instance.0.clone(), seen, since_unix_ms: began_ms }; 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 turns = 0; + let mut put_refusals = 0; 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); + // 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 between turns does not replay a message she + // answered, and a line whose record did not land is never acked past. + let settle = |acked: &mut Option| { + let records = match start.trace.records() { + Ok(records) => records, + 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 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) { @@ -401,19 +387,36 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { } } if rooms.is_empty() || !aside.is_empty() { - settle(&taken, &mut acked); + settle(&mut acked); } for (index, room) in rooms.iter().enumerate() { - // The turn's own key, which names its sends: an answer is the answer to the oldest line it wakes on, so a start that - // finds the line still pending (the record did not land, or the ack is held below it) sends it under the id it already - // went out under, and the mouth answers it as the send it was. A beat answers no line and is a fresh speech each start. - let key = waking.iter().find(|line| line.room == *room).map_or_else(|| format!("b{began_ms}-t{index}"), |line| format!("l{}", line.event)); - let record_key = format!("{stem}-t{index}"); let now = (start.clock)(); - let past = match start.trace.records() { - Ok(records) => history(&records), + let records = match start.trace.records() { + Ok(records) => records, Err(fault) => return failed("her trace was not read", fault), }; + // A decision of hers in this room that still owes a send goes out as it was recorded, under the ids it was recorded with, and + // the model is not asked again: a post that was lost is the same post. One older than the homeserver remembers a transaction is + // given up, since the same id could no longer be told from a new line. + let owed: Vec<&Value> = records.iter().filter(|record| record["room"] == *room && record["owed"].as_array().is_some_and(|owed| !owed.is_empty())).collect(); + if !owed.is_empty() { + for record in owed { + let mut record = record.clone(); + let age = record["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map_or(i64::MAX, |at| (now - at.with_timezone(&Utc)).num_seconds()); + deliver(&mouth, &mut record, age > OWED_WINDOW_S); + if let Err(fault) = start.trace.record(record["key"].as_str().unwrap_or_default(), &record) { + eprintln!("mind-persona: the record of a send owed in {room} was not rewritten: {fault:#}"); + } + } + turns += 1; + settle(&mut acked); + continue; + } + // The turn's own key, which names its sends: an answer is the answer to the oldest line it wakes on, so a re-run of that + // line is the same key. A beat answers no line and is a fresh speech each start. + let key = waking.iter().find(|line| line.room == *room).map_or_else(|| format!("b{began_ms}-t{index}"), |line| format!("l{}", line.event)); + let record_key = format!("{stem}-t{index}"); + let past = history(&records); let request = Request { instance: instance.0.clone(), kind, @@ -435,9 +438,10 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { last_wake: past.last_wake, records: past.records, }; - let mut turn = take(&organs, &request, &mouth, &key, now); + let mut turn = decide(&organs, &request, &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["key"] = json!(record_key); turn.record["held"] = json!(deliveries.iter().filter(|delivery| delivery.room_alias == **room).map(|delivery| delivery.event_id.as_str()).collect::>()); // A turn that could not be set up (her tuning file, her own id) is the body's fault and no line's: the start fails loudly, charges no // strike and sets nothing aside. What it left pending is tried again by the next start. @@ -450,27 +454,34 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { { turn.record["strike"] = json!(line.event); } - 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, start.clock.as_ref()) { Ok(landed) => state = landed, Err((fresh, why)) => { - put_refused = true; + put_refusals += 1; turn.record["put_refused"] = json!(why); eprintln!("mind-persona: the put of turn {key} was refused twice: {why}"); state = fresh; } } } - // 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(&record_key, &turn.record) { - eprintln!("mind-persona: the record of turn {key} was not appended: {fault:#}"); + // Write ahead: the record of the decision, every line's words and send id, is durable before any of it is sent. A record + // that cannot be written sends nothing, and the line is decided by no one until it is. + turns += 1; + match start.trace.record(&record_key, &turn.record) { + Ok(()) => { + deliver(&mouth, &mut turn.record, false); + if turn.record.get("failed").is_none() + && let Err(fault) = start.trace.record(&record_key, &turn.record) + { + eprintln!("mind-persona: the receipts of turn {key} were not appended, so its lines are owed again under their ids: {fault:#}"); + } + } + Err(fault) => eprintln!("mind-persona: the record of turn {key} was not appended, so nothing of it was sent: {fault:#}"), } - taken.push(Turn { room: (*room).to_owned(), decided: turn.record.get("failed").is_none(), put_refused }); - settle(&taken, &mut acked); + settle(&mut acked); } - Outcome::Drained { turns: taken.len(), acked_through: acked, put_refused: taken.iter().filter(|turn| turn.put_refused).count() } + Outcome::Drained { turns, acked_through: acked, put_refused: put_refusals } } /// Her put through the persona door, the one writer of her state a start has. diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 13e3c96..f661cd5 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -2,6 +2,7 @@ //! put, trace append and ack can be read. use std::cell::{Cell, RefCell}; +use std::collections::BTreeMap; use std::rc::Rc; use anyhow::{Result, bail}; @@ -59,6 +60,13 @@ struct FakeMouth { 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 next send lands and its answer is lost on the way back. + answer_lost: Cell, + /// Every id a send came under, retries and deduped ones included. + attempts: RefCell>, log: Log, } @@ -68,10 +76,19 @@ impl Chat for Rc { 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![] }) } fn send(&self, request: &ChatSendRequest) -> Result { + self.attempts.borrow_mut().push(request.request_id.clone()); + 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![] }) } fn open_direct(&self, _: &ChatOpenDirectRequest) -> Result { @@ -137,16 +154,23 @@ struct MemTrace { rows: 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() { + if self.fail.get() || self.allow.get() == 0 { bail!("no space left on device"); } + self.allow.set(self.allow.get() - 1); self.log.borrow_mut().push("trace".into()); - self.rows.borrow_mut().push((key.to_owned(), record.clone())); + let mut rows = self.rows.borrow_mut(); + match rows.iter_mut().find(|(held, _)| held == key) { + Some(row) => row.1 = record.clone(), + None => rows.push((key.to_owned(), record.clone())), + } Ok(()) } fn records(&self) -> Result> { @@ -215,9 +239,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), ack_fails: Cell::new(false), page: Cell::new(usize::MAX), tail: RefCell::default(), 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), page: Cell::new(usize::MAX), tail: RefCell::default(), txn: RefCell::default(), forgot: Cell::new(false), answer_lost: Cell::new(false), attempts: 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: Cell::new(false), log: log.clone() }); + let trace = Rc::new(MemTrace { rows: RefCell::default(), fail: Cell::new(false), allow: Cell::new(usize::MAX), log: log.clone() }); Self { mouth, store, trace, log, dir, ticks: Rc::default() } } @@ -268,8 +292,8 @@ fn t_l2_drain_acks_after_decision() { assert_eq!(*rig.mouth.acks.borrow(), [1, 3], "each ack stops below the first waking line of a room not yet decided"); let log = rig.log(); let events: Vec<&str> = log.iter().map(String::as_str).filter(|event| *event != "put").collect(); - assert_eq!(events, ["send", "trace", "ack", "send", "trace", "ack"], "each ack follows its turn's trace append: {log:?}"); - let ids: Vec = rig.mouth.sent.borrow().iter().map(|request| base(&request.request_id)).collect(); + assert_eq!(events, ["trace", "send", "trace", "ack", "trace", "send", "trace", "ack"], "each turn's record is written before its send, receipts follow, and the ack follows them: {log:?}"); + let ids: Vec = rig.mouth.sent.borrow().iter().map(|request| request.request_id.clone()).collect(); assert_eq!(ids.len(), 2); assert_eq!(ids, ["l$e1:s0", "l$e2:s0"], "a send is named by the line it answers"); let keys: Vec = rig.trace.rows.borrow().iter().map(|(key, _)| key.clone()).collect(); @@ -345,7 +369,7 @@ fn t_l2_second_stale_put_is_put_refused_in_the_record() { let rows = rig.trace.rows.borrow(); assert_eq!(rows.len(), 1, "the record is appended though the put was refused"); assert!(rows[0].1["put_refused"].is_string(), "{:?}", rows[0].1); - assert_eq!(rig.log().iter().position(|event| event == "trace"), Some(rig.log().len() - 2), "the append comes after the puts: {:?}", rig.log()); + assert_eq!(rig.log().iter().position(|event| event == "trace"), Some(rig.log().len() - 4), "the record comes after the puts: {:?}", rig.log()); assert!(rig.store.puts.borrow().is_empty(), "nothing of hers landed"); } @@ -441,15 +465,6 @@ fn t_l2_she_is_told_the_next_wake_that_her_turn_on_the_line_failed_and_it_was_se 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() { @@ -651,8 +666,8 @@ fn t_l2_a_failure_nobody_named_cannot_hold_the_ack_forever() { assert!(rig.held_seqs().is_empty(), "the ack passed the line: {:?}", rig.held_seqs()); } -/// Soul's probe: her trace stops being writable once the oldest room's failed turn has landed, so the room-1 answer goes out -/// with no record, while the failed turn holds the ack below it. +/// Her trace stops being writable once the oldest room's failed turn has landed: the room-1 answer is never sent, for it has no +/// record, while the failed turn holds the ack below it. struct TraceDiesAfterTheFailedTurn { inner: Flaky, trace: Rc, @@ -667,29 +682,27 @@ impl Model for TraceDiesAfterTheFailedTurn { } } -/// A reply whose record did not land is the answer to the line it answered: the next start, finding the line still pending -/// because the ack is held below it, sends it under the id it already went out under, never a second id. +/// A reply whose record did not land was never sent; the next start answers the line once, under the id of the line. #[test] -fn t_l2_a_reply_whose_record_did_not_land_goes_out_again_under_the_same_id() { +fn t_l2_a_reply_whose_record_did_not_land_was_not_sent_and_goes_out_once_later() { let rig = Rig::new(vec![line(1, &room(2), META, "FAILME bravo"), line(2, &room(1), META, "alpha")]); rig.run(TraceDiesAfterTheFailedTurn { inner: failing(OUTAGE), trace: rig.trace.clone() }); + assert_eq!(sends_to(&rig, &room(1)), 0, "no record, no send"); rig.trace.fail.set(false); rig.run(failing(OUTAGE)); - let ids: std::collections::BTreeSet = rig.mouth.sent.borrow().iter().filter(|request| request.room_alias == room(1)).map(|request| base(&request.request_id)).collect(); - assert_eq!(ids.len(), 1, "one id for the one line: {ids:?}"); + let ids: Vec = rig.mouth.sent.borrow().iter().filter(|request| request.room_alias == room(1)).map(|request| request.request_id.clone()).collect(); + assert_eq!(ids, ["l$e2:s0"], "one send, under the line's id"); assert_eq!(rig.held_seqs(), [1, 2], "the outage holds the ack, as it should"); } -/// Soul's probe: two beats, and no record lands for either; the second speech is not swallowed as the first. +/// A beat whose record cannot land speaks nothing. #[test] -fn t_l2_two_beats_with_no_trace_record_do_not_share_a_send_id() { +fn t_l2_a_beat_whose_record_cannot_land_speaks_nothing() { let rig = Rig::new(vec![]); rig.trace.fail.set(true); rig.run(scripted(false)); rig.run(scripted(false)); - let ids: std::collections::BTreeSet = rig.mouth.sent.borrow().iter().map(|request| base(&request.request_id)).collect(); - assert_eq!(rig.mouth.sent.borrow().len(), 2, "each beat spoke"); - assert_eq!(ids.len(), 2, "under two ids: {ids:?}"); + assert!(rig.mouth.sent.borrow().is_empty()); } /// A line set aside is done: while the mouth cannot take the ack, the next starts neither set it aside again nor tell her twice. @@ -740,7 +753,7 @@ fn t_l2_the_open_floor_is_hers_only_on_the_lines_the_heartbeat_woke_her_for() { 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| base(&request.request_id)).collect::>(), ["l$e1:s0"], "the heartbeat woke her for the hello: she answers it"); + 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"); } /// Her stewardships, as the drain reads them: read, or the mind did not answer. @@ -779,7 +792,7 @@ fn run_with(rig: &Rig, view: Box, down: bool) -> Outcome { } fn sent_ids(rig: &Rig) -> Vec { - rig.mouth.sent.borrow().iter().map(|request| base(&request.request_id)).collect() + rig.mouth.sent.borrow().iter().map(|request| request.request_id.clone()).collect() } /// Soul R21 p2: a member's untagged line in her own room, the floor closed by a Mind's line just before it; the heartbeat woke her @@ -826,37 +839,103 @@ fn t_l2_an_unread_heartbeat_state_fails_the_start() { assert!(matches!(run_with(&rig, Box::new(Unread), false), Outcome::Failed(why) if why.contains("heartbeat state was not read"))); assert!(sent_ids(&rig).is_empty() && rig.held_seqs() == [1] && rig.mouth.acks.borrow().is_empty(), "nothing sent or acked"); } +/// A model that must not be asked: the turn is already decided. +struct Never; -/// A send's id as the turn names it: the transaction id the mouth sent, without the digest of the words. -fn base(id: &str) -> String { - id.rsplit_once('.').map_or(id, |(base, _)| base).to_owned() +impl Model for Never { + fn ask(&self, _: &str, _: &str, _: &str, _: Option<&str>) -> std::result::Result { + panic!("the model was asked again for a turn her trace already decides"); + } } -/// A start that posted her line and then lost its record and its ack (the process died, the mouth went down) leaves the line -/// pending; the next start is the same turn again. The homeserver forgets a transaction id after 30 to 60 minutes, so the id -/// alone cannot keep that start from posting twice: her line in the room's tail is the receipt, and it is that send. +static VARIED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// A model whose words differ on every render, as a live one's do. +fn varying() -> Scripted { + Scripted::new(|_| format!("He nods. Answer number {}.", VARIED.fetch_add(1, std::sync::atomic::Ordering::SeqCst))).interpreting(drafted_lines) +} + +fn texts(rig: &Rig, room: &str) -> Vec { + rig.mouth.sent.borrow().iter().filter(|request| request.room_alias == room).map(|request| request.text.clone()).collect() +} + +/// A send whose answer never came is owed by her record, and the next start sends it as it was recorded, under the id it was +/// recorded with: it does not ask the model again, so words that would differ cannot make a second answer to the line. +/// (Soul s4 rerender-posts-second-answer.) #[test] -fn t_l2_a_turn_whose_record_was_lost_posts_nothing_twice_even_when_the_homeserver_forgot() { +fn t_l2_a_send_that_did_not_answer_goes_out_again_as_recorded_and_the_model_is_not_asked() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.mouth.answer_lost.set(true); + rig.run(varying()); + let first = texts(&rig, &room(1)); + assert_eq!(first.len(), 1, "it landed, and its answer was lost"); + let owing = rig.trace.rows.borrow()[0].1.clone(); + assert!(owing["owed"].as_array().is_some_and(|owed| owed.len() == 1) && owing["posted"] == json!([]), "her record owes it: {owing}"); + assert_eq!(rig.held_seqs(), [1], "an owed line is not decided: the ack waits"); + assert_eq!(rig.run(Never), Outcome::Drained { turns: 1, acked_through: Some(1), put_refused: 0 }); + assert_eq!(texts(&rig, &room(1)), first, "the room shows it once: the homeserver answered the same id with the event it made"); + let ids: std::collections::BTreeSet = rig.mouth.attempts.borrow().iter().cloned().collect(); + assert_eq!(ids.len(), 1, "both under one id: {:?}", rig.mouth.attempts.borrow()); + let record = rig.trace.rows.borrow()[0].1.clone(); + assert!(record.get("owed").is_none() && record["posted"][0]["event"] == "$sent-1" && record["posted"][0]["text"] == first[0].as_str(), "settled: {record}"); + assert_eq!(rig.trace.rows.borrow().len(), 1, "one record, rewritten"); +} + +/// Her record is written before anything is sent, and its receipts after; when the rewrite is the write that fails, the lines are +/// still owed under their ids, and the next start repeats them rather than rendering the line again. (Soul s4 +/// rerender-posts-second-answer, the trace that dies after the send.) +#[test] +fn t_l2_a_trace_that_dies_after_the_send_repeats_the_recorded_words_not_new_ones() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.trace.allow.set(1); + rig.run(varying()); + rig.trace.allow.set(usize::MAX); + let first = texts(&rig, &room(1)); + rig.run(Never); + assert_eq!(texts(&rig, &room(1)), first, "one answer to the line"); + assert!(rig.held_seqs().is_empty()); +} + +/// A record that cannot be written sends nothing: no line goes out that her trace does not hold, so a lost record can never be +/// followed by a second, different answer. +#[test] +fn t_l2_a_trace_that_cannot_be_written_sends_nothing_and_acks_nothing() { let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); - rig.mouth.ack_fails.set(true); rig.trace.fail.set(true); + rig.run(varying()); + rig.run(varying()); + assert!(rig.mouth.sent.borrow().is_empty() && rig.held_seqs() == [1], "nothing sent, the line still pending"); + rig.trace.fail.set(false); + rig.run(varying()); + assert_eq!(sends_to(&rig, &room(1)), 1, "once her record lands, one answer"); + assert!(rig.held_seqs().is_empty()); +} + +/// The homeserver forgets a transaction id after 30 to 60 minutes, so a send still owed after that is given up and refused +/// `owed_too_old`, never posted again, and the line is decided. (Soul s3 send-id-dedupe-window.) +#[test] +fn t_l2_a_send_owed_past_the_homeservers_memory_is_given_up_and_posts_nothing_twice() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.mouth.answer_lost.set(true); rig.run(scripted(false)); assert_eq!(rig.mouth.sent.borrow().len(), 1); - rig.mouth.ack_fails.set(false); - rig.trace.fail.set(false); - rig.run(scripted(false)); - assert_eq!(rig.mouth.sent.borrow().len(), 1, "her line is already in the room: counted as sent, not posted again"); - assert!(rig.held_seqs().is_empty(), "and the line is decided and acked"); - let record = rig.trace.rows.borrow().last().cloned().unwrap().1; - assert_eq!(record["posted"][0]["event"], "$sent-1", "the record keeps the event that is in the room"); + rig.mouth.forgot.set(true); + rig.ticks.set(rig.ticks.get() + 3600); + rig.run(Never); + assert_eq!(rig.mouth.sent.borrow().len(), 1, "no second post, though the homeserver forgot the id"); + let record = rig.trace.rows.borrow()[0].1.clone(); + assert_eq!(record["refused_sends"][0]["refusal"], "owed_too_old", "{record}"); + assert!(rig.held_seqs().is_empty(), "the line is decided"); } -/// Other words are another transaction: a turn rendered again, whose first post went out under the same line, never gets the old -/// event back for its new words. +/// A trace that holds a decision with its lines sent is all that decides a line: a start that finds the same line pending again +/// (its ack failed) neither asks the model nor sends. #[test] -fn t_l2_a_line_rendered_again_goes_out_under_another_transaction_id() { - let one = crate::projection::wire_id("l$e1:s0", "Hello there, friend."); - assert_eq!(one, crate::projection::wire_id("l$e1:s0", "Hello there, friend."), "the same words are the same send"); - assert_ne!(one, crate::projection::wire_id("l$e1:s0", "Hello again, friend."), "other words are another"); - assert_ne!(one, crate::projection::wire_id("l$e1:s1", "Hello there, friend."), "and another place is another"); +fn t_l2_a_decided_line_pending_behind_a_failed_ack_is_not_asked_again() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.mouth.ack_fails.set(true); + rig.run(scripted(false)); + rig.mouth.ack_fails.set(false); + assert_eq!(rig.run(Never), Outcome::Drained { turns: 0, acked_through: Some(1), put_refused: 0 }); + assert_eq!(sends_to(&rig, &room(1)), 1); } diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 63b2bfc..055d54b 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -50,9 +50,7 @@ pub use narrate::{Answer, Continued, Failed, KitModel, Model, Reasoning, Spent, pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource}; pub use select::TurnKind; pub(crate) use commit::apply as apply_commit; -pub(crate) use turn::{Mouth, Taken, history, take}; -#[cfg(test)] -pub(crate) use turn::wire_id; +pub(crate) use turn::{Mouth, Taken, decide, decided, deliver, history}; pub use tuning::{TUNING_FILE, TUNING_ROOT}; use narrate::{cap_prose, cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words}; diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 5af424b..8c659b0 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -1139,7 +1139,7 @@ fn t_l1_sim_and_mouth_records_same_shape() { bail!("unused") } } - let mouth = Mouth { chat: &Chat1, persona: "eureka".into(), seen: Default::default(), since_unix_ms: 0, posted: vec![], counted: Default::default() }; + let mouth = Mouth { chat: &Chat1, persona: "eureka".into(), seen: Default::default(), since_unix_ms: 0 }; let live = take(&organs, &request, &mouth, "r1-t1", fixture.now); let keys = |record: &Value| record.as_object().unwrap().keys().cloned().collect::>(); assert_eq!(keys(&simulated.record), keys(&live.record), "one record shape, simulated or live"); diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs index 8747ec7..5611c97 100644 --- a/crates/mind-body/src/projection/turn.rs +++ b/crates/mind-body/src/projection/turn.rs @@ -2,26 +2,30 @@ //! simulator's room and the live mouth are the two actuators; `take` is the one turn they share, so the simulator tests //! the turn the Minds take on chat. Her records are her trace: what she last did, what she showed lately, what she has //! said in this conversation and when she last woke are read back from them (`history`), and kept nowhere else. +//! +//! A turn is two steps, `decide` and `deliver`, so the live drain can make its record durable between them: the record of a +//! decision carries every line it owes, words and send id (`owed`), and `deliver` settles them. A line is decided, for +//! whoever asks (`decided`), when her trace holds a record of it with nothing owed. -use std::cell::RefCell; use std::collections::{BTreeMap, BTreeSet}; use chrono::{DateTime, Utc}; use serde_json::{Value, json}; -use sha2::{Digest, Sha256}; use super::commit; use super::{Organs, Request, project}; -use crate::chat_client::{Chat, ChatSendRequest, SendBasis, TailLine}; +use crate::chat_client::{Chat, ChatSendRequest, SendBasis}; /// How many of her earlier projections freshness remembers, and how many of her records a packet reads. const RECENT: usize = 5; const RECORDS: usize = 50; -/// How an actuator answered a send: the event it made, or why it made none (the refusal's name). +/// How an actuator answered a send: the event it made, why it made none (the refusal's name), or that no answer came, so the +/// send is still owed. pub(crate) enum Sent { Posted(String), Refused(String), + Lost, } /// The refusal that kept an amendment out of the room, or none when it was made. @@ -30,8 +34,8 @@ pub(crate) type Edited = Option<&'static str>; /// What a turn's decision reaches the world through. A refusal is an answer the record keeps, never a fault. pub(crate) trait Actuator { /// Say `text` in `room`, replying to the line `in_reply_to` and waking `mentions`, where the actuator carries them. `id` - /// names this send, `{key}:s{index}` of the turn's key and the line's place in what she decided: the one source of the - /// mouth's transaction id, so the same turn sent again is the same send and no two sends of a turn share one. + /// names this send, `{key}:s{index}` of the turn's key and the line's place in what she decided, and the record keeps it: + /// the mouth's transaction id is this id, so a send repeated from the record is the same transaction. fn send(&self, id: &str, room: &str, text: &str, in_reply_to: Option<&str>, mentions: &[String]) -> Sent; /// Add `added` to her line `event`. fn edit(&self, event: &str, added: &str) -> Edited; @@ -39,7 +43,7 @@ pub(crate) trait Actuator { /// The mouth as the actuator. `chat_send_request.v2` carries no mentions and no reply link, so her line goes out plain and /// the receipt records the text that went, not the decision; the mouth has no edit, so an amendment is refused -/// `no_edit_at_the_mouth` and told to her as not amended. Each send is its own transaction, the id `take` names. +/// `no_edit_at_the_mouth` and told to her as not amended. Each send is its own transaction, the id the record names. pub(crate) struct Mouth<'a> { pub chat: &'a dyn Chat, pub persona: String, @@ -47,44 +51,19 @@ pub(crate) struct Mouth<'a> { pub seen: BTreeMap, /// When her process began. pub since_unix_ms: u64, - /// Her own lines the room tail holds that follow a line she answers now: what an earlier start of this same turn already posted - /// (its record did not land). A send whose words are among them is that send, and posts nothing again. - pub posted: Vec, - /// The `posted` lines a send has already counted, so two sends of the same words are two lines. - pub counted: RefCell>, -} - -/// The first words of a line, the same head the mouth keeps of a message in a later context. -fn head(text: &str) -> String { - text.trim().chars().take(200).collect() -} - -/// The transaction id a send goes out under: the turn's id and a digest of the words, so a retry of the same words is the same -/// transaction (the homeserver answers it with the event it made, for as long as it remembers), and other words are another one -/// and never get the old event back. -pub(crate) fn wire_id(id: &str, text: &str) -> String { - let digest = Sha256::digest(text.as_bytes()); - format!("{id}.{}", digest.iter().take(4).map(|byte| format!("{byte:02x}")).collect::()) } impl Actuator for Mouth<'_> { fn send(&self, id: &str, room: &str, text: &str, _in_reply_to: Option<&str>, _mentions: &[String]) -> Sent { - // The homeserver forgets a transaction after 30 to 60 minutes (Synapse `HttpTransactionCache`), so a retry later than - // that would post again. Her line already in the room is the receipt: it is that send. - let earlier = self.posted.iter().find(|line| line.room == room && head(&line.body) == head(text) && !self.counted.borrow().contains(&line.event_id)); - if let Some(line) = earlier { - self.counted.borrow_mut().insert(line.event_id.clone()); - return Sent::Posted(line.event_id.clone()); - } let basis = SendBasis { seen_event_id: self.seen.get(room).cloned(), since_unix_ms: self.since_unix_ms }; - let request = ChatSendRequest { request_id: wire_id(id, text), persona: self.persona.clone(), room_alias: room.to_owned(), text: text.to_owned(), basis: Some(basis) }; + let request = ChatSendRequest { request_id: id.to_owned(), persona: self.persona.clone(), room_alias: room.to_owned(), text: text.to_owned(), basis: Some(basis) }; match self.chat.send(&request) { Ok(receipt) => match (receipt.event_id, receipt.refusal) { (_, Some(refusal)) => Sent::Refused(refusal.name().to_owned()), (Some(event), None) => Sent::Posted(event), (None, None) => Sent::Refused("no_event".to_owned()), }, - Err(_) => Sent::Refused("unreachable".to_owned()), + Err(_) => Sent::Lost, } } @@ -100,10 +79,17 @@ pub(crate) struct Taken { pub state: Value, } -/// One turn: `project` through the Interpreter, each said line through `actuator.send`, each amendment through -/// `actuator.edit`, the record of what happened, and the commit's application of her proposals to her state. `key` names -/// the turn (`-t`). A failed turn sends nothing, amends nothing and applies nothing. +/// One turn: `decide`, then `deliver`. pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, key: &str, now: DateTime) -> Taken { + let mut taken = decide(organs, request, key, now); + deliver(actuator, &mut taken.record, false); + taken +} + +/// The Interpreter's decision, with nothing sent: `project` through the Interpreter, the record of what she decided (each said +/// line as an owed send under its id `{key}:s{index}`, each amendment as one to make) and the commit's application of her +/// proposals to her state. `key` names the turn. A failed turn decided nothing and owes nothing. +pub(crate) fn decide(organs: &Organs, request: &Request, key: &str, now: DateTime) -> Taken { let report = project(organs, request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") })); let render = &report["renders"][0]; // Which stage's failure ended the turn, and whether the connector's typed kind made it an outage. A `project` error is no stage's: @@ -117,25 +103,22 @@ pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, Some(failed) => json!({ "failed": failed }), None => { // What she says is the Interpreter's decision alone. - let (mut posted, mut refused_sends, mut edited) = (Vec::new(), Vec::new(), Vec::new()); - for (index, decided) in render["interpreter"]["said"].as_array().into_iter().flatten().enumerate() { - let room = decided["room"].as_str().unwrap_or(&here); - let text = decided["text"].as_str().unwrap_or_default(); - let mentions: Vec = decided["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); - let reply = decided["in_reply_to"]["event"].as_str(); - match actuator.send(&format!("{key}:s{index}"), room, text, reply, &mentions) { - Sent::Posted(event) => posted.push(json!({ "event": event, "room": room, "text": text })), - Sent::Refused(refusal) => refused_sends.push(match reply { - Some(event) => json!({ "room": room, "text": text, "in_reply_to": event, "refusal": refusal }), - None => json!({ "room": room, "text": text, "refusal": refusal }), - }), - } - } - for amended in render["interpreter"]["amended"].as_array().into_iter().flatten() { - let event = amended["event"].as_str().unwrap_or_default(); - edited.push(json!({ "event": event, "refusal": actuator.edit(event, amended["added"].as_str().unwrap_or_default()) })); - } - json!({ "interpreter": render["interpreter"], "posted": posted, "edited": edited, "refused_sends": refused_sends }) + let owed: Vec = render["interpreter"]["said"] + .as_array() + .into_iter() + .flatten() + .enumerate() + .map(|(index, decided)| { + let mentions: Vec<&str> = decided["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + let mut send = json!({ "id": format!("{key}:s{index}"), "room": decided["room"].as_str().unwrap_or(&here), "text": decided["text"].as_str().unwrap_or_default(), "mentions": mentions }); + if let Some(event) = decided["in_reply_to"]["event"].as_str() { + send["in_reply_to"] = json!(event); + } + send + }) + .collect(); + let amend: Vec = render["interpreter"]["amended"].as_array().into_iter().flatten().map(|amended| json!({ "event": amended["event"].as_str().unwrap_or_default(), "added": amended["added"].as_str().unwrap_or_default() })).collect(); + json!({ "interpreter": render["interpreter"], "posted": [], "edited": [], "refused_sends": [], "owed": owed, "amend": amend }) } }; // A later step of her wake that broke (a continuation or a later Interpreter call, map 16.22.3): what was decided @@ -152,8 +135,60 @@ pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, Taken { report, record, state } } +/// Settles what `record` owes through `actuator`: each owed send is posted, refused (a refusal is an answer) or, when no answer +/// came, still owed. With `give_up` nothing is sent: each owed send is refused `owed_too_old`. The amendments follow once nothing +/// is owed. A record that owes nothing is the shape the simulator and the mouth share. +pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, give_up: bool) { + let owed: Vec = record["owed"].as_array().cloned().unwrap_or_default(); + let mut still = Vec::new(); + for send in owed { + let (room, text) = (send["room"].as_str().unwrap_or_default(), send["text"].as_str().unwrap_or_default()); + let refusal = |why: &str| match send["in_reply_to"].as_str() { + Some(event) => json!({ "room": room, "text": text, "in_reply_to": event, "refusal": why }), + None => json!({ "room": room, "text": text, "refusal": why }), + }; + let mentions: Vec = send["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); + let sent = if give_up { Sent::Refused("owed_too_old".to_owned()) } else { actuator.send(send["id"].as_str().unwrap_or_default(), room, text, send["in_reply_to"].as_str(), &mentions) }; + match sent { + Sent::Posted(event) => record["posted"].as_array_mut().into_iter().for_each(|posted| posted.push(json!({ "event": event, "room": room, "text": text }))), + Sent::Refused(why) => record["refused_sends"].as_array_mut().into_iter().for_each(|refused| refused.push(refusal(&why))), + Sent::Lost => still.push(send), + } + } + if still.is_empty() { + let amend: Vec = record["amend"].as_array().cloned().unwrap_or_default(); + if let Some(fields) = record.as_object_mut() { + fields.remove("owed"); + fields.remove("amend"); + } + for amended in amend { + let event = amended["event"].as_str().unwrap_or_default(); + let edit = json!({ "event": event, "refusal": actuator.edit(event, amended["added"].as_str().unwrap_or_default()) }); + if let Some(edited) = record["edited"].as_array_mut() { + edited.push(edit); + } + } + } else { + record["owed"] = json!(still); + } +} + +/// The events her trace shows she is done with: every line a record that did not fail held (`held`, the room's event ids the drain +/// read for it) once that record owes no send, and every line set aside (`set_aside`). The one reader of "was this line decided", +/// for the drain and the poll alike. +pub(crate) fn decided(records: &[Value]) -> BTreeSet<&str> { + let mut done = BTreeSet::new(); + for record in records.iter().filter(|record| record.get("failed").is_none() && record["owed"].as_array().is_none_or(Vec::is_empty)) { + 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 +} + /// What her records say of her: her last turn's record, the ids her last projections selected, her last records and -/// when she last woke. The one reader, over a run's list or her trace. +/// when she last woke. The one reader, over a run's list or her trace. A failed turn is in her trace and not in her packet's +/// window: an outage that fails every wake for an hour must not push her real turns out of it, so only her last outcome may be +/// one. #[derive(Debug, Default, PartialEq)] pub(crate) struct Past { pub last_outcome: Option, @@ -165,12 +200,13 @@ pub(crate) struct Past { /// Her `records`, oldest first, read. pub(crate) fn history(records: &[Value]) -> Past { let selected = |record: &Value| record["selected"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_owned).collect::>()); - let mut recent: Vec> = records.iter().filter_map(selected).collect(); + let real: Vec<&Value> = records.iter().filter(|record| record.get("failed").is_none()).collect(); + let mut recent: Vec> = real.iter().copied().filter_map(selected).collect(); recent.drain(..recent.len().saturating_sub(RECENT)); Past { last_outcome: records.last().cloned(), recent, - records: records[records.len().saturating_sub(RECORDS)..].to_vec(), + records: real[real.len().saturating_sub(RECORDS)..].iter().map(|record| (*record).clone()).collect(), last_wake: last_wake(records), } } diff --git a/crates/mind-body/src/projection/turn/tests.rs b/crates/mind-body/src/projection/turn/tests.rs index 8ea1577..ed16bda 100644 --- a/crates/mind-body/src/projection/turn/tests.rs +++ b/crates/mind-body/src/projection/turn/tests.rs @@ -50,7 +50,7 @@ impl Chat for FakeChat { } fn mouth(chat: &FakeChat) -> Mouth<'_> { - Mouth { chat, persona: "eureka".into(), seen: BTreeMap::new(), since_unix_ms: 7, posted: vec![], counted: Default::default() } + Mouth { chat, persona: "eureka".into(), seen: BTreeMap::new(), since_unix_ms: 7 } } /// One turn from the operator-warm fixture, she saying one line in reply, through `actuator`. @@ -75,7 +75,7 @@ fn t_l1_mouth_sends_the_text_that_went_and_records_the_receipt() { let taken = warm_turn(&mouth(&chat)); let sent = chat.sent.borrow(); assert_eq!(sent.len(), 1); - assert_eq!((sent[0].request_id.as_str(), sent[0].persona.as_str(), sent[0].room_alias.as_str(), sent[0].text.as_str()), (wire_id("run-t1:s0", "Missed you too, friend.").as_str(), "eureka", "!dm-meta:gamecult.org", "Missed you too, friend.")); + assert_eq!((sent[0].request_id.as_str(), sent[0].persona.as_str(), sent[0].room_alias.as_str(), sent[0].text.as_str()), ("run-t1:s0", "eureka", "!dm-meta:gamecult.org", "Missed you too, friend.")); assert_eq!(taken.record["posted"], json!([{ "event": "$sent-1", "room": "!dm-meta:gamecult.org", "text": "Missed you too, friend." }])); } @@ -86,7 +86,7 @@ fn t_l2_each_send_of_a_turn_has_its_own_id_and_its_own_rooms_basis() { let taken = warm_turn_saying("He types. First thing. Then more. Second, and different.", &mouth_in_dm); let sent = chat.sent.borrow(); let ids: Vec = sent.iter().map(|request| request.request_id.clone()).collect(); - assert_eq!(ids, [wire_id("run-t1:s0", "First thing."), wire_id("run-t1:s1", "Second, and different.")], "one id per said line, named by the turn's key, the line's place and its words"); + assert_eq!(ids, ["run-t1:s0", "run-t1:s1"], "one id per said line, named by the turn's key and the line's place"); assert_eq!(taken.record["posted"].as_array().unwrap().len(), 2); let basis = |request: &ChatSendRequest| request.basis.clone().unwrap(); assert_eq!(basis(&sent[0]), SendBasis { seen_event_id: Some("$newest".into()), since_unix_ms: 7 }, "the basis is the room's own newest event"); @@ -162,8 +162,36 @@ fn t_l1_history_from_records() { let past = history(&records); assert_eq!(past.last_outcome.as_ref().map(|last| last["failed"].clone()), Some(json!("Overloaded")), "her last outcome is the failure"); assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6)), "a failed turn is no wake"); - assert_eq!(past.recent.last(), Some(&vec!["m7".to_owned()]), "a failed turn still showed what it selected"); + assert_eq!(past.recent.last(), Some(&vec!["m6".to_owned()]), "a failed turn is not in the window, so what it selected is not remembered"); let long: Vec = (0..60).map(|at| turn(at, &[])).collect(); assert_eq!(history(&long).records.len(), 50); assert_eq!(history(&long).records[0]["at"], json!(at(10)), "her last fifty, oldest first"); } + +/// An outage that fails every wake is in her trace and not in her packet's window: her real turns stay in the 50 she reads, and +/// the run of failures is what the poll backs off by. (Soul s4 outage-rewake-floods-records.) +#[test] +fn t_l2_failed_records_never_push_her_real_turns_out_of_the_window() { + let real = |n: usize| json!({ "interpreter": {}, "posted": [], "held": [format!("$e{n}")], "selected": [format!("m{n}")], "at": format!("2026-11-27T10:00:{n:02}Z") }); + let failed = |n: usize| json!({ "failed": "the connector did not answer: unavailable", "outage": true, "at": format!("2026-11-27T11:{:02}:00Z", n % 60) }); + let mut records: Vec = (0..3).map(real).collect(); + records.extend((0..200).map(failed)); + let past = history(&records); + assert_eq!(past.records.len(), 3, "the window holds her decided turns and no failure"); + assert!(past.records.iter().all(|record| record.get("failed").is_none())); + assert_eq!(past.recent.len(), 3, "and so do her recent selections"); + assert!(past.last_outcome.is_some_and(|last| last.get("failed").is_some()), "her last outcome may be the failure: she is told once"); + assert_eq!(past.last_wake.map(|at| at.to_rfc3339()), Some("2026-11-27T10:00:02+00:00".to_owned()), "and her last wake is her last decision"); +} + +/// A record is decided when it holds its lines and owes no send; a failure decides nothing. +#[test] +fn t_l2_a_line_is_decided_by_a_record_that_owes_nothing() { + let records = vec![ + json!({ "held": ["$a"], "owed": [{ "id": "l$a:s0", "room": "r", "text": "hi" }] }), + json!({ "held": ["$b"], "posted": [] }), + json!({ "failed": "x", "held": ["$c"] }), + json!({ "set_aside": [{ "event": "$d" }] }), + ]; + assert_eq!(decided(&records).into_iter().collect::>(), ["$b", "$d"]); +}