From dd1ed19f3fe7e53ea60172b864d6b2f8f5e8a884 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 01:55:24 +0100 Subject: [PATCH] heartbeat poll: her trace is the one record of what she decided; a failed wake is waited out Seat carries her trace, read-only (MIND_HEARTBEAT_TRACES, a path with {slug}). The poll wakes her for a line that wakes her and her trace does not hold decided, by the same function the drain uses; a trace it cannot read judges nothing. A claim (handled key) is a record of who was woken for what, and stands while her unit runs or her trace holds the line decided; otherwise it lapses. Re-waking after failures backs off by the failed records in a row at the end of her trace: 20 s doubling to the beat. Deleted: the release of a claim because its line was still pending, the rollback of the saved state when a start was refused, and the handled-key gate on waking. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/bin/mind-heartbeat.rs | 13 +- crates/mind-body/src/heartbeat.rs | 68 +++++++--- crates/mind-body/src/heartbeat/tests.rs | 116 +++++++++++++++++- crates/mind-body/src/projection.rs | 2 +- crates/mind-body/src/projection/turn.rs | 7 ++ crates/mind-body/src/projection/turn/tests.rs | 2 + crates/mind-body/tests/public_surface.txt | 2 +- 7 files changed, 182 insertions(+), 28 deletions(-) diff --git a/crates/mind-body/src/bin/mind-heartbeat.rs b/crates/mind-body/src/bin/mind-heartbeat.rs index 081da72..e06dfed 100644 --- a/crates/mind-body/src/bin/mind-heartbeat.rs +++ b/crates/mind-body/src/bin/mind-heartbeat.rs @@ -13,7 +13,8 @@ //! entries separated by `;`, the last field her own Huginn daemon: each Mind is //! its own daemon), `MIND_PERSONA_OPERATOR` (id[,id]), `HEARTBEAT_POLL_S`, //! `HEARTBEAT_BEAT_S` (seconds between beats, default 1800), `BIFROST_CHAT_ENDPOINT`, -//! `BIFROST_CHAT_KEY_FILE`, and `STATE_DIRECTORY` (`heartbeat.cc` lives there). +//! `BIFROST_CHAT_KEY_FILE`, `STATE_DIRECTORY` (`heartbeat.cc` lives there) and `MIND_HEARTBEAT_TRACES`, the path of each Persona's +//! `persona-trace.cc` with `{slug}` where her slug goes (read-only: her trace is the record of which lines she has decided). //! The heartbeat holds no connector key. use std::net::SocketAddr; @@ -24,6 +25,7 @@ use anyhow::{Context, Result, anyhow, bail}; use eureka_state::HuginnClient; use mind_body::chat_rudp::{RudpChat, connection_id}; use mind_body::heartbeat::{Config, DEFAULT_BEAT_S, FileControl, FileStore, Organs, PersonaId, Seat, poll}; +use mind_body::persona::FileTrace; use mind_body::launch::{SystemClock, SystemdLauncher}; use mind_body::queue::HuginnMind; @@ -84,11 +86,16 @@ fn run() -> Result<()> { let poll_s = u64::try_from(whole("HEARTBEAT_POLL_S", 20)?).map_err(|_| anyhow!("HEARTBEAT_POLL_S is negative"))?.max(1); let minds: Vec = config.personas.iter().map(|who| HuginnMind::new(HuginnClient::new(who.huginn, who.slug.clone(), TIMEOUT))).collect(); let chats: Vec = config.personas.iter().map(|who| RudpChat::new(chat_address, chat_id, who.slug.0.clone(), CHAT_TIMEOUT)).collect(); + let traces_at = required("MIND_HEARTBEAT_TRACES")?; + if !traces_at.contains("{slug}") { + bail!("MIND_HEARTBEAT_TRACES names no {{slug}}"); + } + let traces: Vec = config.personas.iter().map(|who| FileTrace::new(traces_at.replace("{slug}", &who.slug.0))).collect(); let seats: Vec = config .personas .iter() - .zip(minds.iter().zip(chats.iter())) - .map(|(who, (mind, chat))| Seat { who: who.clone(), mind, chat }) + .zip(minds.iter().zip(chats.iter().zip(traces.iter()))) + .map(|(who, (mind, (chat, trace)))| Seat { who: who.clone(), mind, chat, trace }) .collect(); let launcher = SystemdLauncher::new(); let organs = Organs { seats: &seats, control: &FileControl, launcher: &launcher, clock: &SystemClock, store: &store }; diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 01755e2..fa8bfbc 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -20,7 +20,7 @@ //! //! A held swarm brake ends the poll before the mind or the mouth is touched. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use std::net::SocketAddr; use std::path::PathBuf; @@ -35,6 +35,8 @@ use crate::address::{Addressee, Name, is_for, project_names}; 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::Trace; +use crate::projection::{decided, failed_run}; use crate::queue::{MindPort, headers, in_force, of_kind}; use crate::tempo::{self, Standing}; @@ -42,6 +44,8 @@ use crate::tempo::{self, Standing}; const MENTIONS_KEPT: usize = 64; /// The most pages of pending chat one poll reads for one Persona. const PENDING_PAGES: usize = 16; +/// How long after one failed wake the next may come, in seconds; each failure in a row doubles it, up to the beat. +const BACKOFF_BASE_S: i64 = 20; /// The beat, in seconds, when `HEARTBEAT_BEAT_S` is not set. pub const DEFAULT_BEAT_S: u32 = 1800; @@ -382,6 +386,8 @@ pub struct Seat<'a> { pub who: PersonaId, pub mind: &'a dyn MindPort, pub chat: &'a dyn Chat, + /// Her trace, read-only: the one record of which lines she has decided. + pub trace: &'a dyn Trace, } pub struct Organs<'a> { @@ -699,6 +705,13 @@ fn row_facts(row: &Row, pending: &[&ChatDelivery], minds: &[String], taken: &[St facts } +/// Whether a Mind's claim on a line stands: her turn on it is running, or her trace holds it decided. The claim of a Mind whose +/// unit is idle and whose trace does not hold the line (her turn failed, died or never started) has lapsed; one whose trace could +/// not be read is kept. +fn claim_stands(rows: &[Row], who: &str, event: &str) -> bool { + rows.iter().find(|row| row.slug().0 == who).is_none_or(|row| !row.idle() || row.done.as_ref().is_none_or(|done| done.contains(event))) +} + /// What the open floor decides over the pending lines: per row, the events that fall to her, and whether she holds a hello /// another Mind has taken. struct Floor { @@ -746,7 +759,7 @@ fn floors(rows: &[Row], state: &HeartbeatState, now: DateTime, config: &Con if !open_line(&hearers, speaker) { continue; } - let takers: Vec<&str> = state.handled_mentions.iter().filter_map(|key| key.split_once(':').filter(|(_, held)| *held == event).map(|(who, _)| who)).collect(); + let takers: Vec<&str> = state.handled_mentions.iter().filter_map(|key| key.split_once(':').filter(|(who, held)| *held == event && claim_stands(rows, who, held)).map(|(who, _)| who)).collect(); if !takers.is_empty() { for (at, place) in &held { floor.spoken_for[*at] |= raw[*at][*place].open_floor && takers.iter().any(|who| *who != rows[*at].slug().0); @@ -771,6 +784,10 @@ struct Row<'a> { addressee: Addressee, /// Her rooms among the pending deliveries': those named for a repo she stewards, as the last poll read her stewardships. own_rooms: Vec, + /// The lines her trace holds decided (`projection::decided`), as the drain reads them; none when it could not be read, and then no line is judged. + done: Option>, + /// How many of her last records are failures in a row, and when the last was made. + failures: (u32, Option>), note: String, } @@ -783,6 +800,13 @@ impl Row<'_> { self.released && !self.busy } + /// 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) + } + /// 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) @@ -833,9 +857,19 @@ 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![], 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); + } + Err(error) => { + eventful = true; + row.note = format!("trace unread: {error:#}"); + } + } match read_pending(seat.chat) { Ok(pending) => row.pending = pending.deliveries, Err(_) => { @@ -857,13 +891,9 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { rows.push(row); } - // A claim whose turn did not finish its line is given back. A drain acks every line she decided and every line it set aside, - // so a line still pending in the chat of a Mind whose unit is not running is one her turn left: it failed, or died before it - // drained, or never started. Her key is dropped, so the line wakes her again by the ordinary rule and the open floor judges it - // afresh: a taken hello does not stay barred from every other Mind for the window. - state.handled_mentions.retain(|key| { - key.split_once(':').is_none_or(|(who, event)| !rows.iter().any(|row| row.slug().0 == who && row.idle() && row.pending.iter().any(|delivery| delivery.event_id == event))) - }); + // A claim whose turn did not decide its line has lapsed, and is dropped. Her trace is the one record of what she decided: a Mind + // 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))); let beat_s = config.beat_s; let mut launches: Vec = Vec::new(); @@ -872,16 +902,18 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { // Off the beat: a line that wakes her by `wakes`, once per message. It does not wait for the beat; it needs her idle and // released. The open floor is decided first, over every Mind's pending lines, so one Mind of the roster takes each. let minds: Vec = config.personas.iter().map(|mind| mind.matrix_id.clone()).collect(); - // A Mind whose start failed on a line the floor gave her passes it on: the next of the pick takes it in the same poll. - let mut passed_over: Vec = Vec::new(); + // A Mind whose start failed on a line the floor gave her passes it on: the next of the pick takes it in the same poll. One whose + // last wakes failed is waited out (`cooling`) and passes the floor on likewise. + let mut passed_over: Vec = rows.iter().filter(|row| row.cooling(now, beat_s)).map(|row| row.slug().0.clone()).collect(); let mut tried: Vec = Vec::new(); 'floor: loop { let floor = floors(&rows, &state, now, config, &minds, &passed_over).won; for (index, row) in rows.iter_mut().enumerate() { - if !row.idle() || tried.contains(&index) { + if !row.idle() || tried.contains(&index) || row.cooling(now, beat_s) { continue; } let slug = row.slug().clone(); + // The first line that wakes her and her trace does not hold decided: that, and only that, decides whether she is woken. let mentioned = { let mut pending: Vec<&ChatDelivery> = row.pending.iter().collect(); pending.sort_by_key(|delivery| delivery.seq); @@ -891,12 +923,12 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { .zip(facts) .filter(|(delivery, facts)| wakes(&row.addressee, delivery, config.speaker(&row.addressee, delivery), *facts).is_some()) .map(|(delivery, _)| delivery.event_id.clone()) - .find(|event| !state.handled_mentions.contains(&format!("{}:{event}", slug.0))) + .find(|event| row.done.as_ref().is_some_and(|done| !done.contains(event))) }; 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 fails gives them back. - let before = state.clone(); + // The wake's lines are recorded before her unit starts, so the start reads them. A start that does not happen leaves the + // claim to lapse (`claim_stands`): she is neither running nor has she decided the line. for event in claimed(Some(&event), &floor[index]) { let key = format!("{}:{event}", slug.0); if !state.handled_mentions.contains(&key) { @@ -905,17 +937,15 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { } let excess = state.handled_mentions.len().saturating_sub(MENTIONS_KEPT); state.handled_mentions.drain(..excess); - state.last_turn_at.insert(slug.0.clone(), now); organs.store.save(&state)?; match wake(organs, row) { Woke::Started => { + state.last_turn_at.insert(slug.0.clone(), now); row.busy = true; launches.push(slug.0.clone()); launched.push(slug); } refused => { - state = before; - organs.store.save(&state)?; match refused { Woke::Refused(why) => row.note = why, _ => row.busy = true, diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index e5f8779..2489617 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -181,7 +181,28 @@ const ANN: usize = 0; const BOB: usize = 1; const NAMES: [&str; 2] = ["ann", "bob"]; +/// A Persona's trace as the poll reads it: the records her drain wrote, or none readable. +#[derive(Default)] +struct FakeTrace { + rows: RefCell>, + unreadable: Cell, +} + +impl Trace for FakeTrace { + fn record(&self, _: &str, record: &serde_json::Value) -> Result<()> { + self.rows.borrow_mut().push(record.clone()); + Ok(()) + } + fn records(&self) -> Result> { + if self.unreadable.get() { + bail!("her trace is unreadable"); + } + Ok(self.rows.borrow().clone()) + } +} + struct Rig { + traces: Vec, minds: Vec, calls: Vec>, admits: Cell, @@ -198,6 +219,7 @@ struct Rig { impl Rig { fn new() -> Box { Box::new(Self { + traces: vec![FakeTrace::default(), FakeTrace::default()], minds: vec![TestMind::seeded_as("ann"), TestMind::seeded_as("bob")], calls: vec![Cell::new(0), Cell::new(0)], admits: Cell::new(0), @@ -231,7 +253,7 @@ impl Rig { .zip(&self.calls) .map(|(inner, calls)| Counting { inner, calls, admits: &self.admits, stewardship_reads: &self.stewardship_reads, stewardship_down: &self.stewardship_down }) .collect(); - let seats: Vec = self.config.personas.iter().enumerate().map(|(index, who)| Seat { who: who.clone(), mind: &ports[index], chat: &self.chats[index] }).collect(); + let seats: Vec = self.config.personas.iter().enumerate().map(|(index, who)| Seat { who: who.clone(), mind: &ports[index], chat: &self.chats[index], trace: &self.traces[index] }).collect(); let organs = Organs { seats: &seats, control: &self.control, launcher: &self.launcher, clock: &self.clock, store: &self.store }; poll(&organs, &self.config).unwrap() } @@ -270,12 +292,20 @@ impl Rig { self.launcher.kill_as(&Slug(NAMES[who].into()), RunTurn::PersonaTurn); } - /// Her turn finished: her unit ends and her drain acked what was pending, so her chat holds none of it. + /// Her turn finished: her unit ends, her trace holds the pending lines decided and her drain acked them, so her chat holds none of it. fn finish_turn(&self, who: usize) { self.end_unit(who); + let held: Vec = self.chats[who].deliveries.borrow().iter().map(|line| line.event_id.clone()).collect(); + self.traces[who].rows.borrow_mut().push(serde_json::json!({ "held": held, "at": self.now().to_rfc3339() })); self.chats[who].deliveries.borrow_mut().clear(); } + /// Her turn failed: her unit ends, her trace holds a failed record, and her chat still holds the lines. + fn fail_turn(&self, who: usize) { + self.end_unit(who); + self.traces[who].rows.borrow_mut().push(serde_json::json!({ "failed": "the connector did not answer: unavailable", "outage": true, "at": self.now().to_rfc3339() })); + } + /// Her unit is active. fn in_a_turn(&self, who: usize) { self.launcher.revive_as(&Slug(NAMES[who].into()), RunTurn::PersonaTurn); @@ -877,7 +907,7 @@ mod wake_rule { } #[test] - fn the_lines_a_wake_is_for_are_recorded_before_her_unit_starts_and_given_back_when_it_does_not_start() { + fn the_lines_a_wake_is_for_are_recorded_before_her_unit_starts_and_lapse_when_it_does_not_start() { let mut rig = quiet_rig(); rig.launcher.log = rig.store.log.clone(); said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); @@ -891,8 +921,11 @@ mod wake_rule { rig.launcher.fail.set(true); said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }); + rig.launcher.fail.set(false); + rig.advance(1); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "nothing was taken: the claim of a start that did not happen lapsed, and the hello is judged afresh"); let state = rig.store.state.borrow().clone().unwrap(); - assert!(woken_for(&state, "ann").is_empty() && woken_for(&state, "bob").is_empty(), "a start that failed claims nothing: {:?}", state.handled_mentions); + assert!(woken_for(&state, "bob").is_empty() && woken_for(&state, "ann").len() == 1, "one claim, hers: {:?}", state.handled_mentions); } #[test] @@ -976,6 +1009,8 @@ mod wake_rule { #[test] fn an_old_hello_whose_taken_key_was_forgotten_wakes_no_one_and_the_keys_are_bounded() { let rig = quiet_rig(); + let old: Vec = (0..70).map(|at| format!("$old{at}")).collect(); + rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": old, "at": rig.now().to_rfc3339() })); rig.with_state(|state| state.handled_mentions = (0..70).map(|at| format!("ann:$old{at}")).collect()); said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); @@ -1152,3 +1187,76 @@ fn the_file_store_view_fails_on_an_unreadable_state() { std::fs::write(&path, b"not a cultcache file").unwrap(); assert!(HeartbeatView::woken_for(&FileStore::new(path), "ann").is_err()); } + +/// Soul s4 release-regives-answered-hello: she decided the hello, but an older room's failed turn holds the ack below it, so it is +/// still pending in her queue. Her trace says it is hers and done; the poll does not read "still pending" as "her turn left it". +#[test] +fn a_hello_she_decided_whose_ack_is_held_is_not_given_to_a_second_mind() { + let rig = quiet_rig(); + wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); + rig.end_unit(ANN); + rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "at": rig.now().to_rfc3339() })); + assert!(!rig.chats[ANN].deliveries.borrow().is_empty(), "the ack is held: the hello is still in her queue"); + for _ in 0..5 { + rig.advance(60); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "decided by her trace: not hers again, not Bob's"); + } +} + +/// A line her trace holds decided is not woken for again however long the mouth keeps it; one it does not hold is. +#[test] +fn only_her_trace_decides_whether_a_line_is_woken_for() { + let rig = quiet_rig(); + rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[])); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); + rig.end_unit(ANN); + rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "at": rig.now().to_rfc3339() })); + rig.advance(120); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "decided"); + rig.say(ANN, delivery(2, "@op:chat", "Ann, again", &[])); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "a new line is not"); +} + +/// A trace the poll cannot read decides nothing: she is not woken on a guess, and the poll says so. +#[test] +fn an_unreadable_trace_wakes_no_one_and_is_noted() { + let rig = quiet_rig(); + rig.traces[ANN].unreadable.set(true); + rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[])); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }); + assert!(rig.notes().iter().any(|note| note.contains("trace unread")), "{:?}", rig.notes()); +} + +/// Soul s4 outage-rewake-floods-records: a wake whose turn failed is waited out, 20 s doubling with each failure in a row her trace +/// holds, up to the beat, instead of failing every poll. +#[test] +fn a_wake_that_failed_is_waited_out_by_the_failures_in_a_row_up_to_the_beat() { + let rig = quiet_rig(); + rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[])); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); + for run in 1..=9u32 { + rig.fail_turn(ANN); + let wait = (20i64 << (run - 1)).min(i64::from(BEAT_S)); + rig.advance(wait - 1); + rig.beat_fell(); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "failure {run}: still waiting out {wait} s"); + rig.advance(1); + rig.beat_fell(); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "failure {run}: {wait} s passed"); + } + assert_eq!(rig.launched().len(), 10); + rig.finish_turn(ANN); + rig.advance(1); + rig.beat_fell(); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "decided: the run ends"); +} + +/// A Mind that is waiting out failures passes the open floor on, as one whose start failed does. +#[test] +fn a_mind_waiting_out_failures_passes_the_hello_to_the_other() { + let rig = quiet_rig(); + rig.fail_turn(ANN); + wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }); +} diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 055d54b..50b9104 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -50,7 +50,7 @@ pub use narrate::{Answer, Continued, Failed, KitModel, Model, Reasoning, Spent, 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, decide, decided, deliver, history}; +pub(crate) use turn::{Mouth, Taken, decide, decided, deliver, failed_run, history}; 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}; diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs index 5611c97..6dc1a49 100644 --- a/crates/mind-body/src/projection/turn.rs +++ b/crates/mind-body/src/projection/turn.rs @@ -185,6 +185,13 @@ pub(crate) fn decided(records: &[Value]) -> BTreeSet<&str> { done } +/// How many records at the end of her trace are failures in a row, and when the last of them was made: what the poll backs off by. +pub(crate) fn failed_run(records: &[Value]) -> (u32, Option>) { + let run = records.iter().rev().take_while(|record| record.get("failed").is_some()).count(); + let at = records.last().filter(|_| run > 0).and_then(|record| record["at"].as_str()).and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc)); + (u32::try_from(run).unwrap_or(u32::MAX), at) +} + /// What her records say of her: her last turn's record, the ids her last projections selected, her last records and /// when she last woke. The one reader, over a run's list or her trace. A failed turn is in her trace and not in her packet's /// window: an outage that fails every wake for an hour must not push her real turns out of it, so only her last outcome may be diff --git a/crates/mind-body/src/projection/turn/tests.rs b/crates/mind-body/src/projection/turn/tests.rs index ed16bda..623c124 100644 --- a/crates/mind-body/src/projection/turn/tests.rs +++ b/crates/mind-body/src/projection/turn/tests.rs @@ -182,6 +182,8 @@ fn t_l2_failed_records_never_push_her_real_turns_out_of_the_window() { assert_eq!(past.recent.len(), 3, "and so do her recent selections"); assert!(past.last_outcome.is_some_and(|last| last.get("failed").is_some()), "her last outcome may be the failure: she is told once"); assert_eq!(past.last_wake.map(|at| at.to_rfc3339()), Some("2026-11-27T10:00:02+00:00".to_owned()), "and her last wake is her last decision"); + assert_eq!(failed_run(&records).0, 200); + assert_eq!(failed_run(&records[..3]).0, 0); } /// A record is decided when it holds its lines and owes no send; a failure decides nothing. diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index fabb09a..5ef101b 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -180,7 +180,7 @@ mind_body::heartbeat: struct InstanceTrace # [derive (Clone , Debug , PartialEq mind_body::heartbeat: struct Organs< 'a > pub-fields[seats: & 'a [Seat < 'a >], control: & 'a dyn Control, launcher: & 'a dyn Launcher, clock: & 'a dyn Clock, store: & 'a dyn Store] mind_body::heartbeat: struct PersonaId # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[slug: Slug, public_name: String, handle: String, matrix_id: String, huginn: SocketAddr] mind_body::heartbeat: struct PollTrace # [derive (Clone , Debug , PartialEq , Eq , DatabaseEntry)] pub-fields[at: DateTime < Utc >, tempo_s: u32, instances: Vec < InstanceTrace >, launches: Vec < String >] -mind_body::heartbeat: struct Seat< 'a > pub-fields[who: PersonaId, mind: & 'a dyn MindPort, chat: & 'a dyn Chat] +mind_body::heartbeat: struct Seat< 'a > pub-fields[who: PersonaId, mind: & 'a dyn MindPort, chat: & 'a dyn Chat, trace: & 'a dyn Trace] mind_body::launch: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum StopScope < 'a > { Mind (& 'a Slug) , Swarm , } mind_body::launch: impl Clock for SystemClock mind_body::launch: impl Default for SystemdLauncher