persona drain: a resend the mouth cannot vouch for is unknown, never posted again

Bifrost answers ResendUnknown for a resend of an id it does not remember attempting for that Persona and room within its window. The first try may have
posted, so the send is recorded in unknown_sends (as past the window), holds its room, and is told at her next real turn. The refusal is read through
Refusal::reading, which names every kind as declined, no answer, or unknown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 04:52:01 +01:00
commit 33eb637c15
5 changed files with 75 additions and 27 deletions

View file

@ -511,6 +511,9 @@ pub enum Refusal {
UnknownPersona,
/// A send with a basis found the room had moved past it: the receipt names what moved it.
RoomMoved,
/// A resend the mouth cannot vouch for: it did not attempt that request id for this Persona and room within its resend window (forgotten,
/// too old, lost in a restart). It posted nothing now, and whether the first try posted is unknown.
ResendUnknown,
/// The mouth does not serve this document kind. Answers an open-direct request only: a send receipt never carries it.
UnknownKind,
}
@ -526,24 +529,36 @@ impl Refusal {
Self::SendFailed => "SendFailed",
Self::UnknownPersona => "UnknownPersona",
Self::RoomMoved => "RoomMoved",
Self::ResendUnknown => "ResendUnknown",
Self::UnknownKind => "UnknownKind",
}
}
}
impl Refusal {
/// Whether the refusal says the mouth got no answer from the homeserver, so the send may or may not have been made. Every other kind
/// is an answer: the mouth declined before it put anything. The match names every kind, so a new one has to be placed.
pub(crate) fn is_no_answer(self) -> bool {
/// 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 {
match self {
// The mouth's PUT timed out or the homeserver answered 5xx or 429: the event may have been persisted.
Self::SendFailed => true,
// 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,
// 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.
Self::Brake | Self::PersonaMismatch | Self::UnknownRoom | Self::EmptyText | Self::UnknownPersona | Self::RoomMoved | Self::UnknownKind => false,
Self::Brake | Self::PersonaMismatch | Self::UnknownRoom | Self::EmptyText | Self::UnknownPersona | Self::RoomMoved | Self::UnknownKind => Reading::Declined,
}
}
}
/// How a send's settlement reads a refusal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Reading {
Declined,
NoAnswer,
Unknown,
}
impl Serialize for Refusal {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.name())
@ -553,7 +568,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::UnknownKind]
[Self::Brake, Self::PersonaMismatch, Self::UnknownRoom, Self::EmptyText, Self::SendFailed, Self::UnknownPersona, Self::RoomMoved, Self::ResendUnknown, Self::UnknownKind]
.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

@ -67,6 +67,8 @@ struct FakeMouth {
down: RefCell<Vec<String>>,
/// The next send lands and its answer is lost on the way back.
answer_lost: Cell<bool>,
/// The mouth answers every resend `ResendUnknown`: it does not remember the id.
resend_unknown: Cell<bool>,
/// Every id a send came under, retries and deduped ones included.
attempts: RefCell<Vec<String>>,
log: Log,
@ -79,6 +81,9 @@ impl Chat for Rc<FakeMouth> {
}
fn send(&self, request: &ChatSendRequest) -> Result<ChatSendReceipt> {
self.attempts.borrow_mut().push(request.request_id.clone());
if request.resend && self.resend_unknown.get() {
return Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: None, refusal: Some(crate::chat_client::Refusal::ResendUnknown), newer: vec![] });
}
if self.down.borrow().contains(&request.room_alias) {
bail!("the homeserver did not answer");
}
@ -249,7 +254,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), 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), 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() }
@ -1217,3 +1222,20 @@ fn t_l3_the_window_is_1800_seconds_and_every_send_past_it_is_unknown_even_in_a_h
assert!(texts(&rig, &room(1)).is_empty(), "nothing past the window was sent");
assert_eq!(texts(&rig, &room(2)), ["inside"], "inside the window it is repeated");
}
/// A resend the mouth cannot vouch for (`ResendUnknown`) is unknown: never posted again, recorded in `unknown_sends` with the start's stamp, no newer
/// line goes into its room, and she is told at her next real turn.
#[test]
fn t_l3_a_resend_the_mouth_cannot_vouch_for_is_unknown_holds_its_room_and_is_told() {
let rig = Rig::new(vec![]);
owing_record(&rig, "n0-t0", 60, &[("lold:s0", &room(1), "the old line")]);
owing_record(&rig, "n1-t0", 30, &[("lnew:s0", &room(1), "the newer line")]);
rig.mouth.resend_unknown.set(true);
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"], "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_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");
}

View file

