persona drain: a decision is her trace's, owed or settled; owed sends go out first in every start; the heartbeat reads her trace without a lock

A line is decided as soon as her trace holds any decision on it (decided()), so a hello whose
answer is owed is never given to a second Mind. Every start delivers all owed sends, in every
room, before it takes a turn; the ack stops below any line whose decision still owes a send
(owing()). A send given up as owed_too_old is stamped, logged and told to her at her next wake
by her words, from the trace's given-up records; a line of hers already in the room is the
send's receipt, so a posted line is never recorded refused. The decision record is written
before her state is put, so a retry after a failed record never applies her proposals twice.
The heartbeat reads each trace through CultLib's pull_all_read_only_snapshot (TraceSnapshot,
TraceView), which creates no lock file and opens nothing for write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 02:39:00 +01:00
commit 46016c46f7
10 changed files with 340 additions and 63 deletions

View file

@ -14,7 +14,7 @@
//! 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`, `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).
//! `persona-trace.cc` with `{slug}` where her slug goes (read through a lock-free snapshot, no write access: her trace is the record of which lines she has decided).
//! The heartbeat holds no connector key.
use std::net::SocketAddr;
@ -25,7 +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::persona::TraceSnapshot;
use mind_body::launch::{SystemClock, SystemdLauncher};
use mind_body::queue::HuginnMind;
@ -90,7 +90,7 @@ fn run() -> Result<()> {
if !traces_at.contains("{slug}") {
bail!("MIND_HEARTBEAT_TRACES names no {{slug}}");
}
let traces: Vec<FileTrace> = config.personas.iter().map(|who| FileTrace::new(traces_at.replace("{slug}", &who.slug.0))).collect();
let traces: Vec<TraceSnapshot> = config.personas.iter().map(|who| TraceSnapshot::new(traces_at.replace("{slug}", &who.slug.0))).collect();
let seats: Vec<Seat> = config
.personas
.iter()

View file

@ -35,7 +35,7 @@ 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::persona::TraceView;
use crate::projection::{decided, failed_run};
use crate::queue::{MindPort, headers, in_force, of_kind};
use crate::tempo::{self, Standing};
@ -387,7 +387,7 @@ pub struct Seat<'a> {
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 trace: &'a dyn TraceView,
}
pub struct Organs<'a> {

View file

@ -15,6 +15,7 @@ use huginn_mind::PipelineSelectionPage;
use tempfile::TempDir;
use super::*;
use crate::persona::Trace;
use crate::address::addresses;
use crate::control::{Brake, ControlState, SwarmState};
use crate::testkit::{Fixed, Recording, TestMind, at, reference};
@ -193,6 +194,9 @@ impl Trace for FakeTrace {
self.rows.borrow_mut().push(record.clone());
Ok(())
}
}
impl TraceView for FakeTrace {
fn records(&self) -> Result<Vec<serde_json::Value>> {
if self.unreadable.get() {
bail!("her trace is unreadable");
@ -1260,3 +1264,32 @@ fn a_mind_waiting_out_failures_passes_the_hello_to_the_other() {
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())] });
}
/// 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.
#[test]
fn a_hello_she_decided_whose_send_is_owed_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!"));
rig.poll();
rig.end_unit(ANN);
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![], "no one is given an owed hello");
assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"], "her claim stands");
}
/// Soul's S12: a claim survives a trace that cannot be read, so the line is not given on a guess.
#[test]
fn a_claim_survives_a_trace_that_cannot_be_read() {
let rig = quiet_rig();
wake_rule::said_in_general(&rig, wake_rule::general(1, "@newcomer:chat", "hello everyone!"));
rig.poll();
rig.end_unit(ANN);
rig.traces[ANN].unreadable.set(true);
rig.advance(60);
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert_eq!(launched, vec![]);
assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"]);
}

View file

