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 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 05:48:02 +01:00
commit 65974e2196
2 changed files with 76 additions and 20 deletions

View file

@ -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<String, DateTime<Utc>>,
/// 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<String, u32>,
}
const STATE_KEY: &str = "state";
@ -774,6 +778,11 @@ fn floors(rows: &[Row], state: &HeartbeatState, now: DateTime<Utc>, 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<DateTime<Utc>>),
/// 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<DateTime<Utc>>),
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<Utc>, 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<Utc>, 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<Outcome> {
}
let now = organs.clock.now();
let stored = organs.store.load()?;
let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new() });
let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::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<Outcome> {
// 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<Outcome> {
// 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<String> = Vec::new();
let mut launched: Vec<Slug> = Vec::new();
@ -928,12 +949,17 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
.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);

View file

@ -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::<Utc>::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::<Utc>::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::<Vec<_>>(), ["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<i64> = 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.