@ -14,7 +14,7 @@ use serde_json::{Value, json};
use super::commit;
use super::{Organs, Request, project};
use crate::chat_client::{Chat, ChatSendRequest, SendBasis};
use crate::chat_client::{Chat, ChatSendRequest, Reading, SendBasis};
/// How many of her earlier projections freshness remembers, and how many of her records a packet reads.
const RECENT: usize = 5;
@ -26,6 +26,8 @@ pub(crate) enum Sent {
Posted(String),
Refused(String),
Lost,
/// 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
@ -68,8 +70,11 @@ 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)) if refusal.is_no_answer() => Sent::Lost,
(_, Some(refusal)) => Sent::Refused(refusal.name().to_owned()),
(_, Some(refusal)) => match refusal.reading() {
Reading::NoAnswer => Sent::Lost,
Reading::Unknown => Sent::Unknown,
Reading::Declined => Sent::Refused(refusal.name().to_owned()),
},
(Some(event), None) => Sent::Posted(event),
(None, None) => Sent::Refused("no_event".to_owned()),
},
@ -164,13 +169,16 @@ pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, pass: Pass, s
None => json!({ "room": room, "text": text, "refusal": why }),
};
let mentions: Vec<String> = send["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
if pass == Pass::Past {
let unknown_send = |record: &mut Value, stalled: &mut BTreeSet<String>| {
let unknown = json!({ "room": room, "text": text });
match record["unknown_sends"].as_array_mut() {
Some(unknowns) => unknowns.push(unknown),
None => record["unknown_sends"] = json!([unknown]),
}
stalled.insert(room.to_owned());
};
if pass == Pass::Past {
unknown_send(record, stalled);
continue;
}
if stalled.contains(room) {
@ -184,6 +192,7 @@ pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, pass: Pass, s
stalled.insert(room.to_owned());
still.push(send);
}
Sent::Unknown => unknown_send(record, stalled),
}
}
if still.is_empty() {

View file

@ -247,23 +247,24 @@ fn t_l3_an_unknown_sends_own_record_reports_no_line_missing_its_receipt() {
/// 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, true),
(Refusal::Brake, false),
(Refusal::PersonaMismatch, false),
(Refusal::UnknownRoom, false),
(Refusal::EmptyText, false),
(Refusal::UnknownPersona, false),
(Refusal::RoomMoved, false),
(Refusal::UnknownKind, false),
(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, no_answer) in kinds {
for (refusal, reading) in kinds {
let chat = FakeChat::new(Some(refusal));
let taken = warm_turn(&mouth(&chat));
let owed = taken.record["owed"].as_array().is_some_and(|owed| !owed.is_empty());
let refused = taken.record["refused_sends"].as_array().is_some_and(|refused| !refused.is_empty());
assert_eq!((owed, refused), (no_answer, !no_answer), "{}: {}", refusal.name(), taken.record);
if refused {
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());
}
}

View file

@ -19,7 +19,7 @@ mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub e
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum DirectOutcome { Opened , Existing , Brake , PersonaMismatch , UnknownPersona , EmptyText , ForeignUser , NotAPerson , NoSuchUser , InvitePending , Declined , DailyLimit , SendFailed , }
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum FetchOutcome { Stored , StoredUnverified , NotAMember , BridgedRoom , TooLarge , TypeRefused , NoAttachment , HashMismatch , RateLimited , Brake , PersonaMismatch , UnknownPersona , FetchFailed , StoreFailed , }
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum ReceiptMode { Posted , Existing , }
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Refusal { Brake , PersonaMismatch , UnknownRoom , EmptyText , SendFailed , UnknownPersona , RoomMoved , UnknownKind , }
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Refusal { Brake , PersonaMismatch , UnknownRoom , EmptyText , SendFailed , UnknownPersona , RoomMoved , ResendUnknown , UnknownKind , }
mind_body::chat_client: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum ReplyViolation { NotATriple , BadEventId , BadSenderId , ExcerptNotText , ExcerptTooLong , }
mind_body::chat_client: # [derive (Clone , Debug , Default , PartialEq , Eq)] pub enum ReplyLink { # [default] Absent , Quote (ReplyTo) , Dropped (ReplyViolation) , }
mind_body::chat_client: const ACK : & str
@ -40,6 +40,7 @@ mind_body::chat_client: const REFUSAL : & str
mind_body::chat_client: const REPLY_EXCERPT_CHARS : usize
mind_body::chat_client: const SEND_RECEIPT : & str
mind_body::chat_client: const SEND_REQUEST : & str
mind_body::chat_client: const SEND_REQUEST_V3 : & str
mind_body::chat_client: fn decode < T : DeserializeOwned > (bytes : & [u8]) -> Result < T >
mind_body::chat_client: fn encode < T : Serialize > (document : & T) -> Result < Vec < u8 > >
mind_body::chat_client: fn reply_warnings (pending : & ChatPending , warned : & mut std :: collections :: BTreeSet < String >) -> Vec < String >
@ -91,7 +92,7 @@ mind_body::chat_client: struct ChatPendingRequest # [derive (Clone , Debug , Par
mind_body::chat_client: struct ChatRead # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[persona: String, room: String, event_id: String, at_unix_ms: u64]
mind_body::chat_client: struct ChatRefusal # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[persona: String, refusal: Refusal]
mind_body::chat_client: struct ChatSendReceipt # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, event_id: Option < String >, refusal: Option < Refusal >, newer: Vec < String >]
mind_body::chat_client: struct ChatSendRequest # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, persona: String, room_alias: String, text: String, basis: Option < SendBasis > , resend: bool]
mind_body::chat_client: struct ChatSendRequest # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[request_id: String, persona: String, room_alias: String, text: String, basis: Option < SendBasis >, resend: bool]
mind_body::chat_client: struct ContextLine # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[sender: String, text: String, at_unix_ms: u64]
mind_body::chat_client: struct MouthRefused # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub-fields[0: Refusal]
mind_body::chat_client: struct ReplyTo # [derive (Clone , Debug , PartialEq , Eq , Serialize)] pub-fields[event_id: String, sender: String, excerpt: Option < String >, at_cap: bool]