From 8f04b70f86842e92650d15f064329cdb80bf2034 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 15:09:10 +0100 Subject: [PATCH] persona: each held start appends its own hold row; a day's old holds are no evidence; the left-out note says what became of the lines (Soul s4) failed_run counts hold rows after the last completed wake as it counts failed wakes, and only those dated today (UTC). The rewrite-in-place row and its starts counter are gone. Hold rows stay out of her packet's window. The backlog note no longer points at a read tool that cannot read a room. MemTrace reads in the live trace's (seq, at) order; backlog edge tests pin a newest line over budget, the hand-computed count and the oldest left-out line. Co-Authored-By: Claude Sonnet 5.5 --- crates/mind-body/src/heartbeat.rs | 2 +- crates/mind-body/src/heartbeat/tests.rs | 8 +- crates/mind-body/src/persona.rs | 21 ++-- crates/mind-body/src/persona/drain_tests.rs | 105 +++++++++++++++--- crates/mind-body/src/projection/turn.rs | 26 +++-- crates/mind-body/src/projection/turn/tests.rs | 32 ++++-- 6 files changed, 139 insertions(+), 55 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 82a7850..01bf67f 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -872,7 +872,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { match seat.trace.records() { Ok(records) => { row.done = Some(decided(&records).into_iter().map(str::to_owned).collect()); - row.failures = failed_run(&records); + row.failures = failed_run(&records, now); } Err(error) => { eventful = true; diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index b2f58c3..f25dbb3 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -1397,7 +1397,6 @@ fn t_h4_held_starts_back_off_like_failures_and_never_hold_her_for_a_day() { rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[])); let t0 = rig.now(); let far = (t0 + Duration::days(300)).to_rfc3339(); - let mut starts = 0u64; let mut launches: Vec = vec![]; for _ in 0..360 { rig.advance(10); @@ -1405,11 +1404,10 @@ fn t_h4_held_starts_back_off_like_failures_and_never_hold_her_for_a_day() { 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; + // What the drain does at a start it holds: appends a row of its own, at the place the trace has reached. 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() })); + let seq = rows.len(); + rows.push(serde_json::json!({ "held_by": "day_cap", "spent": 3.2, "cap": 3.0, "until": far, "at": rig.now().to_rfc3339(), "seq": seq })); } } let gaps: Vec = launches.windows(2).map(|pair| pair[1] - pair[0]).collect(); diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index 7bf66f6..3573e77 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -466,20 +466,15 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { }; // 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 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. + // raised. This drain alone decides she is held, on every start. Each held start appends its own row to her trace, as a failed wake + // does (`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); - 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) { + let row = json!({ "held_by": DAY_CAP_HOLD, "spent": spent, "cap": bounds.agent.day_usd, "at": now.to_rfc3339(), "seq": records.len() as u64 }); + if let Err(fault) = start.trace.record(&format!("{stem}-held"), &row) { eprintln!("mind-persona: the record that the day cap holds her was not appended: {fault:#}"); } - return Outcome::Held { until }; + return Outcome::Held { until: day_ends(now) }; } // Where this wake begins in her trace: what she is told at it is every row from her last completed wake's start up to here, // and what her next wake is told starts here. @@ -595,7 +590,7 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { } /// 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 has the `read` tool for the rest, and far under what a day's backlog in a busy room +/// 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. const HELD_LINES_BUDGET: usize = 16 * 1024; @@ -610,7 +605,7 @@ fn agent_input(waked: &Waked, deliveries: &[&ChatDelivery], held: &[&str], own_s .map(|delivery| (delivery, format!("room={} sender={} event={} text={}", quoted(&delivery.room_alias), quoted(if delivery.sender_display.is_empty() { &delivery.sender } else { &delivery.sender_display }), quoted(&delivery.event_id), quoted(&delivery.text)))) .collect(); // The newest lines up to the budget, the newest always. The lines left out are still held by this wake, so a completed wake acks them: - // she is told how many and where they start, and reads them back with her `read` tool. + // she is told how many, where the oldest was and that they will not be shown again. let mut kept = 0; let mut used = 0; for line in lines.iter().rev() { @@ -623,7 +618,7 @@ fn agent_input(waked: &Waked, deliveries: &[&ChatDelivery], held: &[&str], own_s let dropped = lines.len() - kept; if dropped > 0 { let oldest = &lines[0].0; - input.push_str(&format!("\n{dropped} older line(s) are not shown, the oldest in room={} at {}; read the room back with your read tool if you need them. They are decided with this wake.\n", quoted(&oldest.room_alias), DateTime::from_timestamp_millis(i64::try_from(oldest.at_unix_ms).unwrap_or_default()).unwrap_or_default().to_rfc3339())); + input.push_str(&format!("\n{dropped} older line(s) were not shown, the oldest in room={} at {}. They were marked handled with this wake and will not be shown again.\n", quoted(&oldest.room_alias), DateTime::from_timestamp_millis(i64::try_from(oldest.at_unix_ms).unwrap_or_default()).unwrap_or_default().to_rfc3339())); } if kept > 0 { let shown: Vec<&str> = lines[dropped..].iter().map(|line| line.1.as_str()).collect(); diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index c4f2369..a93d813 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -5,7 +5,7 @@ use std::cell::{Cell, RefCell}; use std::rc::Rc; use anyhow::{Result, bail}; -use chrono::{Duration, TimeZone, Utc}; +use chrono::{DateTime, Duration, TimeZone, Utc}; use serde_json::{Value, json}; use tempfile::TempDir; @@ -17,7 +17,7 @@ use model_connector::{InputItem, StopReason}; use crate::chat_client::{ChatFetchReceipt, ChatFetchRequest, ChatOpenDirectReceipt, ChatOpenDirectRequest, ChatPending, ChatRead, ChatSendReceipt, ChatSendRequest, Form, Refusal}; use crate::control::{ControlWriter, FileSource, SwarmWriter}; use crate::projection::harness::tests::{Scripted, control}; -use crate::projection::{Answer, Failed, PersonaSource, Spent, StepRequest, Stepped, ToolCall, is_wake}; +use crate::projection::{Answer, Failed, PersonaSource, Spent, StepRequest, Stepped, ToolCall, failed_run, is_wake}; use crate::testkit::at; const META: &str = "@meta:gamecult.org"; @@ -174,7 +174,8 @@ impl Trace for Rc { impl TraceView for Rc { fn records(&self) -> Result> { - Ok(self.rows.borrow().iter().map(|(_, record)| record.clone()).collect()) + // The order the live trace gives (`ordered`): by the place each row carries, then its time, never by when it was appended. + Ok(ordered(self.rows.borrow().iter().cloned())) } } @@ -860,7 +861,7 @@ fn organ_calls(rig: &Rig) -> Vec { } /// 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 counts the starts held. +/// wake is recorded, the lines that would have woken her stay unacked, and each held start appends its own row. #[test] fn t_h3_cap_holds_lines() { let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]); @@ -871,16 +872,53 @@ 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::>(); let rows = held(&rig); - assert_eq!((rows.len(), rows[0]["starts"].as_u64(), rows[0]["cap"].as_f64()), (1, Some(1), Some(3.0)), "{rows:?}"); + assert_eq!((rows.len(), rows[0]["cap"].as_f64()), (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"); 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_eq!(rows.len(), 2, "and appends its own row, rewriting none: {rows:?}"); + assert_ne!(rows[0]["seq"], rows[1]["seq"], "each at its own place"); 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()); } +/// Soul s4 second-hold-keeps-stale-seq: the trace is read in the order the live one gives (by place, then time), and a start held after a +/// completed wake sorts after it. Hold, completed wake, hold, hold on one day is a run of two held starts, and the poll backs off by them; +/// a hold row kept at its first place would sort before the wake and make the run none. +#[test] +fn t_h5_a_start_held_after_a_completed_wake_counts_in_the_run() { + let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]); + spend_the_day(&rig); + let cap = |usd: f64| std::fs::write(rig.dir.path().join("persona-tuning.toml"), format!("[agent]\nday_usd = {usd:?}\n")).unwrap(); + assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. })); + cap(1000.0); + rig.agent.answers.borrow_mut().push_back(says(&room(1), "I am here.")); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "the raised cap wakes her"); + cap(3.0); + rig.mouth.held.borrow_mut().push(line(2, &room(1), META, "and again")); + assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. })); + assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. })); + let trace = rig.trace.records().unwrap(); + let last_hold = trace.iter().rev().find(|row| row["held_by"] == "day_cap").unwrap(); + let now: DateTime = last_hold["at"].as_str().unwrap().parse().unwrap(); + assert_eq!(failed_run(&trace, now), (2, Some(now)), "the two holds after the wake: {trace:?}"); + assert_eq!(trace.iter().filter(|row| row["held_by"] == "day_cap").count(), 3, "every held start has its own row"); +} + +/// Soul s4 rollover-delayed-by-old-hold: the cap resets at the UTC midnight, so the holds of yesterday are no evidence today. +#[test] +fn t_h5_yesterdays_holds_do_not_cool_today() { + let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]); + spend_the_day(&rig); + assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. })); + assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. })); + let trace = rig.trace.records().unwrap(); + let today: DateTime = trace.last().unwrap()["at"].as_str().unwrap().parse().unwrap(); + assert_eq!(failed_run(&trace, today).0, 2); + assert_eq!(failed_run(&trace, today + Duration::days(1)), (0, None), "the next day starts clean"); +} + /// The same trace once the UTC day has rolled over: the held line wakes her, is answered and is acked, with no new message. #[test] fn t_h3_rollover_wakes_held_lines() { @@ -911,20 +949,55 @@ fn t_h4_a_day_spent_to_exactly_the_cap_holds() { assert!(rig.acks().is_empty()); } -/// A day's backlog wakes her with the newest lines up to the byte budget and the count of the older ones she is not shown, with where -/// they start; the wake holds all of them, so its completion acks them all. +/// Her agent's first user text of the one wake a test ran. +fn agent_first_input(rig: &Rig) -> String { + match rig.agent.seen.borrow().first().and_then(|input| input.first()) { + Some(InputItem::UserText { text }) => text.clone(), + other => panic!("the agent's first item is her input: {other:?}"), + } +} + +/// `line` as the first user text renders it: the room, sender, event and quoted text, one line. +fn rendered_len(seq: u64, text_len: usize) -> usize { + format!(r#"room="{}" sender="{META}" event="$e{seq}" text=""#, room(1)).len() + text_len + 1 +} + +/// A day's backlog wakes her with the newest lines up to the byte budget. Lines of different lengths, so a budget counted from the oldest +/// line, or a count read off what is shown, comes out otherwise: the lines shown are exactly the newest ones the budget holds, the count +/// of the others and where the oldest of them was are said, and what the note says is true, the others are acked with the wake. #[test] fn t_h4_a_backlog_over_the_budget_shows_the_newest_lines_and_says_how_many_it_left_out() { - let lines: Vec = (1..=300).map(|n| line(n, &room(1), META, &format!("{n:04} {}", "x".repeat(180)))).collect(); + let text_len = |n: u64| 100 + usize::try_from(n % 7).unwrap() * 45; + let lines: Vec = (1..=300).map(|n| line(n, &room(1), META, &format!("{n:04} {}", "x".repeat(text_len(n) - 5)))).collect(); let rig = Rig::new(lines); rig.agent.answers.borrow_mut().push_back(says(&room(1), "I am here.")); assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(300) }, "every line is acked, shown or not"); - let input = format!("{:?}", rig.agent.seen.borrow().last().unwrap()); - let shown = input.matches("event=").count(); - assert!(shown > 20 && shown < 300, "the budget cut the lines: {shown}"); - assert!(input.contains("0300 xxx") && !input.contains("0001 xxx"), "the newest are kept"); - let left = 300 - shown; - assert!(input.contains(&format!("{left} older line(s) are not shown")), "the count is said ({left}): {}", &input[..600.min(input.len())]); - assert!(input.contains("2026-"), "and where the left-out lines start"); + let input = agent_first_input(&rig); + // The count by hand: newest first, each line and its newline, until the next would pass the budget. + let (mut used, mut kept) = (0, 0_u64); + while kept < 300 && used + rendered_len(300 - kept, text_len(300 - kept)) + 1 <= HELD_LINES_BUDGET { + used += rendered_len(300 - kept, text_len(300 - kept)) + 1; + kept += 1; + } + let dropped = 300 - kept; + assert!(dropped > 20 && kept > 20, "the budget cut the lines: {kept} kept"); + assert_eq!(input.matches("event=").count() as u64, kept); + for n in 1..=300_u64 { + assert_eq!(input.contains(&format!("event=\"$e{n}\"")), n > dropped, "line {n}: the newest {kept} are shown and no other"); + } + assert!(input.contains(&format!("\n{dropped} older line(s) were not shown, the oldest in room=\"{}\" at {}.", room(1), DateTime::from_timestamp_millis(i64::try_from(BASE_MS - 120_000 + 1000).unwrap()).unwrap().to_rfc3339())), "the count, and the room and time of the oldest of those left out (line 1): {}", &input[..700.min(input.len())]); + assert!(input.contains("marked handled") && input.contains("will not be shown again") && !input.contains("read tool"), "the note says what became of them, and points at no tool"); assert!(input.len() < HELD_LINES_BUDGET + 8 * 1024, "the input is bounded: {}", input.len()); } + +/// A single newest line over the whole budget is kept, with the older line left out: the wake is never given nothing to answer. +#[test] +fn t_h5_a_newest_line_over_the_budget_is_kept_and_the_older_one_is_left_out() { + let rig = Rig::new(vec![line(1, &room(1), META, "older and small"), line(2, &room(1), META, &format!("big {}", "y".repeat(HELD_LINES_BUDGET + 100)))]); + rig.agent.answers.borrow_mut().push_back(says(&room(1), "I am here.")); + assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(2) }); + let input = agent_first_input(&rig); + assert!(input.contains("big yyy") && !input.contains("older and small"), "the newest is kept alone"); + assert!(input.contains("\n1 older line(s) were not shown, the oldest in room=\"!dm-1:gamecult.org\" at "), "{}", &input[..400.min(input.len())]); + assert_eq!(input.matches("event=").count(), 1); +} diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs index 0eb8e16..f7a533b 100644 --- a/crates/mind-body/src/projection/turn.rs +++ b/crates/mind-body/src/projection/turn.rs @@ -55,22 +55,26 @@ pub(crate) fn decided(records: &[Value]) -> BTreeSet<&str> { done } -/// 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>) { - let starts: Vec<&Value> = records.iter().filter(|record| is_wake(record) || record["held_by"] == DAY_CAP_HOLD).collect(); +/// 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; so is +/// each day-cap hold row (`persona::drain` appends one per held start), none of them a strike. A completed wake ends the run. The day +/// cap resets at the UTC midnight, so a hold row dated before `now`'s day is no evidence of today and is not counted. +pub(crate) fn failed_run(records: &[Value], now: DateTime) -> (u32, Option>) { + let at_of = |record: &Value| record["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.with_timezone(&Utc)); + let starts: Vec<&Value> = records.iter().filter(|record| is_wake(record) || (is_hold(record) && at_of(record).is_some_and(|at| at.date_naive() == now.date_naive()))).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) { + if is_hold(record) || 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) + (run, starts.last().filter(|_| run > 0).and_then(|record| at_of(record))) +} + +/// Whether `record` is the row a start appended because her agent had spent its day's cap (`persona::drain`). +pub(crate) fn is_hold(record: &Value) -> bool { + record["held_by"] == DAY_CAP_HOLD } /// 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`). @@ -91,9 +95,9 @@ 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::>()); let mut recent: Vec> = records.iter().filter(|record| completed(record)).filter_map(selected).collect(); recent.drain(..recent.len().saturating_sub(RECENT)); - // A failed wake is in her trace and not in her packet's window: an outage that fails every wake for an hour must not push + // A failed wake or a day-cap hold row is in her trace and not in her packet's window: an outage that fails every wake for an hour must not push // what she did out of it. - let kept: Vec<&Value> = records.iter().filter(|record| !(is_wake(record) && failed(record))).collect(); + let kept: Vec<&Value> = records.iter().filter(|record| !(is_wake(record) && failed(record)) && !is_hold(record)).collect(); Past { told: outcome::told(records), recent, records: kept[kept.len().saturating_sub(RECORDS)..].iter().map(|record| (*record).clone()).collect(), last_wake: last_wake(records) } } diff --git a/crates/mind-body/src/projection/turn/tests.rs b/crates/mind-body/src/projection/turn/tests.rs index d96959b..7dcd567 100644 --- a/crates/mind-body/src/projection/turn/tests.rs +++ b/crates/mind-body/src/projection/turn/tests.rs @@ -1,4 +1,4 @@ -use chrono::Duration; +use chrono::{DateTime, Duration, Utc}; use serde_json::{Value, json}; use super::*; @@ -39,8 +39,8 @@ fn t_l2_failed_records_never_push_her_real_turns_out_of_the_window() { let past = history(&records); assert_eq!(past.records.len(), 4, "the window holds her wakes and her agent's row, and no failure"); assert_eq!(past.recent.len(), 3); - assert_eq!(failed_run(&records).0, 200); - assert_eq!(failed_run(&records[..3]).0, 0); + assert_eq!(failed_run(&records, "2026-11-27T12:00:00Z".parse().unwrap()).0, 200); + assert_eq!(failed_run(&records[..3], "2026-11-27T12:00:00Z".parse().unwrap()).0, 0); } /// A completed wake decides the lines it held; a failed one decides nothing; a set-aside row decides its line. @@ -56,13 +56,27 @@ fn t_l2_a_line_is_decided_by_the_record_that_holds_it() { assert_eq!(decided(&records).into_iter().collect::>(), ["$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. +/// Each day-cap hold row is one failed start in a row, none of them a strike, and a completed wake after it ends the run. A hold row +/// dated before the current UTC day is no evidence of today and is not counted (Soul s4 rollover-delayed-by-old-hold). #[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 }); +fn t_h4_a_day_cap_hold_row_counts_as_a_failed_start_in_the_run() { + let hold = |at: &str, seq: u64| json!({ "held_by": "day_cap", "at": at, "seq": seq }); 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"); + let now: DateTime = "2026-11-27T12:00:00Z".parse().unwrap(); + let holds = [hold("2026-11-27T11:00:00Z", 5), hold("2026-11-27T11:00:20Z", 6), hold("2026-11-27T11:01:00Z", 7)]; + assert_eq!(failed_run(&[vec![done.clone()], holds.to_vec()].concat(), now), (3, Some("2026-11-27T11:01:00Z".parse().unwrap()))); + assert_eq!(failed_run(&[vec![done.clone(), failed.clone()], holds[..2].to_vec()].concat(), now).0, 3, "with the failed wake before them"); + assert_eq!(failed_run(&[holds.to_vec(), vec![done.clone()]].concat(), now), (0, None), "a completed wake after them ends the run"); + let yesterday = [hold("2026-11-26T23:58:00Z", 5), hold("2026-11-26T23:59:00Z", 6)]; + assert_eq!(failed_run(&[vec![done.clone()], yesterday.to_vec()].concat(), now), (0, None), "yesterday's holds are no evidence today"); + assert_eq!(failed_run(&[vec![done, failed], yesterday.to_vec(), holds[..1].to_vec()].concat(), now).0, 2, "today's hold and the failed wake count; yesterday's do not"); +} + +/// Her packet's window holds her turns: a day's hold rows are in her trace and not in it, as failed wakes are not. +#[test] +fn t_h5_hold_rows_never_enter_her_packets_window() { + let mut records: Vec = (0..3).map(|n| wake(n, &[&format!("m{n}")])).collect(); + records.extend((0..150).map(|n| json!({ "held_by": "day_cap", "at": "2026-11-27T11:00:00Z", "seq": n + 3 }))); + assert_eq!(history(&records).records.len(), 3); }