From 65974e21968effbb20de9cf31b62a27ab35c296e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 05:48:02 +0100 Subject: [PATCH] persona poll: starts for a send owed back off by the poll's own count of them, so a trace that takes no writes is still waited out The poll keeps, in its heartbeat state, how many starts in a row it made for a send her trace holds owed since it last saw her owe none, and waits out the next as it waits out failed wakes: 20 s doubling to the beat. Over 30 minutes of one-minute polls she is started 7 times, not 30, the last still inside the 25 minutes a repeat is safe. It reads nothing from her trace, so a full state disk cannot defeat it. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/heartbeat.rs | 36 ++++++++++++--- crates/mind-body/src/heartbeat/tests.rs | 60 ++++++++++++++++++------- 2 files changed, 76 insertions(+), 20 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index e9a4c3b..1e7ac50 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -145,6 +145,10 @@ pub struct HeartbeatState { /// When the heartbeat last started each Persona's turn, by instance slug. #[cultcache(key = 2, default)] pub last_turn_at: BTreeMap>, + /// How many starts in a row the poll made for a send her trace holds owed, by instance slug, since it last saw her owe none: what the owed waker backs + /// off by (`BACKOFF_BASE_S`, doubled by each, up to the beat). The poll's own record, so a trace that takes no writes still backs it off. + #[cultcache(key = 3, default)] + pub owed_starts: BTreeMap, } const STATE_KEY: &str = "state"; @@ -774,6 +778,11 @@ fn floors(rows: &[Row], state: &HeartbeatState, now: DateTime, config: &Con floor } +/// How long after the last of `run` failed or unpaid starts in a row the next may come, in seconds: `BACKOFF_BASE_S`, doubled by each, up to the beat. +fn backoff(run: u32, beat_s: u32) -> i64 { + BACKOFF_BASE_S.saturating_mul(1i64 << run.saturating_sub(1).min(30)).min(i64::from(beat_s)) +} + struct Row<'a> { seat: &'a Seat<'a>, released: bool, @@ -790,6 +799,8 @@ struct Row<'a> { failures: (u32, Option>), /// Her trace holds a send still owed: the poll starts her for it, and no one else. owes: bool, + /// How many starts in a row the poll made for a send owed, and when it last started her (`HeartbeatState::owed_starts`, `last_turn_at`). + owed_starts: (u32, Option>), note: String, } @@ -805,8 +816,13 @@ impl Row<'_> { /// A failed wake is waited out before the next: `BACKOFF_BASE_S`, doubled by each failure in a row her trace holds, to the beat. fn cooling(&self, now: DateTime, beat_s: u32) -> bool { let (run, at) = self.failures; - let wait = BACKOFF_BASE_S.saturating_mul(1i64 << (run.saturating_sub(1)).min(30)).min(i64::from(beat_s)); - run > 0 && at.is_some_and(|at| (now - at).num_seconds() < wait) + run > 0 && at.is_some_and(|at| (now - at).num_seconds() < backoff(run, beat_s)) + } + + /// A start for a send owed that left it owed is waited out the same way, by the poll's own count of them: the trace need not take a write for it. + fn owed_cooling(&self, now: DateTime, beat_s: u32) -> bool { + let (run, at) = self.owed_starts; + run > 0 && at.is_some_and(|at| (now - at).num_seconds() < backoff(run, beat_s)) } /// A member (not the operator) has a pending message that names or tags her. @@ -844,7 +860,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { } let now = organs.clock.now(); let stored = organs.store.load()?; - let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new() }); + let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new(), owed_starts: BTreeMap::new() }); let mut eventful = false; // The table as the last poll left it; unreadable counts as none, is noted in the trace, and is not overwritten. let (stored_addressing, addressing_unread) = match organs.store.load_addressing() { @@ -859,7 +875,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { // Her last-read names when the table holds her, else her roster names alone. let roster = Addressee::new(&seat.who.matrix_id, [seat.who.public_name.as_str(), seat.who.handle.as_str()]); let kept = stored_addressing.minds.iter().find(|stored| stored.matrix_id() == seat.who.matrix_id).cloned().unwrap_or_else(|| roster.clone()); - let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], done: None, failures: (0, None), owes: false, note: String::new() }; + let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], done: None, failures: (0, None), owes: false, owed_starts: (state.owed_starts.get(&seat.who.slug.0).copied().unwrap_or(0), state.last_turn_at.get(&seat.who.slug.0).copied()), note: String::new() }; // Pending chat, read-only, for a released Mind. if row.released { match seat.trace.records() { @@ -898,6 +914,11 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { // whose unit is not running and whose trace does not hold the line decided did not take it, and the open floor judges it afresh. state.handled_mentions.retain(|key| key.split_once(':').is_none_or(|(who, event)| claim_stands(&rows, who, event))); + // A trace read that holds no send owed ends the count of starts made for one. + for row in rows.iter().filter(|row| row.done.is_some() && !row.owes) { + state.owed_starts.remove(&row.slug().0); + } + let beat_s = config.beat_s; let mut launches: Vec = Vec::new(); let mut launched: Vec = Vec::new(); @@ -928,12 +949,17 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { .map(|(delivery, _)| delivery.event_id.clone()) .find(|event| row.done.as_ref().is_some_and(|done| !done.contains(event))) }; - // A send her trace holds owed starts her, whatever the room says: it is hers alone, and waits out her failed wakes like any wake. + // A send her trace holds owed starts her, whatever the room says: it is hers alone, and waits out her failed wakes like any wake, and the + // starts the poll has made for it that left it owed. if mentioned.is_none() && row.owes { + if row.owed_cooling(now, beat_s) { + continue; + } tried.push(index); match wake(organs, row) { Woke::Started => { state.last_turn_at.insert(slug.0.clone(), now); + *state.owed_starts.entry(slug.0.clone()).or_insert(0) += 1; row.busy = true; launches.push(slug.0.clone()); launched.push(slug); diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index a397eac..681c684 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -264,7 +264,7 @@ impl Rig { /// The stored state, made if there is none, changed by `change`. fn with_state(&self, change: impl FnOnce(&mut HeartbeatState)) { - let mut state = self.store.state.borrow().clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new() }); + let mut state = self.store.state.borrow().clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new(), owed_starts: BTreeMap::new() }); change(&mut state); *self.store.state.borrow_mut() = Some(state); } @@ -670,7 +670,7 @@ fn trace_at(seconds: i64, tempo_s: u32) -> PollTrace { } fn state_at(milliseconds: i64) -> HeartbeatState { - HeartbeatState { last_beat_at: crate::testkit::at(milliseconds), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::from([("ann".to_string(), crate::testkit::at(3))]) } + HeartbeatState { last_beat_at: crate::testkit::at(milliseconds), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::from([("ann".to_string(), crate::testkit::at(3))]), owed_starts: BTreeMap::new() } } #[test] @@ -713,7 +713,7 @@ fn a_state_written_before_the_cut_reads_with_no_turns() { cache.pull_all_backing_stores().unwrap(); cache.put(STATE_KEY, &StateBeforeTheCut { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()] }).unwrap(); let state = FileStore::new(&path).load().unwrap().expect("the old state reads"); - assert_eq!(state, HeartbeatState { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::new() }); + assert_eq!(state, HeartbeatState { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::new(), owed_starts: BTreeMap::new() }); } #[test] @@ -1178,7 +1178,7 @@ fn the_file_store_view_reads_the_lines_the_poll_recorded_for_her() { let dir = TempDir::new().unwrap(); let store = FileStore::new(dir.path().join("heartbeat.cc")); assert!(HeartbeatView::woken_for(&store, "ann").unwrap().is_empty(), "no state yet: no claims"); - store.save(&HeartbeatState { last_beat_at: at(0), handled_mentions: vec!["ann:$e1".into(), "bob:$e2".into(), "ann:$e3".into()], last_turn_at: BTreeMap::new() }).unwrap(); + store.save(&HeartbeatState { last_beat_at: at(0), handled_mentions: vec!["ann:$e1".into(), "bob:$e2".into(), "ann:$e3".into()], last_turn_at: BTreeMap::new(), owed_starts: BTreeMap::new() }).unwrap(); assert_eq!(HeartbeatView::woken_for(&store, "ann").unwrap(), ["$e1", "$e3"]); assert_eq!(HeartbeatView::woken_for(&store, "bob").unwrap(), ["$e2"]); } @@ -1311,9 +1311,10 @@ fn the_beat_does_not_start_a_mind_that_is_cooling() { assert!(!launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}"); } -/// Soul's q3: her answer was decided and its send is owed (the answer was lost), her unit ended and nothing new arrives. The next poll -/// starts her, and only her, so the send is retried well inside the 30 minutes a homeserver remembers its id, in a quiet room, with the -/// beat's turn on the far side of the first poll. +/// Soul's q3 and s8 held-sibling-restart-storm: her answer was decided and its send is owed (the answer was lost), her unit ended and nothing new arrives. The +/// next poll starts her, and only her, so the send is retried well inside the 30 minutes a homeserver remembers its id, in a quiet room, with the beat's turn +/// on the far side of the first poll. A start that leaves it owed is waited out like a failed wake, 20 s doubling to the beat, by the poll's own count of them: +/// over 30 minutes of one-minute polls she is started 7 times, not 30. #[test] fn t_l3_an_owed_send_with_nothing_new_starts_her_at_the_next_poll_and_no_one_else() { let rig = quiet_rig(); @@ -1321,18 +1322,47 @@ fn t_l3_an_owed_send_with_nothing_new_starts_her_at_the_next_poll_and_no_one_els rig.poll(); rig.end_unit(ANN); rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() })); - rig.advance(60); - let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; - assert_eq!(launched.iter().map(|slug| slug.0.as_str()).collect::>(), ["ann"], "her, at the first poll after it was owed, and no one else"); - // Her unit ends with the send still owed: every poll starts her again, never another Mind, until it settles. - for minute in 2..=25 { - rig.end_unit(ANN); + let mut starts: Vec = Vec::new(); + for minute in 1..=30 { rig.advance(60); let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; assert!(launched.iter().all(|slug| slug.0 == "ann" || slug.0 == "bob" && minute >= 15), "minute {minute}: {launched:?}"); - assert!(launched.iter().any(|slug| slug.0 == "ann"), "minute {minute}: a send owed is retried at the next poll: {launched:?}"); + if launched.iter().any(|slug| slug.0 == "ann") { + starts.push(minute); + } + rig.end_unit(ANN); } - assert!(rig.started_turns().iter().filter(|(slug, _)| slug == "ann").count() >= 20, "retried inside the dedupe window, not at the beat"); + assert_eq!(starts.first(), Some(&1), "her, at the first poll after it was owed: {starts:?}"); + assert_eq!(starts, [1, 2, 3, 5, 8, 14, 24], "20 s doubling to the beat, and still retried inside the dedupe window at minute 24"); +} + +/// Soul s7 unwritable-owed-wakes-every-poll. A trace that takes no writes (her state disk full) carries no failed record, so the poll's backoff cannot +/// read one: the poll's own count of starts it made that left the send owed backs it off instead, and a send settled ends the count. +#[test] +fn t_l3_a_trace_that_takes_no_writes_is_still_backed_off_by_the_polls_own_count_of_starts_that_left_a_send_owed() { + let rig = quiet_rig(); + rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() })); + let started = |rig: &Rig| { + let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; + launched.iter().any(|slug| slug.0 == "ann") + }; + assert!(started(&rig), "the first start for the send"); + rig.end_unit(ANN); + rig.advance(10); + assert!(!started(&rig), "ten seconds after a start that left it owed"); + rig.advance(11); + assert!(started(&rig), "20 s later"); + rig.end_unit(ANN); + rig.advance(30); + assert!(!started(&rig), "the second doubles it to 40 s"); + // The send settles: her trace holds it posted, and the count ends. + rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "posted": [{ "event": "$sent-1", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() })); + rig.advance(1); + assert!(!started(&rig), "nothing is owed"); + assert!(rig.store.state.borrow().as_ref().is_some_and(|state| state.owed_starts.is_empty()), "the count of starts for a send owed ended with it"); + rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e2"], "owed": [{ "id": "l$e2:s0", "room": "!op", "text": "Again." }], "at": rig.now().to_rfc3339() })); + rig.advance(1); + assert!(started(&rig), "a new send owed starts her at the next poll: the count began again"); } /// The owed send's start waits out her failed wakes like any other start: an outage is not retried every poll.