@ -35,7 +35,7 @@ use std::path::PathBuf;
use anyhow::{Result, anyhow, bail};
use chrono::{DateTime, Utc};
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore, decode_payload};
use eureka_pipeline::{MemoryOrigin, Slug};
use huginn_mind::{Faculty, HuginnMindResponse, MindRefusal, PersonaPutOutcome, PipelineProvenance};
use serde_json::{Value, json};
@ -44,7 +44,7 @@ use crate::address::{Addressee, addresses, is_for, localpart};
use crate::chat_client::{Basis, Chat, ChatDelivery, TailLine};
use crate::control::{ControlSource, Effective, HeldReason, derive};
use crate::heartbeat::{HeartbeatView, Speaker, own_rooms, pending_facts, read_pending, wakes};
use crate::projection::{DomainSource, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, decide, decided, deliver, history, own_addressee as heard_as};
use crate::projection::{DomainSource, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, decide, decided, deliver, history, owing, Landed, own_addressee as heard_as};
/// The admitting agent's name on what her Persona admitted; `self_run::inbox` still reads her briefs by it.
pub const AGENT: &str = "mind-persona";
@ -150,8 +150,12 @@ impl Config {
/// Where a turn's record goes: the record itself, the shape `projection::outcome::outcome_of` reads, keyed `<run>-t<turn>`.
/// Her last outcome, her recent selections, her exchange records and her last wake are read back from it
/// (`projection::turn::history`); nothing else holds them.
pub trait Trace {
pub trait Trace: TraceView {
fn record(&self, key: &str, record: &Value) -> Result<()>;
}
/// Her records, read and nothing else: what a reader that does not own the trace holds.
pub trait TraceView {
/// Every record, oldest first.
fn records(&self) -> Result<Vec<Value>>;
}
@ -188,14 +192,41 @@ impl Trace for FileTrace {
self.open()?.put(key.to_owned(), &TurnRecord { value: record.clone() })?;
Ok(())
}
}
impl TraceView for FileTrace {
fn records(&self) -> Result<Vec<Value>> {
let mut rows: Vec<(String, String, Value)> = self.open()?.get_all_with_keys::<TurnRecord>()?.into_iter().map(|(key, row)| (row.value["at"].as_str().unwrap_or_default().to_owned(), key, row.value)).collect();
rows.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
Ok(rows.into_iter().map(|(_, _, value)| value).collect())
Ok(ordered(self.open()?.get_all_with_keys::<TurnRecord>()?.into_iter().map(|(key, row)| (key, row.value))))
}
}
/// The trace as a reader without write authority sees it: one snapshot of the file, taken with no lock file created or opened for
/// write (CultLib `pull_all_read_only_snapshot`). The owner replaces the file whole, so a snapshot is a complete trace.
pub struct TraceSnapshot {
path: PathBuf,
}
impl TraceSnapshot {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into() }
}
}
impl TraceView for TraceSnapshot {
fn records(&self) -> Result<Vec<Value>> {
let envelopes = SingleFileMessagePackBackingStore::new(&self.path).pull_all_read_only_snapshot()?;
let rows = envelopes.into_iter().filter(|envelope| envelope.r#type == TurnRecord::TYPE).map(|envelope| Ok((envelope.key, decode_payload::<TurnRecord>(&envelope.payload)?.value))).collect::<Result<Vec<_>>>()?;
Ok(ordered(rows))
}
}
/// Records oldest first: by the time each carries, then by key.
fn ordered(rows: impl IntoIterator<Item = (String, Value)>) -> Vec<Value> {
let mut rows: Vec<(String, String, Value)> = rows.into_iter().map(|(key, value)| (value["at"].as_str().unwrap_or_default().to_owned(), key, value)).collect();
rows.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
rows.into_iter().map(|(_, _, value)| value).collect()
}
/// What a start did. Every outcome is an answer.
#[derive(Debug, PartialEq, Eq)]
pub enum Outcome {
@ -262,6 +293,9 @@ const STRIKES: usize = 2;
/// same id is no longer the same send, so a repeat could post twice; the send is given up.
const OWED_WINDOW_S: i64 = 1800;
/// How much earlier than its record a line may be stamped and still be taken as that record's send: the mouth's clock and hers differ.
const OWED_SKEW_MS: u64 = 60_000;
/// A waking line: where it sits in the mouth's queue, and which room and event it is.
struct Waking<'a> {
seq: u64,
@ -361,7 +395,7 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
let mut put_refusals = 0;
let mut acked: Option<u64> = None;
// The ack is cleanup behind her trace and decides nothing: through the highest seq below the first line this start was to
// answer or set aside that her trace does not yet hold as decided. A start killed between turns does not replay a message she
// answer or set aside that her trace does not yet hold as decided, or whose decision still owes a send. A start killed between turns does not replay a message she
// answered, and a line whose record did not land is never acked past.
let settle = |acked: &mut Option<u64>| {
let records = match start.trace.records() {
@ -369,7 +403,8 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
Err(fault) => return eprintln!("mind-persona: her trace was not read, so nothing is acked: {fault:#}"),
};
let done = decided(&records);
let blocked = aside.iter().chain(&waking).filter(|line| !done.contains(line.event)).map(|line| line.seq).min();
let owing = owing(&records);
let blocked = aside.iter().chain(&waking).filter(|line| !done.contains(line.event)).map(|line| line.seq).chain(deliveries.iter().filter(|delivery| owing.contains(delivery.event_id.as_str())).map(|delivery| delivery.seq)).min();
let through = deliveries.iter().map(|delivery| delivery.seq).filter(|seq| blocked.is_none_or(|limit| *seq < limit)).max().filter(|seq| acked.is_none_or(|held| *seq > held));
if let Some(seq) = through {
match start.chat.ack(seq) {
@ -378,6 +413,33 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
}
}
};
// Every send her trace shows owed goes out first, in every room, as it was recorded and under the ids it was recorded with: the
// model is not asked again, and a post that was lost is the same post. A record older than the homeserver remembers a transaction
// is given up, since the same id could no longer be told from a new line; a line of hers already in the room is its receipt.
let owed: Vec<Value> = trace.iter().filter(|record| record.get("failed").is_none() && record["owed"].as_array().is_some_and(|owed| !owed.is_empty())).cloned().collect();
for mut record in owed {
let now = (start.clock)();
let recorded_ms = record["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.timestamp_millis());
let age = recorded_ms.map_or(i64::MAX, |at| (now.timestamp_millis() - at) / 1000);
let landed = |send: &Value| -> Option<String> {
let (room, text) = (send["room"].as_str()?, send["text"].as_str()?.trim());
let since = u64::try_from(recorded_ms?).unwrap_or_default().saturating_sub(OWED_SKEW_MS);
let tail = pending.tail.iter().flatten();
tail.filter(|line| line.sender == config.own_sender && line.room == room && line.at_unix_ms >= since).find(|line| !line.body.trim().is_empty() && text.starts_with(line.body.trim().trim_end_matches('…').trim())).map(|line| line.event_id.clone())
};
let give_up: Option<Landed> = (age > OWED_WINDOW_S).then_some(&landed);
deliver(&mouth, &mut record, give_up);
let given_up: Vec<&Value> = record["refused_sends"].as_array().into_iter().flatten().filter(|refused| refused["refusal"] == "owed_too_old").collect();
if !given_up.is_empty() {
eprintln!("mind-persona: {} owed send(s) were given up as too old to repeat, and are told to her at her next wake: {given_up:?}", given_up.len());
record["gave_up_at"] = json!(now.to_rfc3339());
}
if let Err(fault) = start.trace.record(record["key"].as_str().unwrap_or_default(), &record) {
eprintln!("mind-persona: the record of a send owed was not rewritten: {fault:#}");
}
turns += 1;
settle(&mut acked);
}
// A line set aside is recorded, then acked past before the room's turn, so that turn reads the room without it.
if !aside.is_empty() {
let lines: Vec<Value> = aside.iter().map(|line| json!({ "room": line.room, "event": line.event, "sender": line.sender, "text": line.text })).collect();
@ -395,23 +457,6 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
Ok(records) => records,
Err(fault) => return failed("her trace was not read", fault),
};
// A decision of hers in this room that still owes a send goes out as it was recorded, under the ids it was recorded with, and
// the model is not asked again: a post that was lost is the same post. One older than the homeserver remembers a transaction is
// given up, since the same id could no longer be told from a new line.
let owed: Vec<&Value> = records.iter().filter(|record| record["room"] == *room && record["owed"].as_array().is_some_and(|owed| !owed.is_empty())).collect();
if !owed.is_empty() {
for record in owed {
let mut record = record.clone();
let age = record["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map_or(i64::MAX, |at| (now - at.with_timezone(&Utc)).num_seconds());
deliver(&mouth, &mut record, age > OWED_WINDOW_S);
if let Err(fault) = start.trace.record(record["key"].as_str().unwrap_or_default(), &record) {
eprintln!("mind-persona: the record of a send owed in {room} was not rewritten: {fault:#}");
}
}
turns += 1;
settle(&mut acked);
continue;
}
// The turn's own key, which names its sends: an answer is the answer to the oldest line it wakes on, so a re-run of that
// line is the same key. A beat answers no line and is a fresh speech each start.
let key = waking.iter().find(|line| line.room == *room).map_or_else(|| format!("b{began_ms}-t{index}"), |line| format!("l{}", line.event));
@ -454,30 +499,30 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
{
turn.record["strike"] = json!(line.event);
}
if turn.record.get("failed").is_none() && turn.state != state {
match put_applied(start.persona.as_ref(), &state, &turn, &key, now, start.clock.as_ref()) {
Ok(landed) => state = landed,
Err((fresh, why)) => {
put_refusals += 1;
turn.record["put_refused"] = json!(why);
eprintln!("mind-persona: the put of turn {key} was refused twice: {why}");
state = fresh;
}
}
}
// Write ahead: the record of the decision, every line's words and send id, is durable before any of it is sent. A record
// that cannot be written sends nothing, and the line is decided by no one until it is.
// Write ahead: the record of the decision, every line's words and send id, is durable before any of it is applied or sent. A
// record that cannot be written puts nothing and sends nothing, and the line is decided by no one until it is.
turns += 1;
match start.trace.record(&record_key, &turn.record) {
Ok(()) => {
deliver(&mouth, &mut turn.record, false);
if turn.record.get("failed").is_none() && turn.state != state {
match put_applied(start.persona.as_ref(), &state, &turn, &key, now, start.clock.as_ref()) {
Ok(landed) => state = landed,
Err((fresh, why)) => {
put_refusals += 1;
turn.record["put_refused"] = json!(why);
eprintln!("mind-persona: the put of turn {key} was refused twice: {why}");
state = fresh;
}
}
}
deliver(&mouth, &mut turn.record, None);
if turn.record.get("failed").is_none()
&& let Err(fault) = start.trace.record(&record_key, &turn.record)
{
eprintln!("mind-persona: the receipts of turn {key} were not appended, so its lines are owed again under their ids: {fault:#}");
}
}
Err(fault) => eprintln!("mind-persona: the record of turn {key} was not appended, so nothing of it was sent: {fault:#}"),
Err(fault) => eprintln!("mind-persona: the record of turn {key} was not appended, so nothing of it was put or sent: {fault:#}"),
}
settle(&mut acked);
}
@ -546,7 +591,7 @@ fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str,
}
/// The newest `last` records of her trace as JSON lines, oldest first. Read-only.
pub fn trace_lines(trace: &dyn Trace, last: usize) -> Result<Vec<String>> {
pub fn trace_lines(trace: &dyn TraceView, last: usize) -> Result<Vec<String>> {
let records = trace.records()?;
Ok(records[records.len().saturating_sub(last)..].iter().map(Value::to_string).collect())
}

View file

@ -173,6 +173,9 @@ impl Trace for Rc<MemTrace> {
}
Ok(())
}
}
impl TraceView for Rc<MemTrace> {
fn records(&self) -> Result<Vec<Value>> {
Ok(self.rows.borrow().iter().map(|(_, record)| record.clone()).collect())
}
@ -369,7 +372,7 @@ fn t_l2_second_stale_put_is_put_refused_in_the_record() {
let rows = rig.trace.rows.borrow();
assert_eq!(rows.len(), 1, "the record is appended though the put was refused");
assert!(rows[0].1["put_refused"].is_string(), "{:?}", rows[0].1);
assert_eq!(rig.log().iter().position(|event| event == "trace"), Some(rig.log().len() - 4), "the record comes after the puts: {:?}", rig.log());
assert_eq!(rig.log().iter().position(|event| event == "trace"), Some(0), "the record comes before the puts: {:?}", rig.log());
assert!(rig.store.puts.borrow().is_empty(), "nothing of hers landed");
}
@ -919,6 +922,7 @@ fn t_l2_a_send_owed_past_the_homeservers_memory_is_given_up_and_posts_nothing_tw
rig.mouth.answer_lost.set(true);
rig.run(scripted(false));
assert_eq!(rig.mouth.sent.borrow().len(), 1);
rig.mouth.tail.borrow_mut().clear();
rig.mouth.forgot.set(true);
rig.ticks.set(rig.ticks.get() + 3600);
rig.run(Never);
@ -939,3 +943,127 @@ fn t_l2_a_decided_line_pending_behind_a_failed_ack_is_not_asked_again() {
assert_eq!(rig.run(Never), Outcome::Drained { turns: 0, acked_through: Some(1), put_refused: 0 });
assert_eq!(sends_to(&rig, &room(1)), 1);
}
fn owed_of(rig: &Rig) -> Vec<Value> {
rig.trace.rows.borrow().iter().filter(|(_, record)| record["owed"].as_array().is_some_and(|owed| !owed.is_empty())).map(|(_, record)| record["owed"].clone()).collect()
}
/// A hello she decided whose send answer was lost: a later start that no line woke sends it as recorded, once, and acks it.
#[test]
fn t_l3_an_owed_send_goes_out_at_the_next_start_whatever_woke_it() {
let rig = Rig::new(vec![line(1, MINDS, "@deru:gamecult.org", "hello all")]);
rig.mouth.answer_lost.set(true);
rig.run_woken(scripted(false), &["$e1"]);
assert_eq!((owed_of(&rig).len(), rig.held_seqs()), (1, vec![1]), "the send is owed and the ack stays below it");
rig.run_woken(Never, &["$e1"]);
assert_eq!(rig.mouth.sent.borrow().len(), 1, "one post under the one id");
assert!(owed_of(&rig).is_empty(), "the record settled");
assert!(rig.held_seqs().is_empty(), "and the line is acked once its send is");
}
/// The owed send of one room goes out in a start woken for another room only (S8), before that room's turn.
#[test]
fn t_l3_an_owed_send_goes_out_in_a_start_woken_for_another_room() {
let rig = Rig::new(vec![line(1, MINDS, "@deru:gamecult.org", "hello all")]);
rig.mouth.answer_lost.set(true);
rig.run_woken(scripted(false), &["$e1"]);
rig.mouth.held.borrow_mut().push(line(2, &room(1), META, "ping"));
rig.run(scripted(false));
assert!(owed_of(&rig).is_empty(), "the hello's send is settled by a start that was woken for the dm");
assert_eq!(rig.mouth.sent.borrow().len(), 2, "the hello's one post and the dm's answer");
assert!(rig.held_seqs().is_empty());
}
/// The ack never passes a line whose send is still owed, however the start was woken.
#[test]
fn t_l3_the_ack_stays_below_a_line_whose_send_is_still_owed() {
let rig = Rig::new(vec![line(1, MINDS, "@deru:gamecult.org", "hello all"), line(2, &room(1), META, "ping")]);
rig.mouth.answer_lost.set(true);
rig.run_woken(scripted(false), &["$e1", "$e2"]);
assert_eq!(owed_of(&rig).len(), 1, "the hello's send is owed");
assert_eq!(rig.held_seqs(), [1, 2], "the ack stops below the owed line though her trace holds it decided, and the line after it waits with it");
}
/// A send owed past the homeserver's memory whose line is not in the room is given up: told to her, logged, never re-asked.
#[test]
fn t_l3_a_send_given_up_is_recorded_stamped_and_not_decided_again() {
let rig = Rig::new(vec![line(1, MINDS, "@deru:gamecult.org", "hello all")]);
rig.mouth.answer_lost.set(true);
rig.run_woken(scripted(false), &["$e1"]);
rig.mouth.tail.borrow_mut().clear();
rig.mouth.forgot.set(true);
rig.ticks.set(rig.ticks.get() + 3600);
rig.run_woken(Never, &["$e1"]);
let rows = rig.trace.rows.borrow();
let record = &rows[0].1;
assert_eq!(record["refused_sends"][0]["refusal"], "owed_too_old");
assert!(record["gave_up_at"].is_string(), "{record}");
assert!(record.get("owed").is_none());
assert_eq!(rig.mouth.sent.borrow().len(), 1, "nothing was posted twice");
}
/// Soul's p8: the post landed and its receipt rewrite died; a start past the window finds her own line in the room, and the line is
/// recorded as posted, never as refused.
#[test]
fn t_l3_a_send_that_landed_is_never_recorded_refused() {
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
rig.trace.allow.set(1);
rig.run(scripted(false));
assert_eq!(rig.mouth.sent.borrow().len(), 1);
rig.trace.allow.set(usize::MAX);
rig.mouth.forgot.set(true);
rig.ticks.set(rig.ticks.get() + 1900);
rig.run(Never);
let rows = rig.trace.rows.borrow();
let record = &rows[0].1;
assert!(record["refused_sends"].as_array().is_some_and(Vec::is_empty), "{record}");
assert_eq!(record["posted"].as_array().map(Vec::len), Some(1), "{record}");
assert_eq!(rig.mouth.sent.borrow().len(), 1);
}
/// Soul's p9: a record that cannot be written puts nothing; the retry applies her memory of the turn once.
#[test]
fn t_l3_a_retry_after_a_failed_record_applies_her_proposals_once() {
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
rig.trace.fail.set(true);
rig.run(scripted(true));
rig.run(scripted(true));
assert!(rig.store.puts.borrow().is_empty(), "no put without its record");
rig.trace.fail.set(false);
rig.run(scripted(true));
let stored = rig.store.stored.borrow().clone();
let ids: Vec<&str> = stored["thoughtMemory"]["shortTerm"].as_array().into_iter().flatten().filter_map(|entry| entry["id"].as_str()).filter(|id| id.starts_with('l')).collect();
assert_eq!((rig.store.puts.borrow().len(), ids.len()), (1, 1), "{ids:?}");
}
/// A set-aside line is acked past only once its record landed (S10).
#[test]
fn t_l3_the_ack_waits_for_a_set_aside_lines_record() {
let rig = Rig::new(vec![line(1, &room(1), META, "FAILME hello")]);
rig.run(failing(REFUSED));
rig.run(failing(REFUSED));
rig.trace.fail.set(true);
rig.run(failing(REFUSED));
assert!(!set_aside(&rig) && rig.held_seqs() == [1], "its record did not land, so the line is not acked past");
rig.trace.fail.set(false);
rig.run(failing(REFUSED));
assert!(set_aside(&rig) && rig.held_seqs().is_empty());
}
/// The heartbeat's reader opens nothing for write: the lock file stays absent where `records()` of the owner would make it.
#[test]
fn t_l3_the_snapshot_reader_creates_no_lock_file() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("persona-trace.cc");
let owner = FileTrace::new(&path);
owner.record("n0-t0", &json!({ "held": ["$e1"], "at": "2026-11-28T00:00:00Z" })).unwrap();
owner.record("n1-t0", &json!({ "held": ["$e2"], "at": "2026-11-28T00:01:00Z" })).unwrap();
let lock = dir.path().join("persona-trace.cc.lock");
std::fs::remove_file(&lock).unwrap();
let seen = TraceSnapshot::new(&path).records().unwrap();
assert_eq!(seen, owner.records().unwrap().into_iter().rev().rev().collect::<Vec<_>>());
std::fs::remove_file(&lock).unwrap();
assert_eq!(seen.len(), 2);
assert!(TraceSnapshot::new(&path).records().is_ok() && !lock.exists(), "a snapshot creates no lock file");
assert!(TraceSnapshot::new(dir.path().join("absent.cc")).records().unwrap().is_empty());
}

View file

@ -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, failed_run, history};
pub(crate) use turn::{Landed, Mouth, Taken, decide, decided, deliver, failed_run, history, owing};
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

