From a8b59c2a5170f1ffac0173c6f3e76bf3cfa4e4b6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 08:33:54 +0100 Subject: [PATCH] persona: what she is told of her last turn is her last real turn's record, and untold is ordered by her trace, not the clock A record carries seq, its place in her trace (the length it had when appended). An unknown or refused send carries the length when it was settled; a set-aside line, a put refused and a failed turn are stamped one past their record's place. An item is untold while no real turn has seq at or after its stamp. The trace is read in seq order. history takes last_outcome from the newest record that is neither failed nor set aside (is_real, the line untold uses); a failed turn is told once, as an untold item. Deleted: the positional records.last() reading, outcome_of's failed and malformed-receipts branches, put_refused_at, and the wall-clock stamps on items. Items stamped before r45 (at only) read as told. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/persona.rs | 14 +- crates/mind-body/src/persona/drain_tests.rs | 50 +++++-- crates/mind-body/src/projection/outcome.rs | 28 +--- .../mind-body/src/projection/outcome/tests.rs | 25 +--- crates/mind-body/src/projection/simulate.rs | 2 +- .../src/projection/simulate/tests.rs | 4 +- crates/mind-body/src/projection/turn.rs | 75 ++++++---- crates/mind-body/src/projection/turn/tests.rs | 137 ++++++++++++------ 8 files changed, 208 insertions(+), 127 deletions(-) diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index 8f497ba..8e902c6 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -224,9 +224,9 @@ impl TraceView for TraceSnapshot { } } -/// Records oldest first: by the time each carries, then by key. +/// Records oldest first: by the place each holds in her trace (`seq`, the length the trace had when it was appended), then by the time it carries, then by key. A record with no place (one written before places were kept) comes first. fn ordered(rows: impl IntoIterator) -> Vec { - let mut rows: Vec<(String, String, Value)> = rows.into_iter().map(|(key, value)| (value["at"].as_str().unwrap_or_default().to_owned(), key, value)).collect(); + let mut rows: Vec<((u64, String), String, Value)> = rows.into_iter().map(|(key, value)| ((value["seq"].as_u64().unwrap_or_default(), value["at"].as_str().unwrap_or_default().to_owned()), key, value)).collect(); rows.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1))); rows.into_iter().map(|(_, _, value)| value).collect() } @@ -432,14 +432,14 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { let recorded_ms = record["at"].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()).map(|at| at.timestamp_millis()); let age = recorded_ms.map_or(i64::MAX, |at| (now.timestamp_millis() - at) / 1000); let key = record["key"].as_str().unwrap_or_default().to_owned(); - deliver(&mouth, &mut record, if age > OWED_WINDOW_S { Pass::Past } else { Pass::Within }, now, &mut stalled, &mut ahead(start, &key)); + deliver(&mouth, &mut record, if age > OWED_WINDOW_S { Pass::Past } else { Pass::Within }, trace.len() as u64, &mut stalled, &mut ahead(start, &key)); if let Some(unknown) = record["unknown_sends"].as_array() { eprintln!("mind-persona: {} owed send(s) got no answer within the time a repeat is safe, so whether they went out is unknown, and she is told at her next real turn: {unknown:?}", unknown.len()); } if let Err(fault) = start.trace.record(record["key"].as_str().unwrap_or_default(), &record) { // The send stays owed in her trace, so the poll would start her again at every poll: the start fails as an outage, and the // poll waits it out. The failure is recorded if the trace takes it; the outcome is the failure either way. - let _ = start.trace.record(&format!("{stem}-f"), &json!({ "failed": format!("the record of a send owed was not rewritten: {fault:#}"), "outage": true, "at": now.to_rfc3339() })); + let _ = start.trace.record(&format!("{stem}-f"), &json!({ "failed": format!("the record of a send owed was not rewritten: {fault:#}"), "outage": true, "at": now.to_rfc3339(), "seq": trace.len() })); return failed("the record of a send owed was not rewritten", fault); } turns += 1; @@ -449,7 +449,7 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { if !aside.is_empty() { let lines: Vec = aside.iter().map(|line| json!({ "room": line.room, "event": line.event, "sender": line.sender, "text": line.text })).collect(); eprintln!("mind-persona: {} waking line(s) failed {STRIKES} turns and were set aside: {lines:?}", lines.len()); - if let Err(fault) = start.trace.record(&format!("{stem}-a"), &json!({ "set_aside": lines, "at": began.to_rfc3339() })) { + if let Err(fault) = start.trace.record(&format!("{stem}-a"), &json!({ "set_aside": lines, "at": began.to_rfc3339(), "seq": trace.len() })) { eprintln!("mind-persona: the record of the lines set aside was not appended: {fault:#}"); } } @@ -492,6 +492,7 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { // What the turn held, for the starts after it to read: which lines she has decided, and which she has failed on. turn.record["room"] = json!(room); turn.record["key"] = json!(record_key); + turn.record["seq"] = json!(records.len()); turn.record["held"] = json!(deliveries.iter().filter(|delivery| delivery.room_alias == **room).map(|delivery| delivery.event_id.as_str()).collect::>()); // A turn that could not be set up (her tuning file, her own id) is the body's fault and no line's: the start fails loudly, charges no // strike and sets nothing aside. What it left pending is tried again by the next start. @@ -515,13 +516,12 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { Err((fresh, why)) => { put_refusals += 1; turn.record["put_refused"] = json!(why); - turn.record["put_refused_at"] = json!((start.clock)().to_rfc3339()); eprintln!("mind-persona: the put of turn {key} was refused twice: {why}"); state = fresh; } } } - deliver(&mouth, &mut turn.record, Pass::Within, (start.clock)(), &mut stalled, &mut ahead(start, &record_key)); + deliver(&mouth, &mut turn.record, Pass::Within, records.len() as u64 + 1, &mut stalled, &mut ahead(start, &record_key)); if turn.record.get("failed").is_none() && let Err(fault) = start.trace.record(&record_key, &turn.record) { diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index c646fc2..9ae36b6 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -396,7 +396,7 @@ fn t_l2_second_stale_put_is_put_refused_in_the_record() { assert_eq!(rig.log().iter().filter(|event| *event == "put").count(), 2, "never a third put"); let rows = rig.trace.rows.borrow(); assert_eq!(rows.len(), 1, "the record is appended though the put was refused"); - assert!(rows[0].1["put_refused"].is_string() && rows[0].1["put_refused_at"].is_string(), "the refusal is stamped once, when it was made: {:?}", rows[0].1); + assert!(rows[0].1["put_refused"].is_string(), "the refusal is kept: {:?}", rows[0].1); assert_eq!(rig.log().iter().position(|event| event == "trace"), Some(0), "the record comes before the puts: {:?}", rig.log()); assert!(rig.store.puts.borrow().is_empty(), "nothing of hers landed"); drop(rows); @@ -924,15 +924,15 @@ fn t_l3_a_told_unknown_keeps_its_first_stamp_when_its_record_is_rewritten() { rig.trace.rows.borrow_mut().push(("n0-t0".into(), json!({ "key": "n0-t0", "room": room(1), "held": [], "owed": [ { "id": "la:s0", "room": room(1), "text": "ZULU old line", "handed": true }, { "id": "la:s1", "room": room(1), "text": "YANKEE sibling" }], "posted": [], "refused_sends": [], "edited": [], "at": at.to_rfc3339() }))); rig.run(Never); - let first = rig.trace.rows.borrow()[0].1["unknown_sends"][0]["at"].clone(); - assert!(first.is_string(), "stamped when it went unknown"); + let first = rig.trace.rows.borrow()[0].1["unknown_sends"][0]["seq"].clone(); + assert!(first.is_u64(), "stamped when it went unknown"); rig.mouth.held.borrow_mut().push(line(1, &room(1), META, "hello")); let telling = Rc::new(RefCell::new(Vec::new())); rig.run(Spy { inner: scripted(false), prompts: telling.clone() }); assert!(telling.borrow().iter().any(|prompt| prompt.contains("ZULU")), "told at her next real turn"); rig.run(Never); let rows: Vec = rig.trace.rows.borrow().iter().map(|(_, record)| record.clone()).collect(); - assert_eq!(rows[0]["unknown_sends"][0]["at"], first, "the rewrite that paid the sibling kept the first stamp: {}", rows[0]); + assert_eq!(rows[0]["unknown_sends"][0]["seq"], first, "the rewrite that paid the sibling kept the first stamp: {}", rows[0]); assert!(crate::projection::untold_rooms(&rows).is_empty(), "its room is not held again"); assert!(texts(&rig, &room(1)).iter().any(|text| text == "YANKEE sibling"), "the sibling was paid"); rig.mouth.held.borrow_mut().push(line(2, &room(1), META, "are you there?")); @@ -1096,7 +1096,7 @@ fn t_l3_a_send_with_no_answer_in_the_window_is_recorded_unknown_stamped_and_not_ let rows = rig.trace.rows.borrow(); let record = &rows[0].1; assert_eq!(record["unknown_sends"][0]["room"], MINDS); - assert!(record["unknown_sends"][0]["at"].is_string(), "{record}"); + assert!(record["unknown_sends"][0]["seq"].is_u64(), "{record}"); assert!(record.get("owed").is_none() && record["posted"] == json!([]) && record["refused_sends"] == json!([]), "{record}"); } assert_eq!(rig.mouth.sent.borrow().len(), 1, "nothing was posted twice"); @@ -1118,7 +1118,7 @@ fn t_l3_words_in_the_room_are_never_a_receipt() { let record = rig.trace.rows.borrow()[0].1.clone(); assert_eq!(record["posted"], json!([]), "{name}: the tail proves nothing: {record}"); assert_eq!(record["unknown_sends"][0]["text"], owed, "{name}: {record}"); - assert!(record["refused_sends"] == json!([]) && record["unknown_sends"][0]["at"].is_string(), "{name}: {record}"); + assert!(record["refused_sends"] == json!([]) && record["unknown_sends"][0]["seq"].is_u64(), "{name}: {record}"); assert!(rig.mouth.sent.borrow().is_empty(), "{name}: past the window nothing is sent"); } } @@ -1162,7 +1162,7 @@ fn t_l3_an_unknown_send_is_told_at_her_next_real_turn_exactly_once_though_a_line let before_turn: Vec = all.iter().filter(|record| record["room"] != json!(room(3))).cloned().collect(); let told = |records: &[Value]| crate::projection::history(records).last_outcome.map(|last| last["untold"].clone()); let row = json!({ "kind": "unknown", "room": MINDS, "text": rig.mouth.sent.borrow()[0].text }); - assert!(told(&before_turn).is_some_and(|rows| rows.as_array().is_some_and(|rows| rows.contains(&row) && rows.len() == 1 + usize::from(aside))), "aside={aside}: told at her next turn, with the line set aside"); + assert!(told(&before_turn).is_some_and(|rows| rows.as_array().is_some_and(|rows| rows.contains(&row) && rows.len() == 1 + 2 * usize::from(aside))), "aside={aside}: told at her next turn, with the line set aside and the turns that failed on it"); rig.run(scripted(false)); assert_eq!(told(&records(&rig)), Some(Value::Null), "aside={aside}: told once"); } @@ -1331,7 +1331,7 @@ fn t_l3_a_resend_the_mouth_cannot_vouch_for_is_unknown_holds_its_room_and_is_tol rig.run(Never); let rows: Vec = rig.trace.rows.borrow().iter().map(|(_, record)| record.clone()).collect(); assert_eq!(rows[0]["unknown_sends"][0]["text"], "the old line", "{}", rows[0]); - assert!(rows[0].get("owed").is_none() && rows[0]["refused_sends"] == json!([]) && rows[0]["unknown_sends"][0].get("at").is_some(), "unknown, neither refused nor owed: {}", rows[0]); + assert!(rows[0].get("owed").is_none() && rows[0]["refused_sends"] == json!([]) && rows[0]["unknown_sends"][0].get("seq").is_some(), "unknown, neither refused nor owed: {}", rows[0]); assert_eq!(rig.mouth.attempts.borrow().len(), 1, "the newer line was not tried in the held room: {:?}", rig.mouth.attempts.borrow()); assert!(rows[1]["owed"].as_array().is_some_and(|owed| owed.len() == 1), "it stays owed"); assert!(crate::projection::history(&rows).last_outcome.is_some_and(|last| last["untold"][0]["text"] == "the old line"), "she is told"); @@ -1485,6 +1485,38 @@ fn t_l3_a_held_sibling_stays_owed_unhanded_until_the_window_and_is_then_told_as_ assert!(!crate::projection::owes(&rows) && rows[0]["refused_sends"][0]["refusal"] == "not_sent_past_the_window", "{}", rows[0]); } +/// Soul s10 clock-step-back-loses-untold. The wall clock steps back after a real turn, and a send settled unknown in the start after is stamped by her +/// trace's length, not by the clock: she is still to be told, her room is held until then, and her telling turn tells it once. +#[test] +fn t_l3_an_unknown_settled_after_the_clock_steps_back_is_still_untold_and_holds_its_room() { + let rig = Rig::new(vec![line(1, &room(2), META, "hi")]); + rig.ticks.set(5000); + rig.run(scripted(false)); + rig.ticks.set(200); + rig.trace.rows.borrow_mut().push(("old".into(), json!({ "key": "old", "room": room(1), "held": [], "owed": [{ "id": "lz:s0", "room": room(1), "text": "ZULU stepped", "handed": true }], "posted": [], "refused_sends": [], "edited": [], + "at": (Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap() - Duration::seconds(3600)).to_rfc3339() }))); + rig.run(Never); + let rows = |rig: &Rig| rig.trace.rows.borrow().iter().map(|(_, record)| record.clone()).collect::>(); + assert_eq!(crate::projection::untold_rooms(&rows(&rig)), BTreeSet::from([room(1)]), "the unknown holds its room though the clock is behind her last real turn"); + assert!(crate::projection::history(&rows(&rig)).last_outcome.is_some_and(|last| last["untold"][0]["text"] == "ZULU stepped"), "and she is to be told it"); + rig.mouth.held.borrow_mut().push(line(2, &room(1), META, "you there?")); + rig.run(scripted(false)); + assert!(crate::projection::untold_rooms(&rows(&rig)).is_empty(), "her next real turn told it"); + assert!(crate::projection::history(&rows(&rig)).last_outcome.is_some_and(|last| last.get("untold").is_none()), "once"); +} + +/// Her records are read in the order they were appended, whatever the clock says: a clock that stepped back does not put a newer record first. +#[test] +fn t_l2_her_records_are_read_in_the_order_they_were_appended_though_the_clock_stepped_back() { + let rows = vec![ + ("n1-t0".to_owned(), json!({ "seq": 4, "at": "2026-11-28T11:00:00Z" })), + ("n0-t0".to_owned(), json!({ "seq": 3, "at": "2026-11-28T12:00:00Z" })), + ("n2-t0".to_owned(), json!({ "seq": 5, "at": "2026-11-28T10:00:00Z" })), + ("old".to_owned(), json!({ "at": "2026-11-28T13:00:00Z" })), + ]; + assert_eq!(super::ordered(rows).iter().map(|record| record["seq"].as_u64()).collect::>(), [None, Some(3), Some(4), Some(5)], "a record with no place was written before places were kept, so it is first"); +} + /// A start killed after a write ahead still tells her of an unknown the same record held by then: the write carries the stamp the final rewrite would. #[test] fn t_l3_a_write_ahead_carries_the_stamp_of_an_unknown_the_record_already_holds() { @@ -1497,5 +1529,5 @@ fn t_l3_a_write_ahead_carries_the_stamp_of_an_unknown_the_record_already_holds() let Outcome::Failed(_) = rig.run(Never) else { panic!("the rewrite cannot land") }; let record = rig.trace.rows.borrow()[0].1.clone(); assert_eq!(record["unknown_sends"][0]["text"], "one", "{record}"); - assert!(record["unknown_sends"][0]["at"].is_string(), "the unknown is told even if the start dies here: {record}"); + assert!(record["unknown_sends"][0]["seq"].is_u64(), "the unknown is told even if the start dies here: {record}"); } diff --git a/crates/mind-body/src/projection/outcome.rs b/crates/mind-body/src/projection/outcome.rs index 2476fce..8d3a9cc 100644 --- a/crates/mind-body/src/projection/outcome.rs +++ b/crates/mind-body/src/projection/outcome.rs @@ -3,10 +3,10 @@ //! never sees, so her next packet opens with them, first and under its own guard (`select`). //! //! `outcome_of` derives it from one turn's record, and nothing else writes it: no persona-state field, no file. The -//! record is one of two shapes, never both (map 16.20.7): the Interpreter's decision unchanged under `interpreter`, with +//! record is the Interpreter's decision unchanged under `interpreter`, with //! the actuator's receipts beside it (`posted`, each line that went out as `{event, room, text}`; `edited`; //! `refused_sends`, each said line the actuator refused, as `{room, text, refusal}`) and -//! `broke_after` when a later step broke; or `failed` alone, when the turn sent nothing and broke off. The simulator +//! `broke_after` when a later step broke. A turn that failed decided nothing and has no outcome: it is told as an untold item (`turn::untold`). The simulator //! builds it from a turn's report and the lines its room appended; live, it is the C3c commit's trace record, which must //! carry that shape. //! @@ -286,17 +286,11 @@ fn words(value: &Value) -> Option { value.as_str().map(str::trim).filter(|text| !text.is_empty()).map(str::to_owned) } -/// Whether the record holds a receipt of anything having happened: a line that went out, or an edit the actuator answered. -fn has_receipts(record: &Value) -> bool { - ["posted", "edited"].iter().any(|key| record[*key].as_array().is_some_and(|receipts| !receipts.is_empty())) -} - /// What came of the turn `record` records; None when there is no record. A record with nothing to tell (a chosen silence, /// nothing drafted, nothing reached for) is an empty outcome, and no section is rendered from it. /// -/// The record is one of two shapes, never both (C3c, map 16.20.7): `failed`, when the turn sent nothing and broke off; or -/// the decision with its receipts, and `broke_after` naming the step when a later step broke. A record with both `failed` -/// and receipts is malformed: she is told nothing of it, and it is reported. +/// The record is the decision with its receipts, and `broke_after` naming the step when a later step broke; a failed turn is no record of this +/// shape (it is the `failed` untold item), and a record with no decision tells only what her trace holds untold. pub(crate) fn outcome_of(record: &Value) -> Option { if !record.is_object() { return None; @@ -317,20 +311,12 @@ pub(crate) fn outcome_of(record: &Value) -> Option { (Some("refused"), Some(text)) => outcome.parts.push(Part::Unsent { room, text, reach: false }), (Some("set_aside"), text) => outcome.parts.push(Part::SetAside { room, line: words(&item["sender"]).zip(text) }), (Some("not_kept"), _) => outcome.parts.push(Part::NotKept), + (Some("failed"), _) => outcome.parts.push(Part::Failed), _ => outcome.omitted.push(format!("an untold item she cannot be told truly: {item}")), } } - let failed = record.get("failed").is_some() || decision.get("failed").is_some(); - if failed && has_receipts(record) { - outcome.omitted.push("a malformed record: it says the turn failed and carries receipts".to_owned()); - return Some(outcome); - } - if failed { - outcome.parts.push(Part::Failed); - return Some(outcome); - } - // A record the drain wrote when it set lines aside carries no decision. - if record.get("set_aside").is_some() { + // A record with no decision (the carrier of what a trace holds untold when no real turn of hers has been) tells only its untold rows. + if decision.is_null() { return Some(outcome); } let room = words(&decision["room"]); diff --git a/crates/mind-body/src/projection/outcome/tests.rs b/crates/mind-body/src/projection/outcome/tests.rs index 18dd8b0..997ee80 100644 --- a/crates/mind-body/src/projection/outcome/tests.rs +++ b/crates/mind-body/src/projection/outcome/tests.rs @@ -20,7 +20,9 @@ fn told(record: &Value) -> (Vec, Vec) { /// What she is told after `record` alone is her trace: the items it holds that she has not been told come from the one derivation, not from the record's own fields. fn outcome_trace(record: &Value) -> Outcome { - crate::projection::history(std::slice::from_ref(record)).last_outcome.and_then(|last| outcome_of(&last)).expect("a record") + let mut record = record.clone(); + record["seq"] = json!(0); + crate::projection::history(std::slice::from_ref(&record)).last_outcome.and_then(|last| outcome_of(&last)).expect("a record") } fn told_trace(record: &Value) -> (Vec, Vec) { @@ -107,22 +109,12 @@ fn an_unfinished_draft_a_failed_turn_and_a_later_break_are_told_as_what_they_wer let (lines, _) = told(&record("I was about to tell you that", json!({ "say": [], "gaps": [] }), &[])); assert_eq!(lines, ["- Nothing of this reached #minds:gamecult.org: the turn ended before he finished writing it. He had drafted: \"I was about to tell you that\"."]); let failed = "- Nothing reached the room, and nothing he meant last time happened: the turn broke off, not by his choice."; - assert_eq!(told(&json!({ "failed": "the provider failed the call: Overloaded" })).0, [failed]); - assert_eq!(told(&json!({ "interpreter": { "failed": "the answer is not the speech contract" }, "posted": [] })).0, [failed]); + assert_eq!(told_trace(&json!({ "failed": "the provider failed the call: Overloaded" })).0, [failed]); let mut broke = record("Hi Nibu.", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &["Hi Nibu."]); broke["broke_after"] = json!("commit"); assert_eq!(told(&broke).0, ["- #minds:gamecult.org has, from him: \"Hi Nibu.\".", "- Nothing more reached #minds:gamecult.org: the rest of that turn broke off, not by his choice."], "the receipts, then the rest of that turn broke off (C3c, 16.20.7)"); } -#[test] -fn a_record_that_failed_and_carries_receipts_is_malformed_told_nothing_and_reported() { - let mut both = record("Hi Nibu.", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &["Hi Nibu."]); - both["failed"] = json!("the commit broke"); - let (lines, omitted) = told(&both); - assert!(lines.is_empty(), "{lines:?}"); - assert!(omitted.len() == 1 && omitted[0].contains("malformed"), "{omitted:?}"); -} - #[test] fn a_chosen_silence_tells_him_nothing_and_no_record_is_no_outcome() { let silent = outcome_of(&record("The quiet is fine. I let it be.", json!({ "say": [], "gaps": [] }), &[])).unwrap(); @@ -241,7 +233,7 @@ fn every_row() -> Vec { amended("zz", json!([])), note(json!([{ "kind": "idea", "draft": 1, "about": null, "private": false }, { "kind": "idea", "draft": 2, "about": null, "private": false }])), note(json!([{ "kind": "idea", "draft": 1, "about": null, "private": true }])), - json!({ "failed": "the provider failed the call: Overloaded" }), + json!({ "untold": [{ "kind": "failed" }] }), broke, ] } @@ -642,7 +634,7 @@ fn t6_a_refused_send_is_told_as_not_gone_out() { let refused = |posted: Value, gaps: Value| { let mut record = record(&format!("{text}"), json!({ "say": [{ "draft": 1 }], "gaps": gaps }), &[]); record["posted"] = posted; - record["refused_sends"] = json!([{ "room": MINDS, "text": text, "in_reply_to": "$gone", "refusal": "reply_target_not_in_room", "at": "2026-11-27T10:00:00Z" }]); + record["refused_sends"] = json!([{ "room": MINDS, "text": text, "in_reply_to": "$gone", "refusal": "reply_target_not_in_room", "seq": 1 }]); record }; let (lines, omitted) = told_trace(&refused(json!([]), json!([]))); @@ -666,10 +658,9 @@ fn t6_a_refused_send_is_told_as_not_gone_out() { fn a_put_refused_twice_and_a_set_aside_line_are_told_plainly() { let mut refused = record("Hi Nibu.", json!({ "say": [{ "draft": 1 }], "gaps": [] }), &["Hi Nibu."]); refused["put_refused"] = json!("stale again"); - refused["put_refused_at"] = json!("2026-11-27T10:00:00Z"); assert_eq!(told_trace(&refused).0, ["- What he meant to keep from that turn was not kept.", "- #minds:gamecult.org has, from him: \"Hi Nibu.\"."], "the refusal's words are the mind's, not hers: she is told only that it was not kept"); - let aside = json!({ "set_aside": [{ "room": MINDS, "event": "$e1", "sender": "Nibu", "text": "are you there" }], "at": "2026-11-27T10:00:00Z" }); + let aside = json!({ "set_aside": [{ "room": MINDS, "event": "$e1", "sender": "Nibu", "text": "are you there" }]}); assert_eq!(told_trace(&aside).0, ["- Nothing reached #minds:gamecult.org. His turn on Nibu's line \"are you there\" failed twice, so it was set aside."]); - let unnamed = json!({ "set_aside": [{ "room": MINDS, "event": "$e1" }], "at": "2026-11-27T10:00:00Z" }); + let unnamed = json!({ "set_aside": [{ "room": MINDS, "event": "$e1" }]}); assert_eq!(told_trace(&unnamed).0, ["- Nothing reached #minds:gamecult.org. His turn on a line there failed twice, so it was set aside."]); } diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index 11bb6b2..1ab6426 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -511,7 +511,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) let reads = member.entry.reads.as_ref().map(|recorded| CastReads { recorded, domain: member.entry.domain.as_ref() }); let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model, domain: member.entry.domain.as_ref().map(|facts| facts as &dyn DomainSource), reads: reads.as_ref().map(|reads| reads as &dyn ReadSource) }; let actuator = SimRoom { lines: &room, her: &id, name: &member.entry.name, here: &here, dm_to, cast: &cast, operators: &plan.operators, now, sent: Cell::new(0) }; - turn::take(&organs, &request, &actuator, &key, now) + turn::take(&organs, &request, &actuator, &key, now, records[at].len() as u64) }; lines = room.into_inner(); let cause = cause_word(why.as_ref().map(|why| why.cause)); diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 8c659b0..ca02fb8 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -1117,7 +1117,7 @@ fn t_l1_sim_and_mouth_records_same_shape() { let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter); let lines = RefCell::new(Vec::new()); let sim = SimRoom { lines: &lines, her: TOBIAH, name: "Tobiah", here: "!dm-meta:gamecult.org", dm_to: None, cast: &[], operators: &[], now: fixture.now, sent: Cell::new(0) }; - let simulated = take(&organs, &request, &sim, "r1-t1", fixture.now); + let simulated = take(&organs, &request, &sim, "r1-t1", fixture.now, 0); struct Chat1; impl crate::chat_client::Chat for Chat1 { fn pending(&self, _: u64) -> Result { @@ -1140,7 +1140,7 @@ fn t_l1_sim_and_mouth_records_same_shape() { } } let mouth = Mouth { chat: &Chat1, persona: "eureka".into(), seen: Default::default(), since_unix_ms: 0 }; - let live = take(&organs, &request, &mouth, "r1-t1", fixture.now); + let live = take(&organs, &request, &mouth, "r1-t1", fixture.now, 0); let keys = |record: &Value| record.as_object().unwrap().keys().cloned().collect::>(); assert_eq!(keys(&simulated.record), keys(&live.record), "one record shape, simulated or live"); assert_eq!(lines.borrow().len(), 1, "the room appended her line"); diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs index 87b7276..7bffe76 100644 --- a/crates/mind-body/src/projection/turn.rs +++ b/crates/mind-body/src/projection/turn.rs @@ -97,10 +97,11 @@ pub(crate) struct Taken { pub state: Value, } -/// One turn: `decide`, then `deliver`. -pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, key: &str, now: DateTime) -> Taken { +/// One turn: `decide`, then `deliver`. `seq` is the record's place in her trace: the length it had when the record was appended. +pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, key: &str, now: DateTime, seq: u64) -> Taken { let mut taken = decide(organs, request, key, now); - deliver(actuator, &mut taken.record, Pass::Within, now, &mut BTreeSet::new(), &mut |_| true); + taken.record["seq"] = json!(seq); + deliver(actuator, &mut taken.record, Pass::Within, seq + 1, &mut BTreeSet::new(), &mut |_| true); taken } @@ -172,20 +173,20 @@ fn unmark(send: &mut Value) { /// posted nor refused, and she is told it may or may not have gone out; each not handed over is refused as not sent, which is all that is known. `stalled` /// holds the rooms whose earlier send got no answer, was not sent or went unknown in this start: nothing is sent into them after it, so her lines never /// arrive out of order and none goes in before she is told, and a send held back stays owed. Each send this call settles unknown or refused is -/// stamped `at: now`, once: the stamp is what says whether she has been told (`untold`), and a record rewritten later keeps it. -pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, pass: Pass, now: DateTime, stalled: &mut BTreeSet, ahead: &mut dyn FnMut(&Value) -> bool) { +/// stamped `seq`, once, the length her trace had when it was settled: the stamp is what says whether she has been told (`untold`), and a record rewritten later keeps it. +pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, pass: Pass, seq: u64, stalled: &mut BTreeSet, ahead: &mut dyn FnMut(&Value) -> bool) { let owed: Vec = record["owed"].as_array().cloned().unwrap_or_default(); let mut still = Vec::new(); for (index, mut send) in owed.iter().cloned().enumerate() { let (room, text) = (send["room"].as_str().unwrap_or_default().to_owned(), send["text"].as_str().unwrap_or_default().to_owned()); let reply = send["in_reply_to"].as_str().map(str::to_owned); let refusal = |why: &str| match reply.as_deref() { - Some(event) => json!({ "room": room, "text": text, "in_reply_to": event, "refusal": why, "at": now.to_rfc3339() }), - None => json!({ "room": room, "text": text, "refusal": why, "at": now.to_rfc3339() }), + Some(event) => json!({ "room": room, "text": text, "in_reply_to": event, "refusal": why, "seq": seq }), + None => json!({ "room": room, "text": text, "refusal": why, "seq": seq }), }; let mentions: Vec = send["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); let unknown_send = |record: &mut Value, stalled: &mut BTreeSet| { - let unknown = json!({ "room": room, "text": text, "at": now.to_rfc3339() }); + let unknown = json!({ "room": room, "text": text, "seq": seq }); match record["unknown_sends"].as_array_mut() { Some(unknowns) => unknowns.push(unknown), None => record["unknown_sends"] = json!([unknown]), @@ -303,26 +304,41 @@ pub(crate) fn owes(records: &[Value]) -> bool { records.iter().any(owes_send) } +/// A real turn: a record that decided something. A failed turn decided nothing, and a record that only set lines aside is no turn. The one +/// definition, for what she is told of her last turn (`history`) and for what her trace holds untold (`untold`). +pub(crate) fn is_real(record: &Value) -> bool { + record.get("failed").is_none() && record.get("set_aside").is_none() +} + /// What her trace holds that she has not been told, from whichever record holds it: each send unknown (`unknown_sends`) or refused -/// (`refused_sends`), each line set aside and each put refused, as `{kind, ..}` rows. The one derivation of it. An item is told at her next -/// real turn, once: it carries the stamp it was given when it was made (`at`, set once and kept when the record is rewritten), and it is -/// untold while no real turn of hers has started after it. A real turn is a record that decided something: a failed turn and a record that only -/// set lines aside are none, and a rewrite keeps its `at`, so where a record sits in the trace decides nothing. +/// (`refused_sends`), each line set aside, each put refused and a failed turn (once, whatever the number), as `{kind, ..}` rows. The one derivation +/// of it. An item is told at her next real turn, once. Time is no part of it: a record's place in her trace is `seq`, the length the trace had +/// when it was appended, and a send settled unknown or refused carries `seq` too, the length when it was settled. An item is untold while no real +/// turn has `seq` at or after its stamp (a turn appended after the item was made); a set-aside line, a failed turn and a put refused have the stamp +/// one past their record's own place. A rewrite keeps `seq`, so where a record sits decides nothing, and a clock that steps back changes nothing. fn untold(records: &[Value]) -> Vec { - let at = |stamp: &Value| stamp.as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok()); - let last_start = records.iter().filter(|record| record.get("failed").is_none() && record.get("set_aside").is_none()).filter_map(|record| at(&record["at"])).max(); - let fresh = |stamp: &Value| at(stamp).is_some_and(|made| last_start.is_none_or(|start| start <= made)); + let last_start = records.iter().filter(|record| is_real(record)).filter_map(|record| record["seq"].as_u64()).max(); + let fresh = |stamp: Option| stamp.is_some_and(|made| last_start.is_none_or(|start| start < made)); + let after = |record: &Value| record["seq"].as_u64().map(|place| place + 1); let mut told = Vec::new(); - for record in records.iter().filter(|record| record.get("failed").is_none()) { + let mut failed = false; + for record in records { + if record.get("failed").is_some() { + failed |= fresh(after(record)); + continue; + } for (kind, field) in [("unknown", "unknown_sends"), ("refused", "refused_sends")] { - told.extend(record[field].as_array().into_iter().flatten().filter(|sent| fresh(&sent["at"])).map(|sent| json!({ "kind": kind, "room": sent["room"], "text": sent["text"] }))); + told.extend(record[field].as_array().into_iter().flatten().filter(|sent| fresh(sent["seq"].as_u64())).map(|sent| json!({ "kind": kind, "room": sent["room"], "text": sent["text"] }))); } - if fresh(&record["at"]) { + if fresh(after(record)) { told.extend(record["set_aside"].as_array().into_iter().flatten().map(|line| json!({ "kind": "set_aside", "room": line["room"], "sender": line["sender"], "text": line["text"] }))); + if record.get("put_refused").is_some() { + told.push(json!({ "kind": "not_kept" })); + } } - if record.get("put_refused").is_some() && fresh(&record["put_refused_at"]) { - told.push(json!({ "kind": "not_kept" })); - } + } + if failed { + told.push(json!({ "kind": "failed" })); } told } @@ -339,13 +355,20 @@ pub(crate) fn history(records: &[Value]) -> Past { let mut recent: Vec> = real.iter().copied().filter_map(selected).collect(); recent.drain(..recent.len().saturating_sub(RECENT)); Past { - last_outcome: records.last().cloned().map(|mut last| { + last_outcome: { + // What she is told of her last turn is her last real turn's record, whatever lies after it, with what her trace holds untold. When she + // has had no real turn, what is untold is told alone. let untold = untold(records); - if !untold.is_empty() { - last["untold"] = json!(untold); + match records.iter().rev().find(|record| is_real(record)).cloned() { + Some(mut last) => { + if !untold.is_empty() { + last["untold"] = json!(untold); + } + Some(last) + } + None => (!untold.is_empty()).then(|| json!({ "untold": untold })), } - last - }), + }, recent, records: real[real.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 dd550af..c4a1c2b 100644 --- a/crates/mind-body/src/projection/turn/tests.rs +++ b/crates/mind-body/src/projection/turn/tests.rs @@ -69,7 +69,7 @@ fn warm_turn_ahead(actuator: &dyn Actuator, ahead: &mut dyn FnMut(&Value) -> boo let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None }; let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter); let mut taken = decide(&organs, &request, "run-t1", fixture.now); - deliver(actuator, &mut taken.record, Pass::Within, Utc::now(), &mut BTreeSet::new(), ahead); + deliver(actuator, &mut taken.record, Pass::Within, 1, &mut BTreeSet::new(), ahead); taken } @@ -81,7 +81,7 @@ fn warm_turn_saying(prose: &'static str, actuator: &dyn Actuator) -> Taken { let harness = harness(dir.path(), None, Some(&model)); let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None }; let request = fixture_request(&harness, &fixture, Some(control()), 3, Some(1), Through::Interpreter); - take(&organs, &request, actuator, "run-t1", fixture.now) + take(&organs, &request, actuator, "run-t1", fixture.now, 0) } #[test] @@ -153,11 +153,11 @@ fn t_l1_failed_turn_record() { let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: harness.model, domain: None, reads: None }; let state = control(); let request = fixture_request(&harness, &fixture, Some(state.clone()), 3, Some(1), Through::Interpreter); - let taken = take(&organs, &request, &mouth(&chat), "run-t1", fixture.now); + let taken = take(&organs, &request, &mouth(&chat), "run-t1", fixture.now, 0); assert!(chat.sent.borrow().is_empty(), "a failed turn sends nothing"); assert_eq!(taken.record["failed"].as_str(), Some("the provider failed the call: Overloaded")); let mut keys: Vec<&str> = taken.record.as_object().unwrap().keys().map(String::as_str).collect(); - keys.retain(|key| !matches!(*key, "selected" | "at" | "committed")); + keys.retain(|key| !matches!(*key, "selected" | "at" | "committed" | "seq")); assert_eq!(keys, ["failed"], "the record holds the failure alone beside what every record carries"); assert_eq!(taken.state, state, "a failed turn applies nothing"); assert_eq!(taken.record["committed"], json!(Applied::default())); @@ -166,16 +166,17 @@ fn t_l1_failed_turn_record() { #[test] fn t_l1_history_from_records() { let at = |minute: i64| (chrono::DateTime::from_timestamp(1_800_000_000, 0).unwrap() + Duration::minutes(minute)).to_rfc3339(); - let turn = |minute: i64, ids: &[&str]| json!({ "interpreter": {}, "selected": ids, "at": at(minute) }); + let turn = |minute: i64, ids: &[&str]| json!({ "interpreter": {}, "selected": ids, "at": at(minute), "seq": minute }); let mut records: Vec = (0..7).map(|at| turn(at, &[&format!("m{at}")])).collect(); assert_eq!(history(&[]), Past::default()); let past = history(&records); assert_eq!(past.recent, [["m2"], ["m3"], ["m4"], ["m5"], ["m6"]], "the last five selections, oldest first"); assert_eq!(past.last_outcome.as_ref(), records.last()); assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6))); - records.push(json!({ "failed": "Overloaded", "selected": ["m7"], "at": at(7) })); + records.push(json!({ "failed": "Overloaded", "selected": ["m7"], "at": at(7), "seq": 7 })); let past = history(&records); - assert_eq!(past.last_outcome.as_ref().map(|last| last["failed"].clone()), Some(json!("Overloaded")), "her last outcome is the failure"); + assert_eq!(past.last_outcome.as_ref().map(|last| last["selected"].clone()), Some(json!(["m6"])), "her last outcome is her last real turn, whatever failed after it"); + assert_eq!(past.last_outcome.as_ref().map(|last| last["untold"].clone()), Some(json!([{ "kind": "failed" }])), "and the failed turn is told through what her trace holds untold, once"); assert_eq!(past.last_wake.map(|wake| wake.to_rfc3339()), Some(at(6)), "a failed turn is no wake"); assert_eq!(past.recent.last(), Some(&vec!["m6".to_owned()]), "a failed turn is not in the window, so what it selected is not remembered"); let long: Vec = (0..60).map(|at| turn(at, &[])).collect(); @@ -187,15 +188,15 @@ fn t_l1_history_from_records() { /// the run of failures is what the poll backs off by. (Soul s4 outage-rewake-floods-records.) #[test] fn t_l2_failed_records_never_push_her_real_turns_out_of_the_window() { - let real = |n: usize| json!({ "interpreter": {}, "posted": [], "held": [format!("$e{n}")], "selected": [format!("m{n}")], "at": format!("2026-11-27T10:00:{n:02}Z") }); - let failed = |n: usize| json!({ "failed": "the connector did not answer: unavailable", "outage": true, "at": format!("2026-11-27T11:{:02}:00Z", n % 60) }); + let real = |n: usize| json!({ "interpreter": {}, "posted": [], "held": [format!("$e{n}")], "selected": [format!("m{n}")], "at": format!("2026-11-27T10:00:{n:02}Z"), "seq": n }); + let failed = |n: usize| json!({ "failed": "the connector did not answer: unavailable", "outage": true, "at": format!("2026-11-27T11:{:02}:00Z", n % 60), "seq": n + 3 }); let mut records: Vec = (0..3).map(real).collect(); records.extend((0..200).map(failed)); let past = history(&records); assert_eq!(past.records.len(), 3, "the window holds her decided turns and no failure"); assert!(past.records.iter().all(|record| record.get("failed").is_none())); assert_eq!(past.recent.len(), 3, "and so do her recent selections"); - assert!(past.last_outcome.is_some_and(|last| last.get("failed").is_some()), "her last outcome may be the failure: she is told once"); + assert!(past.last_outcome.is_some_and(|last| last.get("failed").is_none() && last["selected"] == json!(["m2"]) && last["untold"] == json!([{ "kind": "failed" }])), "her last outcome is her last real turn, with the failures told once, as one item"); assert_eq!(past.last_wake.map(|at| at.to_rfc3339()), Some("2026-11-27T10:00:02+00:00".to_owned()), "and her last wake is her last decision"); assert_eq!(failed_run(&records).0, 200); assert_eq!(failed_run(&records[..3]).0, 0); @@ -218,47 +219,95 @@ fn t_l2_a_line_is_decided_by_the_record_that_holds_it() { /// the rewrite that settled the send are no turn of hers; once a real turn follows, it is told no more. #[test] fn t_l3_an_unknown_send_is_told_at_her_next_real_turn_and_once() { - let wake = |at: &str| json!({ "held": ["$e9"], "posted": [], "refused_sends": [], "interpreter": { "said": [] }, "at": at }); - let unknown = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "unknown_sends": [{ "room": "#minds", "text": "welcome aboard", "at": "2026-11-28T02:00:00Z" }], "at": "2026-11-28T00:00:00Z" }); + let wake = |seq: u64| json!({ "held": ["$e9"], "posted": [], "refused_sends": [], "interpreter": { "said": [] }, "seq": seq }); + let unknown = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "unknown_sends": [{ "room": "#minds", "text": "welcome aboard", "seq": 3 }], "seq": 0 }); let told_at = |records: Vec| history(&records).last_outcome.map(|last| (last.get("untold").cloned(), outcome_of(&last).expect("an outcome").lines(forms(&json!({}))))); - let (list, told) = told_at(vec![unknown.clone(), wake("2026-11-28T00:30:00Z")]).expect("her last record"); + let (list, told) = told_at(vec![unknown.clone(), wake(1)]).expect("her last record"); assert!(list.is_some() && told.iter().any(|line| line.contains("welcome aboard") && line.contains("may or may not have gone out")), "{told:?}"); assert!(!told.iter().any(|line| line.contains("did not go out")), "never told as unsent: {told:?}"); - for (name, between) in [("a failed turn", json!({ "failed": "x", "at": "2026-11-28T03:00:00Z" })), ("a record that set a line aside", json!({ "set_aside": [{ "room": "#a", "event": "$s", "sender": "Nibu", "text": "hi" }], "at": "2026-11-28T03:00:00Z" }))] { - let (list, _) = told_at(vec![unknown.clone(), wake("2026-11-28T00:30:00Z"), between]).expect("her last record"); + for (name, between) in [("a failed turn", json!({ "failed": "x", "seq": 4 })), ("a record that set a line aside", json!({ "set_aside": [{ "room": "#a", "event": "$s", "sender": "Nibu", "text": "hi" }], "seq": 4 }))] { + let (list, _) = told_at(vec![unknown.clone(), wake(1), between]).expect("her last record"); assert!(list.is_some(), "{name} is no turn of hers: she is still to be told"); } - let (list, _) = told_at(vec![unknown, wake("2026-11-28T00:30:00Z"), wake("2026-11-28T03:00:00Z")]).expect("her last record"); + let (list, _) = told_at(vec![unknown, wake(1), wake(3)]).expect("her last record"); assert!(list.is_none(), "a real turn after it has told it"); } /// Everything her trace holds that she has not been told is told at her next real turn, once, whichever record holds it: an unknown send, a send -/// refused or never made, a line set aside, a put refused. Each carries the stamp it was made with; a real turn that started after the stamp has -/// told it, whatever the record's place in the trace, and a real turn that started before it has not. +/// refused or never made, a line set aside, a put refused, a failed turn. A send carries the length her trace had when it was settled; the others +/// are stamped by their record's place. A real turn whose place is at or after the stamp has told it, whatever the record's place in the trace, and +/// an earlier turn has not. #[test] fn t_l3_every_untold_item_is_told_at_her_next_real_turn_once_from_whichever_record_holds_it() { - let wake = |at: &str| json!({ "held": ["$w"], "posted": [], "refused_sends": [], "interpreter": { "said": [] }, "at": at }); - let sent = |text: &str, stamp: &str| json!({ "room": "#a", "text": text, "refusal": "not_sent_past_the_window", "at": stamp }); - // One old record, rewritten after her later turns, holds an unknown, a refusal and a put refused, each stamped when it was made; a - // record that set a line aside was written at 03:00. - let old = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "at": "2026-11-28T00:00:00Z", - "unknown_sends": [{ "room": "#a", "text": "ZULU unknown", "at": "2026-11-28T01:00:00Z" }], "refused_sends": [sent("YANKEE refused", "2026-11-28T01:00:00Z")], "put_refused": "stale", "put_refused_at": "2026-11-28T01:00:00Z" }); - let aside = json!({ "set_aside": [{ "room": "#a", "event": "$s", "sender": "Nibu", "text": "XRAY aside" }], "at": "2026-11-28T03:00:00Z" }); - let told = |records: Vec| history(&records).last_outcome.map(|last| outcome_of(&last).expect("an outcome").lines(forms(&json!({})))).unwrap_or_default().join(" -"); - // Later turns of hers started before the stamps: the old record is not her last, and all four are still to be told. - let said = told(vec![old.clone(), wake("2026-11-28T00:30:00Z"), aside.clone(), wake("2026-11-28T00:40:00Z")]); - for word in ["ZULU", "YANKEE", "XRAY"] { + let wake = |seq: u64| json!({ "held": ["$w"], "posted": [], "refused_sends": [], "interpreter": { "said": [] }, "seq": seq }); + let sent = |text: &str, stamp: u64| json!({ "room": "#a", "text": text, "refusal": "not_sent_past_the_window", "seq": stamp }); + // One old record (place 2), rewritten later, holds an unknown, a refusal and a put refused: the sends settled at length 5, the put refused with + // the record. A record that set a line aside sits at place 3, and a failed turn at place 6. + let old = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "seq": 2, + "unknown_sends": [{ "room": "#a", "text": "ZULU unknown", "seq": 5 }], "refused_sends": [sent("YANKEE refused", 5)], "put_refused": "stale" }); + let aside = json!({ "set_aside": [{ "room": "#a", "event": "$s", "sender": "Nibu", "text": "XRAY aside" }], "seq": 3 }); + let failed = json!({ "failed": "x", "seq": 6 }); + let told = |records: Vec| history(&records).last_outcome.map(|last| outcome_of(&last).expect("an outcome").lines(forms(&json!({})))).unwrap_or_default().join("\n"); + // Her later turns began before the stamps: every item is still to be told. + let said = told(vec![wake(1), old.clone(), aside.clone(), failed.clone()]); + for word in ["ZULU", "YANKEE", "XRAY", "not kept", "broke off"] { assert!(said.contains(word), "{word} is told at her next real turn though its record is not her last: {said}"); } - assert!(said.contains("not kept") || said.lines().count() >= 4, "{said}"); - // A real turn that started after every stamp has told them all, and tells nothing again. - let after = told(vec![old.clone(), wake("2026-11-28T00:30:00Z"), aside, wake("2026-11-28T04:00:00Z")]); - for word in ["ZULU", "YANKEE", "XRAY"] { + // A real turn that began after every stamp has told them all, and tells nothing again. + let after = told(vec![wake(1), aside, old.clone(), failed, wake(7)]); + for word in ["ZULU", "YANKEE", "XRAY", "not kept", "broke off"] { assert!(!after.contains(word), "{word} was told once: {after}"); } - // A rewrite keeps the stamp it was given: the record is rewritten after her turn at 04:00, and nothing is told again. - assert!(untold_rooms(&[old, wake("2026-11-28T04:00:00Z")]).is_empty(), "a told unknown does not hold its room again"); + // A rewrite keeps the stamp it was given, so a told unknown does not hold its room again. + assert!(untold_rooms(&[old, wake(7)]).is_empty(), "a told unknown does not hold its room again"); +} + +/// Soul s10 outcome-rows-still-positional. What she is told of her last turn is her last real turn's record, whatever is newer in her trace: a failed +/// turn and a record that only set lines aside never hide it, and the turn that failed is told once through what her trace holds untold. +#[test] +fn t_l3_her_last_real_turns_outcome_is_told_though_a_failed_turn_or_a_set_aside_record_is_newer() { + let real = json!({ "held": ["$e1"], "posted": [{ "event": "$p1", "room": "#a", "text": "SENTLINE" }], "refused_sends": [], "interpreter": { "said": [{ "room": "#a", "text": "SENTLINE" }], "room": "#a" }, "seq": 0 }); + let told = |records: Vec| history(&records).last_outcome.map(|last| outcome_of(&last).expect("an outcome").lines(forms(&json!({})))).unwrap_or_default().join("\n"); + let plain = told(vec![real.clone()]); + assert!(plain.contains("SENTLINE"), "{plain}"); + for newer in [json!({ "failed": "x", "outage": true, "seq": 1 }), json!({ "set_aside": [{ "room": "#a", "event": "$s", "sender": "Nibu", "text": "hi" }], "seq": 1 })] { + let said = told(vec![real.clone(), newer.clone()]); + assert!(said.contains("SENTLINE"), "her last real turn's outcome is told with {newer} newer: {said}"); + let said = told(vec![real.clone(), newer.clone(), json!({ "failed": "y", "seq": 2 })]); + assert!(said.contains("SENTLINE"), "and with a failed turn after it: {said}"); + } + let failed = told(vec![real.clone(), json!({ "failed": "x", "seq": 1 })]); + assert_eq!(failed.matches("broke off").count(), 1, "the failed turn is told: {failed}"); + let twice = told(vec![real, json!({ "failed": "x", "seq": 1 }), json!({ "failed": "y", "seq": 2 })]); + assert_eq!(twice.matches("broke off").count(), 1, "however many failed, once: {twice}"); + // Before any real turn there is nothing to tell of one, and the failure is still told. + let first = told(vec![json!({ "failed": "x", "seq": 0 })]); + assert!(first.contains("broke off") && !first.contains("SENTLINE"), "{first}"); + assert_eq!(told(vec![]), ""); +} + +/// Soul s10 clock-step-back-loses-untold. What is untold is ordered by her trace's length, never by the wall clock: a clock that steps back leaves an +/// item untold until a real turn follows it in her trace. +#[test] +fn t_l3_an_untold_item_survives_a_clock_stepped_back_between_starts() { + // The real turn at place 0 is stamped 12:00; the clock then steps back an hour, and the next start settles a send unknown on that record. + let wake = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "at": "2026-11-28T12:00:00Z", "seq": 0, + "unknown_sends": [{ "room": "#a", "text": "ZULU unknown", "seq": 1 }] }); + let back = json!({ "failed": "x", "outage": true, "at": "2026-11-28T11:00:00Z", "seq": 1 }); + let records = vec![wake.clone(), back.clone()]; + assert_eq!(untold_rooms(&records), BTreeSet::from(["#a".to_owned()]), "the unknown holds its room"); + assert!(history(&records).last_outcome.is_some_and(|last| last["untold"][0]["text"] == "ZULU unknown"), "and she is told it"); + // Her next real turn is stamped 11:05, still before the old record's 12:00: it follows in her trace, so it tells it. + let next = json!({ "held": ["$e2"], "posted": [], "interpreter": { "said": [] }, "at": "2026-11-28T11:05:00Z", "seq": 2 }); + let records = vec![wake, back, next]; + assert!(untold_rooms(&records).is_empty() && history(&records).last_outcome.is_some_and(|last| last.get("untold").is_none()), "told once, by that turn"); +} + +/// Soul s10 untold-on-failed-last-unpinned (T5). Only a send that may have gone out holds its room: a refused send is known not to have, and holds nothing. +#[test] +fn t_l3_only_an_unknown_send_holds_its_room_a_refused_one_does_not() { + let record = json!({ "interpreter": {}, "seq": 0, "unknown_sends": [{ "room": "#u", "text": "a", "seq": 1 }], "refused_sends": [{ "room": "#r", "text": "b", "refusal": "no_event", "seq": 1 }] }); + assert_eq!(untold_rooms(&[record]), BTreeSet::from(["#u".to_owned()])); } /// A trace that holds an owed send says so; a failed record's owed send and a settled one are not owed. @@ -329,7 +378,7 @@ fn t_l3_every_refusal_kind_is_placed_for_a_first_send_and_for_a_repeat() { let handed = FakeChat::new(Some(Refusal::SendFailed)); taken = warm_turn(&mouth(&handed)); let again = FakeChat::new(Some(refusal)); - deliver(&mouth(&again), &mut taken.record, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| true); + deliver(&mouth(&again), &mut taken.record, Pass::Within, 1, &mut BTreeSet::new(), &mut |_| true); assert_eq!(again.sent.borrow().iter().map(|request| request.resend).collect::>(), [true], "{}: a repeat says resend", refusal.name()); assert_eq!(settled(&taken.record), repeat, "{} to a repeat: {}", refusal.name(), taken.record); } @@ -351,7 +400,7 @@ fn t_l3_a_send_never_handed_over_goes_out_as_a_first_send_and_only_a_handed_one_ assert!(writes[0]["owed"][0]["handed"] == true && writes[0]["posted"] == json!([]), "the mark is durable before the mouth is called: {}", writes[0]); let id = first.sent.borrow()[0].request_id.clone(); let again = FakeChat::new(None); - deliver(&mouth(&again), &mut taken.record, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| panic!("a repeat is already marked, and writes nothing ahead")); + deliver(&mouth(&again), &mut taken.record, Pass::Within, 1, &mut BTreeSet::new(), &mut |_| panic!("a repeat is already marked, and writes nothing ahead")); assert_eq!(again.sent.borrow().iter().map(|request| (request.request_id.clone(), request.resend)).collect::>(), [(id.clone(), true)], "the repeat is under the recorded id and says so"); assert!(taken.record.get("owed").is_none() && taken.record["posted"][0]["event"] == "$sent-1", "{}", taken.record); @@ -359,7 +408,7 @@ fn t_l3_a_send_never_handed_over_goes_out_as_a_first_send_and_only_a_handed_one_ let never = FakeChat::new(None); let mut record = json!({ "owed": [{ "id": id, "room": "!a:b", "text": "hi" }], "posted": [], "refused_sends": [], "edited": [] }); let mut marked = 0; - deliver(&mouth(&never), &mut record, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| { + deliver(&mouth(&never), &mut record, Pass::Within, 1, &mut BTreeSet::new(), &mut |_| { marked += 1; true }); @@ -371,7 +420,7 @@ fn t_l3_a_send_never_handed_over_goes_out_as_a_first_send_and_only_a_handed_one_ let silent = FakeChat::new(None); let mut record = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "one" }, { "id": "k:s1", "room": "!a:b", "text": "two" }], "posted": [], "refused_sends": [], "edited": [] }); let mut stalled = BTreeSet::new(); - deliver(&mouth(&silent), &mut record, Pass::Within, Utc::now(), &mut stalled, &mut |_| false); + deliver(&mouth(&silent), &mut record, Pass::Within, 1, &mut stalled, &mut |_| false); assert!(silent.sent.borrow().is_empty() && stalled.contains("!a:b"), "a send whose mark cannot be written is not made"); assert_eq!(record["owed"].as_array().map(Vec::len), Some(2)); assert!(record["owed"].as_array().unwrap().iter().all(|send| send.get("handed").is_none()), "{record}"); @@ -384,10 +433,10 @@ fn t_l3_an_answer_with_neither_event_nor_refusal_is_refused_for_a_first_send_and let mut chat = FakeChat::new(None); chat.bare = true; let mut first = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "one" }], "posted": [], "refused_sends": [], "edited": [] }); - deliver(&mouth(&chat), &mut first, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| true); + deliver(&mouth(&chat), &mut first, Pass::Within, 1, &mut BTreeSet::new(), &mut |_| true); assert_eq!(settled(&first), "refused", "{first}"); let mut repeat = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "one", "handed": true }], "posted": [], "refused_sends": [], "edited": [] }); - deliver(&mouth(&chat), &mut repeat, Pass::Within, Utc::now(), &mut BTreeSet::new(), &mut |_| true); + deliver(&mouth(&chat), &mut repeat, Pass::Within, 1, &mut BTreeSet::new(), &mut |_| true); assert_eq!(settled(&repeat), "unknown", "{repeat}"); } @@ -397,10 +446,10 @@ fn t_l3_an_answer_with_neither_event_nor_refusal_is_refused_for_a_first_send_and fn t_l3_past_the_window_a_handed_send_is_unknown_and_one_never_handed_is_refused_as_not_sent() { let chat = FakeChat::new(None); let mut record = json!({ "owed": [{ "id": "k:s0", "room": "!a:b", "text": "handed", "handed": true }, { "id": "k:s1", "room": "!c:d", "text": "never" }], "posted": [], "refused_sends": [], "edited": [] }); - deliver(&mouth(&chat), &mut record, Pass::Past, Utc::now(), &mut BTreeSet::new(), &mut |_| true); + deliver(&mouth(&chat), &mut record, Pass::Past, 1, &mut BTreeSet::new(), &mut |_| true); assert!(chat.sent.borrow().is_empty(), "nothing is made past the window"); assert_eq!(record["unknown_sends"].as_array().map(|sends| sends.iter().map(|sent| (sent["room"].clone(), sent["text"].clone())).collect::>()), Some(vec![(json!("!a:b"), json!("handed"))])); - assert!(record["unknown_sends"][0]["at"].is_string() && record["refused_sends"][0]["at"].is_string(), "each is stamped when it is made: {record}"); + assert!(record["unknown_sends"][0]["seq"] == 1 && record["refused_sends"][0]["seq"] == 1, "each is stamped with the length her trace had when it is made: {record}"); assert_eq!(record["refused_sends"][0]["refusal"], "not_sent_past_the_window"); assert!(record.get("owed").is_none()); } -- 2.47.3