persona drain: a send is written ahead as handed over; one never handed over goes out as a first send; NotSent clears the mark; a refused resend is unknown

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 05:48:03 +01:00
commit 0c06eaf31e
5 changed files with 315 additions and 64 deletions

View file

@ -507,7 +507,10 @@ pub enum Refusal {
PersonaMismatch,
UnknownRoom,
EmptyText,
/// The PUT was attempted and not answered (timed out, 5xx, 429): the event may exist.
SendFailed,
/// The mouth attempted no PUT (its start, a room join or a head read failed first): the send is certainly not posted.
NotSent,
UnknownPersona,
/// A send with a basis found the room had moved past it: the receipt names what moved it.
RoomMoved,
@ -519,6 +522,9 @@ pub enum Refusal {
}
impl Refusal {
/// Every kind the mouth names.
pub const ALL: [Self; 10] = [Self::Brake, Self::PersonaMismatch, Self::UnknownRoom, Self::EmptyText, Self::SendFailed, Self::NotSent, Self::UnknownPersona, Self::RoomMoved, Self::ResendUnknown, Self::UnknownKind];
/// The mouth's spelling: a MessagePack string, whatever the codec does with unit variants.
pub fn name(self) -> &'static str {
match self {
@ -527,6 +533,7 @@ impl Refusal {
Self::UnknownRoom => "UnknownRoom",
Self::EmptyText => "EmptyText",
Self::SendFailed => "SendFailed",
Self::NotSent => "NotSent",
Self::UnknownPersona => "UnknownPersona",
Self::RoomMoved => "RoomMoved",
Self::ResendUnknown => "ResendUnknown",
@ -536,16 +543,21 @@ impl Refusal {
}
impl Refusal {
/// What the mouth's refusal says of a send, which a settled send needs: the mouth declined before it put anything (`Declined`), it got no answer from
/// the homeserver so the event may exist and the send is repeated (`NoAnswer`), or it cannot say whether an earlier try posted and the send is
/// never repeated (`Unknown`). The match names every kind, so a new one has to be placed.
pub(crate) fn reading(self) -> Reading {
/// What the mouth's refusal says of a send, which a settled send needs, by whether the send is a repeat of one already handed to the mouth (`resend`). It
/// says the homeserver was not heard, so the event may exist and the send stays owed (`NoAnswer`); that the mouth attempted no PUT, so the send is certainly
/// not posted and goes out as a first send later (`NotSent`); that an earlier try's outcome cannot be told, so the send is never repeated (`Unknown`); or that the
/// mouth declined before it put anything (`Declined`), which for a repeat says nothing of the earlier try, whose outcome stays unknown. The match
/// names every kind, so a new one has to be placed.
pub(crate) fn reading(self, resend: bool) -> Reading {
match self {
// The mouth's PUT timed out or the homeserver answered 5xx or 429: the event may have been persisted, and the same id is safe to repeat.
Self::SendFailed => Reading::NoAnswer,
// The mouth made no PUT: nothing can have been posted.
Self::NotSent => Reading::NotSent,
// A resend the mouth does not remember attempting: the first try may have posted, and the id can no longer be told from a new line.
Self::ResendUnknown => Reading::Unknown,
// `RoomMoved` cannot answer a resend, which skips the basis check.
// The mouth's checks that come before its vouch for a resend, and `RoomMoved`, which a resend skips.
Self::Brake | Self::PersonaMismatch | Self::UnknownRoom | Self::EmptyText | Self::UnknownPersona | Self::RoomMoved | Self::UnknownKind if resend => Reading::Unknown,
Self::Brake | Self::PersonaMismatch | Self::UnknownRoom | Self::EmptyText | Self::UnknownPersona | Self::RoomMoved | Self::UnknownKind => Reading::Declined,
}
}
@ -556,6 +568,7 @@ impl Refusal {
pub(crate) enum Reading {
Declined,
NoAnswer,
NotSent,
Unknown,
}
@ -568,7 +581,7 @@ impl Serialize for Refusal {
impl<'de> Deserialize<'de> for Refusal {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let name = String::deserialize(deserializer)?;
[Self::Brake, Self::PersonaMismatch, Self::UnknownRoom, Self::EmptyText, Self::SendFailed, Self::UnknownPersona, Self::RoomMoved, Self::ResendUnknown, Self::UnknownKind]
Self::ALL
.into_iter()
.find(|refusal| refusal.name() == name)
.ok_or_else(|| serde::de::Error::custom("the mouth named a refusal this side does not know"))

View file

@ -13,8 +13,10 @@
//! 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
//! that cannot be written sends nothing. So is each send's `handed` mark, written just before the mouth is called: the trace says exactly which sends the
//! mouth may have attempted. The receipts rewrite the same record. A send handed over whose answer never came stays owed, and the next
//! start repeats it as recorded, under the recorded id (`resend`), without asking the model; one never handed over (held back in a stalled room, a start
//! killed before its first send, a mouth that attempted nothing) goes out as a first send, with its basis check. One handed over and owed longer than the homeserver remembers
//! a transaction (`OWED_WINDOW_S`) is recorded in `unknown_sends` instead of risking a second post, and she is told it may or may not have gone
//! out. The only receipt is the mouth's answer to a send, an event id; words in a room's tail prove nothing. A send that got no answer holds back
//! every later send into its room for the rest of the start. Her record is appended after the put, refused or not.
@ -311,6 +313,18 @@ fn strikes(records: &[Value], event: &str) -> usize {
records.iter().filter(|record| record["strike"] == event).count()
}
/// 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.
fn ahead<'a, C: Chat>(start: &'a Start<C>, 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()
}
}
fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
let began = (start.clock)();
let began_ms = u64::try_from(began.timestamp_millis()).unwrap_or_default();
@ -423,7 +437,8 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
let now = (start.clock)();
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);
deliver(&mouth, &mut record, if age > OWED_WINDOW_S { Pass::Past } else { Pass::Retry }, &mut stalled);
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));
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());
@ -512,7 +527,7 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
}
}
}
deliver(&mouth, &mut turn.record, Pass::First, &mut stalled);
deliver(&mouth, &mut turn.record, Pass::Within, &mut stalled, &mut ahead(start, &record_key));
if turn.record.get("failed").is_none()
&& let Err(fault) = start.trace.record(&record_key, &turn.record)
{

View file

@ -69,6 +69,10 @@ struct FakeMouth {
answer_lost: Cell<bool>,
/// The mouth answers every resend `ResendUnknown`: it does not remember the id.
resend_unknown: Cell<bool>,
/// 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<bool>,
/// The mouth answers every send with this refusal.
refuse: Cell<Option<crate::chat_client::Refusal>>,
/// Every id a send came under, retries and deduped ones included.
attempts: RefCell<Vec<String>>,
log: Log,
@ -80,8 +84,12 @@ impl Chat for Rc<FakeMouth> {
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<ChatSendReceipt> {
let attempted = self.txn.borrow().contains_key(&request.request_id) || self.down.borrow().contains(&request.room_alias) && self.attempts.borrow().contains(&request.request_id);
self.attempts.borrow_mut().push(request.request_id.clone());
if request.resend && self.resend_unknown.get() {
if let Some(refusal) = self.refuse.get() {
return Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: None, refusal: Some(refusal), newer: vec![] });
}
if request.resend && (self.resend_unknown.get() || self.vouches_attempted.get() && !attempted) {
return Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: None, refusal: Some(crate::chat_client::Refusal::ResendUnknown), newer: vec![] });
}
if self.down.borrow().contains(&request.room_alias) {
@ -254,7 +262,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), 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(), 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() }
@ -1162,10 +1170,20 @@ fn t_l3_the_snapshot_reader_creates_no_lock_file() {
assert!(TraceSnapshot::new(dir.path().join("absent.cc")).records().unwrap().is_empty());
}
/// A record of hers as written ahead, owing `sends` (id, room, text), `age_s` seconds before the rig's clock begins.
/// A record of hers owing `sends` (id, room, text), each handed to the mouth, `age_s` seconds before the rig's clock begins: what an attempt whose answer
/// did not come leaves.
fn owing_record(rig: &Rig, key: &str, age_s: i64, sends: &[(&str, &str, &str)]) {
owing_record_as(rig, key, age_s, sends, true);
}
/// The same record as written ahead, with no send yet handed to the mouth: what a start killed before its first send leaves.
fn unhanded_record(rig: &Rig, key: &str, age_s: i64, sends: &[(&str, &str, &str)]) {
owing_record_as(rig, key, age_s, sends, false);
}
fn owing_record_as(rig: &Rig, key: &str, age_s: i64, sends: &[(&str, &str, &str)], handed: bool) {
let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap() - Duration::seconds(age_s);
let owed: Vec<Value> = sends.iter().map(|(id, room, text)| json!({ "id": id, "room": room, "text": text })).collect();
let owed: Vec<Value> = sends.iter().map(|(id, room, text)| if handed { json!({ "id": id, "room": room, "text": text, "handed": true }) } else { json!({ "id": id, "room": room, "text": text }) }).collect();
rig.trace.rows.borrow_mut().push((key.into(), json!({ "key": key, "room": sends[0].1, "held": [], "owed": owed, "posted": [], "refused_sends": [], "edited": [], "at": at.to_rfc3339() })));
}
@ -1239,3 +1257,98 @@ fn t_l3_a_resend_the_mouth_cannot_vouch_for_is_unknown_holds_its_room_and_is_tol
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");
}
/// 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`,
/// which the mouth vouches for only for an id it reached the PUT with: it goes out as a first send, with its basis, and so does one whose start was killed
/// before its first send. Only the send handed over is repeated. Her later replies in the room go out, none turning unknown behind it.
#[test]
fn t_l3_a_send_never_handed_over_goes_out_as_a_first_send_and_every_later_reply_posts() {
let rig = Rig::new(vec![]);
rig.mouth.vouches_attempted.set(true);
// Her two-line answer: the first send was handed over and its answer lost (the homeserver has it), the second was held back in the stalled room.
rig.trace.rows.borrow_mut().push(("n0-t0".into(), json!({ "key": "n0-t0", "room": room(1), "held": [], "owed": [
{ "id": "l1:s0", "room": room(1), "text": "one", "handed": true }, { "id": "l1:s1", "room": room(1), "text": "two" }], "posted": [], "refused_sends": [], "edited": [],
"at": (Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap() - Duration::seconds(30)).to_rfc3339() })));
rig.mouth.txn.borrow_mut().insert("l1:s0".into(), "$ev-0".into());
// And a start killed before its first send, in another room.
unhanded_record(&rig, "n1-t0", 20, &[("l2:s0", &room(2), "killed before it went")]);
rig.run(Never);
let rows: Vec<Value> = rig.trace.rows.borrow().iter().map(|(_, record)| record.clone()).collect();
assert!(rows.iter().all(|record| record.get("unknown_sends").is_none() && record["refused_sends"] == json!([]) && record.get("owed").is_none()), "all settled, none unknown: {rows:?}");
assert_eq!(rows[0]["posted"].as_array().map(Vec::len), Some(2), "{}", rows[0]);
let requests = rig.mouth.sent.borrow();
assert_eq!(requests.iter().map(|request| (request.request_id.as_str(), request.resend, request.basis.is_some())).collect::<Vec<_>>(), [("l1:s1", false, true), ("l2:s0", false, true)], "the unhanded sends went out as first sends with their basis, and the handed one was answered with the original event");
drop(requests);
// Her later replies in the room: each posts.
for turn in 0..2 {
rig.mouth.held.borrow_mut().push(line(turn + 1, &room(1), META, "next"));
rig.run(scripted(false));
}
assert_eq!(texts(&rig, &room(1)).len(), 3, "the held reply and each later one: {:?}", texts(&rig, &room(1)));
assert!(rig.trace.rows.borrow().iter().all(|(_, record)| record.get("unknown_sends").is_none()), "no reply turned unknown");
}
/// The mark is written ahead of the attempt: the trace holds the send handed over before the mouth is called, so a start killed after the call repeats it
/// as a resend, which the mouth vouches for. Without the write the send could not be told from one never attempted.
#[test]
fn t_l3_the_mark_is_in_her_trace_before_the_mouth_is_called_and_a_killed_start_repeats_as_a_resend() {
let rig = Rig::new(vec![]);
rig.mouth.vouches_attempted.set(true);
unhanded_record(&rig, "n0-t0", 20, &[("l1:s0", &room(1), "hello")]);
// One write lands (the mark), then the trace takes no more, as a process killed after the mouth was called: the rewrite after the send never lands.
rig.trace.allow.set(1);
rig.log.borrow_mut().clear();
let Outcome::Failed(_) = rig.run(Never) else { panic!("the rewrite after the send cannot land") };
assert_eq!(rig.log(), ["trace", "send"], "the mark landed, then the mouth was called");
assert_eq!(rig.trace.rows.borrow()[0].1["owed"][0]["handed"], true);
rig.trace.allow.set(usize::MAX);
rig.run(Never);
let requests = rig.mouth.sent.borrow();
assert_eq!(requests.len(), 1, "posted once: the repeat is answered with the original event");
assert!(rig.trace.rows.borrow()[0].1["unknown_sends"].is_null(), "{}", rig.trace.rows.borrow()[0].1);
assert_eq!(rig.mouth.attempts.borrow().len(), 2);
assert!(rig.trace.rows.borrow()[0].1["posted"][0]["event"].is_string());
}
/// Soul s8 sendfailed-before-put-unvouched. A mouth that attempted no PUT (`NotSent`) says the send is certainly not posted: the mark is cleared, the room held,
/// the send stays owed, and it goes out later as a first send, which a mouth that vouches only for what it attempted accepts.
#[test]
fn t_l3_a_send_the_mouth_attempted_nothing_for_goes_out_later_as_a_first_send() {
let rig = Rig::new(vec![]);
rig.mouth.vouches_attempted.set(true);
unhanded_record(&rig, "n0-t0", 20, &[("l1:s0", &room(1), "hello"), ("l1:s1", &room(1), "and more")]);
rig.mouth.refuse.set(Some(crate::chat_client::Refusal::NotSent));
rig.run(Never);
{
let rows = rig.trace.rows.borrow();
let owed = rows[0].1["owed"].as_array().expect("still owed");
assert_eq!(owed.len(), 2, "both stay owed");
assert!(owed.iter().all(|send| send.get("handed").is_none()), "not handed over: {}", rows[0].1);
assert!(rows[0].1.get("unknown_sends").is_none() && rows[0].1["refused_sends"] == json!([]), "neither unknown nor refused");
}
assert_eq!(rig.mouth.attempts.borrow().len(), 1, "the room is held after it: the second send is not tried");
rig.mouth.refuse.set(None);
rig.run(Never);
let rows = rig.trace.rows.borrow();
assert!(rows[0].1.get("owed").is_none() && rows[0].1.get("unknown_sends").is_none(), "{}", rows[0].1);
assert_eq!(rig.mouth.sent.borrow().iter().map(|request| (request.request_id.as_str(), request.resend)).collect::<Vec<_>>(), [("l1:s0", false), ("l1:s1", false)], "both posted as first sends, in order");
}
/// Soul s8 declined-on-resend-told-unsent. A refusal answered to a repeat of a send that was handed over says nothing of the earlier try, which may have
/// posted: it is recorded unknown and she is told so, never that it did not go out. A refusal to a first send stays a refusal.
#[test]
fn t_l3_a_refusal_answered_to_a_resend_is_unknown_and_told_and_to_a_first_send_is_a_refusal() {
for refusal in [crate::chat_client::Refusal::Brake, crate::chat_client::Refusal::UnknownRoom, crate::chat_client::Refusal::PersonaMismatch, crate::chat_client::Refusal::EmptyText, crate::chat_client::Refusal::RoomMoved] {
let rig = Rig::new(vec![]);
owing_record(&rig, "n0-t0", 20, &[("l1:s0", &room(1), "handed over")]);
unhanded_record(&rig, "n1-t0", 10, &[("l2:s0", &room(2), "never handed")]);
rig.mouth.refuse.set(Some(refusal));
rig.run(Never);
let rows: Vec<Value> = rig.trace.rows.borrow().iter().map(|(_, record)| record.clone()).collect();
assert_eq!(rows[0]["unknown_sends"][0]["text"], "handed over", "{}: {}", refusal.name(), rows[0]);
assert!(rows[0]["refused_sends"] == json!([]) && rows[0].get("owed").is_none(), "{}: not told as unsent: {}", refusal.name(), rows[0]);
assert_eq!(rows[1]["refused_sends"][0]["refusal"], refusal.name(), "a first send stays refused: {}", rows[1]);
assert!(rows[1].get("unknown_sends").is_none());
assert!(crate::projection::history(&rows).last_outcome.is_some_and(|last| last["unknown"][0]["text"] == "handed over"), "she is told it is unknown");
}
}

