From f6fc66b7e876b70a0be9c0e0d6b8e894b5df5138 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 16:50:22 +0100 Subject: [PATCH] persona-wake-span W2 (Soul hold): day cap judged from the trace, a no-call turn decides nothing, the stagger restored whole, reseed carries the wake, unmetered_usd decoupled H1: wake_end reads the day's spend from her trace before each turn, so a turn that completed and crossed the cap ends the wake before another is taken on lines it would not answer. A turn that made no model call holds no line and decides nothing (a first turn so fails the wake as an outage). M2: stagger_ms is the first experiment's, whole: the Minds a line did not address rank after the addressed ones. Both cases pinned. M3: sweeps pin the ack's watch on a waking line no turn took, the trailing list's exclusion of waking lines, and the open's lines the close does not decide. M1: a session that starts fresh at a later turn is seeded with what the wake already did (her says and acts, the same compact form as the Interpreter's ACTS, newest within 4 KiB). L2: unmetered_usd is its own tuning, default 0.40. Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/persona.rs | 56 ++++++- crates/mind-body/src/persona/drain_tests.rs | 14 +- .../src/persona/drain_tests/open_wake.rs | 158 ++++++++++++++++++ crates/mind-body/src/persona/live.rs | 31 ++-- crates/mind-body/src/persona/live/tests.rs | 32 +++- crates/mind-body/src/persona/tests.rs | 14 ++ crates/mind-body/src/projection.rs | 2 +- crates/mind-body/src/projection/agent.rs | 9 +- .../mind-body/src/projection/agent/tests.rs | 11 ++ crates/mind-body/src/projection/tests.rs | 3 +- crates/mind-body/src/projection/tuning.rs | 4 + 11 files changed, 305 insertions(+), 29 deletions(-) diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index 89045ba..763fa12 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -59,7 +59,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, Receipt, day_ends, day_usd, Executor, FileSession, Steps, TraceLedger, Wake as AgentWake, instructions as agent_instructions, ready_intentions, step, wake_usd}; -use crate::projection::{Applied, DAY_CAP_HOLD, DomainSource, Failed, Fault, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Through, TurnKind, Waked, decided, failed as record_failed, heard_of, history, interpret_and_put, is_wake, load_tuning, settle_handed, wake, own_addressee as heard_as}; +use crate::projection::{Applied, DAY_CAP_HOLD, DomainSource, Failed, Fault, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Through, TurnKind, Waked, decided, failed as record_failed, acts_of, heard_of, history, interpret_and_put, is_wake, load_tuning, settle_handed, wake, own_addressee as heard_as}; mod live; @@ -621,13 +621,23 @@ fn drain(instance: &Slug, start: &Start, staggered: bool) -> Outcome } let input = lines_input(&refs, &hold, &config.own_sender, if k == 1 { &told } else { &[] }); let turn_id = format!("{wake_id}-t{k}"); - let mut last = match step(&agent, &AgentWake { id: &turn_id, wake: &wake_id, instructions: &instructions, opening: &opening, input: &input, fresh: &fresh, first: k == 1 }) { + // A session that starts fresh at a later turn (discarded as too long, cold or orphaned) is seeded with what this wake already did, after her + // intentions: it is never seeded with the bare lines of a turn it does not remember the others of. + let seed = format!("{fresh}{}", if k > 1 { done_so_far(&receipts) } else { String::new() }); + let mut last = match step(&agent, &AgentWake { id: &turn_id, wake: &wake_id, instructions: &instructions, opening: &opening, input: &input, fresh: &seed, first: k == 1 }) { Ok(turn) => { + // A turn that made no model call (the day's or the wake's cap stood before it) showed her nothing: it holds no line and decides nothing. + let unspent = !matches!(turn.ended, Ended::Failed(_)) && turn.model_calls == 0; + let failure = match &turn.ended { + Ended::Failed(failed) => Some(Fault { reason: failed.reason.clone(), outage: failed.outage }), + other if unspent && k == 1 => Some(Fault { reason: format!("her agent made no call: {other:?}"), outage: true }), + _ => None, + }; let mut row = json!({ "wake": wake_id, "turn": k, - "held": hold, - "status": if matches!(turn.ended, Ended::Failed(_)) { "failed" } else { "completed" }, + "held": if unspent { Vec::<&str>::new() } else { hold.clone() }, + "status": if failure.is_some() { "failed" } else if unspent { "capped" } else { "completed" }, "ended": format!("{:?}", turn.ended), "model_calls": turn.model_calls, "tool_calls": turn.tool_calls, @@ -635,7 +645,6 @@ fn drain(instance: &Slug, start: &Start, staggered: bool) -> Outcome "at": (start.clock)().to_rfc3339(), "seq": place(&*start.trace), }); - let failure = if let Ended::Failed(failed) = &turn.ended { Some(Fault { reason: failed.reason.clone(), outage: failed.outage }) } else { None }; if let Some(failure) = &failure { mark(&mut row, failure, taking.strike.as_deref()); } @@ -653,6 +662,11 @@ fn drain(instance: &Slug, start: &Start, staggered: bool) -> Outcome }; let failed_turn = failure.is_some(); match failure { + None if unspent => { + for event in &taking.hold { + taken.remove(event); + } + } None => { completed += 1; receipts.extend(turn.receipts); @@ -688,7 +702,8 @@ fn drain(instance: &Slug, start: &Start, staggered: bool) -> Outcome Vec::new() } }; - if let Some(over) = wake_end(&span, &last, wake_usd(&records, &wake_id, &bounds.agent), (start.clock)(), &bounds.agent) { + let now = (start.clock)(); + if let Some(over) = wake_end(&span, &last, wake_usd(&records, &wake_id, &bounds.agent), day_usd(&records, now, &bounds.agent), now, &bounds.agent) { end = Some(over); break; } @@ -776,6 +791,35 @@ fn drain(instance: &Slug, start: &Start, staggered: bool) -> Outcome Outcome::Drained { wakes: 1, turns: turns_run, ended: Some(end), acked_through: acked } } +/// The most bytes of what the wake already did that a reseeded session is told. +const DONE_BYTES: usize = 4 * 1024; + +/// What this wake already did, for a session that starts fresh at a later turn: her own lines and her other acts of the turns before, from their +/// receipts in the compact form the Interpreter reads them in (`acts_of`), the newest kept within `DONE_BYTES`. Empty when nothing was done. +fn done_so_far(receipts: &[Receipt]) -> String { + let acts = acts_of(receipts); + let mut kept = 0; + let mut used = 0; + for line in acts.iter().rev() { + if kept > 0 && used + line.len() + 1 > DONE_BYTES { + break; + } + used += line.len() + 1; + kept += 1; + } + if acts.is_empty() { + return String::new(); + } + let left_out = acts.len() - kept; + let note = if left_out > 0 { format!("({left_out} earlier act(s) are not shown.) +") } else { String::new() }; + format!("What your agent has already done in this wake, before the lines below (what you said is among it; do not say it again): +{note}{} + +", acts[left_out..].join(" +")) +} + /// The most bytes of held lines her agent's first user text carries: sixteen times the Persona packet's 1500-byte stimulus, since the /// agent reads a room's lines to answer them, and far under what a day's backlog in a busy room /// would be (an 889 KB input from 3000 lines). The newest lines are kept: they are what she answers. diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 92d9b94..0cb0288 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -321,6 +321,14 @@ struct Rig { arrivals: Rc>>, /// Every wait a start asked for, in order. pauses: Rc>>, + /// The day's cap is crossed by someone else's spend the moment a line arrives: a call row the day's sum reads, written by the pause that delivers it. + crossing: Rc>, +} + +/// A call row that spends more than any day: written into her trace by whatever else spends from the same cap. +fn crossing_row() -> (String, Value) { + let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap().to_rfc3339(); + ("seed-cross".into(), json!({ "agent": "call", "at": at, "usage": json!(Spent { input_tokens: 5_000_000, ..spent() }), "seq": 0 })) } impl Rig { @@ -334,12 +342,13 @@ impl Rig { let trace = Rc::new(MemTrace { rows: RefCell::default(), fail: Cell::new(false), fail_suffix: RefCell::default(), log: log.clone() }); let store = FakeStore { log: log.clone(), ..FakeStore::new(control()) }; let agent = Rc::new(Script { answers: RefCell::default(), seen: RefCell::default(), log: log.clone() }); - Self { mouth, trace, store: Rc::new(store), dir, ticks: Rc::default(), review: RefCell::default(), agent, log, arrivals: Rc::default(), pauses: Rc::default() } + Self { mouth, trace, store: Rc::new(store), dir, ticks: Rc::default(), review: RefCell::default(), agent, log, arrivals: Rc::default(), pauses: Rc::default(), crossing: Rc::default() } } fn run(&self, model: impl Model + 'static) -> Outcome { let ticks = self.ticks.clone(); let (pause_ticks, arrivals, pauses, mouth) = (self.ticks.clone(), self.arrivals.clone(), self.pauses.clone(), self.mouth.clone()); + let (crossing, trace) = (self.crossing.clone(), self.trace.clone()); let start = || { Ok(Start { config: Config { rooms: vec!["#minds:gamecult.org".into()], operators: vec![META.into()], minds: vec!["@eureka:gamecult.org".into(), LIBBY.into()], own_sender: "@eureka:gamecult.org".into(), model: "test-model".into(), review_room: self.review.borrow().clone() }, @@ -365,6 +374,9 @@ impl Rig { let (due, later): (Vec<_>, Vec<_>) = arrivals.borrow_mut().drain(..).partition(|(at, _)| *at <= now); *arrivals.borrow_mut() = later; mouth.waiting.set(true); + if crossing.get() && !due.is_empty() { + trace.rows.borrow_mut().push(crossing_row()); + } for (_, line) in due { mouth.arrive(line); } diff --git a/crates/mind-body/src/persona/drain_tests/open_wake.rs b/crates/mind-body/src/persona/drain_tests/open_wake.rs index 6aa4594..8d0aa98 100644 --- a/crates/mind-body/src/persona/drain_tests/open_wake.rs +++ b/crates/mind-body/src/persona/drain_tests/open_wake.rs @@ -307,3 +307,161 @@ fn t_w2_the_open_waits_her_rank_and_reads_the_mouth_afresh() { rig.run(Tally::default()); assert_eq!(rig.pauses.borrow().first().copied(), Some(std::time::Duration::from_secs(5)), "ranked first: no wait before the wake, only the span's polls"); } + +// --------------------------------------------------------------------------------------------- +// Soul's hold on 9187ee0. + +/// H1, Soul's probe: a turn that completed and crossed the day's cap ends the wake. The line that arrived after it is never taken, so it is neither shown +/// to her agent nor decided nor acked, nor told to the Interpreter as heard, and the next start (held) leaves it for the day that follows. +#[test] +fn t_h1_a_day_cap_crossed_by_a_completed_turn_ends_the_wake_before_the_next_line_is_taken() { + let rig = Rig::new(vec![line(1, &room(1), META, "first")]); + tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n"); + // $0.9999 of the day is spent: turn 1's one call, $0.0003, crosses the cap, and the turn still completes. + let usage = json!(Spent { input_tokens: 499_950, output_tokens: 0, ..spent() }); + let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap().to_rfc3339(); + rig.trace.rows.borrow_mut().push(("seed-g0".into(), json!({ "agent": "call", "at": at, "usage": usage, "seq": 0 }))); + answers(&rig, [done(), done()]); + arrives(&rig, 60, later(2, &room(1), 60, "second, never shown")); + let model = Tally::default(); + assert_eq!(rig.run(model.clone()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::DayCap), acked_through: Some(1) }); + assert_eq!(rig.agent.seen.borrow().len(), 1, "her agent was called for turn 1 alone"); + assert!(!rig.agent.seen.borrow().iter().any(|items| format!("{items:?}").contains("never shown"))); + assert!(!decided(&rig.trace.records().unwrap()).contains("$e2"), "the line was shown to no one, so nothing decided it"); + assert!(model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)).all(|prompt| !prompt.contains("never shown"))); + assert_eq!(rig.turns().len(), 1); +} + +/// H1's second half: a turn that made no model call (the cap crossed between the wake's judgement and the turn) holds no line and decides nothing: its +/// row holds none, its line is not acked, and the wake closes `day_cap` with the turns before it. +#[test] +fn t_h1_a_turn_that_made_no_model_call_holds_no_line_and_decides_nothing() { + let rig = Rig::new(vec![line(1, &room(1), META, "first")]); + tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n"); + rig.crossing.set(true); + answers(&rig, [done(), done()]); + arrives(&rig, 60, later(2, &room(1), 60, "second, never shown")); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::DayCap), acked_through: Some(1) }); + let turn = &rig.turns()[1]; + assert_eq!((turn["model_calls"].clone(), turn["held"].clone(), turn["status"].as_str()), (json!(0), json!([]), Some("capped")), "{turn}"); + assert!(!decided(&rig.trace.records().unwrap()).contains("$e2")); + assert_eq!(rig.agent.seen.borrow().len(), 1, "no call reached her agent's model for it"); + assert_eq!(rig.records()[0]["status"], "completed", "turn 1 completed, and the Interpreter ran over it"); + assert_eq!(calls(&rig, "interpreter"), 2); +} + +/// The same race at her first turn: nothing was shown, so the wake fails as an outage, strikes nothing, and decides nothing. +#[test] +fn t_h1_a_first_turn_that_made_no_model_call_fails_the_wake_as_an_outage() { + struct Spends(Rc, Tally); + impl Model for Spends { + fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { + if !prompt.starts_with("You are a private Projector.") && !prompt.starts_with(INTERPRETER) { + self.0.rows.borrow_mut().push(crossing_row()); + } + self.1.ask(request_id, model, prompt, schema) + } + } + let rig = Rig::new(vec![line(1, &room(1), META, "first")]); + tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n"); + assert_eq!(rig.run(Spends(rig.trace.clone(), Tally::default())), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::DayCap), acked_through: None }); + assert_eq!(rig.turns()[0]["held"], json!([])); + assert!(!decided(&rig.trace.records().unwrap()).contains("$e1")); + assert!(rig.all_records().iter().all(|row| row.get("strike").is_none()) && rig.records()[0]["outage"] == true); + assert_eq!(rig.agent.seen.borrow().len(), 0); +} + +/// M3, the ack's guard: a line that wakes her in a room the wake has not joined holds the ack behind it until a turn takes it, wherever the wake ended. The +/// line is held back by its stagger and the wake is made to end at every moment around it; whenever the wake ended with the line untaken, nothing past it +/// was acked and it is still in the mouth. +#[test] +fn t_m3_a_waking_line_no_turn_took_holds_the_ack_behind_it_wherever_the_wake_ends() { + let event = event_ranking_her(1); + let mut left_untaken = 0; + for tick in 8..90 { + let rig = Rig::new(vec![line(1, &room(1), META, "first")]); + tune(&rig, "[agent]\nidle_s = 30\nspan_s = 60\n"); + let side = ChatDelivery { room_alias: "#side:gamecult.org".into(), room_id: "#side:gamecult.org".into(), ..to_both(2, &event, tick) }; + let mut notice = later(3, &room(1), tick, "a notice"); + notice.form = Form::Notice; + arrives(&rig, tick, side); + arrives(&rig, tick, notice); + rig.run(Tally::default()); + let taken = decided(&rig.trace.records().unwrap()).contains(event.as_str()); + if !taken && rig.mouth.held.borrow().iter().any(|held| held.event_id == event) { + left_untaken += 1; + assert!(rig.acks().iter().all(|seq| *seq < 2), "tick {tick}: the ack passed a waking line no turn took: {:?}", rig.acks()); + } + if !rig.mouth.held.borrow().iter().any(|held| held.event_id == event) && !taken { + assert!(rig.arrivals.borrow().iter().any(|(_, held)| held.event_id == event) || rig.acks().iter().all(|seq| *seq < 2), "tick {tick}: the line was acked undecided"); + } + } + assert!(left_untaken > 0, "the sweep never ended a wake with the line read and untaken: it proves nothing"); +} + +/// M3, the trailing list's guard: the wake record holds the quiet lines of the wake's rooms and never a line that wakes her. A line that tags two Minds +/// and waits out its stagger is in a joined room; if the wake ends before it is taken, the record must not decide it unshown. +#[test] +fn t_m3_the_wake_record_never_decides_a_waking_line_it_did_not_show() { + let event = event_ranking_her(1); + let mut left_untaken = 0; + for tick in 8..90 { + let tagged_her = ChatDelivery { mentions: vec![EUREKA.into()], ..line_at(1, MINDS, META, "hello Eureka", BASE_MS - 100_000) }; + let rig = Rig::new(vec![tagged_her]); + tune(&rig, "[agent]\nidle_s = 30\nspan_s = 60\n"); + arrives(&rig, tick, to_both(2, &event, tick)); + rig.run(Tally::default()); + let decided_it = decided(&rig.trace.records().unwrap()).contains(event.as_str()); + let shown = rig.agent.seen.borrow().iter().any(|items| format!("{items:?}").contains("both of you")); + assert!(!decided_it || shown, "tick {tick}: the line was decided and never shown to her agent"); + left_untaken += usize::from(!decided_it && rig.mouth.held.borrow().iter().any(|held| held.event_id == event)); + } + assert!(left_untaken > 0, "the sweep never ended a wake with the line read and untaken: it proves nothing"); +} + +/// M3, the open's guard: a quiet line the open had and no turn showed (the page had no room for it) is not the close's to decide. It stays undecided, +/// and the ack stops below it. +#[test] +fn t_m3_a_quiet_line_the_open_had_and_no_turn_showed_stays_undecided_at_close() { + let mut lines = vec![line(1, &room(1), META, "hello")]; + lines.extend((2..=61).map(|seq| line_at(seq, MINDS, ANN, &format!("line {seq} of a long talk in the room, said at some length so that the page fills"), BASE_MS - 110_000 + seq * 100))); + lines.push(ChatDelivery { mentions: vec![EUREKA.into()], ..line_at(62, MINDS, META, "Eureka, what do you make of it", BASE_MS - 40_000) }); + let rig = Rig::new(lines); + assert!(matches!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, .. })); + let held: Vec = rig.turns()[0]["held"].as_array().unwrap().iter().map(|event| event.as_str().unwrap().to_owned()).collect(); + let unshown: Vec = (2..=61).filter(|seq| !held.contains(&format!("$e{seq}"))).collect(); + assert!(!unshown.is_empty() && held.contains(&"$e62".to_owned()), "the page left some of the quiet lines out: {held:?}"); + let done = decided(&rig.trace.records().unwrap()).into_iter().map(str::to_owned).collect::>(); + assert!(unshown.iter().all(|seq| !done.contains(&format!("$e{seq}"))), "a line no one was shown is not decided by the wake record: {done:?}"); + assert!(rig.acks().iter().all(|seq| *seq < unshown[0]), "and the ack stops below the first of them: {:?}", rig.acks()); + assert_eq!(rig.records()[0]["held"], json!([])); +} + +/// M1: a session that starts fresh at turn 2 is told what the wake already did, her own say among it, so she does not say it again. The session is +/// discarded as too long between the turns. +#[test] +fn t_m1_a_session_reseeded_at_turn_two_carries_turn_ones_say_and_acts() { + let rig = Rig::new(vec![line(1, &room(1), META, "first")]); + tune(&rig, "[agent]\nmax_session_tokens = 50\n"); + answers(&rig, [says(&room(1), "I will be there at noon"), shells("one", "ls /srv/one"), done(), done()]); + arrives(&rig, 60, later(2, &room(1), 60, "and the second line")); + rig.run(Tally::default()); + let seen = rig.agent.seen.borrow(); + let turn_two = seen.iter().find(|items| items.len() == 1 && format!("{items:?}").contains("and the second line")).expect("turn 2 began a fresh session"); + let text = user_text(turn_two); + assert!(text.contains("I will be there at noon") && text.contains("ls /srv/one"), "turn 1's say and acts are in the reseed: {text}"); + assert!(text.contains("What she lives now") && text.contains("and the second line"), "with the wake's opening, and the new line: {text}"); + assert!(text.find("I will be there at noon").unwrap() < text.find("and the second line").unwrap(), "what was done comes before the lines"); + assert!(rig.all_records().iter().any(|row| row["agent"] == "session_discarded" && row["why"] == "too_long")); +} + +/// A kept session is not told what it already has. +#[test] +fn t_m1_a_kept_session_is_not_told_the_wake_again() { + let rig = Rig::new(vec![line(1, &room(1), META, "first")]); + answers(&rig, [says(&room(1), "I will be there at noon"), done(), done()]); + arrives(&rig, 60, later(2, &room(1), 60, "and the second line")); + rig.run(Tally::default()); + let seen = rig.agent.seen.borrow(); + assert!(!user_text(&seen[2]).contains("I will be there at noon") && !user_text(&seen[2]).contains("already done")); +} diff --git a/crates/mind-body/src/persona/live.rs b/crates/mind-body/src/persona/live.rs index 4d7d5b2..6c8a6c9 100644 --- a/crates/mind-body/src/persona/live.rs +++ b/crates/mind-body/src/persona/live.rs @@ -32,7 +32,7 @@ pub(crate) const STAGGER_STEP_S: u64 = 8; pub enum End { /// A turn failed, or the wake could not read the mouth or her trace. Failed, - /// A turn reached the day's cap. + /// The day's cap is reached: her trace holds the day's spend at it, or a turn stopped at it. DayCap, /// This wake's spend reached `agent.wake_usd`. Spend, @@ -67,12 +67,14 @@ pub(crate) struct Span { pub last_ended: DateTime, } -/// Whether the wake ends now, and why. `last` is how her last turn ended, `spent_usd` this wake's spend over all its turns. -pub(crate) fn wake_end(span: &Span, last: &Ended, spent_usd: f64, now: DateTime, bounds: &AgentTuning) -> Option { +/// Whether the wake ends now, and why. `last` is how her last turn ended, `spent_usd` this wake's spend over all its turns and `day_spent_usd` the +/// UTC day's, both read from her trace before the next turn is judged: a turn that completed and crossed the day's cap ends the wake before another +/// turn is taken on lines it would never answer. +pub(crate) fn wake_end(span: &Span, last: &Ended, spent_usd: f64, day_spent_usd: f64, now: DateTime, bounds: &AgentTuning) -> Option { let seconds = |secs: u64| Duration::seconds(i64::try_from(secs).unwrap_or(i64::MAX)); if matches!(last, Ended::Failed(_)) { Some(End::Failed) - } else if matches!(last, Ended::Cap(Cap::DaySpend)) { + } else if day_spent_usd >= bounds.day_usd || matches!(last, Ended::Cap(Cap::DaySpend)) { Some(End::DayCap) } else if spent_usd >= bounds.wake_usd || matches!(last, Ended::Cap(Cap::WakeSpend)) { Some(End::Spend) @@ -87,20 +89,25 @@ pub(crate) fn wake_end(span: &Span, last: &Ended, spent_usd: f64, now: DateTime< /// How long after a poll first sees `delivery` a Mind takes it, in milliseconds. This is the first experiment's stagger, ported from /// `crates/mind-body/src/persona.rs` at `0fd1232^` (`stagger_ms`, ruling `eureka-body:ruling:unaddressed-tell-stagger-ruled`): none in a direct -/// message, otherwise her rank times `STAGGER_STEP_S`. The Minds the line is for rank by a hash of the Mind and the event, so the first Mind -/// by that order takes it at once and the others one step apart: addressing several does not make a chorus, and the later ones read the -/// earlier ones' answers before they give theirs. A rank is the number of Minds addressed whose hash sorts before hers, from the line and the -/// addressing table alone (the sender is not counted), so every process computes the same order with no word between them and nobody is always -/// last. A line that is not for her (an own-room or exchange line, an open floor) is hers alone to take: no delay. +/// message, otherwise her rank times `STAGGER_STEP_S`. The Minds the message names (tagged, named, or named by a project, by `address::addresses` +/// over the swarm's addressing) rank first, by a hash of the Mind and the event, and the rest follow them, ranked the same way: the first addressed Mind +/// takes it at once, the others one step apart, so addressing several does not make a chorus, and the later ones read the earlier ones' answers before +/// they give theirs. A rank is the number of Minds in her set whose hash sorts before hers, from the message and the addressing table alone (the +/// sender, who will not take its own message, is not counted), so every process computes the same order with no word between them and nobody is +/// always last. The set is the addressed Minds when she is among them, else the others, after the addressed ones. Verbatim from the first +/// experiment, `own` standing for `config.own_sender`. pub(crate) fn stagger_ms(own: &Addressee, addressing: &[Addressee], delivery: &ChatDelivery) -> u64 { - if delivery.is_direct || !is_for(own, delivery) { + if delivery.is_direct { return 0; } - let mut minds: Vec<&Addressee> = addressing.iter().filter(|mind| mind.matrix_id() != delivery.sender && mind.matrix_id() != own.matrix_id() && addresses(mind, delivery)).collect(); + let mut minds: Vec<&Addressee> = addressing.iter().filter(|mind| mind.matrix_id() != delivery.sender).collect(); minds.sort_unstable_by_key(|mind| mind.matrix_id()); minds.dedup_by_key(|mind| mind.matrix_id()); + let (addressed, others): (Vec<&Addressee>, Vec<&Addressee>) = minds.into_iter().partition(|mind| if mind.matrix_id() == own.matrix_id() { is_for(mind, delivery) } else { addresses(mind, delivery) }); + let own_is_addressed = addressed.iter().any(|mind| mind.matrix_id() == own.matrix_id()); + let (set, before) = if own_is_addressed { (&addressed, 0) } else { (&others, addressed.len()) }; let mine = (stagger_hash(own.matrix_id(), &delivery.event_id), own.matrix_id()); - let rank = minds.iter().filter(|mind| (stagger_hash(mind.matrix_id(), &delivery.event_id), mind.matrix_id()) < mine).count(); + let rank = before + set.iter().filter(|mind| (stagger_hash(mind.matrix_id(), &delivery.event_id), mind.matrix_id()) < mine).count(); rank as u64 * STAGGER_STEP_S * 1000 } diff --git a/crates/mind-body/src/persona/live/tests.rs b/crates/mind-body/src/persona/live/tests.rs index 4b8dad8..766dcf8 100644 --- a/crates/mind-body/src/persona/live/tests.rs +++ b/crates/mind-body/src/persona/live/tests.rs @@ -12,7 +12,7 @@ fn at(secs: i64) -> DateTime { /// A wake that opened at 0 and whose last turn ended at `last`, judged at `now`. fn ends(last: Ended, spent: f64, ended_at: i64, now: i64) -> Option { - wake_end(&Span { opened: at(0), last_ended: at(ended_at) }, &last, spent, at(now), &AgentTuning::default()) + wake_end(&Span { opened: at(0), last_ended: at(ended_at) }, &last, spent, 0.0, at(now), &AgentTuning::default()) } fn failed() -> Ended { @@ -50,6 +50,14 @@ fn a_turn_that_hit_the_day_cap_or_failed_ends_the_wake() { assert_eq!(ends(Ended::Cap(Cap::ModelCalls), 0.1, 0, 10), None); } +/// H1: the day's spend is read from her trace before each turn is judged, so a turn that completed and crossed the cap ends the wake. +#[test] +fn a_day_spent_to_its_cap_ends_the_wake_though_her_last_turn_ended_well() { + let end = |day: f64| wake_end(&Span { opened: at(0), last_ended: at(0) }, &Ended::EndTurn, 0.1, day, at(10), &AgentTuning::default()); + assert_eq!(end(2.99), None); + assert_eq!(end(3.0), Some(End::DayCap), "day_usd is 3.00"); +} + #[test] fn the_ends_are_judged_in_order() { // Everything true at once: failed, then the day cap, then the wake's spend, then the span, then idle. @@ -110,19 +118,35 @@ fn the_order_changes_from_event_to_event_so_nobody_is_always_last() { } #[test] -fn the_sender_is_not_counted_and_a_line_not_for_her_or_in_a_direct_message_waits_for_no_one() { +fn the_sender_is_not_counted_and_a_direct_message_waits_for_no_one() { let table = table(); // Libby tags Eureka and Kiko: two Minds, not three. let line = said("$x", ALL[1], "#minds:gamecult.org", false, &[ALL[0], ALL[2]], "you two"); let mut ranks: Vec = [&table[0], &table[2]].iter().map(|own| stagger_ms(own, &table, &line)).collect(); ranks.sort_unstable(); assert_eq!(ranks, [0, 8000]); - // A line that is not for Kiko is hers to take at once, whoever else it names. - assert_eq!(stagger_ms(&table[1], &table, &said("$y", "@meta:gamecult.org", "#minds:gamecult.org", false, &[ALL[0]], "just you")), 0); // A direct message is one Mind's alone. assert_eq!(stagger_ms(&table[0], &table, &said("$z", "@meta:gamecult.org", "!dm:gamecult.org", true, &[], "hello")), 0); } +/// The first experiment ranked the Minds a line did not address after the addressed ones, so a line to one Mind sends the others behind her: the +/// addressed Mind takes it at once, and the two it did not name one and two steps after. +#[test] +fn the_minds_a_line_did_not_address_rank_after_the_addressed_ones() { + let table = table(); + for event in ["$a", "$b", "$c", "$d", "$e", "$f"] { + let line = said(event, "@meta:gamecult.org", "#minds:gamecult.org", false, &[ALL[0]], "just you, Eureka"); + let delays: Vec = table.iter().map(|own| stagger_ms(own, &table, &line)).collect(); + assert_eq!(delays[0], 0, "{event}: the Mind it names takes it at once"); + let mut behind = vec![delays[1], delays[2]]; + behind.sort_unstable(); + assert_eq!(behind, [8000, 16000], "{event}: the others follow her, one step apart"); + } + // Two named: the unnamed third is one step behind them. + let line = said("$g", "@meta:gamecult.org", "#minds:gamecult.org", false, &[ALL[0], ALL[1]], "you two"); + assert_eq!(stagger_ms(&table[2], &table, &line), 16000, "two addressed ahead of her"); +} + #[test] fn the_hash_is_fixed_so_every_process_computes_the_same_order() { assert_eq!(stagger_hash("@eureka:gamecult.org", "$e1"), stagger_hash("@eureka:gamecult.org", "$e1")); diff --git a/crates/mind-body/src/persona/tests.rs b/crates/mind-body/src/persona/tests.rs index 3f1a16e..32204d2 100644 --- a/crates/mind-body/src/persona/tests.rs +++ b/crates/mind-body/src/persona/tests.rs @@ -393,3 +393,17 @@ fn a_named_gap_with_no_lines_reads_unknown_and_never_empty() { let none = render_tail(&config(), &[], Some(vec![]), &[], &rooms, &[], &[]); assert!(none.text.contains("Recent tail of your rooms: empty."), "{}", none.text); } + +/// M1: what a reseeded session is told of the wake so far is bounded, keeps the newest acts, says how many it left out, and is nothing when nothing was done. +#[test] +fn done_so_far_keeps_the_newest_acts_within_its_budget() { + use crate::projection::agent::Status; + assert_eq!(done_so_far(&[]), ""); + let receipts: Vec = (0..300).map(|n| Receipt::new("say", Status::Ok, json!({ "room": "#minds:gamecult.org", "text": format!("act number {n:03} {}", "z".repeat(120)) }))).collect(); + let told = done_so_far(&receipts); + assert!(told.len() < DONE_BYTES + 400, "{}", told.len()); + assert!(told.contains("act number 299") && !told.contains("act number 000"), "the newest are kept"); + assert!(told.contains("earlier act(s) are not shown")); + let few = done_so_far(&receipts[..2]); + assert!(few.contains("act number 000") && few.contains("act number 001") && !few.contains("not shown")); +} diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 0e44c38..6564b7a 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -54,7 +54,7 @@ pub use select::TurnKind; pub(crate) use commit::Applied; #[cfg(test)] pub(crate) use commit::Heard; -pub(crate) use interpret::{heard_of, interpret_and_put}; +pub(crate) use interpret::{acts_of, heard_of, interpret_and_put}; #[cfg(test)] pub(crate) use interpret::put_applied; pub(crate) use turn::{DAY_CAP_HOLD, decided, failed, failed_run, history, is_wake}; diff --git a/crates/mind-body/src/projection/agent.rs b/crates/mind-body/src/projection/agent.rs index c55fea4..3c7bbba 100644 --- a/crates/mind-body/src/projection/agent.rs +++ b/crates/mind-body/src/projection/agent.rs @@ -14,7 +14,7 @@ //! and no other store holds it. Past a bound the loop ends with a `cap` receipt; a call is never made past one. //! //! The day's sum fails closed. A `call` row is written before its call is made, holding the call's place in the day at the -//! worst case (`unmetered_usd`, the wake's cap); a `settle` row after it names the usage, and the call is priced by that +//! worst case (`unmetered_usd`, its own tuning); a `settle` row after it names the usage, and the call is priced by that //! instead. So a trace that cannot be read, or cannot take the `call` row, makes no call; a `settle` row that cannot be //! written ends the wake with its call still at the worst case; and a call whose usage is not known, a failed one that //! reports none included, is charged the worst case and never nothing. @@ -545,10 +545,11 @@ fn price(bounds: &AgentTuning, usage: &Spent) -> f64 { (usage.input_tokens as f64 * price.input + usage.output_tokens as f64 * price.output + usage.cache_read_tokens as f64 * price.cache_read + usage.cache_write_tokens as f64 * price.cache_write(bounds.retention)) / million } -/// What a call costs that no usage is known for: the most a wake may spend, the dearest a call can be taken to cost. Every -/// price that cannot be read from her trace is this, so a trace that fails never lowers the day's sum. +/// What a call costs that no usage is known for: `agent.unmetered_usd`, the dearest a call can be taken to cost. It is not the wake's cap: a wake may +/// spend a dollar over many calls, and one call cut off by a brake is not charged a dollar of the day for it. Every price that cannot be read from +/// her trace is this, so a trace that fails never lowers the day's sum. fn unmetered_usd(bounds: &AgentTuning) -> f64 { - bounds.wake_usd + bounds.unmetered_usd } /// What a call that reported `usage` is charged: its price, or `unmetered_usd` when it reports no token at all. A call that diff --git a/crates/mind-body/src/projection/agent/tests.rs b/crates/mind-body/src/projection/agent/tests.rs index ba8c7df..d273f0d 100644 --- a/crates/mind-body/src/projection/agent/tests.rs +++ b/crates/mind-body/src/projection/agent/tests.rs @@ -516,6 +516,17 @@ fn t_a1_a_failed_call_with_no_usage_is_charged_the_worst_case() { assert!(near(day_of(&rig), 0.002), "{}", day_of(&rig)); } +/// L2: a call whose usage is not known is charged `agent.unmetered_usd`, not the wake's cap: with a wake cap of $1 a cut-off call stands at $0.40 of the day. +#[test] +fn t_a1_an_unmetered_call_is_charged_its_own_figure_not_the_wake_cap() { + let mut rig = Rig::new(); + rig.bounds.wake_usd = 1.0; + rig.ledger.append(json!({ "agent": "call", "at": noon().to_rfc3339(), "call": "cut" })).unwrap(); + assert!(near(day_of(&rig), 0.40), "{}", day_of(&rig)); + rig.bounds.unmetered_usd = 0.25; + assert!(near(day_of(&rig), 0.25), "the figure is tuning"); +} + #[test] fn t_a1_a_call_that_was_never_settled_stands_at_the_worst_case() { // A start killed between the call row and its answer leaves a call row alone. diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index dcc638c..b9d99d3 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -885,7 +885,7 @@ fn tuning_absent_is_the_defaults_and_a_file_overrides_and_an_unknown_key_refuses #[test] fn the_agent_bounds_are_the_maps_and_a_file_prices_another_model() { let defaults = Tuning::default().agent; - assert_eq!((defaults.tool_calls, defaults.model_calls, defaults.wake_usd, defaults.day_usd, defaults.idle_s, defaults.span_s, defaults.ttl_s.short, defaults.ttl_s.long), (8, 10, 1.00, 3.00, 300, 1800, 300, 3600)); + assert_eq!((defaults.tool_calls, defaults.model_calls, defaults.wake_usd, defaults.day_usd, defaults.unmetered_usd, defaults.idle_s, defaults.span_s, defaults.ttl_s.short, defaults.ttl_s.long), (8, 10, 1.00, 3.00, 0.40, 300, 1800, 300, 3600)); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join(TUNING_FILE); std::fs::write(&path, "[agent] @@ -959,6 +959,7 @@ fn a_value_out_of_range_refuses_the_agent_tuning() { ("[agent]\nwake_usd = -1.0\n".to_owned(), "agent.wake_usd must be above 0"), ("[agent]\nwake_usd = inf\n".to_owned(), "agent.wake_usd must be above 0"), ("[agent]\nwake_usd = 5.5\nday_usd = 20.0\n".to_owned(), "agent.wake_usd must be above 0"), + ("[agent]\nunmetered_usd = 0.0\n".to_owned(), "agent.unmetered_usd must be above 0"), ("[agent]\nday_usd = 0.0\n".to_owned(), "agent.day_usd must be above 0"), ("[agent]\nday_usd = -1.0\n".to_owned(), "agent.day_usd must be above 0"), ("[agent]\nday_usd = 50.5\n".to_owned(), "agent.day_usd must be above 0"), diff --git a/crates/mind-body/src/projection/tuning.rs b/crates/mind-body/src/projection/tuning.rs index 1b000fc..c369990 100644 --- a/crates/mind-body/src/projection/tuning.rs +++ b/crates/mind-body/src/projection/tuning.rs @@ -127,6 +127,8 @@ pub struct AgentTuning { /// The most a wake may spend across all its turns, and the most a Mind may spend in a UTC day, summed from her trace. pub wake_usd: f64, pub day_usd: f64, + /// What a call is charged whose usage is not known (cut off by a brake, or a failure that reported none): the worst case the day's sum stands at, never nothing. + pub unmetered_usd: f64, /// How long an open wake waits, in seconds, for a line that wakes her after her last turn ended, before it closes (`persona::live::wake_end`). pub idle_s: u64, /// The longest a wake stays open, in seconds, from its start. The unit's `RuntimeMaxSec` is the backstop, and the close needs room inside it. @@ -186,6 +188,7 @@ impl Default for AgentTuning { model_calls: 10, wake_usd: 1.00, day_usd: 3.00, + unmetered_usd: 0.40, idle_s: 300, span_s: 1800, max_session_tokens: 80_000, @@ -231,6 +234,7 @@ impl AgentTuning { let usd = |name: &str, value: f64, most: f64| if value.is_finite() && value > 0.0 && value <= most { Ok(()) } else { Err(anyhow::anyhow!("{name} must be above 0 and at most {most}, not {value}")) }; usd("agent.wake_usd", self.wake_usd, AGENT_WAKE_USD_MAX)?; usd("agent.day_usd", self.day_usd, AGENT_DAY_USD_MAX)?; + usd("agent.unmetered_usd", self.unmetered_usd, AGENT_WAKE_USD_MAX)?; if self.wake_usd > self.day_usd { bail!("agent.wake_usd must be at most agent.day_usd"); }