persona drain: a send's transaction id carries a digest of its words, and her own line already in the room is the receipt of the send a retry repeats

Synapse keeps a transaction id 30 to 60 minutes (HttpTransactionCache CLEANUP_PERIOD), so a turn retried later than that, whose record never landed, would post again; and a line rendered again under the same id would get the old event back for its new words. The mouth now counts her own tail lines that follow the line the turn answers as the sends they are, and names a send by turn, place and words.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 01:16:23 +01:00
commit 7111a4b56b
6 changed files with 92 additions and 17 deletions

View file

@ -266,6 +266,7 @@ const STRIKES: usize = 2;
/// 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.
@ -336,7 +337,7 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> 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, 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, 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() })
.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
@ -367,7 +368,14 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
}
}
let seen = newest.into_iter().map(|(room, (_, event))| (room.to_owned(), event.to_owned())).collect();
let mouth = Mouth { chat: &start.chat, persona: instance.0.clone(), seen, since_unix_ms: began_ms };
// 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<TailLine> = 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 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<Turn> = Vec::new();
let mut acked: Option<u64> = None;

View file

@ -57,17 +57,21 @@ struct FakeMouth {
ack_fails: Cell<bool>,
/// How many deliveries one page of `pending` holds.
page: Cell<usize>,
/// The room tail: every line she sent, as the mouth would show it.
tail: RefCell<Vec<crate::chat_client::TailLine>>,
log: Log,
}
impl Chat for Rc<FakeMouth> {
fn pending(&self, after: u64) -> Result<ChatPending> {
self.reads.set(self.reads.get() + 1);
Ok(ChatPending { persona: "eureka".into(), deliveries: self.held.borrow().iter().filter(|delivery| delivery.seq > after).take(self.page.get()).cloned().collect(), tail: Some(vec![]), tail_gaps: vec![] })
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> {
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() });
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<ChatOpenDirectReceipt> {
@ -211,7 +215,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), sent: RefCell::default(), acks: RefCell::default(), reads: Cell::new(0), ack_fails: Cell::new(false), page: Cell::new(usize::MAX), 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(), 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() });
Self { mouth, store, trace, log, dir, ticks: Rc::default() }
@ -265,7 +269,7 @@ fn t_l2_drain_acks_after_decision() {
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<String> = rig.mouth.sent.borrow().iter().map(|request| request.request_id.clone()).collect();
let ids: Vec<String> = rig.mouth.sent.borrow().iter().map(|request| base(&request.request_id)).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<String> = rig.trace.rows.borrow().iter().map(|(key, _)| key.clone()).collect();
@ -671,7 +675,7 @@ fn t_l2_a_reply_whose_record_did_not_land_goes_out_again_under_the_same_id() {
rig.run(TraceDiesAfterTheFailedTurn { inner: failing(OUTAGE), trace: rig.trace.clone() });
rig.trace.fail.set(false);
rig.run(failing(OUTAGE));
let ids: std::collections::BTreeSet<String> = rig.mouth.sent.borrow().iter().filter(|request| request.room_alias == room(1)).map(|request| request.request_id.clone()).collect();
let ids: std::collections::BTreeSet<String> = 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:?}");
assert_eq!(rig.held_seqs(), [1, 2], "the outage holds the ack, as it should");
}
@ -683,7 +687,7 @@ fn t_l2_two_beats_with_no_trace_record_do_not_share_a_send_id() {
rig.trace.fail.set(true);
rig.run(scripted(false));
rig.run(scripted(false));
let ids: std::collections::BTreeSet<String> = rig.mouth.sent.borrow().iter().map(|request| request.request_id.clone()).collect();
let ids: std::collections::BTreeSet<String> = 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:?}");
}
@ -736,7 +740,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| request.request_id.clone()).collect::<Vec<_>>(), ["l$e1:s0"], "the heartbeat woke her for the hello: she answers it");
assert_eq!(rig.mouth.sent.borrow().iter().map(|request| base(&request.request_id)).collect::<Vec<_>>(), ["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.
@ -775,7 +779,7 @@ fn run_with(rig: &Rig, view: Box<dyn HeartbeatView>, down: bool) -> Outcome {
}
fn sent_ids(rig: &Rig) -> Vec<String> {
rig.mouth.sent.borrow().iter().map(|request| request.request_id.clone()).collect()
rig.mouth.sent.borrow().iter().map(|request| base(&request.request_id)).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
@ -822,3 +826,37 @@ 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 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()
}
/// 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.
#[test]
fn t_l2_a_turn_whose_record_was_lost_posts_nothing_twice_even_when_the_homeserver_forgot() {
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
rig.mouth.ack_fails.set(true);
rig.trace.fail.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");
}
/// 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.
#[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");
}

View file

@ -51,6 +51,8 @@ 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 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};

View file

@ -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 };
let mouth = Mouth { chat: &Chat1, persona: "eureka".into(), seen: Default::default(), since_unix_ms: 0, posted: vec![], counted: Default::default() };
let live = take(&organs, &request, &mouth, "r1-t1", fixture.now);
let keys = |record: &Value| record.as_object().unwrap().keys().cloned().collect::<Vec<_>>();
assert_eq!(keys(&simulated.record), keys(&live.record), "one record shape, simulated or live");

View file

@ -3,14 +3,16 @@
//! 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.
use std::collections::BTreeMap;
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};
use crate::chat_client::{Chat, ChatSendRequest, SendBasis, TailLine};
/// How many of her earlier projections freshness remembers, and how many of her records a packet reads.
const RECENT: usize = 5;
@ -45,12 +47,37 @@ pub(crate) struct Mouth<'a> {
pub seen: BTreeMap<String, String>,
/// 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<TailLine>,
/// The `posted` lines a send has already counted, so two sends of the same words are two lines.
pub counted: RefCell<BTreeSet<String>>,
}
/// 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::<String>())
}
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: id.to_owned(), persona: self.persona.clone(), room_alias: room.to_owned(), text: text.to_owned(), basis: Some(basis) };
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) };
match self.chat.send(&request) {
Ok(receipt) => match (receipt.event_id, receipt.refusal) {
(_, Some(refusal)) => Sent::Refused(refusal.name().to_owned()),

View file

@ -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 }
Mouth { chat, persona: "eureka".into(), seen: BTreeMap::new(), since_unix_ms: 7, posted: vec![], counted: Default::default() }
}
/// 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()), ("run-t1:s0", "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()), (wire_id("run-t1:s0", "Missed you too, friend.").as_str(), "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." }]));
}
@ -85,8 +85,8 @@ fn t_l2_each_send_of_a_turn_has_its_own_id_and_its_own_rooms_basis() {
let mouth_in_dm = Mouth { seen: BTreeMap::from([("!dm-meta:gamecult.org".to_owned(), "$newest".to_owned())]), ..mouth(&chat) };
let taken = warm_turn_saying("He types. <typed>First thing.</typed> Then more. <typed>Second, and different.</typed>", &mouth_in_dm);
let sent = chat.sent.borrow();
let ids: Vec<&str> = sent.iter().map(|request| request.request_id.as_str()).collect();
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");
let ids: Vec<String> = 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!(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");