View file

@ -20,22 +20,23 @@ use crate::chat_client::{Chat, ChatSendRequest, Reading, SendBasis};
const RECENT: usize = 5;
const RECORDS: usize = 50;
/// 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.
/// How an actuator answered a send: the event it made, why it made none (the refusal's name), that no answer came, so the
/// send is still owed, or that it made no attempt at all.
pub(crate) enum Sent {
Posted(String),
Refused(String),
Lost,
/// The mouth attempted nothing: the send is certainly not posted, still owed, and goes out as a first send later.
NotSent,
/// The mouth cannot say whether an earlier try posted: the send is never repeated, and is recorded unknown.
Unknown,
}
/// Which pass over a record's owed sends this is. `First` is the turn's own, made against what she saw; `Retry` repeats what an earlier start owed, under the
/// recorded id, and says so to the mouth (`resend`); `Past` is a start that finds the record older than the homeserver remembers an id.
/// Which pass over a record's owed sends this is. `Within` makes the sends (a first send or a repeat, as each send's mark says); `Past` is a start that finds the
/// record older than the homeserver remembers an id.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Pass {
First,
Retry,
Within,
Past,
}
@ -70,12 +71,14 @@ impl Actuator for Mouth<'_> {
let request = ChatSendRequest { request_id: id.to_owned(), persona: self.persona.clone(), room_alias: room.to_owned(), text: text.to_owned(), basis: Some(basis), resend };
match self.chat.send(&request) {
Ok(receipt) => match (receipt.event_id, receipt.refusal) {
(_, Some(refusal)) => match refusal.reading() {
(_, Some(refusal)) => match refusal.reading(resend) {
Reading::NoAnswer => Sent::Lost,
Reading::NotSent => Sent::NotSent,
Reading::Unknown => Sent::Unknown,
Reading::Declined => Sent::Refused(refusal.name().to_owned()),
},
(Some(event), None) => Sent::Posted(event),
(None, None) if resend => Sent::Unknown,
(None, None) => Sent::Refused("no_event".to_owned()),
},
Err(_) => Sent::Lost,
@ -97,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<Utc>) -> Taken {
let mut taken = decide(organs, request, key, now);
deliver(actuator, &mut taken.record, Pass::First, &mut BTreeSet::new());
deliver(actuator, &mut taken.record, Pass::Within, &mut BTreeSet::new(), &mut |_| true);
taken
}
@ -154,17 +157,21 @@ pub(crate) fn decide(organs: &Organs, request: &Request, key: &str, now: DateTim
/// came, still owed. The only receipt is the mouth's answer to a send, an event id; her lines in the room's tail are never one. The
/// amendments follow once nothing is owed. A record that owes nothing is the shape the simulator and the mouth share.
///
/// A send is made under its recorded id, so the homeserver answers a repeat with the original event. `Pass::Past` (the record is older
/// than the homeserver remembers an id) sends nothing: each owed send is recorded in `unknown_sends`, neither posted nor refused, and
/// she is told it may or may not have gone out. `stalled` holds the rooms whose earlier send got no answer 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 not sent stays owed. A send past
/// the window is unknown whether or not its room is stalled: it cannot be repeated, so waiting would owe it for ever.
pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, pass: Pass, stalled: &mut BTreeSet<String>) {
/// Each send's `handed` mark says it was handed to the mouth. It is written ahead (`ahead` makes the record durable, and the send is not made when
/// it cannot) so a record read later says exactly which sends the mouth may have attempted. A send not handed over goes out as a first send, with
/// its basis; one handed over is repeated under its recorded id and says so (`resend`), so the homeserver answers it with the original event, and a
/// refusal of such a repeat leaves the earlier try's outcome unknown. A mouth that attempted no PUT (`NotSent`) clears the mark this call made.
/// `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<String>, ahead: &mut dyn FnMut(&Value) -> bool) {
let owed: Vec<Value> = 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() {
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 }),
};
@ -175,21 +182,48 @@ pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, pass: Pass, s
Some(unknowns) => unknowns.push(unknown),
None => record["unknown_sends"] = json!([unknown]),
}
stalled.insert(room.to_owned());
stalled.insert(room.clone());
};
let handed = send["handed"] == true;
if pass == Pass::Past {
unknown_send(record, stalled);
if handed {
unknown_send(record, stalled);
} else if let Some(refused) = record["refused_sends"].as_array_mut() {
refused.push(refusal("not_sent_past_the_window"));
}
continue;
}
if stalled.contains(room) {
if stalled.contains(&room) {
still.push(send);
continue;
}
match actuator.send(send["id"].as_str().unwrap_or_default(), room, text, send["in_reply_to"].as_str(), &mentions, pass == Pass::Retry) {
if !handed {
// Write ahead of the attempt: what is owed now is what is still owed, this send marked, and what follows it.
send["handed"] = json!(true);
record["owed"] = json!(still.iter().chain(std::iter::once(&send)).chain(&owed[index + 1..]).collect::<Vec<_>>());
if !ahead(record) {
if let Some(fields) = send.as_object_mut() {
fields.remove("handed");
}
stalled.insert(room.clone());
still.push(send);
continue;
}
}
match actuator.send(send["id"].as_str().unwrap_or_default(), &room, &text, reply.as_deref(), &mentions, handed) {
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 => {
stalled.insert(room.to_owned());
stalled.insert(room.clone());
still.push(send);
}
Sent::NotSent => {
stalled.insert(room.clone());
if !handed {
if let Some(fields) = send.as_object_mut() {
fields.remove("handed");
}
}
still.push(send);
}
Sent::Unknown => unknown_send(record, stalled),

View file

@ -2,7 +2,7 @@ use std::cell::RefCell;
use anyhow::{Result, bail};
use chrono::Duration;
use serde_json::json;
use serde_json::{Value, json};
use super::*;
use crate::chat_client::{ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatRead, ChatSendReceipt, Refusal};
@ -55,7 +55,20 @@ fn mouth(chat: &FakeChat) -> Mouth<'_> {
/// One turn from the operator-warm fixture, she saying one line in reply, through `actuator`.
fn warm_turn(actuator: &dyn Actuator) -> Taken {
warm_turn_saying("He smiles at the screen, then types. <typed>Missed you too, friend.</typed>", actuator)
warm_turn_ahead(actuator, &mut |_| true)
}
/// The same, with the write ahead of each send handed to `ahead`.
fn warm_turn_ahead(actuator: &dyn Actuator, ahead: &mut dyn FnMut(&Value) -> bool) -> Taken {
let dir = tempfile::tempdir().unwrap();
let model = Scripted::new(move |_| "He smiles at the screen, then types. <typed>Missed you too, friend.</typed>".into());
let fixture = room("operator-warm.toml");
let harness = harness(dir.path(), None, Some(&model));
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);
taken
}
/// The same turn, her prose being `prose`.
@ -242,47 +255,110 @@ fn t_l3_an_unknown_sends_own_record_reports_no_line_missing_its_receipt() {
assert!(outcome.omitted.is_empty(), "{:?}", outcome.omitted);
}
/// Soul s7 mouth-no-answer-recorded-refused. Every refusal kind the mouth names is placed: `SendFailed` says the homeserver was not heard
/// (the PUT timed out or was answered 5xx), so the event may exist and the send stays owed; each other kind is the mouth declining before it
/// put anything, which settles the send as refused.
#[test]
fn t_l3_a_refusal_is_no_answer_only_when_the_homeserver_was_not_heard() {
use crate::chat_client::Reading::{Declined, NoAnswer, Unknown};
let kinds = [
(Refusal::SendFailed, NoAnswer),
(Refusal::ResendUnknown, Unknown),
(Refusal::Brake, Declined),
(Refusal::PersonaMismatch, Declined),
(Refusal::UnknownRoom, Declined),
(Refusal::EmptyText, Declined),
(Refusal::UnknownPersona, Declined),
(Refusal::RoomMoved, Declined),
(Refusal::UnknownKind, Declined),
];
for (refusal, reading) in kinds {
let chat = FakeChat::new(Some(refusal));
let taken = warm_turn(&mouth(&chat));
let has = |field: &str| taken.record[field].as_array().is_some_and(|held| !held.is_empty());
assert_eq!((has("owed"), has("unknown_sends"), has("refused_sends")), (reading == NoAnswer, reading == Unknown, reading == Declined), "{}: {}", refusal.name(), taken.record);
if reading == Declined {
assert_eq!(taken.record["refused_sends"][0]["refusal"], refusal.name());
}
/// What a record says became of its one send: still owed (`owed`, or `owed, handed` when the mouth may have attempted it), unknown or refused.
fn settled(record: &Value) -> String {
let held = |field: &str| record[field].as_array().is_some_and(|held| !held.is_empty());
match (held("owed"), held("unknown_sends"), held("refused_sends"), held("posted")) {
(true, false, false, false) if record["owed"][0]["handed"] == true => "owed, handed".into(),
(true, false, false, false) => "owed".into(),
(false, true, false, false) => "unknown".into(),
(false, false, true, false) => "refused".into(),
(false, false, false, true) => "posted".into(),
_ => format!("not one thing: {record}"),
}
}
/// A send the turn makes is a first try and says so; one repeated from the record under its id is a resend and says that, so the mouth does
/// not hold it to the basis of the first try. The second try of a send whose first got no answer is answered with the event.
/// Every refusal kind the mouth names is placed, for a first send and for a repeat of a send already handed to the mouth. `SendFailed` says the PUT
/// was attempted and not answered, so the send stays owed, handed over. `NotSent` says no PUT was attempted: a first send is owed again as not handed
/// over, so it goes out as a first send later; a repeat keeps its mark, since the earlier try is no less unknown. `ResendUnknown` is unknown. Each other
/// kind is the mouth declining before it put anything: a first send is refused, and a repeat is unknown, since the earlier try may have posted.
#[test]
fn t_l3_a_first_send_carries_no_resend_flag_and_every_repeat_does() {
fn t_l3_every_refusal_kind_is_placed_for_a_first_send_and_for_a_repeat() {
let kinds = [
(Refusal::SendFailed, "owed, handed", "owed, handed"),
(Refusal::NotSent, "owed", "owed, handed"),
(Refusal::ResendUnknown, "unknown", "unknown"),
(Refusal::Brake, "refused", "unknown"),
(Refusal::PersonaMismatch, "refused", "unknown"),
(Refusal::UnknownRoom, "refused", "unknown"),
(Refusal::EmptyText, "refused", "unknown"),
(Refusal::UnknownPersona, "refused", "unknown"),
(Refusal::RoomMoved, "refused", "unknown"),
(Refusal::UnknownKind, "refused", "unknown"),
];
assert_eq!(kinds.map(|(refusal, ..)| refusal), Refusal::ALL, "every kind the mouth names is in the table, in order");
for (refusal, first, repeat) in kinds {
let chat = FakeChat::new(Some(refusal));
let mut taken = warm_turn(&mouth(&chat));
assert_eq!(settled(&taken.record), first, "{} to a first send: {}", refusal.name(), taken.record);
if first == "refused" {
assert_eq!(taken.record["refused_sends"][0]["refusal"], refusal.name());
}
// The repeat of a send handed over: the record of one the mouth did not answer.
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);
assert_eq!(again.sent.borrow().iter().map(|request| request.resend).collect::<Vec<_>>(), [true], "{}: a repeat says resend", refusal.name());
assert_eq!(settled(&taken.record), repeat, "{} to a repeat: {}", refusal.name(), taken.record);
}
}
/// A send the turn makes is a first try and says so, and is written ahead as handed over before the mouth hears it. One owed that was handed over is
/// repeated under its recorded id and says resend, so the mouth does not hold it to the basis of the first try; one never handed over (held back in a
/// stalled room, or a start killed before its first send) goes out as a first send, with its basis. A record that cannot be written ahead hands nothing over.
#[test]
fn t_l3_a_send_never_handed_over_goes_out_as_a_first_send_and_only_a_handed_one_is_repeated() {
let first = FakeChat::new(Some(Refusal::SendFailed));
let mut taken = warm_turn(&mouth(&first));
let mut writes: Vec<Value> = Vec::new();
let mut taken = warm_turn_ahead(&mouth(&first), &mut |record| {
writes.push(record.clone());
true
});
assert_eq!(first.sent.borrow().iter().map(|request| request.resend).collect::<Vec<_>>(), [false], "a first send");
assert_eq!(writes.len(), 1, "one write ahead of the one attempt");
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::Retry, &mut BTreeSet::new());
let repeats = again.sent.borrow();
assert_eq!(repeats.iter().map(|request| (request.request_id.clone(), request.resend)).collect::<Vec<_>>(), [(id, true)], "the repeat is under the recorded id and says so");
deliver(&mouth(&again), &mut taken.record, Pass::Within, &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::<Vec<_>>(), [(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);
// A send never handed over, as a start killed before its first send leaves it: a first send, with its basis.
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 |_| {
marked += 1;
true
});
let sent = never.sent.borrow();
assert_eq!(sent.iter().map(|request| (request.resend, request.basis.is_some())).collect::<Vec<_>>(), [(false, true)], "first send, v2 with its basis");
assert_eq!(marked, 1);
// The write ahead fails: nothing is handed over, the send stays owed and unmarked, and its room is held.
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);
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}");
}
/// A send of a record past the window is unknown when it was handed over and refused as not sent when it was not: the first may have posted, the second
/// cannot have.
#[test]
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);
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");
assert!(record.get("owed").is_none());
}
}
/// Soul s7 owed-predicate-split. One predicate says a record owes a send, and the poll's `owes`, the ack's `owing` and the drain's owed list