From 7b3db5925832914806d4ec5d3eb2178bc9db4e96 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 21:23:28 +0100 Subject: [PATCH] heartbeat: delete the owed waker; a record's owed list is read by no one Nothing settles an owed send now, so a poll that started a Mind for one would start her forever. Removes owes/owes_send, the heartbeat's owed_starts state field and its backoff, and the tests that pinned them; a record carrying `owed` decides its held lines and wakes no one (t_l3_an_owed_list_in_her_trace_starts_no_one). No live trace holds a turn_record with an owed key (read-only key scan, 2026-11-29). Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/heartbeat.rs | 46 +---------- crates/mind-body/src/heartbeat/tests.rs | 81 ++++--------------- crates/mind-body/src/projection.rs | 2 +- crates/mind-body/src/projection/turn.rs | 18 +---- crates/mind-body/src/projection/turn/tests.rs | 38 --------- 5 files changed, 22 insertions(+), 163 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 1e7ac50..d3e0e0d 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -36,7 +36,7 @@ use crate::chat_client::{Basis, Chat, ChatDelivery, ChatPending, Form}; use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable}; use crate::launch::{Clock, Launcher}; use crate::persona::TraceView; -use crate::projection::{decided, failed_run, owes}; +use crate::projection::{decided, failed_run}; use crate::queue::{MindPort, headers, in_force, of_kind}; use crate::tempo::{self, Standing}; @@ -145,10 +145,6 @@ 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"; @@ -797,10 +793,6 @@ struct Row<'a> { done: Option>, /// How many of her last records are failures in a row, and when the last was made. 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, } @@ -819,12 +811,6 @@ impl Row<'_> { 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. fn addressed_by_member(&self, config: &Config) -> bool { addressed_by_member(&config.operators, &self.addressee, &self.pending) @@ -860,7 +846,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(), owed_starts: BTreeMap::new() }); + let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: 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() { @@ -875,14 +861,13 @@ 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, 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() }; + let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], done: None, failures: (0, None), note: String::new() }; // Pending chat, read-only, for a released Mind. if row.released { match seat.trace.records() { Ok(records) => { row.done = Some(decided(&records).into_iter().map(str::to_owned).collect()); row.failures = failed_run(&records); - row.owes = owes(&records); } Err(error) => { eventful = true; @@ -914,11 +899,6 @@ 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(); @@ -949,26 +929,6 @@ 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, 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); - } - Woke::Refused(why) => row.note = why, - Woke::Busy => row.busy = true, - } - continue; - } let Some(event) = mentioned else { continue }; tried.push(index); // The wake's lines are recorded before her unit starts, so the start reads them. A start that does not happen leaves the diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index de70a07..055574c 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(), owed_starts: 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() }); 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))]), owed_starts: BTreeMap::new() } + 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))]) } } #[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(), owed_starts: BTreeMap::new() }); + assert_eq!(state, HeartbeatState { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: 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(), owed_starts: 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() }).unwrap(); assert_eq!(HeartbeatView::woken_for(&store, "ann").unwrap(), ["$e1", "$e3"]); assert_eq!(HeartbeatView::woken_for(&store, "bob").unwrap(), ["$e2"]); } @@ -1265,10 +1265,10 @@ fn a_mind_waiting_out_failures_passes_the_hello_to_the_other() { assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }); } -/// Soul's p5: a hello she decided whose send is owed is decided; her claim stands when her unit ends, and no second Mind is given it: -/// the poll starts her, for the send, and no one else. +/// Soul's p5: a hello she decided is decided, whatever her record also holds: her claim stands when her unit ends, no second Mind is given it, and +/// nothing starts her again for it. A record's `owed` list is read by no one. #[test] -fn a_hello_she_decided_whose_send_is_owed_is_not_given_to_a_second_mind() { +fn a_hello_she_decided_is_not_given_to_a_second_mind_and_starts_no_one() { let rig = quiet_rig(); wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!")); rig.poll(); @@ -1276,7 +1276,7 @@ fn a_hello_she_decided_whose_send_is_owed_is_not_given_to_a_second_mind() { rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "#general:chat", "text": "hi" }], "at": rig.now().to_rfc3339() })); rig.advance(60); let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; - assert_eq!(launched, vec![Slug("ann".into())], "she is started for her owed send, and no one is given the hello"); + assert_eq!(launched, vec![], "no one is started, and no one is given the hello"); assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"], "her claim stands"); } @@ -1311,75 +1311,24 @@ fn the_beat_does_not_start_a_mind_that_is_cooling() { assert!(!launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}"); } -/// 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 the 30 minutes a homeserver remembers an id, of one-minute polls, she is started 7 times, not 29. +/// A record that holds a send in `owed` wakes no one: nothing settles such a list now, so a poll that started her for it would start her forever. +/// Every poll over half an hour, with nothing new arriving, starts her never (the beat's turn for the others aside). #[test] -fn t_l3_an_owed_send_with_nothing_new_starts_her_at_the_next_poll_and_no_one_else() { +fn t_l3_an_owed_list_in_her_trace_starts_no_one() { let rig = quiet_rig(); rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[])); 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() })); - let mut starts: Vec = Vec::new(); for minute in 1..=29 { 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:?}"); - if launched.iter().any(|slug| slug.0 == "ann") { - starts.push(minute); - } + assert!(!launched.iter().any(|slug| slug.0 == "ann"), "minute {minute}: {launched:?}"); rig.end_unit(ANN); } - 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, 25], "20 s doubling to the beat, and still retried inside the dedupe window at minute 25"); } -/// 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 its record rewritten, posted, and the count ends. - rig.traces[ANN].rows.borrow_mut()[0] = 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. -#[test] -fn t_l3_an_owed_send_waits_out_her_failed_wakes() { - 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() })); - rig.fail_turn(ANN); - rig.advance(5); - let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; - assert!(launched.is_empty(), "cooling: {launched:?}"); - rig.advance(i64::from(BEAT_S)); - let Outcome::Polled { launched } = rig.poll() else { panic!("held") }; - assert!(launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}"); -} - -/// A send owed and settled starts no one. +/// A send settled starts no one. #[test] fn t_l3_a_send_settled_starts_no_one() { let rig = quiet_rig(); @@ -1390,9 +1339,9 @@ fn t_l3_a_send_settled_starts_no_one() { } /// Soul s7 pins-on-new-lines. A line that wakes her and her trace does not hold decided starts her by the wake rule, which writes the claim for -/// the line; the owed waker is for a poll with nothing waking her, and does not take its place. +/// the line, whatever an older record of hers holds in `owed`. #[test] -fn t_l3_a_new_waking_line_is_woken_for_by_the_wake_rule_even_while_a_send_is_owed() { +fn t_l3_a_new_waking_line_is_woken_for_by_the_wake_rule_with_an_owed_list_in_her_trace() { let rig = quiet_rig(); rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[])); rig.poll(); diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index b39a537..113a6d7 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -50,7 +50,7 @@ pub use narrate::{Answer, Failed, KitModel, Model, Spent, connector_key}; pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource}; pub use select::TurnKind; pub(crate) use commit::apply as apply_commit; -pub(crate) use turn::{Taken, decided, failed_run, history, owes}; +pub(crate) use turn::{Taken, decided, failed_run, history}; pub(crate) use wake::wake; pub use tuning::{TUNING_FILE, TUNING_ROOT}; diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs index a68c823..ea6f962 100644 --- a/crates/mind-body/src/projection/turn.rs +++ b/crates/mind-body/src/projection/turn.rs @@ -21,10 +21,9 @@ pub(crate) struct Taken { pub state: Value, } -/// The events her trace shows she has decided: every line a record that did not fail held (`held`, the room's event ids the drain -/// read for it), whether its sends went out or are still owed, and every line set aside (`set_aside`). A decision is made once, when -/// it is written; a send owed from it is delivered as recorded and the line is never decided again. The one reader of "was this -/// line decided", for the drain and the poll alike. +/// The events her trace shows she has decided: every line a record that did not fail held (`held`, the event ids the wake showed her) and +/// every line set aside (`set_aside`). A decision is made once, when it is written. An `owed` list an older record carries is read by no one. +/// The one reader of "was this line decided", for the drain and the poll alike. pub(crate) fn decided(records: &[Value]) -> BTreeSet<&str> { let mut done = BTreeSet::new(); for record in records.iter().filter(|record| record.get("failed").is_none()) { @@ -53,17 +52,6 @@ pub(crate) struct Past { pub last_wake: Option>, } -/// Whether `record` owes a send: a record that did not fail and still holds a send in `owed`. The one place that says so, for the drain, the -/// ack and the poll alike. -pub(crate) fn owes_send(record: &Value) -> bool { - record.get("failed").is_none() && record["owed"].as_array().is_some_and(|owed| !owed.is_empty()) -} - -/// Whether any record of hers still owes a send. -pub(crate) fn owes(records: &[Value]) -> bool { - records.iter().any(owes_send) -} - /// A real turn: a record that decided something. A failed turn decided nothing, and a record that only set lines aside is no turn. The one /// definition, for what she is told of her last turn (`history`) and for what her trace holds untold (`untold`). pub(crate) fn is_real(record: &Value) -> bool { diff --git a/crates/mind-body/src/projection/turn/tests.rs b/crates/mind-body/src/projection/turn/tests.rs index 202b4b1..0beec61 100644 --- a/crates/mind-body/src/projection/turn/tests.rs +++ b/crates/mind-body/src/projection/turn/tests.rs @@ -1,26 +1,9 @@ -use std::cell::RefCell; - -use anyhow::{Result, bail}; use chrono::Duration; use serde_json::{Value, json}; use super::*; -use crate::chat_client::{ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatRead, ChatSendReceipt, Refusal}; -use crate::projection::commit::Applied; -use crate::projection::harness::fixture_request; -use crate::projection::harness::tests::{Scripted, control, harness, room}; -use crate::projection::narrate::PROJECTOR_OPENING; use crate::projection::outcome::outcome_of; use crate::projection::select::forms; -use crate::projection::{Answer, Failed, Model, Organs, Through}; - -struct FailingPersona; - -impl Model for FailingPersona { - fn ask(&self, _request_id: &str, _model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result { - if prompt.starts_with(PROJECTOR_OPENING) { Ok(Answer { text: "The room is slow.".into(), usage: None }) } else { Err(Failed { reason: "the provider failed the call: Overloaded".into(), outage: false, usage: None }) } - } -} #[test] fn t_l1_history_from_records() { @@ -97,14 +80,6 @@ fn t_l3_her_last_real_turns_outcome_is_told_though_a_failed_turn_or_a_set_aside_ assert_eq!(told(vec![]), ""); } -/// A trace that holds an owed send says so; a failed record's owed send and a settled one are not owed. -#[test] -fn t_l3_a_trace_owes_a_send_only_while_a_record_holds_it_owed() { - let owed = json!({ "held": [], "owed": [{ "id": "b1-t0:s0", "room": "#a", "text": "hi" }] }); - assert!(owes(std::slice::from_ref(&owed)), "a beat's send holds no line and is owed all the same"); - assert!(!owes(&[json!({ "held": ["$e1"], "owed": [{ "id": "x", "room": "#a", "text": "hi" }], "failed": "x" }), json!({ "held": ["$e2"], "posted": [] })])); -} - /// The record that settled a send as unknown holds its said line with no receipt and no refusal: the line is told by `unknown`, and is /// not also reported as a said line with nothing to show it went out. #[test] @@ -114,16 +89,3 @@ fn t_l3_an_unknown_sends_own_record_reports_no_line_missing_its_receipt() { assert!(outcome.omitted.is_empty(), "{:?}", outcome.omitted); } -/// 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}"), - } -} -