persona: the drain alone decides the day cap holds her; held starts back the poll off like failed wakes (Soul s3)

The poll no longer reads the hold row's until: a held start rewrites the UTC day's one row with its count of starts, failed_run
counts them as failed starts (no strike), so a raised cap releases her within a beat and a bogus row holds no one. Test at exactly
the cap.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-01 14:51:54 +01:00
commit 87a61f3878
7 changed files with 87 additions and 48 deletions

View file

@ -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::{day_held_until, decided, failed_run};
use crate::projection::{decided, failed_run};
use crate::queue::{MindPort, headers, in_force, of_kind};
use crate::tempo::{self, Standing};
@ -797,8 +797,6 @@ struct Row<'a> {
done: Option<BTreeSet<String>>,
/// How many of her last records are failures in a row, and when the last was made.
failures: (u32, Option<DateTime<Utc>>),
/// Until when her trace says her agent's day cap holds her (`projection::day_held_until`).
held_until: Option<DateTime<Utc>>,
note: String,
}
@ -811,11 +809,11 @@ impl Row<'_> {
self.released && !self.busy
}
/// No start is made for her: 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), and a day cap's hold lasts until the UTC midnight her trace's hold row names.
/// No start is made for her: a failed wake, or a start the day cap held, is waited out before the next (`BACKOFF_BASE_S`, doubled by
/// each such start in a row her trace holds, to the beat). Whether she is held is the drain's to say, at each start.
fn cooling(&self, now: DateTime<Utc>, beat_s: u32) -> bool {
let (run, at) = self.failures;
self.held_until.is_some_and(|until| now < until) || run > 0 && at.is_some_and(|at| (now - at).num_seconds() < backoff(run, beat_s))
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.
@ -868,14 +866,13 @@ 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), held_until: None, 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.held_until = day_held_until(&records);
}
Err(error) => {
eventful = true;

View file

@ -1387,24 +1387,32 @@ fn t_l3_a_new_waking_line_is_woken_for_by_the_wake_rule_with_an_owed_list_in_her
assert!(rig.store.state.borrow().clone().unwrap().handled_mentions.contains(&"ann:$e2".to_owned()), "the new line's claim is written: the wake rule started her");
}
/// The day cap's hold is read from her trace, and it is what bounds the start storm: a held start writes no wake record and decides no
/// line, so without it the poll would start her unit for the same undecided line every poll. Every poll before the hold's `until` starts
/// her never; the first after it starts her for the line.
/// A start the day cap held writes no wake record and decides no line, so the poll would start her unit for the same undecided line at
/// every poll. The drain alone says whether she is held; the poll only backs off by her held starts as by failed wakes (20 s, doubling to
/// the beat). A row's `until` is no authority: a far-future one, written by anyone, holds her no longer than the backoff. A start after
/// the backoff is made, so a raised cap releases her within a beat.
#[test]
fn t_h3_a_day_cap_hold_in_her_trace_starts_no_one_until_it_ends() {
fn t_h4_held_starts_back_off_like_failures_and_never_hold_her_for_a_day() {
let rig = quiet_rig();
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
rig.poll();
rig.end_unit(ANN);
let until = rig.now() + Duration::seconds(600);
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held_by": "day_cap", "spent": 3.2, "cap": 3.0, "until": until.to_rfc3339(), "at": rig.now().to_rfc3339() }));
while rig.now() + Duration::seconds(20) < until {
rig.advance(20);
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert!(!launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}");
rig.end_unit(ANN);
let t0 = rig.now();
let far = (t0 + Duration::days(300)).to_rfc3339();
let mut starts = 0u64;
let mut launches: Vec<i64> = vec![];
for _ in 0..360 {
rig.advance(10);
let Outcome::Polled { launched } = rig.poll() else { panic!("polled") };
if launched.iter().any(|slug| slug.0 == "ann") {
launches.push((rig.now() - t0).num_seconds());
rig.end_unit(ANN);
// What the drain does at a start it holds: one row for the day, its count raised, its time now.
starts += 1;
let mut rows = rig.traces[ANN].rows.borrow_mut();
rows.retain(|row| row["held_by"] != "day_cap");
rows.push(serde_json::json!({ "held_by": "day_cap", "starts": starts, "spent": 3.2, "cap": 3.0, "until": far, "at": rig.now().to_rfc3339() }));
}
}
rig.advance(30);
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert!(launched.iter().any(|slug| slug.0 == "ann"), "the line she was held from wakes her after the hold ends: {launched:?}");
let gaps: Vec<i64> = launches.windows(2).map(|pair| pair[1] - pair[0]).collect();
assert_eq!(gaps, [20, 40, 80, 160, 320, 640, 900, 900].map(i64::from), "{launches:?}: each held start waits the failure backoff, to the beat");
assert_eq!(launches.len(), 9, "an hour of held starts costs nine unit starts, not 360: {launches:?}");
}

View file

@ -53,7 +53,7 @@ use crate::projection::agent::request_tool::RequestTool;
use crate::projection::agent::say::{Say, Sent};
use crate::projection::agent::shell::Shell;
use crate::projection::agent::{Agent, Ended, day_ends, day_usd, Executor, FileSession, Steps, TraceLedger, Wake as AgentWake, instructions as agent_instructions, ready_intentions, step};
use crate::projection::{Applied, DAY_CAP_HOLD, DomainSource, Fault, Heard, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, Waked, apply_commit, day_held_until, decided, failed as record_failed, history, interpret, is_wake, load_tuning, people_named, settle_handed, wake, own_addressee as heard_as};
use crate::projection::{Applied, DAY_CAP_HOLD, DomainSource, Fault, Heard, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, Waked, apply_commit, decided, failed as record_failed, history, interpret, is_wake, load_tuning, people_named, settle_handed, wake, 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";
@ -465,16 +465,19 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
Err(fault) => return failed("her tuning was not read", fault),
};
// Her agent has spent the day's cap: she does not wake. No organ is called, no wake is recorded and nothing is acked that this start
// owes a wake (the watched rooms' undecided lines stay below the ack), so the lines wake her after the UTC day rolls over. One row a
// UTC day says so; the poll reads it (`day_held_until`) and starts no unit for her before `until`.
// owes a wake (the watched rooms' undecided lines stay below the ack), so the lines wake her after the UTC day rolls over or the cap is
// raised. This drain alone decides she is held, on every start. Her trace gets one row a UTC day that counts the starts held
// (`failed_run` backs the poll off by them, as by failed wakes) and keeps spent and cap for whoever reads her trace.
let spent = day_usd(&records, now, &bounds.agent);
if spent >= bounds.agent.day_usd {
let until = day_ends(now);
if day_held_until(&records) != Some(until) {
let row = json!({ "held_by": DAY_CAP_HOLD, "spent": spent, "cap": bounds.agent.day_usd, "until": until.to_rfc3339(), "at": now.to_rfc3339(), "seq": place(&*start.trace) });
if let Err(fault) = start.trace.record(&format!("{stem}-h"), &row) {
eprintln!("mind-persona: the record that the day cap holds her was not appended: {fault:#}");
}
let day = now.date_naive();
let prior = records.iter().rev().find(|row| row["held_by"] == DAY_CAP_HOLD && row["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).is_some_and(|at| at.with_timezone(&Utc).date_naive() == day));
let seq = prior.and_then(|row| row["seq"].as_u64()).unwrap_or_else(|| place(&*start.trace) as u64);
let starts = prior.and_then(|row| row["starts"].as_u64()).unwrap_or(0) + 1;
let row = json!({ "held_by": DAY_CAP_HOLD, "starts": starts, "spent": spent, "cap": bounds.agent.day_usd, "at": now.to_rfc3339(), "seq": seq });
if let Err(fault) = start.trace.record(&format!("held-{day}"), &row) {
eprintln!("mind-persona: the record that the day cap holds her was not appended: {fault:#}");
}
return Outcome::Held { until };
}

View file

@ -860,7 +860,7 @@ fn organ_calls(rig: &Rig) -> Vec<String> {
}
/// Ruling persona-day-cap-behaviour (hold-agent-only): a Persona whose agent has spent its day's cap does not wake. No organ is called, no
/// wake is recorded, the lines that would have woken her stay unacked, and one row a UTC day says she is held.
/// wake is recorded, the lines that would have woken her stay unacked, and one row a UTC day counts the starts held.
#[test]
fn t_h3_cap_holds_lines() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
@ -871,10 +871,11 @@ fn t_h3_cap_holds_lines() {
assert!(rig.acks().is_empty(), "the line she owes a wake is not acked: {:?}", rig.acks());
let held = |rig: &Rig| rig.all_records().into_iter().filter(|row| row["held_by"] == "day_cap").collect::<Vec<_>>();
let rows = held(&rig);
assert_eq!((rows.len(), rows[0]["until"].as_str(), rows[0]["cap"].as_f64()), (1, Some(until.to_rfc3339().as_str()), Some(3.0)), "{rows:?}");
assert_eq!((rows.len(), rows[0]["starts"].as_u64(), rows[0]["cap"].as_f64()), (1, Some(1), Some(3.0)), "{rows:?}");
assert!(rows[0]["spent"].as_f64().unwrap() >= 3.0);
assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. }), "a second start the same day holds as well");
assert_eq!(held(&rig).len(), 1, "and writes no second row");
let rows = held(&rig);
assert_eq!((rows.len(), rows[0]["starts"].as_u64()), (1, Some(2)), "and rewrites the day's one row with its count: {rows:?}");
assert!(rig.records().is_empty(), "no wake record");
assert!(rig.all_records().iter().all(|row| row["agent"] != "receipt" && row["kind"] != "cap"), "no cap receipt from a start that never woke: {:?}", rig.all_records());
assert!(rig.mouth.sent.borrow().is_empty());
@ -893,3 +894,19 @@ fn t_h3_rollover_wakes_held_lines() {
assert_eq!(rig.mouth.sent.borrow().len(), 1, "she answered it");
assert_eq!(rig.records().len(), 1);
}
/// A day whose spend is exactly the cap is spent: the drain holds her, calls no organ and acks nothing. The cap is set to the price of
/// the one call her ledger holds, so the comparison meets its boundary.
#[test]
fn t_h4_a_day_spent_to_exactly_the_cap_holds() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
spend_the_day(&rig);
let tuning = rig.dir.path().join("persona-tuning.toml");
let now = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap();
let cap = day_usd(&rig.all_records(), now, &load_tuning(&tuning).unwrap().tuning.agent);
std::fs::write(&tuning, format!("[agent]\nday_usd = {cap:?}\n")).unwrap();
assert_eq!(day_usd(&rig.all_records(), now, &load_tuning(&tuning).unwrap().tuning.agent), cap);
assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. }), "spend == day_usd holds");
assert_eq!(organ_calls(&rig), Vec::<String>::new());
assert!(rig.acks().is_empty());
}

