From ba7e7b7c6816b342bae587c1654608c1781c3bdf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 31 Oct 2026 14:48:56 +0100 Subject: [PATCH] wip2 --- crates/mind-body/src/self_run/decide/tests.rs | 241 +++++++++++++++--- crates/mind-body/src/self_run/inbox/tests.rs | 146 +++++++++++ crates/mind-body/src/self_run/tests.rs | 219 +++++++++++++++- .../mind-body/src/self_run/tests/closure.rs | 6 +- crates/mind-body/src/self_run/tests/lease.rs | 2 +- 5 files changed, 567 insertions(+), 47 deletions(-) create mode 100644 crates/mind-body/src/self_run/inbox/tests.rs diff --git a/crates/mind-body/src/self_run/decide/tests.rs b/crates/mind-body/src/self_run/decide/tests.rs index 814abd2..8f4372c 100644 --- a/crates/mind-body/src/self_run/decide/tests.rs +++ b/crates/mind-body/src/self_run/decide/tests.rs @@ -2,9 +2,21 @@ //! clock: tables, one row per boundary, and an enumeration of event orders that //! asserts the invariants against an oracle kept from the event history alone. +use std::collections::VecDeque; + use super::*; use crate::testkit::at; +/// Long enough that no table below reaches the cap by accident. +const CAP_S: u64 = 100_000; +const RESULT: Event = Event::Result { ttl_1h: true }; +const SHORT_RESULT: Event = Event::Result { ttl_1h: false }; + +/// A session whose first turn is running. +fn working() -> State { + State::started(t(0), CAP_S) +} + fn t(seconds: i64) -> DateTime { at(seconds * 1000) } @@ -19,7 +31,7 @@ fn feed(state: State, event: Event, seconds: i64) -> (State, Action) { /// Runs the events in order, each at its own second, and keeps every action. fn run(events: Vec<(Event, i64)>) -> (State, Vec) { - let mut state = State::default(); + let mut state = working(); let mut actions = Vec::new(); for (event, seconds) in events { let (next, action) = feed(state, event, seconds); @@ -52,8 +64,6 @@ fn the_flush_is_asked_once_at_the_ceiling_and_never_after_a_result_or_an_exit_or assert_eq!(last(vec![(req("a", CEILING_TOKENS + 1), 0)]), Action::WriteFlush); // Once. assert_eq!(last(vec![(req("a", CEILING_TOKENS), 0), (req("b", CEILING_TOKENS + 5), 1)]), Action::None); - // A result first: the child is finishing, there is nothing to flush. - assert_eq!(last(vec![(Event::Result, 0), (req("a", CEILING_TOKENS), 1)]), Action::None); // A child that is gone is not written to. assert_eq!(last(vec![(Event::ChildExited(Some(0)), 0), (req("a", CEILING_TOKENS), 1)]), Action::None); // The same message id is the same request again: it neither counts nor decides. @@ -62,10 +72,82 @@ fn the_flush_is_asked_once_at_the_ceiling_and_never_after_a_result_or_an_exit_or } #[test] -fn the_input_closes_once_at_the_first_result() { - assert_eq!(last(vec![(Event::Result, 0)]), Action::CloseStdin); - assert_eq!(last(vec![(Event::Result, 0), (Event::Result, 1)]), Action::None); - assert_eq!(last(vec![(req("a", CEILING_TOKENS), 0), (Event::Result, 1)]), Action::CloseStdin); +fn a_result_ends_a_turn_and_never_closes_the_input_while_a_brief_waits_or_the_cache_is_warm() { + // The result asks for its briefs to be closed and nothing else; the next pass has nothing to do. + assert_eq!(last(vec![(RESULT, 0)]), Action::CloseBriefs); + assert_eq!(last(vec![(RESULT, 0), (Event::Tick, 0)]), Action::None); + assert_eq!(last(vec![(RESULT, 0), (Event::Tick, 3000)]), Action::None); + // A waiting brief is told, however long the session has been idle, and the input stays open. + assert_eq!(last(vec![(RESULT, 0), (Event::Inbox { pending: true }, 10)]), Action::WriteTells); + assert_eq!(last(vec![(RESULT, 0), (Event::Inbox { pending: true }, 10), (Event::Told, 10), (Event::Tick, 11)]), Action::None); + let waiting = |seconds: i64| last(vec![(RESULT, 0), (Event::Inbox { pending: true }, 10), (Event::Tick, seconds)]); + assert_eq!(waiting(TTL_1H_S * 3), Action::WriteTells, "a waiting brief outranks the cache's end"); + // Mid-turn, a brief is the hook's: the actuator writes nothing, and the next result comes. + assert_eq!(last(vec![(Event::Inbox { pending: true }, 10)]), Action::None); + assert_eq!(last(vec![(Event::Inbox { pending: true }, 10), (RESULT, 20), (Event::Tick, 20)]), Action::WriteTells); +} + +#[test] +fn the_session_ends_where_the_cache_would_be_evicted_with_a_flush_and_closes_after_the_flushs_own_result() { + let idle_at = |result: Event, seconds: i64| last(vec![(result, 0), (Event::Tick, seconds)]); + // An hour's cache: the flush at 3540 s, not before. + assert_eq!(idle_at(RESULT, TTL_1H_S - TTL_MARGIN_S - 1), Action::None); + assert_eq!(idle_at(RESULT, TTL_1H_S - TTL_MARGIN_S), Action::WriteFlush); + // A five-minute cache: at 240 s. + assert_eq!(idle_at(SHORT_RESULT, TTL_5M_S - TTL_MARGIN_S - 1), Action::None); + assert_eq!(idle_at(SHORT_RESULT, TTL_5M_S - TTL_MARGIN_S), Action::WriteFlush); + // The deadline the loop waits for is the same moment. + let (state, _) = run(vec![(RESULT, 5)]); + assert_eq!(next_deadline(&state), Some(t(5 + TTL_1H_S - TTL_MARGIN_S))); + // The input stays open through the flush's turn and closes after its result, one pass later. + let flushed = vec![(RESULT, 0), (Event::Tick, TTL_1H_S - TTL_MARGIN_S)]; + assert_eq!(last([flushed.clone(), vec![(Event::Tick, TTL_1H_S)]].concat()), Action::None); + let ended_turn = [flushed, vec![(SHORT_RESULT, TTL_1H_S)]].concat(); + assert_eq!(last(ended_turn.clone()), Action::CloseBriefs); + assert_eq!(last([ended_turn, vec![(Event::Tick, TTL_1H_S)]].concat()), Action::CloseStdin); +} + +#[test] +fn near_the_cap_an_idle_session_rotates_and_a_working_one_is_asked_for_its_flush() { + let cap = i64::try_from(CAP_S).unwrap(); + // A result so late that the rotation comes before the cache's end. + let late = cap - 1300; + let idle_at = |seconds: i64| last(vec![(RESULT, late), (Event::Tick, seconds)]); + assert_eq!(idle_at(cap - ROTATE_MARGIN_S - 1), Action::None); + assert_eq!(idle_at(cap - ROTATE_MARGIN_S), Action::CloseStdin); + // A waiting brief does not hold the process past the rotation: the next process tells it. + assert_eq!(last(vec![(RESULT, late), (Event::Inbox { pending: true }, cap - ROTATE_MARGIN_S)]), Action::CloseStdin); + // Mid-turn the flush is asked at the margin, once, and it keeps its grace and escalation. + let working_at = |seconds: i64| last(vec![(req("a", 10), 1), (Event::Tick, seconds)]); + assert_eq!(working_at(cap - FLUSH_MARGIN_S - 1), Action::None); + assert_eq!(working_at(cap - FLUSH_MARGIN_S), Action::WriteFlush); + let asked = vec![(req("a", 10), 1), (Event::Tick, cap - FLUSH_MARGIN_S)]; + assert_eq!(last([asked.clone(), vec![(Event::Tick, cap - FLUSH_MARGIN_S + 1)]].concat()), Action::None); + assert_eq!(last([asked, vec![(Event::Tick, cap - FLUSH_MARGIN_S + GRACE)]].concat()), Action::Signal(Stop::Interrupt)); + let (state, _) = run(vec![(req("a", 10), 1)]); + assert_eq!(next_deadline(&state), Some(t(cap - FLUSH_MARGIN_S))); +} + +#[test] +fn pre_compact_asks_the_same_flush_the_ceiling_asks_once() { + assert_eq!(last(vec![(req("a", 10), 0), (Event::PreCompact, 1)]), Action::WriteFlush); + assert_eq!(last(vec![(req("a", 10), 0), (Event::PreCompact, 1), (Event::PreCompact, 2)]), Action::None); + // The ceiling after it asks nothing more; the ceiling before it leaves nothing for the hook to ask. + assert_eq!(last(vec![(req("a", 10), 0), (Event::PreCompact, 1), (req("b", CEILING_TOKENS), 2)]), Action::None); + assert_eq!(last(vec![(req("a", CEILING_TOKENS), 0), (Event::PreCompact, 1)]), Action::None); + // Its flush has the grace and the headroom of any other. + assert_eq!(last(vec![(req("a", 10), 0), (Event::PreCompact, 1), (Event::Tick, 1 + GRACE)]), Action::Signal(Stop::Interrupt)); + // A child that is gone is not written to. + assert_eq!(last(vec![(Event::ChildExited(Some(0)), 0), (Event::PreCompact, 1)]), Action::None); +} + +#[test] +fn a_flush_is_never_asked_of_a_session_whose_input_is_closed() { + let cap = i64::try_from(CAP_S).unwrap(); + let closed = vec![(RESULT, 1), (Event::Tick, cap - ROTATE_MARGIN_S)]; + assert_eq!(last(closed.clone()), Action::CloseStdin); + assert_eq!(last([closed.clone(), vec![(Event::PreCompact, cap)]].concat()), Action::None); + assert_eq!(last([closed, vec![(req("b", CEILING_TOKENS), cap)]].concat()), Action::None); } #[test] @@ -86,25 +168,23 @@ fn the_grace_runs_from_the_flush_write_to_the_second_and_no_later_request_moves_ #[test] fn the_headroom_counts_the_requests_after_the_first_result_after_the_flush_from_the_prefix_of_the_flush() { - let after_result = |request: u64| last(vec![(req("a", CEILING_TOKENS), 0), (Event::Result, 1), (req("b", request), 2)]); + let after_result = |request: u64| last(vec![(req("a", CEILING_TOKENS), 0), (RESULT, 1), (req("b", request), 2)]); assert_eq!(after_result(LIMIT - 1), Action::None); assert_eq!(after_result(LIMIT), Action::Signal(Stop::Interrupt)); assert_eq!(after_result(LIMIT + 1), Action::Signal(Stop::Interrupt)); // Measured from the flush's own prefix, not from the ceiling. - let high = |request: u64| last(vec![(req("a", 400_000), 0), (Event::Result, 1), (req("b", request), 2)]); + let high = |request: u64| last(vec![(req("a", 400_000), 0), (RESULT, 1), (req("b", request), 2)]); assert_eq!((high(459_999), high(460_000)), (Action::None, Action::Signal(Stop::Interrupt))); // The turn already running is not the flush's turn: before a result no request counts. assert_eq!(last(vec![(req("a", CEILING_TOKENS), 0), (req("b", LIMIT + 400_000), 1)]), Action::None); // A big request before the result is forgotten by the boundary; only those after it count. - assert_eq!(last(vec![(req("a", CEILING_TOKENS), 0), (req("b", LIMIT + 1), 1), (Event::Result, 2), (req("c", LIMIT - 1), 3)]), Action::None); - // The result before the flush is not the boundary: the flush cannot be written then. - assert_eq!(last(vec![(Event::Result, 0), (req("a", CEILING_TOKENS), 1), (req("b", 900_000), 2)]), Action::None); + assert_eq!(last(vec![(req("a", CEILING_TOKENS), 0), (req("b", LIMIT + 1), 1), (RESULT, 2), (req("c", LIMIT - 1), 3)]), Action::None); // A prefix that saturates leaves no headroom to count: only the grace is left. - let saturated = |rest: Vec<(Event, i64)>| last([vec![(req("a", u64::MAX), 0), (Event::Result, 1), (req("b", u64::MAX), 2)], rest].concat()); + let saturated = |rest: Vec<(Event, i64)>| last([vec![(req("a", u64::MAX), 0), (RESULT, 1), (req("b", u64::MAX), 2)], rest].concat()); assert_eq!(saturated(vec![]), Action::None); assert_eq!(saturated(vec![(Event::Tick, GRACE)]), Action::Signal(Stop::Interrupt)); // A request counted past the headroom stays counted: a later smaller one does not take the interrupt back. - let (state, actions) = run(vec![(req("a", CEILING_TOKENS), 0), (Event::Result, 1), (req("b", LIMIT), 2)]); + let (state, actions) = run(vec![(req("a", CEILING_TOKENS), 0), (RESULT, 1), (req("b", LIMIT), 2)]); assert_eq!(actions[2], Action::Signal(Stop::Interrupt)); assert_eq!(next_deadline(&state), Some(t(2 + ESC))); } @@ -112,7 +192,7 @@ fn the_headroom_counts_the_requests_after_the_first_result_after_the_flush_from_ #[test] fn the_flush_pass_never_signals_whatever_the_clock_does() { // Two events apart by more than the grace: the write is its own pass, the signal comes in the next. - let (state, action) = feed(State::default(), req("a", CEILING_TOKENS), 0); + let (state, action) = feed(working(), req("a", CEILING_TOKENS), 0); assert_eq!(action, Action::WriteFlush); assert_eq!(feed(state, Event::Tick, 10 * GRACE).1, Action::Signal(Stop::Interrupt)); // A request that both crosses the ceiling and is far past the headroom writes the flush and nothing else. @@ -197,7 +277,7 @@ fn a_child_that_has_exited_is_never_signalled_and_the_run_ends_with_its_stream_o #[test] fn without_a_flush_nothing_is_ever_signalled_and_a_finished_run_decides_nothing_more() { - let quiet = vec![(req("a", 10), 0), (Event::Result, 1), (req("b", 900_000), 2), (Event::Tick, 100_000)]; + let quiet = vec![(req("a", 10), 0), (RESULT, 1), (Event::Tick, 100_000)]; assert!(run(quiet).1.iter().all(|action| !matches!(action, Action::Signal(_)))); let (state, actions) = run(vec![(Event::ChildExited(Some(3)), 0), (Event::StdoutEof, 0)]); assert_eq!(actions[1], ended(Cause::Own, Some(3), 0, 0)); @@ -248,12 +328,18 @@ enum Policy { #[derive(Default)] struct Oracle { ids: Vec, + /// When the flush was written and the prefix it was written at. flush: Option<(i64, u64)>, flushes: u32, closes: u32, + /// The flush is the turn that runs now or has run. boundary: bool, exceeded: bool, - result_seen: bool, + /// No turn is running. + idle: bool, + inbox: bool, + closed: bool, + prefix: u64, exited: Option, eof: bool, signals: Vec<(Stop, i64)>, @@ -263,11 +349,13 @@ struct Oracle { fn check_step(oracle: &mut Oracle, event: &Event, now: i64, action: &Action) { assert!(!oracle.finished || *action == Action::None, "an action after the run ended: {action:?} on {event:?}"); let flush_before = oracle.flush; - let (was_result, was_exited) = (oracle.result_seen, oracle.exited.is_some()); + let was_exited = oracle.exited.is_some(); + let was_idle = oracle.idle; match event { Event::Request { id, prefix } => { if !oracle.ids.contains(id) { oracle.ids.push(id.clone()); + oracle.prefix = *prefix; if oracle.boundary && let Some((_, base)) = oracle.flush && base.checked_add(FLUSH_HEADROOM_TOKENS).is_some_and(|limit| *prefix >= limit) @@ -276,29 +364,47 @@ fn check_step(oracle: &mut Oracle, event: &Event, now: i64, action: &Action) { } } } - Event::Result => { - if oracle.flush.is_some() { + Event::Result { .. } => { + oracle.idle = true; + if oracle.flush.is_some() && !oracle.boundary { oracle.boundary = true; + oracle.idle = false; } - oracle.result_seen = true; } + Event::Inbox { pending } => oracle.inbox = *pending, + Event::Told => { + oracle.inbox = false; + oracle.idle = false; + } + Event::PreCompact | Event::Tick | Event::Signalled { .. } => {} Event::ChildExited(_) => { oracle.exited.get_or_insert(now); } Event::StdoutEof => oracle.eof = true, - Event::Tick | Event::Signalled { .. } => {} } match action { Action::None => {} Action::WriteFlush => { oracle.flushes += 1; - let Event::Request { prefix, .. } = event else { panic!("a flush on {event:?}") }; - assert!(*prefix >= CEILING_TOKENS && !was_result && !was_exited && flush_before.is_none(), "flush at {prefix} after {was_result} {was_exited}"); - oracle.flush = Some((now, *prefix)); + if let Event::Request { prefix, .. } = event { + assert!(*prefix >= CEILING_TOKENS, "a flush at {prefix} on a request"); + } + assert!(flush_before.is_none() && !was_exited && !oracle.closed, "flush twice, to a gone child or to a closed input"); + oracle.flush = Some((now, oracle.prefix)); + // Written while idle, its turn begins at once. + oracle.boundary = oracle.idle; + oracle.idle = false; } + Action::WriteTells => { + assert!(oracle.idle && oracle.inbox && !oracle.closed && !was_exited, "a tell outside idle with a brief waiting"); + } + Action::CloseBriefs => assert!(matches!(event, Event::Result { .. }), "briefs closed on {event:?}"), Action::CloseStdin => { oracle.closes += 1; - assert!(matches!(event, Event::Result) && !was_result && !was_exited); + oracle.closed = true; + let flushed = oracle.flush.is_some() && oracle.boundary; + let rotation = now >= i64::try_from(CAP_S).unwrap() - ROTATE_MARGIN_S; + assert!(was_idle && !was_exited && (flushed || rotation), "closed on {event:?} idle {was_idle} flushed {flushed} rotation {rotation}"); } Action::Signal(how) => { let (flushed_at, _) = flush_before.expect("a signal before the flush was written"); @@ -341,8 +447,55 @@ fn check_step(oracle: &mut Oracle, event: &Event, now: i64, action: &Action) { assert!(oracle.signals.len() <= 3); } +/// What can happen next, each at a time after the last. +#[derive(Clone, Copy, Debug)] +enum Sym { + Low, + AtCeiling, + Huge, + Repeat, + Result, + ShortResult, + Brief, + NoBrief, + PreCompact, + Exit(Option), + Eof, + Soon, + Bound, + Grace, + Cache, +} + +const ALPHABET: [Sym; 16] = [ + Sym::Low, + Sym::AtCeiling, + Sym::Huge, + Sym::Repeat, + Sym::Result, + Sym::ShortResult, + Sym::Brief, + Sym::NoBrief, + Sym::PreCompact, + Sym::Exit(Some(0)), + Sym::Exit(None), + Sym::Eof, + Sym::Soon, + Sym::Bound, + Sym::Grace, + Sym::Cache, +]; + +/// Which signals the operating system lets through. +#[derive(Clone, Copy, Debug)] +enum Policy { + All, + Nothing, + NoKill, +} + fn play(symbols: &[Sym], policy: Policy) { - let mut state = State::default(); + let mut state = working(); let mut oracle = Oracle::default(); let mut now = 0i64; let mut unique = 0u32; @@ -353,27 +506,37 @@ fn play(symbols: &[Sym], policy: Policy) { Sym::AtCeiling => (req_new(&mut unique, CEILING_TOKENS), 1), Sym::Huge => (req_new(&mut unique, LIMIT + 400_000), 1), Sym::Repeat => (req("u1", CEILING_TOKENS + 7), 1), - Sym::Result => (Event::Result, 1), + Sym::Result => (RESULT, 1), + Sym::ShortResult => (SHORT_RESULT, 1), + Sym::Brief => (Event::Inbox { pending: true }, 1), + Sym::NoBrief => (Event::Inbox { pending: false }, 1), + Sym::PreCompact => (Event::PreCompact, 1), Sym::Exit(code) => (Event::ChildExited(*code), 1), Sym::Eof => (Event::StdoutEof, 1), Sym::Soon => (Event::Tick, 1), Sym::Bound => (Event::Tick, ESC + 1), Sym::Grace => (Event::Tick, GRACE + 1), + Sym::Cache => (Event::Tick, TTL_1H_S), }; now += dt; events.push(event.clone()); - let mut next = Some(event); - while let Some(event) = next.take() { + let mut pending = VecDeque::from([event]); + while let Some(event) = pending.pop_front() { let (after, action) = decide(state, event.clone(), t(now)); state = after; check_step(&mut oracle, &event, now, &action); - if let Action::Signal(how) = action { - let delivered = match policy { - Policy::All => true, - Policy::Nothing => false, - Policy::NoKill => how != Stop::Kill, - }; - next = Some(Event::Signalled { how, delivered }); + match action { + Action::Signal(how) => { + let delivered = match policy { + Policy::All => true, + Policy::Nothing => false, + Policy::NoKill => how != Stop::Kill, + }; + pending.push_front(Event::Signalled { how, delivered }); + } + // The loop claims the spool and writes the line: a turn begins. + Action::WriteTells => pending.push_front(Event::Told), + _ => {} } } } @@ -417,9 +580,9 @@ fn enumerate(length: usize, symbols: &mut Vec, policy: Policy) { } #[test] -fn every_order_of_up_to_five_events_keeps_the_invariants_under_every_policy_of_delivery() { +fn every_order_of_up_to_four_events_keeps_the_invariants_under_every_policy_of_delivery() { for policy in [Policy::All, Policy::Nothing, Policy::NoKill] { - for length in 0..=5 { + for length in 0..=4 { enumerate(length, &mut Vec::new(), policy); } } diff --git a/crates/mind-body/src/self_run/inbox/tests.rs b/crates/mind-body/src/self_run/inbox/tests.rs new file mode 100644 index 0000000..9f4ae85 --- /dev/null +++ b/crates/mind-body/src/self_run/inbox/tests.rs @@ -0,0 +1,146 @@ +//! The inbox over a real spool directory and a mind in memory: what is derived, +//! the exactly-once claim, and the hook that prints it. + +use eureka_pipeline::{PipelineDocument, PipelineKind as K, RunOperator, RunTurn}; + +use super::*; +use crate::testkit::{TestMind, at, close as closing, follow_up, id, recorded, reference, run, run_ref, spec, spec_ref}; + +fn spool_dir() -> tempfile::TempDir { + tempfile::tempdir().unwrap() +} + +fn brief_doc(label: &str, owner: &str) -> PipelineDocument { + let PipelineDocument::FollowUp(mut document) = follow_up(label, &spec_ref("x")) else { unreachable!() }; + document.owner = owner.into(); + document.item = format!("Do {label}.").as_str().into(); + PipelineDocument::FollowUp(document) +} + +fn brief_ref(label: &str) -> PipelineRef { + reference(K::FollowUp, &id("follow_up", label)) +} + +fn mind_with(documents: Vec) -> TestMind { + let mind = TestMind::seeded(); + mind.committed(vec![spec("x")]); + mind.committed(documents); + mind +} + +fn entry(n: u64) -> Brief { + Brief { id: format!("eureka-body:follow_up:b{n}"), campaign: "eureka-body".into(), repo: "GameCult/Huginn".into(), item: format!("Item {n}."), ordinal: n } +} + +#[test] +fn the_inbox_is_the_open_self_run_briefs_that_no_closed_run_claims_and_the_session_does_not_hold() { + let mind = mind_with(vec![brief_doc("open", OWNER), brief_doc("claimed-by-old", OWNER), brief_doc("someone-elses", "Hands"), brief_doc("answered", OWNER), brief_doc("held", OWNER)]); + mind.committed(vec![run("old", RunTurn::SelfRun, RunOperator::Mind, &[brief_ref("claimed-by-old")])]); + mind.committed(vec![closing(run_ref("old"), recorded()), closing(brief_ref("answered"), recorded())]); + let spool = spool_dir(); + mark_told(spool.path(), &[Brief { id: brief_ref("held").id.0, ..entry(9) }]).unwrap(); + let derived: Vec = derive(&mind, spool.path()).unwrap().into_iter().map(|brief| brief.id).collect(); + assert_eq!(derived, vec![brief_ref("open").id.0], "only the open one nobody answered and nobody holds"); + // A run that is still open claims without answering: its brief is still asked. + mind.committed(vec![run("live", RunTurn::SelfRun, RunOperator::Mind, &[brief_ref("open")])]); + assert_eq!(derive(&mind, spool.path()).unwrap().len(), 1); +} + +#[test] +fn spooled_entries_are_claimed_in_order_and_hand_back_what_was_written() { + let spool = spool_dir(); + spool_briefs(spool.path(), &[entry(2), entry(1)]); + assert!(pending(spool.path()).unwrap()); + let claimed = claim(spool.path()).unwrap(); + assert_eq!(claimed, vec![entry(1), entry(2)], "oldest first"); + assert!(!pending(spool.path()).unwrap() && claim(spool.path()).unwrap().is_empty(), "a claim empties the spool"); + assert_eq!(told(spool.path()).unwrap(), vec![entry(1), entry(2)]); + forget(spool.path(), &claimed[..1]); + assert_eq!(told(spool.path()).unwrap(), vec![entry(2)]); +} + +fn spool_briefs(dir: &Path, briefs: &[Brief]) { + spool(dir, briefs).unwrap(); +} + +#[test] +fn a_hook_and_the_actuator_claiming_at_once_deliver_each_entry_to_exactly_one_of_them() { + for _ in 0..20 { + let spool = spool_dir(); + let briefs: Vec = (1..=60).map(entry).collect(); + spool_briefs(spool.path(), &briefs); + let path = spool.path().to_path_buf(); + let racers: Vec<_> = (0..4) + .map(|_| { + let path = path.clone(); + std::thread::spawn(move || claim(&path).unwrap()) + }) + .collect(); + let mut seen: Vec = racers.into_iter().flat_map(|racer| racer.join().unwrap()).map(|brief| brief.ordinal).collect(); + seen.sort_unstable(); + assert_eq!(seen, (1..=60).collect::>(), "every entry once, none twice, none lost"); + } +} + +#[test] +fn the_hook_prints_data_only_and_only_for_the_main_thread() { + let spool = spool_dir(); + write_plan(spool.path(), "Plan usage: unobserved.").unwrap(); + assert_eq!(inject(spool.path(), "{}", false).unwrap(), Injection { stdout: String::new(), exit: 0 }, "an empty spool prints nothing"); + spool_briefs(spool.path(), &[entry(1)]); + // A subagent's call (the input carries an agent id) prints nothing and claims nothing. + let subagent = inject(spool.path(), "{\"hook_event_name\":\"PostToolBatch\",\"agent_id\":\"a1\"}", false).unwrap(); + assert_eq!(subagent, Injection { stdout: String::new(), exit: 0 }); + assert!(pending(spool.path()).unwrap()); + let printed = inject(spool.path(), "{\"hook_event_name\":\"PostToolBatch\"}", false).unwrap(); + assert_eq!(printed.exit, 0); + let output: Value = serde_json::from_str(&printed.stdout).unwrap(); + assert_eq!(output["hookSpecificOutput"]["hookEventName"], "PostToolBatch"); + let context = output["hookSpecificOutput"]["additionalContext"].as_str().unwrap(); + for needle in ["eureka-body:follow_up:b1", "campaign eureka-body", "repo GameCult/Huginn", "Item 1.", "Your answer closes it", "Plan usage: unobserved."] { + assert!(context.contains(needle), "{needle}: {context}"); + } + assert_eq!(inject(spool.path(), "{}", false).unwrap().stdout, "", "claimed once"); + // Unreadable input is not a reason to lose a brief or to fail the tool call. + spool_briefs(spool.path(), &[entry(2)]); + assert!(inject(spool.path(), "not json", false).unwrap().stdout.contains("Item 2.")); +} + +#[test] +fn the_pre_compact_hook_blocks_with_exit_2_and_leaves_one_marker() { + let spool = spool_dir(); + spool_briefs(spool.path(), &[entry(1)]); + assert_eq!(inject(spool.path(), "{}", true).unwrap(), Injection { stdout: String::new(), exit: 2 }); + assert!(pending(spool.path()).unwrap(), "blocking claims nothing"); + assert!(take_pre_compact(spool.path()) && !take_pre_compact(spool.path()), "the marker is consumed once"); +} + +#[test] +fn the_settings_name_the_two_hooks_with_absolute_quoted_commands() { + let hooks = Hooks { spool: PathBuf::from("/run/mind-x-self/inbox"), injector: PathBuf::from("/opt/it's/mind-self-run") }; + let settings: Value = serde_json::from_str(&hooks.settings()).unwrap(); + let tell = settings["hooks"]["PostToolBatch"][0]["hooks"][0]["command"].as_str().unwrap(); + assert_eq!(tell, "'/opt/it'\\''s/mind-self-run' inject --spool '/run/mind-x-self/inbox'"); + let compact = &settings["hooks"]["PreCompact"][0]; + assert_eq!(compact["matcher"], "auto"); + assert_eq!(compact["hooks"][0]["command"].as_str().unwrap(), format!("{tell} --pre-compact")); +} + +#[test] +fn closing_resolves_only_the_briefs_still_in_force_in_one_admission() { + let mind = mind_with(vec![brief_doc("a", OWNER), brief_doc("b", OWNER)]); + mind.committed(vec![closing(brief_ref("b"), recorded())]); + let briefs = [(Brief { id: brief_ref("a").id.0, ..entry(1) }, "The answer.".to_string()), (Brief { id: brief_ref("b").id.0, ..entry(2) }, "Ignored.".to_string())]; + let now = at(0); + assert_eq!(close(&mind, now, "selfrun-a", &briefs, "answered").unwrap(), 1); + let rationales: Vec = mind + .ids(K::Resolution) + .iter() + .filter_map(|resolution| match mind.view(K::Resolution, resolution)?.document { + PipelineDocument::Resolution(document) if document.subject == brief_ref("a") => Some(document.rationale.0), + _ => None, + }) + .collect(); + assert_eq!(rationales, vec!["The answer.".to_string()]); + assert_eq!(close(&mind, now, "selfrun-a", &briefs[..1], "answered").unwrap(), 0, "already closed"); +} diff --git a/crates/mind-body/src/self_run/tests.rs b/crates/mind-body/src/self_run/tests.rs index 9a718ca..efe16cb 100644 --- a/crates/mind-body/src/self_run/tests.rs +++ b/crates/mind-body/src/self_run/tests.rs @@ -95,6 +95,8 @@ enum Step { Exit(Option), /// Its stdout ends; the child is not reaped yet. Eof, + /// The clock moves, this runs (the mind changes, a tool call's hook fires), and the read times out. + Do(i64, Rc), } use Step::{Eof, Exit, Idle, Line as Out}; @@ -143,6 +145,11 @@ impl Child for Scripted { self.exited = true; Read::Exited(code) } + Some(Step::Do(seconds, act)) => { + self.clock.0.set(self.clock.0.get() + ChronoDuration::seconds(seconds)); + act(); + Read::Timeout + } Some(Step::Eof) => { self.eof = true; Read::Eof @@ -387,9 +394,15 @@ fn carry_signalled(seen: &Seen, steps: Vec, code: Option, dies_on: Op } fn carry_scripted(seen: &Seen, steps: Vec, code: Option, dies_on: Option, refuses: &[Stop], hangs: bool) -> Ran { + carry_hooked(seen, steps, (code, dies_on, refuses, hangs), test_hooks()) +} + +/// The same with the spool the child's hooks drain named by the test, so that a step can fire the hook. +fn carry_hooked(seen: &Seen, steps: Vec, (code, dies_on, refuses, hangs): (Option, Option, &[Stop], bool), hooks: Hooks) -> Ran { let log = Rc::new(RefCell::new(Vec::new())); let clock = Rc::new(Fixed(Cell::new(at_start()))); - let fake = Fake::with(Some(Scripted { steps: steps.into(), log: log.clone(), clock: clock.clone(), code, dies_on, refuses: refuses.to_vec(), hangs, exited: false, eof: false, asked: 0 }), false); + let mut fake = Fake::with(Some(Scripted { steps: steps.into(), log: log.clone(), clock: clock.clone(), code, dies_on, refuses: refuses.to_vec(), hangs, exited: false, eof: false, asked: 0 }), false); + fake.hooks = hooks; let lender = FakeLender::logging(log.clone(), Answer::Grant); let mut out = Vec::new(); let outcome = carry(seen, &*clock, &lender, &fake, TEST_CAP_S, &mut out); @@ -464,7 +477,7 @@ fn without_exactly_one_open_self_run_of_hers_it_is_no_run_and_no_child_is_spawne fn a_mind_that_cannot_be_read_or_a_child_that_cannot_start_is_an_error_not_an_outcome() { let mind = with_run(); let clock = Rc::new(Fixed(Cell::new(at_start()))); - let refusing = Fake::with(RefCell::new(None), true); + let refusing = Fake::with(None, true); assert!(carry(&Seen::of(&mind), &*clock, &FakeLender::new(Answer::Grant), &refusing, TEST_CAP_S, &mut Vec::new()).is_err()); assert_eq!(refusing.spawns.borrow().len(), 1, "it tried exactly once"); @@ -481,7 +494,7 @@ fn a_mind_that_cannot_be_read_or_a_child_that_cannot_start_is_an_error_not_an_ou unreachable!() } } - let never = Fake::with(RefCell::new(None), false); + let never = Fake::with(None, false); assert!(carry(&Down, &*clock, &FakeLender::new(Answer::Grant), &never, TEST_CAP_S, &mut Vec::new()).is_err()); assert!(never.spawns.borrow().is_empty()); } @@ -998,7 +1011,7 @@ fn the_clock_is_read_once_per_event_so_a_step_of_the_wall_clock_cannot_split_a_p } let steps: VecDeque = vec![Out(at("m1", CEILING_TOKENS)), Out(at("m2", CEILING_TOKENS + 1)), Idle(0)].into(); let child = Scripted { steps, log: log.clone(), clock: Rc::new(Fixed(Cell::new(at_start()))), code: Some(0), dies_on: None, refuses: vec![], hangs: false, exited: false, eof: false, asked: 0 }; - let fake = Fake::with(RefCell::new(Some(child)), false); + let fake = Fake::with(Some(child), false); let outcome = carry(&Seen::of(&mind), &Stepped(clock.clone()), &FakeLender::new(Answer::Grant), &fake, TEST_CAP_S, &mut Vec::new()).unwrap(); let events = log.borrow().clone(); let reads = events.iter().filter(|event| matches!(event, Event::Asked(_))).count() as u32; @@ -1458,3 +1471,201 @@ fn a_run_without_claims_gets_the_identity_lines_alone() { let ran = go(vec![Out(result_line())]); assert_eq!(ran.written()[0], start_message(&Slug("yggdrasil".into()), &run_ref("selfrun-a"), &[plan_window()], 1_793_306_000_000)); } + +// ---- the live session ----------------------------------------------------- + +use eureka_pipeline::PipelineResolution; + +const NO_SIGNALS: &[Stop] = &[]; + +fn live_mind() -> Rc { + let mind = Rc::new(with_run()); + mind.committed(vec![spec("x")]); + mind +} + +/// A brief from her Persona: a follow-up with owner `self-run`. +fn brief(label: &str, item: &str) -> PipelineDocument { + let PipelineDocument::FollowUp(mut document) = follow_up(label, &spec_ref("x")) else { unreachable!() }; + document.item = item.into(); + document.owner = inbox::OWNER.into(); + PipelineDocument::FollowUp(document) +} + +fn brief_ref(label: &str) -> PipelineRef { + reference(K::FollowUp, &id("follow_up", label)) +} + +/// The mind gains these documents, `seconds` into the run. +fn admits(mind: &Rc, seconds: i64, documents: Vec) -> Step { + let mind = mind.clone(); + Step::Do(seconds, Rc::new(move || mind.committed(documents.clone()))) +} + +fn resolutions_of(mind: &TestMind, subject: &PipelineRef) -> Vec { + mind.ids(K::Resolution) + .iter() + .filter_map(|resolution| match mind.view(K::Resolution, resolution)?.document { + PipelineDocument::Resolution(document) if document.subject == *subject => Some(document), + _ => None, + }) + .collect() +} + +/// The text of the probe's result line: what a brief's closure carries. +fn answer_text() -> String { + serde_json::from_str::(&result_line()).unwrap()["result"].as_str().unwrap().to_string() +} + +fn five_minute_request(id: &str, prefix: u64) -> String { + let mut event: Value = serde_json::from_str(&at(id, prefix)).unwrap(); + event["message"]["usage"]["cache_creation"] = json!({"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 100}); + event.to_string() +} + +fn tells(ran: &Ran) -> Vec { + ran.written().into_iter().filter(|text| text.contains("A brief from your Persona")).collect() +} + +#[test] +fn a_result_never_ends_the_session_the_child_ends_it_or_the_cache_does() { + let ran = go(vec![Out(at("m1", 10)), Out(result_line())]); + assert_eq!(ran.count(&Event::InputClosed), 0, "a result is the end of a turn: {:?}", ran.events); + assert_eq!(ran.ended().0, Cause::Own); +} + +#[test] +fn a_brief_to_a_working_self_is_told_once_between_turns_and_closed_by_the_result_that_answers_it() { + let mind = live_mind(); + let steps = vec![ + Out(at("m1", 10)), + admits(&mind, 31, vec![brief("b1", "Survey the noise functions.")]), + // The first turn ends: the brief was spooled while it ran, so it is told now, as the next turn. + Out(result_line()), + Idle(1), + // A later poll does not spool it again. + Idle(31), + Out(result_line()), + Idle(1), + ]; + let ran = carry_with(&Seen::of(&mind), steps, Some(0), false); + let told = tells(&ran); + assert_eq!(told.len(), 1, "{:?}", ran.written()); + assert!(told[0].contains(&brief_ref("b1").id.0) && told[0].contains("Survey the noise functions."), "{}", told[0]); + assert!(told[0].contains("Your answer closes it"), "{}", told[0]); + assert_eq!(ran.count(&Event::InputClosed), 0); + let closures = resolutions_of(&mind, &brief_ref("b1")); + assert_eq!(closures.len(), 1, "closed once"); + assert!(matches!(closures[0].outcome, ResolutionOutcome::Recorded { .. })); + assert_eq!(closures[0].rationale.0, answer_text()); + assert!(!inbox::pending(&ran.hooks.spool).unwrap(), "nothing left to tell"); +} + +#[test] +fn a_brief_told_mid_turn_by_the_hook_is_closed_by_that_turns_result_and_never_told_twice() { + let mind = live_mind(); + let hooks = test_hooks(); + let printed: Rc>> = Rc::new(RefCell::new(Vec::new())); + let fire = { + let (spool, printed) = (hooks.spool.clone(), printed.clone()); + Step::Do(0, Rc::new(move || printed.borrow_mut().push(inbox::inject(&spool, "{\"hook_event_name\":\"PostToolBatch\"}", false).unwrap().stdout))) + }; + let steps = vec![Out(at("m1", 10)), admits(&mind, 31, vec![brief("b2", "Wire the shader uniforms.")]), fire.clone(), fire, Out(result_line()), Idle(1)]; + let ran = carry_hooked(&Seen::of(&mind), steps, (Some(0), None, NO_SIGNALS, false), hooks); + let printed = printed.borrow(); + assert!(printed[0].contains(&brief_ref("b2").id.0) && printed[0].contains("Wire the shader uniforms."), "{printed:?}"); + assert_eq!(printed[1], "", "the second call finds nothing: each brief enters once"); + assert!(tells(&ran).is_empty(), "the hook told it; the actuator did not: {:?}", ran.written()); + let closures = resolutions_of(&mind, &brief_ref("b2")); + assert_eq!((closures.len(), closures[0].rationale.0.as_str()), (1, answer_text().as_str())); +} + +#[test] +fn a_brief_her_self_resolved_is_not_resolved_again_and_one_not_yet_told_stays_open_past_the_result() { + let mind = live_mind(); + let hooks = test_hooks(); + let claim_and_resolve = { + let (spool, mind) = (hooks.spool.clone(), mind.clone()); + Step::Do( + 0, + Rc::new(move || { + inbox::inject(&spool, "{}", false).unwrap(); + mind.committed(vec![close(brief_ref("b3"), recorded())]); + }), + ) + }; + let steps = vec![Out(at("m1", 10)), admits(&mind, 31, vec![brief("b3", "Mine.")]), claim_and_resolve, admits(&mind, 31, vec![brief("b4", "Later.")]), Out(result_line())]; + let ran = carry_hooked(&Seen::of(&mind), steps, (Some(0), None, NO_SIGNALS, false), hooks); + assert_eq!(resolutions_of(&mind, &brief_ref("b3")).len(), 1, "her own resolution stands alone"); + assert!(resolutions_of(&mind, &brief_ref("b4")).is_empty(), "spooled, never told: this result did not answer it"); + assert!(tells(&ran).is_empty()); +} + +#[test] +fn the_past_is_closed_at_session_start_and_only_what_no_closed_run_claimed_is_told() { + let mind = TestMind::seeded(); + mind.committed(vec![spec("x")]); + mind.committed(vec![brief("p1", "Stale."), brief("p2", "Still open.")]); + mind.committed(vec![run("old", RunTurn::SelfRun, RunOperator::Mind, &[brief_ref("p1")])]); + mind.committed(vec![close(run_ref("old"), recorded())]); + mind.committed(vec![self_run("selfrun-a", "5")]); + let ran = carry_with(&Seen::of(&mind), vec![Out(result_line())], Some(0), false); + let closures = resolutions_of(&mind, &brief_ref("p1")); + assert_eq!(closures.len(), 1); + assert!(matches!(closures[0].outcome, ResolutionOutcome::Recorded { .. })); + assert!(closures[0].rationale.0.contains(&run_ref("old").id.0), "names the run that answered it: {}", closures[0].rationale.0); + let start = &ran.written()[0]; + assert!(start.contains("Also open for you") && start.contains(&brief_ref("p2").id.0) && start.contains("Still open."), "{start}"); + assert!(!start.contains(&brief_ref("p1").id.0), "never told: {start}"); + // The unclaimed one was told in the start message, so the first result answers it. + assert_eq!(resolutions_of(&mind, &brief_ref("p2")).len(), 1); +} + +#[test] +fn the_session_ends_where_the_cache_would_be_evicted_with_a_flush_and_a_waiting_brief_keeps_it_open() { + // An hour's cache: warm at 3539 s, the flush at 3540, the input closed after the flush's own result. + let hour = go(vec![Out(at("m1", 10)), Out(result_line()), Idle(3539), Idle(1), Out(result_line()), Idle(1)]); + assert_eq!(hour.written().iter().filter(|text| text.as_str() == FLUSH_MESSAGE).count(), 1); + let flush_at = hour.events.iter().position(|event| matches!(event, Event::Wrote(line) if line.contains(FLUSH_MESSAGE))).unwrap(); + let closed_at = hour.events.iter().position(|event| *event == Event::InputClosed).unwrap(); + assert!(flush_at < closed_at && hour.count(&Event::InputClosed) == 1, "{:?}", hour.events); + // Five minutes' cache: the flush at 240 s. + let short = go(vec![Out(five_minute_request("m1", 10)), Out(result_line()), Idle(239), Idle(1), Out(result_line()), Idle(1)]); + assert_eq!(flushes(&short), 1); + // Not a second early. + let early = go(vec![Out(at("m1", 10)), Out(result_line()), Idle(3539)]); + assert_eq!(flushes(&early), 0); + // A brief waiting at the cache's end is told, not flushed: the session stays open. + let mind = live_mind(); + let steps = vec![Out(at("m1", 10)), Out(result_line()), admits(&mind, 3539, vec![brief("b5", "One more.")]), Idle(1), Idle(1), Out(result_line()), Idle(1)]; + let ran = carry_with(&Seen::of(&mind), steps, Some(0), false); + assert_eq!((flushes(&ran), tells(&ran).len(), ran.count(&Event::InputClosed)), (0, 1, 0), "{:?}", ran.written()); +} + +#[test] +fn near_the_cap_an_idle_session_closes_for_rotation_and_a_working_one_is_asked_for_its_flush() { + let cap = i64::try_from(TEST_CAP_S).unwrap(); + // Idle at cap - 1200 s: closed, with no flush asked. + let idle = go(vec![After(cap - 1400, at("m1", 10)), Out(result_line()), Idle(199), Idle(1)]); + assert_eq!((idle.count(&Event::InputClosed), flushes(&idle)), (1, 0), "{:?}", idle.events); + let early = go(vec![After(cap - 1400, at("m1", 10)), Out(result_line()), Idle(199)]); + assert_eq!(early.count(&Event::InputClosed), 0); + // Mid-turn at cap - 600 s: the flush, once. + let working = go(vec![After(cap - 600, at("m1", 10))]); + assert_eq!(flushes(&working), 1); + let before = go(vec![After(cap - 601, at("m1", 10))]); + assert_eq!(flushes(&before), 0); +} + +#[test] +fn a_pre_compact_block_leaves_a_marker_and_the_session_asks_for_the_flush_once() { + let hooks = test_hooks(); + let fire = { + let spool = hooks.spool.clone(); + Step::Do(1, Rc::new(move || assert_eq!(inbox::inject(&spool, "{}", true).unwrap().exit, 2))) + }; + let mind = with_run(); + let ran = carry_hooked(&Seen::of(&mind), vec![Out(at("m1", 10)), fire.clone(), fire, Out(result_line())], (Some(0), None, NO_SIGNALS, false), hooks); + assert_eq!(flushes(&ran), 1, "{:?}", ran.written()); + assert!(!inbox::take_pre_compact(&ran.hooks.spool), "the marker was taken"); +} diff --git a/crates/mind-body/src/self_run/tests/closure.rs b/crates/mind-body/src/self_run/tests/closure.rs index 04722e2..d9f0222 100644 --- a/crates/mind-body/src/self_run/tests/closure.rs +++ b/crates/mind-body/src/self_run/tests/closure.rs @@ -84,7 +84,7 @@ fn a_child_stopped_by_the_actuator_resolves_the_run_with_how_it_ended() { fn a_child_that_cannot_start_resolves_the_run_and_the_error_stands() { let mind = with_run(); let clock = Rc::new(Fixed(Cell::new(at_start()))); - let refusing = Fake::with(RefCell::new(None), true); + let refusing = Fake::with(None, true); let error = carry(&Seen::of(&mind), &*clock, &FakeLender::new(Answer::Grant), &refusing, TEST_CAP_S, &mut Vec::new()).unwrap_err(); assert_eq!(error.to_string(), "refused"); assert!(reason_of(&mind, "selfrun-a").contains("the actuator failed")); @@ -105,7 +105,7 @@ fn an_error_after_the_run_opened_resolves_it() { let log = Rc::new(RefCell::new(Vec::new())); let clock = Rc::new(Fixed(Cell::new(at_start()))); let child = Scripted { steps: vec![Out(at("m1", 10))].into(), log: log.clone(), clock: clock.clone(), code: Some(0), dies_on: None, refuses: vec![], hangs: true, exited: false, eof: false, asked: 0 }; - let fake = Fake::with(RefCell::new(Some(child)), false); + let fake = Fake::with(Some(child), false); assert!(carry(&Seen::of(&mind), &*clock, &FakeLender::logging(log, Answer::Grant), &fake, TEST_CAP_S, &mut Broken).is_err()); assert!(reason_of(&mind, "selfrun-a").contains("the actuator failed")); } @@ -133,7 +133,7 @@ fn a_resolve_that_fails_is_logged_and_tried_once() { // The same when the run's own error is what is being reported: that error stands. let clock = Rc::new(Fixed(Cell::new(at_start()))); - let refusing = Fake::with(RefCell::new(None), true); + let refusing = Fake::with(None, true); let again = Seen { admit_fails: true, ..Seen::of(&mind) }; let error = carry(&again, &*clock, &FakeLender::new(Answer::Grant), &refusing, TEST_CAP_S, &mut Vec::new()).unwrap_err(); assert_eq!(error.to_string(), "refused"); diff --git a/crates/mind-body/src/self_run/tests/lease.rs b/crates/mind-body/src/self_run/tests/lease.rs index 8d94a90..5a2de7b 100644 --- a/crates/mind-body/src/self_run/tests/lease.rs +++ b/crates/mind-body/src/self_run/tests/lease.rs @@ -7,7 +7,7 @@ use eureka_pipeline::ResolutionOutcome; use super::*; fn never_spawns() -> Fake { - Fake::with(RefCell::new(None), false) + Fake::with(None, false) } #[test]