@ -300,6 +300,12 @@ pub(crate) fn outcome_of(record: &Value) -> Option<Outcome> {
}
let mut outcome = Outcome::default();
let decision = &record["interpreter"];
// Sends the drain gave up (too old to repeat) since her last wake: told as lines that did not go out, whatever record they sit in.
for given_up in record["given_up"].as_array().into_iter().flatten() {
if let Some(text) = words_of(&given_up["text"]) {
outcome.parts.push(Part::Unsent { room: words(&given_up["room"]), text, reach: false });
}
}
let failed = record.get("failed").is_some() || decision.get("failed").is_some();
if failed && has_receipts(record) {
outcome.omitted.push("a malformed record: it says the turn failed and carries receipts".to_owned());

View file

@ -82,7 +82,7 @@ pub(crate) struct Taken {
/// One turn: `decide`, then `deliver`.
pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, key: &str, now: DateTime<Utc>) -> Taken {
let mut taken = decide(organs, request, key, now);
deliver(actuator, &mut taken.record, false);
deliver(actuator, &mut taken.record, None);
taken
}
@ -135,10 +135,16 @@ pub(crate) fn decide(organs: &Organs, request: &Request, key: &str, now: DateTim
Taken { report, record, state }
}
/// Answers, for one owed send, the event of her own line already in the room: that send's receipt.
pub(crate) type Landed<'a> = &'a dyn Fn(&Value) -> Option<String>;
/// Settles what `record` owes through `actuator`: each owed send is posted, refused (a refusal is an answer) or, when no answer
/// came, still owed. With `give_up` nothing is sent: each owed send is refused `owed_too_old`. The amendments follow once nothing
/// came, still owed. The amendments follow once nothing
/// is owed. A record that owes nothing is the shape the simulator and the mouth share.
pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, give_up: bool) {
///
/// With `give_up` (a record older than the homeserver remembers its ids) nothing is sent: `give_up` answers, for each owed send, the
/// event of her own line already in the room, which is that send's receipt; a send with none is refused `owed_too_old`.
pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, give_up: Option<Landed>) {
let owed: Vec<Value> = record["owed"].as_array().cloned().unwrap_or_default();
let mut still = Vec::new();
for send in owed {
@ -148,7 +154,7 @@ pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, give_up: bool
None => json!({ "room": room, "text": text, "refusal": why }),
};
let mentions: Vec<String> = send["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
let sent = if give_up { Sent::Refused("owed_too_old".to_owned()) } else { actuator.send(send["id"].as_str().unwrap_or_default(), room, text, send["in_reply_to"].as_str(), &mentions) };
let sent = if let Some(landed) = give_up { landed(&send).map_or_else(|| Sent::Refused("owed_too_old".to_owned()), Sent::Posted) } else { actuator.send(send["id"].as_str().unwrap_or_default(), room, text, send["in_reply_to"].as_str(), &mentions) };
match sent {
Sent::Posted(event) => record["posted"].as_array_mut().into_iter().for_each(|posted| posted.push(json!({ "event": event, "room": room, "text": text }))),
Sent::Refused(why) => record["refused_sends"].as_array_mut().into_iter().for_each(|refused| refused.push(refusal(&why))),
@ -173,18 +179,28 @@ pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, give_up: bool
}
}
/// The events her trace shows she is done with: every line a record that did not fail held (`held`, the room's event ids the drain
/// read for it) once that record owes no send, and every line set aside (`set_aside`). 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 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.
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() && record["owed"].as_array().is_none_or(Vec::is_empty)) {
for record in records.iter().filter(|record| record.get("failed").is_none()) {
done.extend(record["held"].as_array().into_iter().flatten().filter_map(Value::as_str));
done.extend(record["set_aside"].as_array().into_iter().flatten().filter_map(|aside| aside["event"].as_str()));
}
done
}
/// The events held by a decision that still owes a send: the ack never passes one.
pub(crate) fn owing(records: &[Value]) -> BTreeSet<&str> {
let mut owing = BTreeSet::new();
for record in records.iter().filter(|record| record.get("failed").is_none() && record["owed"].as_array().is_some_and(|owed| !owed.is_empty())) {
owing.extend(record["held"].as_array().into_iter().flatten().filter_map(Value::as_str));
}
owing
}
/// 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<DateTime<Utc>>) {
let run = records.iter().rev().take_while(|record| record.get("failed").is_some()).count();
@ -204,6 +220,20 @@ pub(crate) struct Past {
pub last_wake: Option<DateTime<Utc>>,
}
/// The sends her trace shows given up (`owed_too_old`) that no wake of hers has followed since: each a `{room, text}`, told once, at her next
/// wake. A record gives up when it is rewritten, so it is told by when it gave up (`gave_up_at`), not by where it sits in the trace.
fn given_up(records: &[Value]) -> Vec<Value> {
let at = |record: &Value, field: &str| record[field].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok());
let last_wake = records.iter().filter(|record| record.get("failed").is_none() && record.get("gave_up_at").is_none()).filter_map(|record| at(record, "at")).max();
let mut told = Vec::new();
for record in records.iter().filter(|record| record.get("failed").is_none()) {
if at(record, "gave_up_at").is_some_and(|gave| last_wake.is_none_or(|wake| wake < gave)) {
told.extend(record["refused_sends"].as_array().into_iter().flatten().filter(|refused| refused["refusal"] == "owed_too_old").map(|refused| json!({ "room": refused["room"], "text": refused["text"] })));
}
}
told
}
/// Her `records`, oldest first, read.
pub(crate) fn history(records: &[Value]) -> Past {
let selected = |record: &Value| record["selected"].as_array().map(|ids| ids.iter().filter_map(Value::as_str).map(str::to_owned).collect::<Vec<_>>());
@ -211,7 +241,13 @@ pub(crate) fn history(records: &[Value]) -> Past {
let mut recent: Vec<Vec<String>> = real.iter().copied().filter_map(selected).collect();
recent.drain(..recent.len().saturating_sub(RECENT));
Past {
last_outcome: records.last().cloned(),
last_outcome: records.last().cloned().map(|mut last| {
let given_up = given_up(records);
if !given_up.is_empty() {
last["given_up"] = json!(given_up);
}
last
}),
recent,
records: real[real.len().saturating_sub(RECORDS)..].iter().map(|record| (*record).clone()).collect(),
last_wake: last_wake(records),

View file

@ -186,14 +186,37 @@ fn t_l2_failed_records_never_push_her_real_turns_out_of_the_window() {
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.
/// A record decides the lines it held, owed or settled; a failure decides nothing.
#[test]
fn t_l2_a_line_is_decided_by_a_record_that_owes_nothing() {
fn t_l2_a_line_is_decided_by_the_record_that_holds_it() {
let records = vec![
json!({ "held": ["$a"], "owed": [{ "id": "l$a:s0", "room": "r", "text": "hi" }] }),
json!({ "held": ["$b"], "posted": [] }),
json!({ "failed": "x", "held": ["$c"] }),
json!({ "set_aside": [{ "event": "$d" }] }),
];
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$b", "$d"]);
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$a", "$b", "$d"]);
}
/// A send the drain gave up is told to her at her next wake, by her words, whether or not its record is her newest; once a wake of hers
/// follows it, it is told no more.
#[test]
fn t_l3_a_send_given_up_is_told_at_her_next_wake_and_once() {
let wake = |at: &str| json!({ "held": ["$e9"], "posted": [], "refused_sends": [], "interpreter": { "said": [] }, "at": at });
let given_up = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "refused_sends": [{ "room": "#minds", "text": "welcome aboard", "refusal": "owed_too_old" }], "at": "2026-11-28T00:00:00Z", "gave_up_at": "2026-11-28T02:00:00Z" });
let records = vec![given_up.clone(), wake("2026-11-28T00:30:00Z")];
let last = history(&records).last_outcome.expect("her last record");
let told = outcome_of(&last).expect("an outcome").lines(forms(&json!({})));
assert!(told.iter().any(|line| line.contains("welcome aboard")), "{told:?}");
let records = vec![given_up, wake("2026-11-28T00:30:00Z"), wake("2026-11-28T03:00:00Z")];
let last = history(&records).last_outcome.expect("her last record");
assert!(last.get("given_up").is_none(), "a wake after it has told it");
}
/// An owed record holds its lines decided; the ack alone reads `owing`.
#[test]
fn t_l3_an_owed_record_decides_its_lines_and_owes_them_to_the_ack() {
let records = vec![json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "#a", "text": "hi" }] }), json!({ "held": ["$e2"], "failed": "x" })];
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$e1"]);
assert_eq!(owing(&records).into_iter().collect::<Vec<_>>(), ["$e1"]);
}