View file

@ -53,7 +53,7 @@ pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource};
pub use select::TurnKind;
pub(crate) use commit::{Applied, Heard, apply as apply_commit};
pub(crate) use interpret::{deltas as interpret, people as people_named};
pub(crate) use turn::{DAY_CAP_HOLD, Taken, day_held_until, decided, failed, failed_run, history, is_wake};
pub(crate) use turn::{DAY_CAP_HOLD, Taken, decided, failed, failed_run, history, is_wake};
pub(crate) use agent::say::{Mouth, settle_handed};
pub(crate) use wake::{Fault, Waked, wake};
pub use tuning::{TUNING_FILE, TUNING_ROOT};

View file

@ -55,24 +55,27 @@ pub(crate) fn decided(records: &[Value]) -> BTreeSet<&str> {
done
}
/// How many of her last wake records failed in a row, and when the last of them was made: what the poll backs off by.
/// How many starts of hers failed in a row, and when the last was made: what the poll backs off by. A failed wake is one; a day-cap hold
/// row (`persona::drain`) is as many as it counts starts held, none of them a strike. A completed wake ends the run.
pub(crate) fn failed_run(records: &[Value]) -> (u32, Option<DateTime<Utc>>) {
let wakes: Vec<&Value> = records.iter().filter(|record| is_wake(record)).collect();
let run = wakes.iter().rev().take_while(|record| failed(record)).count();
let at = wakes.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)
let starts: Vec<&Value> = records.iter().filter(|record| is_wake(record) || record["held_by"] == DAY_CAP_HOLD).collect();
let mut run = 0u32;
for record in starts.iter().rev() {
if record["held_by"] == DAY_CAP_HOLD {
run = run.saturating_add(u32::try_from(record["starts"].as_u64().unwrap_or(1)).unwrap_or(u32::MAX));
} else if failed(record) {
run = run.saturating_add(1);
} else {
break;
}
}
let at = starts.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));
(run, at)
}
/// The `held_by` of the row a start writes when her agent has spent its day's cap and she is not woken (`persona::drain`).
pub(crate) const DAY_CAP_HOLD: &str = "day_cap";
/// When her trace says the day cap holds her until: the `until` of her newest `DAY_CAP_HOLD` row. The one reader, for the drain (one row
/// a day) and the poll (she is not started while it lies ahead).
pub(crate) fn day_held_until(records: &[Value]) -> Option<DateTime<Utc>> {
let row = records.iter().rev().find(|record| record["held_by"] == DAY_CAP_HOLD)?;
DateTime::parse_from_rfc3339(row["until"].as_str()?).ok().map(|until| until.with_timezone(&Utc))
}
/// What her records say of her: what she is to be told (`outcome::told`), the ids her last projections selected, her last rows
/// and when she last woke. The one reader, over a run's list or her trace.
#[derive(Debug, Default, PartialEq)]

View file

@ -55,3 +55,14 @@ fn t_l2_a_line_is_decided_by_the_record_that_holds_it() {
];
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$a", "$b", "$d"]);
}
/// A day-cap hold row counts the starts it held as failed starts in a row, none of them a strike, and a completed wake ends the run.
#[test]
fn t_h4_a_day_cap_hold_row_counts_its_held_starts_in_the_run() {
let hold = |starts: u64, at: &str| json!({ "held_by": "day_cap", "starts": starts, "at": at, "seq": 5 });
let failed = json!({ "held": [], "failed": "the connector did not answer: unavailable", "at": "2026-11-27T10:00:00Z", "seq": 4 });
let done = json!({ "held": ["$a"], "at": "2026-11-27T09:00:00Z", "seq": 3 });
assert_eq!(failed_run(&[done.clone(), hold(4, "2026-11-27T11:00:00Z")]), (4, Some("2026-11-27T11:00:00Z".parse().unwrap())));
assert_eq!(failed_run(&[done.clone(), failed.clone(), hold(2, "2026-11-27T11:00:00Z")]).0, 3, "with the failed wake before it");
assert_eq!(failed_run(&[hold(4, "2026-11-27T11:00:00Z"), done]), (0, None), "a completed wake after it ends the run");
}