diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index 68a9f60..8f497ba 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -314,15 +314,9 @@ fn strikes(records: &[Value], event: &str) -> usize { } /// The write ahead of a send handed to the mouth: the record, its `handed` mark set, durable in her trace before the mouth is called. A record that -/// cannot be written hands nothing over. An unknown already in the record carries its stamp, so a start killed after this write still tells her of it. +/// cannot be written hands nothing over. An unknown already in the record carries its own stamp, so a start killed after this write still tells her of it. fn ahead<'a, C: Chat>(start: &'a Start, key: &'a str) -> impl FnMut(&Value) -> bool + 'a { - move |record| { - let mut record = record.clone(); - if record.get("unknown_sends").is_some() { - record["unknown_at"] = json!((start.clock)().to_rfc3339()); - } - start.trace.record(key, &record).is_ok() - } + move |record| start.trace.record(key, record).is_ok() } fn drain(instance: &Slug, start: &Start) -> Outcome { @@ -438,10 +432,9 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { let recorded_ms = record["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.timestamp_millis()); let age = recorded_ms.map_or(i64::MAX, |at| (now.timestamp_millis() - at) / 1000); let key = record["key"].as_str().unwrap_or_default().to_owned(); - deliver(&mouth, &mut record, if age > OWED_WINDOW_S { Pass::Past } else { Pass::Within }, &mut stalled, &mut ahead(start, &key)); + deliver(&mouth, &mut record, if age > OWED_WINDOW_S { Pass::Past } else { Pass::Within }, now, &mut stalled, &mut ahead(start, &key)); if let Some(unknown) = record["unknown_sends"].as_array() { eprintln!("mind-persona: {} owed send(s) got no answer within the time a repeat is safe, so whether they went out is unknown, and she is told at her next real turn: {unknown:?}", unknown.len()); - record["unknown_at"] = json!(now.to_rfc3339()); } if let Err(fault) = start.trace.record(record["key"].as_str().unwrap_or_default(), &record) { // The send stays owed in her trace, so the poll would start her again at every poll: the start fails as an outage, and the @@ -522,12 +515,13 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { Err((fresh, why)) => { put_refusals += 1; turn.record["put_refused"] = json!(why); + turn.record["put_refused_at"] = json!((start.clock)().to_rfc3339()); eprintln!("mind-persona: the put of turn {key} was refused twice: {why}"); state = fresh; } } } - deliver(&mouth, &mut turn.record, Pass::Within, &mut stalled, &mut ahead(start, &record_key)); + deliver(&mouth, &mut turn.record, Pass::Within, (start.clock)(), &mut stalled, &mut ahead(start, &record_key)); if turn.record.get("failed").is_none() && let Err(fault) = start.trace.record(&record_key, &turn.record) { diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 2cafcdd..8e08ed4 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -71,6 +71,8 @@ struct FakeMouth { 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. @@ -84,6 +86,9 @@ 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 { + 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() { @@ -262,7 +267,7 @@ 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), 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(), log: log.clone() }); + 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() } @@ -873,6 +878,69 @@ impl Model for Never { static VARIED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// Soul s9 not-sent-past-window-untold. A send never handed over (the homeserver down before every PUT in its room) reaches the window while she has +/// later turns elsewhere: it is refused as not sent, on its old record, and her words are in the prompt of her next real turn, which is not the last record's. +#[test] +fn t_l3_a_send_not_sent_past_the_window_is_told_at_her_next_real_turn_after_later_turns() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.mouth.not_sent_rooms.borrow_mut().push(room(1)); + rig.run(varying()); + let owed_text = rig.trace.rows.borrow()[0].1["owed"][0]["text"].as_str().unwrap_or_default().to_owned(); + assert!(!owed_text.is_empty()); + rig.mouth.held.borrow_mut().push(line(2, &room(2), META, "over here")); + rig.run(scripted(false)); + rig.ticks.set(rig.ticks.get() + 1800); + rig.run(Never); + assert_eq!(rig.trace.rows.borrow()[0].1["refused_sends"][0]["refusal"], "not_sent_past_the_window"); + rig.mouth.not_sent_rooms.borrow_mut().clear(); + rig.mouth.held.borrow_mut().push(line(3, &room(1), META, "did you get my hello?")); + let prompts = Rc::new(RefCell::new(Vec::new())); + rig.run(Spy { inner: scripted(false), prompts: prompts.clone() }); + assert!(prompts.borrow().iter().any(|prompt| prompt.contains(&owed_text)), "her words are told at her next real turn: {:?}", prompts.borrow()); + // Told once: the turn after has no word of it. + rig.mouth.held.borrow_mut().push(line(4, &room(1), META, "and now?")); + let later = Rc::new(RefCell::new(Vec::new())); + rig.run(Spy { inner: scripted(false), prompts: later.clone() }); + assert!(!later.borrow().iter().any(|prompt| prompt.contains(&owed_text)), "told once: {:?}", later.borrow()); +} + +/// Soul s9 told-unknown-restamped. An unknown that has been told sits in a record that still owes a sibling; paying the sibling rewrites the record and keeps +/// the unknown's first stamp, so it is not told again and its room is not held again. +#[test] +fn t_l3_a_told_unknown_keeps_its_first_stamp_when_its_record_is_rewritten() { + let rig = Rig::new(vec![]); + rig.mouth.vouches_attempted.set(true); + let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap() - Duration::seconds(60); + rig.trace.rows.borrow_mut().push(("n0-t0".into(), json!({ "key": "n0-t0", "room": room(1), "held": [], "owed": [ + { "id": "la:s0", "room": room(1), "text": "ZULU old line", "handed": true }, { "id": "la:s1", "room": room(1), "text": "YANKEE sibling" }], "posted": [], "refused_sends": [], "edited": [], "at": at.to_rfc3339() }))); + rig.run(Never); + let first = rig.trace.rows.borrow()[0].1["unknown_sends"][0]["at"].clone(); + assert!(first.is_string(), "stamped when it went unknown"); + rig.mouth.held.borrow_mut().push(line(1, &room(1), META, "hello")); + let telling = Rc::new(RefCell::new(Vec::new())); + rig.run(Spy { inner: scripted(false), prompts: telling.clone() }); + assert!(telling.borrow().iter().any(|prompt| prompt.contains("ZULU")), "told at her next real turn"); + rig.run(Never); + let rows: Vec = rig.trace.rows.borrow().iter().map(|(_, record)| record.clone()).collect(); + assert_eq!(rows[0]["unknown_sends"][0]["at"], first, "the rewrite that paid the sibling kept the first stamp: {}", rows[0]); + assert!(crate::projection::untold_rooms(&rows).is_empty(), "its room is not held again"); + assert!(texts(&rig, &room(1)).iter().any(|text| text == "YANKEE sibling"), "the sibling was paid"); + rig.mouth.held.borrow_mut().push(line(2, &room(1), META, "are you there?")); + let again = Rc::new(RefCell::new(Vec::new())); + rig.run(Spy { inner: scripted(false), prompts: again.clone() }); + assert!(!again.borrow().iter().any(|prompt| prompt.contains("ZULU")), "told once, not again after the rewrite: {:?}", again.borrow()); +} + +/// Soul s9 ahead-trace-failure-unpinned (mutant S1). A write ahead her trace refuses stops the mouth call: nothing is handed over that her record does not say. +#[test] +fn t_l3_a_write_ahead_her_trace_refuses_stops_the_mouth_call() { + let rig = Rig::new(vec![]); + unhanded_record(&rig, "n0-t0", 60, &[("l1:s0", &room(1), "hello")]); + rig.trace.allow.set(0); + assert!(matches!(rig.run(Never), Outcome::Failed(_)), "the start cannot rewrite its record"); + assert!(rig.mouth.attempts.borrow().is_empty() && rig.mouth.sent.borrow().is_empty(), "no PUT was attempted: {:?}", rig.mouth.attempts.borrow()); +} + /// 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) @@ -1018,7 +1086,7 @@ fn t_l3_a_send_with_no_answer_in_the_window_is_recorded_unknown_stamped_and_not_ let rows = rig.trace.rows.borrow(); let record = &rows[0].1; assert_eq!(record["unknown_sends"][0]["room"], MINDS); - assert!(record["unknown_at"].is_string(), "{record}"); + assert!(record["unknown_sends"][0]["at"].is_string(), "{record}"); assert!(record.get("owed").is_none() && record["posted"] == json!([]) && record["refused_sends"] == json!([]), "{record}"); } assert_eq!(rig.mouth.sent.borrow().len(), 1, "nothing was posted twice"); @@ -1040,7 +1108,7 @@ fn t_l3_words_in_the_room_are_never_a_receipt() { let record = rig.trace.rows.borrow()[0].1.clone(); assert_eq!(record["posted"], json!([]), "{name}: the tail proves nothing: {record}"); assert_eq!(record["unknown_sends"][0]["text"], owed, "{name}: {record}"); - assert!(record["refused_sends"] == json!([]) && record["unknown_at"].is_string(), "{name}: {record}"); + assert!(record["refused_sends"] == json!([]) && record["unknown_sends"][0]["at"].is_string(), "{name}: {record}"); assert!(rig.mouth.sent.borrow().is_empty(), "{name}: past the window nothing is sent"); } } @@ -1252,10 +1320,10 @@ fn t_l3_a_resend_the_mouth_cannot_vouch_for_is_unknown_holds_its_room_and_is_tol rig.run(Never); let rows: Vec = rig.trace.rows.borrow().iter().map(|(_, record)| record.clone()).collect(); assert_eq!(rows[0]["unknown_sends"][0]["text"], "the old line", "{}", rows[0]); - assert!(rows[0].get("owed").is_none() && rows[0]["refused_sends"] == json!([]) && rows[0].get("unknown_at").is_some(), "unknown, neither refused nor owed: {}", rows[0]); + assert!(rows[0].get("owed").is_none() && rows[0]["refused_sends"] == json!([]) && rows[0]["unknown_sends"][0].get("at").is_some(), "unknown, neither refused nor owed: {}", rows[0]); assert_eq!(rig.mouth.attempts.borrow().len(), 1, "the newer line was not tried in the held room: {:?}", rig.mouth.attempts.borrow()); assert!(rows[1]["owed"].as_array().is_some_and(|owed| owed.len() == 1), "it stays owed"); - assert!(crate::projection::history(&rows).last_outcome.is_some_and(|last| last["unknown"][0]["text"] == "the old line"), "she is told"); + assert!(crate::projection::history(&rows).last_outcome.is_some_and(|last| last["untold"][0]["text"] == "the old line"), "she is told"); } /// Soul s8 held-send-never-vouched. A send held back behind another's lost answer was never handed to the mouth, so it is not repeated with `resend`, @@ -1418,5 +1486,5 @@ fn t_l3_a_write_ahead_carries_the_stamp_of_an_unknown_the_record_already_holds() let Outcome::Failed(_) = rig.run(Never) else { panic!("the rewrite cannot land") }; let record = rig.trace.rows.borrow()[0].1.clone(); assert_eq!(record["unknown_sends"][0]["text"], "one", "{record}"); - assert!(record["unknown_at"].is_string(), "the unknown is told even if the start dies here: {record}"); + assert!(record["unknown_sends"][0]["at"].is_string(), "the unknown is told even if the start dies here: {record}"); } diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index 899e26c..c7624de 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -303,11 +303,16 @@ pub(crate) fn outcome_of(record: &Value) -> Option { } let mut outcome = Outcome::default(); let decision = &record["interpreter"]; - // Sends no answer was got for within the homeserver's memory of their ids, since her last real turn: told as lines that may or may not - // have gone out, whatever record they sit in. - for unknown in record["unknown"].as_array().into_iter().flatten() { - if let Some(text) = words_of(&unknown["text"]) { - outcome.parts.push(Part::Unknown { room: words(&unknown["room"]), text }); + // What her trace holds that she has not been told, whatever record holds it (`turn::untold`, the one derivation): a send that may or may not + // have gone out, a send refused or never made, a line set aside, a put refused. No other place tells these. + for item in record["untold"].as_array().into_iter().flatten() { + let room = words(&item["room"]); + match (item["kind"].as_str(), words_of(&item["text"])) { + (Some("unknown"), Some(text)) => outcome.parts.push(Part::Unknown { room, text }), + (Some("unsent"), Some(text)) => outcome.parts.push(Part::Unsent { room, text, reach: false }), + (Some("set_aside"), text) => outcome.parts.push(Part::SetAside { room, line: words(&item["sender"]).zip(text) }), + (Some("not_kept"), _) => outcome.parts.push(Part::NotKept), + _ => outcome.omitted.push(format!("an untold item she cannot be told truly: {item}")), } } let failed = record.get("failed").is_some() || decision.get("failed").is_some(); @@ -319,16 +324,10 @@ pub(crate) fn outcome_of(record: &Value) -> Option { outcome.parts.push(Part::Failed); return Some(outcome); } - // A record the drain wrote when it set lines aside carries no decision: it says only which rooms' lines it left. - for set_aside in record["set_aside"].as_array().into_iter().flatten() { - outcome.parts.push(Part::SetAside { room: words(&set_aside["room"]), line: words(&set_aside["sender"]).zip(words_of(&set_aside["text"])) }); - } + // A record the drain wrote when it set lines aside carries no decision. if record.get("set_aside").is_some() { return Some(outcome); } - if record.get("put_refused").is_some() { - outcome.parts.push(Part::NotKept); - } let room = words(&decision["room"]); // A draft refused as an echo is shown by no row: the echo's line quotes none of it, and a gap naming it quotes nothing. let echoes: Vec<&Value> = decision["refused"].as_array().into_iter().flatten().filter(|refusal| refusal["reason"] == "echo").map(|refusal| &refusal["draft"]).collect(); @@ -345,20 +344,14 @@ pub(crate) fn outcome_of(record: &Value) -> Option { } // The row that tells each draft that did not go out, by its number (K63): a reach naming the draft is a clause of it. let mut rows: Vec<(&Value, usize)> = Vec::new(); - // A said line is told by its receipt; one the actuator refused (T6) by the row of a line that did not go out, which - // `settle` holds to the receipts; one with neither is not told, and reported. - let refused_send = |line: &Value| record["refused_sends"].as_array().into_iter().flatten().any(|refused| refused["room"] == line["room"] && refused["text"] == line["text"]); - // A line whose send is unknown is told by `unknown`, from the record that settled it; its own record shows no receipt and no refusal. - let unknown_send = |line: &Value| record["unknown_sends"].as_array().into_iter().flatten().any(|sent| sent["room"] == line["room"] && sent["text"] == line["text"]); + // A said line is told by its receipt; one the actuator refused (T6) or left unknown by `untold`, from the record that settled it; one with + // none of these is not told, and reported. + let settled_send = |line: &Value| ["refused_sends", "unknown_sends"].iter().any(|field| record[*field].as_array().into_iter().flatten().any(|sent| sent["room"] == line["room"] && sent["text"] == line["text"])); for line in decision["said"].as_array().into_iter().flatten() { let went = receipts.iter().any(|posted| Some(posted.room.as_str()) == line["room"].as_str() && Some(posted.text.as_str()) == line["text"].as_str()); match (went, words_of(&line["text"])) { (true, _) => {} - (false, Some(text)) if refused_send(line) => { - rows.push((&line["rests_on"]["draft"], outcome.parts.len())); - outcome.parts.push(Part::Unsent { room: words(&line["room"]), text, reach: false }); - } - (false, _) if unknown_send(line) => {} + (false, _) if settled_send(line) => {} (false, _) => outcome.omitted.push(format!("a line said with no receipt that it went out: {}", line["text"])), } } @@ -427,7 +420,7 @@ pub(crate) fn outcome_of(record: &Value) -> Option { }; // A reach in a line the decision said and no receipt shows went out: whether it reached the room is unknown, so // she is told neither that nothing happened nor that it did (I16.10), as the line itself is not told. - let unreceipted = |text: &str| decision["said"].as_array().into_iter().flatten().any(|line| line["text"].as_str() == Some(text) && !refused_send(line)); + let unreceipted = |text: &str| decision["said"].as_array().into_iter().flatten().any(|line| line["text"].as_str() == Some(text)); match (quote, sent) { (_, Some(at)) => { unbacked.push(at); diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs index 8b05a94..8ed4d58 100644 --- a/crates/mind-body/src/projection/turn.rs +++ b/crates/mind-body/src/projection/turn.rs @@ -100,7 +100,7 @@ pub(crate) struct Taken { /// 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, Pass::Within, &mut BTreeSet::new(), &mut |_| true); + deliver(actuator, &mut taken.record, Pass::Within, now, &mut BTreeSet::new(), &mut |_| true); taken } @@ -171,20 +171,21 @@ fn unmark(send: &mut Value) { /// `Pass::Past` (the record is older than the homeserver remembers an id) makes no send: each send handed over is recorded in `unknown_sends`, neither /// posted nor refused, and she is told it may or may not have gone out; each not handed over is refused as not sent, which is all that is known. `stalled` /// holds the rooms whose earlier send got no answer, was not sent or went unknown in this start: nothing is sent into them after it, so her lines never -/// arrive out of order and none goes in before she is told, and a send held back stays owed. -pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, pass: Pass, stalled: &mut BTreeSet, ahead: &mut dyn FnMut(&Value) -> bool) { +/// arrive out of order and none goes in before she is told, and a send held back stays owed. Each send this call settles unknown or refused is +/// stamped `at: now`, once: the stamp is what says whether she has been told (`untold`), and a record rewritten later keeps it. +pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, pass: Pass, now: DateTime, stalled: &mut BTreeSet, ahead: &mut dyn FnMut(&Value) -> bool) { let owed: Vec = record["owed"].as_array().cloned().unwrap_or_default(); let mut still = Vec::new(); for (index, mut send) in owed.iter().cloned().enumerate() { let (room, text) = (send["room"].as_str().unwrap_or_default().to_owned(), send["text"].as_str().unwrap_or_default().to_owned()); let reply = send["in_reply_to"].as_str().map(str::to_owned); let refusal = |why: &str| match reply.as_deref() { - Some(event) => json!({ "room": room, "text": text, "in_reply_to": event, "refusal": why }), - None => json!({ "room": room, "text": text, "refusal": why }), + Some(event) => json!({ "room": room, "text": text, "in_reply_to": event, "refusal": why, "at": now.to_rfc3339() }), + None => json!({ "room": room, "text": text, "refusal": why, "at": now.to_rfc3339() }), }; let mentions: Vec = send["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); let unknown_send = |record: &mut Value, stalled: &mut BTreeSet| { - let unknown = json!({ "room": room, "text": text }); + let unknown = json!({ "room": room, "text": text, "at": now.to_rfc3339() }); match record["unknown_sends"].as_array_mut() { Some(unknowns) => unknowns.push(unknown), None => record["unknown_sends"] = json!([unknown]), @@ -302,25 +303,33 @@ pub(crate) fn owes(records: &[Value]) -> bool { records.iter().any(owes_send) } -/// The sends her trace shows unknown (`unknown_sends`) that no real turn of hers has followed since: each a `{room, text}`, told once, at her -/// next real turn. A record is rewritten when its sends are settled, so it is told by when it was (`unknown_at`), not by where it sits in the -/// trace. A real turn is a record that decided something: a failed turn, a record that only set lines aside and a rewrite that settled a -/// send are none. -fn unknown(records: &[Value]) -> Vec { - let at = |record: &Value, field: &str| record[field].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()); - let last_wake = records.iter().filter(|record| record.get("failed").is_none() && record.get("set_aside").is_none()).filter_map(|record| at(record, "at")).max(); +/// What her trace holds that she has not been told, from whichever record holds it: each send unknown (`unknown_sends`) or refused +/// (`refused_sends`), each line set aside and each put refused, as `{kind, ..}` rows. The one derivation of it. An item is told at her next +/// real turn, once: it carries the stamp it was given when it was made (`at`, set once and kept when the record is rewritten), and it is +/// untold while no real turn of hers has started after it. A real turn is a record that decided something: a failed turn and a record that only +/// set lines aside are none, and a rewrite keeps its `at`, so where a record sits in the trace decides nothing. +fn untold(records: &[Value]) -> Vec { + let at = |stamp: &Value| stamp.as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()); + let last_start = records.iter().filter(|record| record.get("failed").is_none() && record.get("set_aside").is_none()).filter_map(|record| at(&record["at"])).max(); + let fresh = |stamp: &Value| at(stamp).is_some_and(|made| last_start.is_none_or(|start| start <= made)); let mut told = Vec::new(); for record in records.iter().filter(|record| record.get("failed").is_none()) { - if at(record, "unknown_at").is_some_and(|gave| last_wake.is_none_or(|wake| wake < gave)) { - told.extend(record["unknown_sends"].as_array().into_iter().flatten().map(|sent| json!({ "room": sent["room"], "text": sent["text"] }))); + for (kind, field) in [("unknown", "unknown_sends"), ("unsent", "refused_sends")] { + told.extend(record[field].as_array().into_iter().flatten().filter(|sent| fresh(&sent["at"])).map(|sent| json!({ "kind": kind, "room": sent["room"], "text": sent["text"] }))); + } + if fresh(&record["at"]) { + told.extend(record["set_aside"].as_array().into_iter().flatten().map(|line| json!({ "kind": "set_aside", "room": line["room"], "sender": line["sender"], "text": line["text"] }))); + } + if record.get("put_refused").is_some() && fresh(&record["put_refused_at"]) { + told.push(json!({ "kind": "not_kept" })); } } told } -/// The rooms of the sends her trace shows unknown and not yet told (`unknown`): no newer line goes into them until a real turn of hers has told her. +/// The rooms of the sends her trace shows unknown and not yet told (`untold`): no newer line goes into them until a real turn of hers has told her. pub(crate) fn untold_rooms(records: &[Value]) -> BTreeSet { - unknown(records).iter().filter_map(|sent| sent["room"].as_str().map(str::to_owned)).collect() + untold(records).iter().filter(|item| item["kind"] == "unknown").filter_map(|item| item["room"].as_str().map(str::to_owned)).collect() } /// Her `records`, oldest first, read. @@ -331,9 +340,9 @@ pub(crate) fn history(records: &[Value]) -> Past { recent.drain(..recent.len().saturating_sub(RECENT)); Past { last_outcome: records.last().cloned().map(|mut last| { - let unknown = unknown(records); - if !unknown.is_empty() { - last["unknown"] = json!(unknown); + let untold = untold(records); + if !untold.is_empty() { + last["untold"] = json!(untold); } last }), diff --git a/crates/mind-body/src/projection/turn/tests.rs b/crates/mind-body/src/projection/turn/tests.rs index 27c317c..d4d6b20 100644 --- a/crates/mind-body/src/projection/turn/tests.rs +++ b/crates/mind-body/src/projection/turn/tests.rs @@ -69,7 +69,7 @@ fn warm_turn_ahead(actuator: &dyn Actuator, ahead: &mut dyn FnMut(&Value) -> boo let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None }; let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter); let mut taken = decide(&organs, &request, "run-t1", fixture.now); - deliver(actuator, &mut taken.record, Pass::Within, &mut BTreeSet::new(), ahead); + deliver(actuator, &mut taken.record, Pass::Within, Utc::now(), &mut BTreeSet::new(), ahead); taken } @@ -219,8 +219,8 @@ fn t_l2_a_line_is_decided_by_the_record_that_holds_it() { #[test] fn t_l3_an_unknown_send_is_told_at_her_next_real_turn_and_once() { let wake = |at: &str| json!({ "held": ["$e9"], "posted": [], "refused_sends": [], "interpreter": { "said": [] }, "at": at }); - let unknown = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "unknown_sends": [{ "room": "#minds", "text": "welcome aboard" }], "at": "2026-11-28T00:00:00Z", "unknown_at": "2026-11-28T02:00:00Z" }); - let told_at = |records: Vec| history(&records).last_outcome.map(|last| (last.get("unknown").cloned(), outcome_of(&last).expect("an outcome").lines(forms(&json!({}))))); + let unknown = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "unknown_sends": [{ "room": "#minds", "text": "welcome aboard", "at": "2026-11-28T02:00:00Z" }], "at": "2026-11-28T00:00:00Z" }); + let told_at = |records: Vec| history(&records).last_outcome.map(|last| (last.get("untold").cloned(), outcome_of(&last).expect("an outcome").lines(forms(&json!({}))))); let (list, told) = told_at(vec![unknown.clone(), wake("2026-11-28T00:30:00Z")]).expect("her last record"); assert!(list.is_some() && told.iter().any(|line| line.contains("welcome aboard") && line.contains("may or may not have gone out")), "{told:?}"); assert!(!told.iter().any(|line| line.contains("did not go out")), "never told as unsent: {told:?}"); @@ -232,6 +232,35 @@ fn t_l3_an_unknown_send_is_told_at_her_next_real_turn_and_once() { assert!(list.is_none(), "a real turn after it has told it"); } +/// Everything her trace holds that she has not been told is told at her next real turn, once, whichever record holds it: an unknown send, a send +/// refused or never made, a line set aside, a put refused. Each carries the stamp it was made with; a real turn that started after the stamp has +/// told it, whatever the record's place in the trace, and a real turn that started before it has not. +#[test] +fn t_l3_every_untold_item_is_told_at_her_next_real_turn_once_from_whichever_record_holds_it() { + let wake = |at: &str| json!({ "held": ["$w"], "posted": [], "refused_sends": [], "interpreter": { "said": [] }, "at": at }); + let sent = |text: &str, stamp: &str| json!({ "room": "#a", "text": text, "refusal": "not_sent_past_the_window", "at": stamp }); + // One old record, rewritten after her later turns, holds an unknown, a refusal and a put refused, each stamped when it was made; a + // record that set a line aside was written at 03:00. + let old = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "at": "2026-11-28T00:00:00Z", + "unknown_sends": [{ "room": "#a", "text": "ZULU unknown", "at": "2026-11-28T01:00:00Z" }], "refused_sends": [sent("YANKEE refused", "2026-11-28T01:00:00Z")], "put_refused": "stale", "put_refused_at": "2026-11-28T01:00:00Z" }); + let aside = json!({ "set_aside": [{ "room": "#a", "event": "$s", "sender": "Nibu", "text": "XRAY aside" }], "at": "2026-11-28T03:00:00Z" }); + let told = |records: Vec| history(&records).last_outcome.map(|last| outcome_of(&last).expect("an outcome").lines(forms(&json!({})))).unwrap_or_default().join(" +"); + // Later turns of hers started before the stamps: the old record is not her last, and all four are still to be told. + let said = told(vec![old.clone(), wake("2026-11-28T00:30:00Z"), aside.clone(), wake("2026-11-28T00:40:00Z")]); + for word in ["ZULU", "YANKEE", "XRAY"] { + assert!(said.contains(word), "{word} is told at her next real turn though its record is not her last: {said}"); + } + assert!(said.contains("not kept") || said.lines().count() >= 4, "{said}"); + // A real turn that started after every stamp has told them all, and tells nothing again. + let after = told(vec![old.clone(), wake("2026-11-28T00:30:00Z"), aside, wake("2026-11-28T04:00:00Z")]); + for word in ["ZULU", "YANKEE", "XRAY"] { + assert!(!after.contains(word), "{word} was told once: {after}"); + } + // A rewrite keeps the stamp it was given: the record is rewritten after her turn at 04:00, and nothing is told again. + assert!(untold_rooms(&[old, wake("2026-11-28T04:00:00Z")]).is_empty(), "a told unknown does not hold its room again"); +} + /// A trace that holds an owed send says so; a failed record's owed send and a settled one are not owed. #[test] fn t_l3_a_trace_owes_a_send_only_while_a_record_holds_it_owed() { @@ -252,7 +281,7 @@ fn t_l3_an_owed_record_decides_its_lines_and_owes_them_to_the_ack() { /// not also reported as a said line with nothing to show it went out. #[test] fn t_l3_an_unknown_sends_own_record_reports_no_line_missing_its_receipt() { - let record = json!({ "held": ["$e1"], "posted": [], "refused_sends": [], "unknown_sends": [{ "room": "#minds", "text": "welcome aboard" }], "interpreter": { "said": [{ "room": "#minds", "text": "welcome aboard" }] }, "at": "2026-11-28T00:00:00Z", "unknown_at": "2026-11-28T02:00:00Z" }); + let record = json!({ "held": ["$e1"], "posted": [], "refused_sends": [], "unknown_sends": [{ "room": "#minds", "text": "welcome aboard", "at": "2026-11-28T02:00:00Z" }], "interpreter": { "said": [{ "room": "#minds", "text": "welcome aboard" }] }, "at": "2026-11-28T00:00:00Z" }); let outcome = outcome_of(&record).expect("an outcome"); assert!(outcome.omitted.is_empty(), "{:?}", outcome.omitted); } @@ -300,7 +329,7 @@ fn t_l3_every_refusal_kind_is_placed_for_a_first_send_and_for_a_repeat() { let handed = FakeChat::new(Some(Refusal::SendFailed)); taken = warm_turn(&mouth(&handed)); let again = FakeChat::new(Some(refusal)); - deliver(&mouth(&again), &mut taken.record, Pass::Within, &mut BTreeSet::new(), &mut |_| true); + deliver(&mouth(&again), &mut taken.record, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| true); assert_eq!(again.sent.borrow().iter().map(|request| request.resend).collect::>(), [true], "{}: a repeat says resend", refusal.name()); assert_eq!(settled(&taken.record), repeat, "{} to a repeat: {}", refusal.name(), taken.record); } @@ -322,7 +351,7 @@ fn t_l3_a_send_never_handed_over_goes_out_as_a_first_send_and_only_a_handed_one_ assert!(writes[0]["owed"][0]["handed"] == true && writes[0]["posted"] == json!([]), "the mark is durable before the mouth is called: {}", writes[0]); let id = first.sent.borrow()[0].request_id.clone(); let again = FakeChat::new(None); - deliver(&mouth(&again), &mut taken.record, Pass::Within, &mut BTreeSet::new(), &mut |_| panic!("a repeat is already marked, and writes nothing ahead")); + deliver(&mouth(&again), &mut taken.record, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| panic!("a repeat is already marked, and writes nothing ahead")); assert_eq!(again.sent.borrow().iter().map(|request| (request.request_id.clone(), request.resend)).collect::>(), [(id.clone(), true)], "the repeat is under the recorded id and says so"); assert!(taken.record.get("owed").is_none() && taken.record["posted"][0]["event"] == "$sent-1", "{}", taken.record); @@ -330,7 +359,7 @@ fn t_l3_a_send_never_handed_over_goes_out_as_a_first_send_and_only_a_handed_one_ let never = FakeChat::new(None); let mut record = json!({ "owed": [{ "id": id, "room": "!a:b", "text": "hi" }], "posted": [], "refused_sends": [], "edited": [] }); let mut marked = 0; - deliver(&mouth(&never), &mut record, Pass::Within, &mut BTreeSet::new(), &mut |_| { + deliver(&mouth(&never), &mut record, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| { marked += 1; true }); @@ -342,7 +371,7 @@ fn t_l3_a_send_never_handed_over_goes_out_as_a_first_send_and_only_a_handed_one_ let silent = FakeChat::new(None); let mut record = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "one" }, { "id": "k:s1", "room": "!a:b", "text": "two" }], "posted": [], "refused_sends": [], "edited": [] }); let mut stalled = BTreeSet::new(); - deliver(&mouth(&silent), &mut record, Pass::Within, &mut stalled, &mut |_| false); + deliver(&mouth(&silent), &mut record, Pass::Within, Utc::now(), &mut stalled, &mut |_| false); assert!(silent.sent.borrow().is_empty() && stalled.contains("!a:b"), "a send whose mark cannot be written is not made"); assert_eq!(record["owed"].as_array().map(Vec::len), Some(2)); assert!(record["owed"].as_array().unwrap().iter().all(|send| send.get("handed").is_none()), "{record}"); @@ -355,10 +384,10 @@ fn t_l3_an_answer_with_neither_event_nor_refusal_is_refused_for_a_first_send_and let mut chat = FakeChat::new(None); chat.bare = true; let mut first = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "one" }], "posted": [], "refused_sends": [], "edited": [] }); - deliver(&mouth(&chat), &mut first, Pass::Within, &mut BTreeSet::new(), &mut |_| true); + deliver(&mouth(&chat), &mut first, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| true); assert_eq!(settled(&first), "refused", "{first}"); let mut repeat = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "one", "handed": true }], "posted": [], "refused_sends": [], "edited": [] }); - deliver(&mouth(&chat), &mut repeat, Pass::Within, &mut BTreeSet::new(), &mut |_| true); + deliver(&mouth(&chat), &mut repeat, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| true); assert_eq!(settled(&repeat), "unknown", "{repeat}"); } @@ -368,7 +397,7 @@ fn t_l3_an_answer_with_neither_event_nor_refusal_is_refused_for_a_first_send_and fn t_l3_past_the_window_a_handed_send_is_unknown_and_one_never_handed_is_refused_as_not_sent() { let chat = FakeChat::new(None); let mut record = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "handed", "handed": true }, { "id": "k:s1", "room": "!c:d", "text": "never" }], "posted": [], "refused_sends": [], "edited": [] }); - deliver(&mouth(&chat), &mut record, Pass::Past, &mut BTreeSet::new(), &mut |_| true); + deliver(&mouth(&chat), &mut record, Pass::Past, Utc::now(), &mut BTreeSet::new(), &mut |_| true); assert!(chat.sent.borrow().is_empty(), "nothing is made past the window"); assert_eq!(record["unknown_sends"], json!([{ "room": "!a:b", "text": "handed" }])); assert_eq!(record["refused_sends"][0]["refusal"], "not_sent_past_the_window");