View file

@ -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, trace: & 'a dyn Trace]
mind_body::heartbeat: struct Seat< 'a > pub-fields[who: PersonaId, mind: & 'a dyn MindPort, chat: & 'a dyn Chat, trace: & 'a dyn TraceView]
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
@ -224,7 +224,7 @@ mind_body::persona: const ENV_ROOMS : & str
mind_body::persona: const ENV_SELF_SENDER : & str
mind_body::persona: const TURNS_PER_START : usize
mind_body::persona: fn carry < C : Chat > (control : & impl ControlSource , swarm : & impl ControlSource , instance : & Slug , build : impl FnOnce () -> Result < Start < C > >) -> Outcome
mind_body::persona: fn trace_lines (trace : & dyn Trace , last : usize) -> Result < Vec < String > >
mind_body::persona: fn trace_lines (trace : & dyn TraceView , last : usize) -> Result < Vec < String > >
mind_body::persona: impl Config
mind_body::persona: impl Config: fn from_args (args : & [String] , usage : & str) -> Result < (Self , Vec < String >) >
mind_body::persona: impl Config: fn from_args_and_env (args : & [String] , lookup : impl Fn (& str) -> Option < String > , usage : & str) -> Result < (Self , Vec < String >) >
@ -234,11 +234,17 @@ mind_body::persona: impl FileTrace: fn new (path : impl Into < PathBuf >) -> Sel
mind_body::persona: impl PersonaStore for HuginnPersonaSource
mind_body::persona: impl Sender
mind_body::persona: impl Trace for FileTrace
mind_body::persona: impl TraceSnapshot
mind_body::persona: impl TraceSnapshot: fn new (path : impl Into < PathBuf >) -> Self
mind_body::persona: impl TraceView for FileTrace
mind_body::persona: impl TraceView for TraceSnapshot
mind_body::persona: impl fmt :: Display for Outcome
mind_body::persona: pub trait Trace { fn record (& self , key : & str , record : & Value) -> Result < () > ; fn records (& self) -> Result < Vec < Value > > ; }
mind_body::persona: pub trait Trace : TraceView { fn record (& self , key : & str , record : & Value) -> Result < () > ; }
mind_body::persona: pub trait TraceView { fn records (& self) -> Result < Vec < Value > > ; }
mind_body::persona: struct Config # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[rooms: Vec < String >, operators: Vec < String >, minds: Vec < String >, own_sender: String, model: String]
mind_body::persona: struct FileTrace pub-fields[]
mind_body::persona: struct Start< C : Chat > pub-fields[config: Config, persona: Box < dyn PersonaStore >, chat: C, trace: Box < dyn Trace >, addressing: Option < Box < dyn HeartbeatView > >, model: Box < dyn Model >, domain: Option < Box < dyn DomainSource > >, reads: Option < Box < dyn ReadSource > >, tuning: PathBuf, clock: Box < dyn Fn () -> DateTime < Utc > >]
mind_body::persona: struct TraceSnapshot pub-fields[]
mind_body::persona: struct TurnRecord # [derive (Clone , Debug , PartialEq , DatabaseEntry)] pub-fields[value: Value]
mind_body::projection: # [derive (Clone , Copy , Debug , Default , PartialEq , Eq , serde :: Deserialize)] # [serde (rename_all = "snake_case")] pub enum Through { # [default] Projector , Persona , Interpreter , }
mind_body::projection: # [derive (Debug , PartialEq , Eq)] pub enum Put { Committed , Stale , Refused (String) , }