diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index 313d6a9..1c6109b 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -329,10 +329,8 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { let done = done_events(&trace); let mut oldest_of_room = BTreeSet::new(); let (aside, waking): (Vec, Vec) = waking_all.into_iter().filter(|line| !done.contains(line.event)).partition(|line| oldest_of_room.insert(line.room) && strikes(&trace, line.event) >= STRIKES); - // The key of every record and send of this start: the newest seq the mouth holds and how long her trace is, so no clock - // names a turn. A start that leaves neither changed re-sends its turns under the same ids, which the mouth answers as the - // sends they already were. - let stem = format!("s{}-n{}", deliveries.last().map_or(0, |delivery| delivery.seq), trace.len()); + // The key of this start's records in her trace: how long it is, so a record that landed is never written over. + let stem = format!("n{}", trace.len()); // The rooms to take a turn in, oldest waking line first; a start no line woke is the beat's. let mut rooms: Vec<&str> = Vec::new(); for line in &waking { @@ -383,7 +381,11 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { settle(&taken, &mut acked); } for (index, room) in rooms.iter().enumerate() { - let key = format!("{stem}-t{index}"); + // The turn's own key, which names its sends: an answer is the answer to the oldest line it wakes on, so a start that + // finds the line still pending (the record did not land, or the ack is held below it) sends it under the id it already + // went out under, and the mouth answers it as the send it was. A beat answers no line and is a fresh speech each start. + let key = waking.iter().find(|line| line.room == *room).map_or_else(|| format!("b{began_ms}-t{index}"), |line| format!("l{}", line.event)); + let record_key = format!("{stem}-t{index}"); let now = (start.clock)(); let past = match start.trace.records() { Ok(records) => history(&records), @@ -433,7 +435,7 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { } // Her lines went out when the record says so, whether or not the trace could keep it: the decision is the turn's and // the ack follows it. A trace that cannot be written loses her memory of the turn, never the answer to her line. - if let Err(fault) = start.trace.record(&key, &turn.record) { + if let Err(fault) = start.trace.record(&record_key, &turn.record) { eprintln!("mind-persona: the record of turn {key} was not appended: {fault:#}"); } taken.push(Turn { room: (*room).to_owned(), decided: turn.record.get("failed").is_none(), put_refused }); diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 800aff5..f97c83e 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -188,6 +188,8 @@ struct Rig { trace: Rc, log: Log, dir: TempDir, + /// The clock's ticks, kept across starts as a real clock is. + ticks: Rc>, } impl Rig { @@ -199,11 +201,11 @@ impl Rig { let mouth = Rc::new(FakeMouth { held: RefCell::new(deliveries), sent: RefCell::default(), acks: RefCell::default(), reads: Cell::new(0), ack_fails: Cell::new(false), page: Cell::new(usize::MAX), log: log.clone() }); let store = Rc::new(FakeStore { stored: RefCell::new(control()), puts: RefCell::default(), outside: Cell::new(0), log: log.clone() }); let trace = Rc::new(MemTrace { rows: RefCell::default(), fail: Cell::new(false), log: log.clone() }); - Self { mouth, store, trace, log, dir } + Self { mouth, store, trace, log, dir, ticks: Rc::default() } } fn run(&self, model: impl Model + 'static) -> Outcome { - let ticks = Cell::new(0i64); + let ticks = self.ticks.clone(); let start = || { Ok(Start { config: Config { rooms: vec![MINDS.into()], operators: vec![META.into()], minds: vec!["@eureka:gamecult.org".into(), LIBBY.into()], own_sender: "@eureka:gamecult.org".into(), model: "test-model".into() }, @@ -243,9 +245,9 @@ fn t_l2_drain_acks_after_decision() { assert_eq!(events, ["send", "trace", "ack", "send", "trace", "ack"], "each ack follows its turn's trace append: {log:?}"); let ids: Vec = rig.mouth.sent.borrow().iter().map(|request| request.request_id.clone()).collect(); assert_eq!(ids.len(), 2); - assert!(ids[0].ends_with("-t0:s0") && ids[1].ends_with("-t1:s0"), "one key per turn, one id per send: {ids:?}"); + assert_eq!(ids, ["l$e1:s0", "l$e2:s0"], "a send is named by the line it answers"); let keys: Vec = rig.trace.rows.borrow().iter().map(|(key, _)| key.clone()).collect(); - assert_eq!(keys.iter().map(|key| format!("{key}:s0")).collect::>(), ids, "the key of the record is the key of the send"); + assert_eq!(keys, ["n0-t0", "n0-t1"], "a record is named by her trace's length and the turn's place"); assert!(rig.held_seqs().is_empty()); } @@ -475,18 +477,18 @@ fn t_l2_an_ack_goes_through_a_seq_once_and_a_failed_ack_is_not_reported_as_acked assert_eq!(rig.held_seqs(), [1]); } -/// Every turn of a start is its own key, and a start that finds her trace longer is under other keys: no wall clock names one. +/// Every record of a start has its own key, and a start that finds her trace longer is under other keys: no wall clock names one. #[test] -fn t_l2_a_turn_key_comes_from_the_mouth_and_her_trace_not_the_clock() { +fn t_l2_a_records_key_comes_from_her_trace_not_the_clock() { let rig = Rig::new(vec![line(7, &room(1), META, "alpha"), line(9, &room(2), META, "bravo")]); rig.run(scripted(false)); let first: Vec = rig.trace.rows.borrow().iter().map(|(key, _)| key.clone()).collect(); - assert_eq!(first, ["s9-n0-t0", "s9-n0-t1"]); + assert_eq!(first, ["n0-t0", "n0-t1"]); rig.mouth.held.borrow_mut().push(line(10, &room(1), META, "again")); rig.run(scripted(false)); let keys: Vec = rig.trace.rows.borrow().iter().map(|(key, _)| key.clone()).collect(); assert_eq!(keys.len(), 3); - assert_eq!(keys[2], "s10-n2-t0", "the key follows the newest seq and the trace's length"); + assert_eq!(keys[2], "n2-t0", "the key follows the trace's length"); } /// The mouth pages what is pending; the drain reads to the end of it, as the heartbeat does, so the wake rule and the ack see one queue. @@ -615,3 +617,82 @@ fn t_l2_a_failure_nobody_named_cannot_hold_the_ack_forever() { assert!(set_aside(&rig)); assert!(rig.held_seqs().is_empty(), "the ack passed the line: {:?}", rig.held_seqs()); } + +/// Soul's probe: her trace stops being writable once the oldest room's failed turn has landed, so the room-1 answer goes out +/// with no record, while the failed turn holds the ack below it. +struct TraceDiesAfterTheFailedTurn { + inner: Flaky, + trace: Rc, +} + +impl Model for TraceDiesAfterTheFailedTurn { + fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { + if !prompt.contains("FAILME") { + self.trace.fail.set(true); + } + self.inner.ask(request_id, model, prompt, schema) + } +} + +/// A reply whose record did not land is the answer to the line it answered: the next start, finding the line still pending +/// because the ack is held below it, sends it under the id it already went out under, never a second id. +#[test] +fn t_l2_a_reply_whose_record_did_not_land_goes_out_again_under_the_same_id() { + let rig = Rig::new(vec![line(1, &room(2), META, "FAILME bravo"), line(2, &room(1), META, "alpha")]); + rig.run(TraceDiesAfterTheFailedTurn { inner: failing(OUTAGE), trace: rig.trace.clone() }); + rig.trace.fail.set(false); + rig.run(failing(OUTAGE)); + let ids: std::collections::BTreeSet = rig.mouth.sent.borrow().iter().filter(|request| request.room_alias == room(1)).map(|request| request.request_id.clone()).collect(); + assert_eq!(ids.len(), 1, "one id for the one line: {ids:?}"); + assert_eq!(rig.held_seqs(), [1, 2], "the outage holds the ack, as it should"); +} + +/// Soul's probe: two beats, and no record lands for either; the second speech is not swallowed as the first. +#[test] +fn t_l2_two_beats_with_no_trace_record_do_not_share_a_send_id() { + let rig = Rig::new(vec![]); + rig.trace.fail.set(true); + rig.run(scripted(false)); + rig.run(scripted(false)); + let ids: std::collections::BTreeSet = rig.mouth.sent.borrow().iter().map(|request| request.request_id.clone()).collect(); + assert_eq!(rig.mouth.sent.borrow().len(), 2, "each beat spoke"); + assert_eq!(ids.len(), 2, "under two ids: {ids:?}"); +} + +/// A line set aside is done: while the mouth cannot take the ack, the next starts neither set it aside again nor tell her twice. +#[test] +fn t_l2_a_line_set_aside_is_done_even_while_its_ack_fails() { + let rig = Rig::new(vec![line(1, &room(1), META, "FAILME one")]); + rig.run(failing(REFUSED)); + rig.run(failing(REFUSED)); + rig.mouth.ack_fails.set(true); + rig.run(failing(REFUSED)); + rig.run(failing(REFUSED)); + let asides = rig.trace.rows.borrow().iter().filter(|(_, record)| record.get("set_aside").is_some()).count(); + assert_eq!(asides, 1, "set aside once, however many acks fail"); + assert_eq!(rig.held_seqs(), [1]); + assert_eq!(rig.trace.rows.borrow().iter().filter(|(_, record)| record.get("failed").is_some()).count(), 2, "and no third turn on it"); +} + +/// Her put is stamped at the put: later than the turn's start, which a write by Self or Life +/// during the turn would overtake. +#[test] +fn t_l2_her_put_is_stamped_at_the_put() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.run(scripted(true)); + let landed = chrono::DateTime::parse_from_rfc3339(rig.store.stored.borrow()["updatedAt"].as_str().unwrap()).unwrap(); + let at = chrono::DateTime::parse_from_rfc3339(rig.trace.rows.borrow()[0].1["at"].as_str().unwrap()).unwrap(); + assert!(landed > at, "the stamp is the clock at the put, later than the turn's start {at}: {landed}"); +} + +/// Her put is stamped after the one stored even when the clock reads earlier than it (a stored `updatedAt` ahead of this +/// host's clock), which the daemon requires. +#[test] +fn t_l2_her_put_is_stamped_after_a_stored_updated_at_that_is_ahead_of_the_clock() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + let ahead = (Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap() + 3_600_000).unwrap()).to_rfc3339(); + rig.store.stored.borrow_mut()["updatedAt"] = json!(ahead); + assert_eq!(rig.run(scripted(true)), Outcome::Drained { turns: 1, acked_through: Some(1), put_refused: 0 }); + let landed = chrono::DateTime::parse_from_rfc3339(rig.store.stored.borrow()["updatedAt"].as_str().unwrap()).unwrap(); + assert!(landed.timestamp_millis() > i64::try_from(BASE_MS).unwrap() + 3_600_000, "later than the stored stamp: {landed}"); +}