persona drain: the only receipt is the mouth's answer; an owed send starts her; her lines keep their order
Delete the text-matching receipt (a line of hers in the room's tail, matched by prefix, was taken as proof a send posted). A retry of an owed send goes out under the recorded id and the mouth's event id is the receipt; past the dedupe window with no answer the send is recorded unknown (unknown_sends, unknown_at), neither posted nor refused, and told at her next real turn as a line that may or may not have gone out. A set-aside record or a failed turn is no real turn of hers. The poll starts a Mind whose trace holds an owed send, subject to her outage backoff, and gives the line to no other; that start takes no beat turn. A send with no answer holds back every later send into its room for the rest of the start. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
659bc6aa2b
commit
083d58a9a5
9 changed files with 297 additions and 94 deletions
|
|
@ -36,7 +36,7 @@ use crate::chat_client::{Basis, Chat, ChatDelivery, ChatPending, Form};
|
|||
use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable};
|
||||
use crate::launch::{Clock, Launcher};
|
||||
use crate::persona::TraceView;
|
||||
use crate::projection::{decided, failed_run};
|
||||
use crate::projection::{decided, failed_run, owes};
|
||||
use crate::queue::{MindPort, headers, in_force, of_kind};
|
||||
use crate::tempo::{self, Standing};
|
||||
|
||||
|
|
@ -788,6 +788,8 @@ struct Row<'a> {
|
|||
done: Option<BTreeSet<String>>,
|
||||
/// How many of her last records are failures in a row, and when the last was made.
|
||||
failures: (u32, Option<DateTime<Utc>>),
|
||||
/// Her trace holds a send still owed: the poll starts her for it, and no one else.
|
||||
owes: bool,
|
||||
note: String,
|
||||
}
|
||||
|
||||
|
|
@ -857,13 +859,14 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
|||
// Her last-read names when the table holds her, else her roster names alone.
|
||||
let roster = Addressee::new(&seat.who.matrix_id, [seat.who.public_name.as_str(), seat.who.handle.as_str()]);
|
||||
let kept = stored_addressing.minds.iter().find(|stored| stored.matrix_id() == seat.who.matrix_id).cloned().unwrap_or_else(|| roster.clone());
|
||||
let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], done: None, failures: (0, None), note: String::new() };
|
||||
let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], done: None, failures: (0, None), owes: false, note: String::new() };
|
||||
// Pending chat, read-only, for a released Mind.
|
||||
if row.released {
|
||||
match seat.trace.records() {
|
||||
Ok(records) => {
|
||||
row.done = Some(decided(&records).into_iter().map(str::to_owned).collect());
|
||||
row.failures = failed_run(&records);
|
||||
row.owes = owes(&records);
|
||||
}
|
||||
Err(error) => {
|
||||
eventful = true;
|
||||
|
|
@ -925,6 +928,21 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
|||
.map(|(delivery, _)| delivery.event_id.clone())
|
||||
.find(|event| row.done.as_ref().is_some_and(|done| !done.contains(event)))
|
||||
};
|
||||
// A send her trace holds owed starts her, whatever the room says: it is hers alone, and waits out her failed wakes like any wake.
|
||||
if mentioned.is_none() && row.owes {
|
||||
tried.push(index);
|
||||
match wake(organs, row) {
|
||||
Woke::Started => {
|
||||
state.last_turn_at.insert(slug.0.clone(), now);
|
||||
row.busy = true;
|
||||
launches.push(slug.0.clone());
|
||||
launched.push(slug);
|
||||
}
|
||||
Woke::Refused(why) => row.note = why,
|
||||
Woke::Busy => row.busy = true,
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(event) = mentioned else { continue };
|
||||
tried.push(index);
|
||||
// The wake's lines are recorded before her unit starts, so the start reads them. A start that does not happen leaves the
|
||||
|
|
|
|||
|
|
@ -1265,7 +1265,8 @@ fn a_mind_waiting_out_failures_passes_the_hello_to_the_other() {
|
|||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] });
|
||||
}
|
||||
|
||||
/// Soul's p5: a hello she decided whose send is owed is decided; her claim stands when her unit ends, and no second Mind is given it.
|
||||
/// Soul's p5: a hello she decided whose send is owed is decided; her claim stands when her unit ends, and no second Mind is given it:
|
||||
/// the poll starts her, for the send, and no one else.
|
||||
#[test]
|
||||
fn a_hello_she_decided_whose_send_is_owed_is_not_given_to_a_second_mind() {
|
||||
let rig = quiet_rig();
|
||||
|
|
@ -1275,7 +1276,7 @@ fn a_hello_she_decided_whose_send_is_owed_is_not_given_to_a_second_mind() {
|
|||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "#general:chat", "text": "hi" }], "at": rig.now().to_rfc3339() }));
|
||||
rig.advance(60);
|
||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
||||
assert_eq!(launched, vec![], "no one is given an owed hello");
|
||||
assert_eq!(launched, vec![Slug("ann".into())], "she is started for her owed send, and no one is given the hello");
|
||||
assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"], "her claim stands");
|
||||
}
|
||||
|
||||
|
|
@ -1309,3 +1310,51 @@ fn the_beat_does_not_start_a_mind_that_is_cooling() {
|
|||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
||||
assert!(!launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}");
|
||||
}
|
||||
|
||||
/// Soul's q3: her answer was decided and its send is owed (the answer was lost), her unit ended and nothing new arrives. The next poll
|
||||
/// starts her, and only her, so the send is retried well inside the 30 minutes a homeserver remembers its id, in a quiet room, with the
|
||||
/// beat's turn on the far side of the first poll.
|
||||
#[test]
|
||||
fn t_l3_an_owed_send_with_nothing_new_starts_her_at_the_next_poll_and_no_one_else() {
|
||||
let rig = quiet_rig();
|
||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
|
||||
rig.poll();
|
||||
rig.end_unit(ANN);
|
||||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
|
||||
rig.advance(60);
|
||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
||||
assert_eq!(launched.iter().map(|slug| slug.0.as_str()).collect::<Vec<_>>(), ["ann"], "her, at the first poll after it was owed, and no one else");
|
||||
// Her unit ends with the send still owed: every poll starts her again, never another Mind, until it settles.
|
||||
for minute in 2..=25 {
|
||||
rig.end_unit(ANN);
|
||||
rig.advance(60);
|
||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
||||
assert!(launched.iter().all(|slug| slug.0 == "ann" || slug.0 == "bob" && minute >= 15), "minute {minute}: {launched:?}");
|
||||
assert!(launched.iter().any(|slug| slug.0 == "ann"), "minute {minute}: a send owed is retried at the next poll: {launched:?}");
|
||||
}
|
||||
assert!(rig.started_turns().iter().filter(|(slug, _)| slug == "ann").count() >= 20, "retried inside the dedupe window, not at the beat");
|
||||
}
|
||||
|
||||
/// The owed send's start waits out her failed wakes like any other start: an outage is not retried every poll.
|
||||
#[test]
|
||||
fn t_l3_an_owed_send_waits_out_her_failed_wakes() {
|
||||
let rig = quiet_rig();
|
||||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
|
||||
rig.fail_turn(ANN);
|
||||
rig.advance(5);
|
||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
||||
assert!(launched.is_empty(), "cooling: {launched:?}");
|
||||
rig.advance(i64::from(BEAT_S));
|
||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
||||
assert!(launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}");
|
||||
}
|
||||
|
||||
/// A send owed and settled starts no one.
|
||||
#[test]
|
||||
fn t_l3_a_send_settled_starts_no_one() {
|
||||
let rig = quiet_rig();
|
||||
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held": ["$e1"], "posted": [{ "event": "$sent-1", "room": "!op", "text": "On it." }], "at": rig.now().to_rfc3339() }));
|
||||
rig.advance(60);
|
||||
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
|
||||
assert!(launched.is_empty(), "{launched:?}");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,9 @@
|
|||
//! Write ahead: the record of a decision, each line's words and send id (`owed`), is durable before any of it is sent, and a record
|
||||
//! that cannot be written sends nothing. The receipts rewrite the same record. A send whose answer never came stays owed, and the next
|
||||
//! start sends it again as recorded, under the recorded id, without asking the model; one owed longer than the homeserver remembers
|
||||
//! a transaction (`OWED_WINDOW_S`) is given up instead of risking a second post. Her record is appended after the put, refused or not.
|
||||
//! a transaction (`OWED_WINDOW_S`) is recorded in `unknown_sends` instead of risking a second post, and she is told it may or may not have gone
|
||||
//! out. The only receipt is the mouth's answer to a send, an event id; words in a room's tail prove nothing. A send that got no answer holds back
|
||||
//! every later send into its room for the rest of the start. Her record is appended after the put, refused or not.
|
||||
//!
|
||||
//! The put is `persona_put` under the `updatedAt` she was read at, stamped at the put and later than the stored one (P5). A stale one (Self or Life put between) reads her
|
||||
//! again, applies the same record again and puts once more; a second refusal is `put_refused` in the record and on stderr.
|
||||
|
|
@ -44,7 +46,7 @@ use crate::address::{Addressee, addresses, is_for, localpart};
|
|||
use crate::chat_client::{Basis, Chat, ChatDelivery, TailLine};
|
||||
use crate::control::{ControlSource, Effective, HeldReason, derive};
|
||||
use crate::heartbeat::{HeartbeatView, Speaker, own_rooms, pending_facts, read_pending, wakes};
|
||||
use crate::projection::{DomainSource, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, decide, decided, deliver, history, owing, Landed, own_addressee as heard_as};
|
||||
use crate::projection::{DomainSource, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, decide, decided, deliver, history, owing, own_addressee as heard_as};
|
||||
|
||||
/// The admitting agent's name on what her Persona admitted; `self_run::inbox` still reads her briefs by it.
|
||||
pub const AGENT: &str = "mind-persona";
|
||||
|
|
@ -290,12 +292,9 @@ pub fn carry<C: Chat>(control: &impl ControlSource, swarm: &impl ControlSource,
|
|||
const STRIKES: usize = 2;
|
||||
|
||||
/// How long a recorded send stays owed, in seconds: the least a homeserver remembers a transaction (Synapse `HttpTransactionCache`). Past it the
|
||||
/// same id is no longer the same send, so a repeat could post twice; the send is given up.
|
||||
/// same id is no longer the same send, so a repeat could post twice; the send is recorded unknown.
|
||||
const OWED_WINDOW_S: i64 = 1800;
|
||||
|
||||
/// How much earlier than its record a line may be stamped and still be taken as that record's send: the mouth's clock and hers differ.
|
||||
const OWED_SKEW_MS: u64 = 60_000;
|
||||
|
||||
/// A waking line: where it sits in the mouth's queue, and which room and event it is.
|
||||
struct Waking<'a> {
|
||||
seq: u64,
|
||||
|
|
@ -368,6 +367,8 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
|
|||
let (aside, waking): (Vec<Waking>, Vec<Waking>) = 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 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());
|
||||
let owed: Vec<Value> = trace.iter().filter(|record| record.get("failed").is_none() && record["owed"].as_array().is_some_and(|owed| !owed.is_empty())).cloned().collect();
|
||||
let mut stalled: BTreeSet<String> = BTreeSet::new();
|
||||
// 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 {
|
||||
|
|
@ -377,7 +378,8 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
|
|||
}
|
||||
rooms.truncate(TURNS_PER_START);
|
||||
let kind = if woken { TurnKind::Chat } else { TurnKind::Beat };
|
||||
if !woken {
|
||||
// A start that paid sends owed has done its work: the beat's turn is not taken on top of it.
|
||||
if !woken && owed.is_empty() {
|
||||
rooms.extend(deliveries.last().map(|delivery| delivery.room_alias.as_str()).or(config.rooms.first().map(String::as_str)));
|
||||
}
|
||||
// The newest event of each room her input held: a send is refused if another sender reached the room after it.
|
||||
|
|
@ -413,26 +415,17 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
|
|||
}
|
||||
}
|
||||
};
|
||||
// Every send her trace shows owed goes out first, in every room, as it was recorded and under the ids it was recorded with: the
|
||||
// model is not asked again, and a post that was lost is the same post. A record older than the homeserver remembers a transaction
|
||||
// is given up, since the same id could no longer be told from a new line; a line of hers already in the room is its receipt.
|
||||
let owed: Vec<Value> = trace.iter().filter(|record| record.get("failed").is_none() && record["owed"].as_array().is_some_and(|owed| !owed.is_empty())).cloned().collect();
|
||||
// Every send her trace shows owed goes out first, in every room, as it was recorded and under the ids it was recorded with: the model is
|
||||
// not asked again, and a post that was lost is the same post, which the homeserver answers with the original event. A record older than
|
||||
// the homeserver remembers a transaction is recorded unknown: the same id could no longer be told from a new line.
|
||||
for mut record in owed {
|
||||
let now = (start.clock)();
|
||||
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 landed = |send: &Value| -> Option<String> {
|
||||
let (room, text) = (send["room"].as_str()?, send["text"].as_str()?.trim());
|
||||
let since = u64::try_from(recorded_ms?).unwrap_or_default().saturating_sub(OWED_SKEW_MS);
|
||||
let tail = pending.tail.iter().flatten();
|
||||
tail.filter(|line| line.sender == config.own_sender && line.room == room && line.at_unix_ms >= since).find(|line| !line.body.trim().is_empty() && text.starts_with(line.body.trim().trim_end_matches('…').trim())).map(|line| line.event_id.clone())
|
||||
};
|
||||
let give_up: Option<Landed> = (age > OWED_WINDOW_S).then_some(&landed);
|
||||
deliver(&mouth, &mut record, give_up);
|
||||
let given_up: Vec<&Value> = record["refused_sends"].as_array().into_iter().flatten().filter(|refused| refused["refusal"] == "owed_too_old").collect();
|
||||
if !given_up.is_empty() {
|
||||
eprintln!("mind-persona: {} owed send(s) were given up as too old to repeat, and are told to her at her next wake: {given_up:?}", given_up.len());
|
||||
record["gave_up_at"] = json!(now.to_rfc3339());
|
||||
deliver(&mouth, &mut record, age > OWED_WINDOW_S, &mut stalled);
|
||||
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());
|
||||
record["unknown_at"] = json!(now.to_rfc3339());
|
||||
}
|
||||
if let Err(fault) = start.trace.record(record["key"].as_str().unwrap_or_default(), &record) {
|
||||
eprintln!("mind-persona: the record of a send owed was not rewritten: {fault:#}");
|
||||
|
|
@ -515,7 +508,7 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
|
|||
}
|
||||
}
|
||||
}
|
||||
deliver(&mouth, &mut turn.record, None);
|
||||
deliver(&mouth, &mut turn.record, false, &mut stalled);
|
||||
if turn.record.get("failed").is_none()
|
||||
&& let Err(fault) = start.trace.record(&record_key, &turn.record)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -63,6 +63,8 @@ struct FakeMouth {
|
|||
/// The transactions the homeserver remembers, by id, and the event each made; `forgot` is its memory expiring.
|
||||
txn: RefCell<BTreeMap<String, String>>,
|
||||
forgot: Cell<bool>,
|
||||
/// The rooms whose sends fail on the way, as a homeserver that is down does.
|
||||
down: RefCell<Vec<String>>,
|
||||
/// The next send lands and its answer is lost on the way back.
|
||||
answer_lost: Cell<bool>,
|
||||
/// Every id a send came under, retries and deduped ones included.
|
||||
|
|
@ -77,6 +79,9 @@ impl Chat for Rc<FakeMouth> {
|
|||
}
|
||||
fn send(&self, request: &ChatSendRequest) -> Result<ChatSendReceipt> {
|
||||
self.attempts.borrow_mut().push(request.request_id.clone());
|
||||
if self.down.borrow().contains(&request.room_alias) {
|
||||
bail!("the homeserver did not answer");
|
||||
}
|
||||
let remembered = self.txn.borrow().get(&request.request_id).cloned();
|
||||
if let Some(event) = remembered.filter(|_| !self.forgot.get()) {
|
||||
return Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: Some(event), refusal: None, newer: vec![] });
|
||||
|
|
@ -242,7 +247,7 @@ impl Rig {
|
|||
let dir = TempDir::new().unwrap();
|
||||
ControlWriter::open(dir.path().join("control.cc")).unwrap().set_brake(true, at(0), "op").unwrap();
|
||||
SwarmWriter::open(dir.path().join("swarm.cc")).unwrap().set_brake(true, at(0), "op").unwrap();
|
||||
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), tail: RefCell::default(), txn: RefCell::default(), forgot: Cell::new(false), answer_lost: Cell::new(false), attempts: RefCell::default(), log: log.clone() });
|
||||
let mouth = Rc::new(FakeMouth { held: RefCell::new(deliveries), down: RefCell::default(), sent: RefCell::default(), acks: RefCell::default(), reads: Cell::new(0), ack_fails: Cell::new(false), page: Cell::new(usize::MAX), tail: RefCell::default(), txn: RefCell::default(), forgot: Cell::new(false), answer_lost: Cell::new(false), attempts: RefCell::default(), 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), allow: Cell::new(usize::MAX), log: log.clone() });
|
||||
Self { mouth, store, trace, log, dir, ticks: Rc::default() }
|
||||
|
|
@ -914,10 +919,10 @@ fn t_l2_a_trace_that_cannot_be_written_sends_nothing_and_acks_nothing() {
|
|||
assert!(rig.held_seqs().is_empty());
|
||||
}
|
||||
|
||||
/// The homeserver forgets a transaction id after 30 to 60 minutes, so a send still owed after that is given up and refused
|
||||
/// `owed_too_old`, never posted again, and the line is decided. (Soul s3 send-id-dedupe-window.)
|
||||
/// The homeserver forgets a transaction id after 30 to 60 minutes, so a send still owed after that is recorded unknown, never posted
|
||||
/// again, and the line is decided. (Soul s3 send-id-dedupe-window.)
|
||||
#[test]
|
||||
fn t_l2_a_send_owed_past_the_homeservers_memory_is_given_up_and_posts_nothing_twice() {
|
||||
fn t_l2_a_send_owed_past_the_homeservers_memory_is_unknown_and_posts_nothing_twice() {
|
||||
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
|
||||
rig.mouth.answer_lost.set(true);
|
||||
rig.run(scripted(false));
|
||||
|
|
@ -928,7 +933,8 @@ fn t_l2_a_send_owed_past_the_homeservers_memory_is_given_up_and_posts_nothing_tw
|
|||
rig.run(Never);
|
||||
assert_eq!(rig.mouth.sent.borrow().len(), 1, "no second post, though the homeserver forgot the id");
|
||||
let record = rig.trace.rows.borrow()[0].1.clone();
|
||||
assert_eq!(record["refused_sends"][0]["refusal"], "owed_too_old", "{record}");
|
||||
assert_eq!(record["unknown_sends"][0]["text"], rig.mouth.sent.borrow()[0].text, "{record}");
|
||||
assert!(record["refused_sends"].as_array().is_some_and(Vec::is_empty) && record["posted"].as_array().is_some_and(Vec::is_empty), "neither posted nor refused: {record}");
|
||||
assert!(rig.held_seqs().is_empty(), "the line is decided");
|
||||
}
|
||||
|
||||
|
|
@ -984,41 +990,122 @@ fn t_l3_the_ack_stays_below_a_line_whose_send_is_still_owed() {
|
|||
assert_eq!(rig.held_seqs(), [1, 2], "the ack stops below the owed line though her trace holds it decided, and the line after it waits with it");
|
||||
}
|
||||
|
||||
/// A send owed past the homeserver's memory whose line is not in the room is given up: told to her, logged, never re-asked.
|
||||
/// A send owed past the homeserver's memory is recorded unknown, stamped and logged, and never decided or sent again.
|
||||
#[test]
|
||||
fn t_l3_a_send_given_up_is_recorded_stamped_and_not_decided_again() {
|
||||
fn t_l3_a_send_with_no_answer_in_the_window_is_recorded_unknown_stamped_and_not_decided_again() {
|
||||
let rig = Rig::new(vec![line(1, MINDS, "@deru:gamecult.org", "hello all")]);
|
||||
rig.mouth.answer_lost.set(true);
|
||||
rig.run_woken(scripted(false), &["$e1"]);
|
||||
rig.mouth.tail.borrow_mut().clear();
|
||||
rig.mouth.forgot.set(true);
|
||||
rig.ticks.set(rig.ticks.get() + 3600);
|
||||
rig.run_woken(Never, &["$e1"]);
|
||||
let rows = rig.trace.rows.borrow();
|
||||
let record = &rows[0].1;
|
||||
assert_eq!(record["refused_sends"][0]["refusal"], "owed_too_old");
|
||||
assert!(record["gave_up_at"].is_string(), "{record}");
|
||||
assert!(record.get("owed").is_none());
|
||||
{
|
||||
let rows = rig.trace.rows.borrow();
|
||||
let record = &rows[0].1;
|
||||
assert_eq!(record["unknown_sends"][0]["room"], MINDS);
|
||||
assert!(record["unknown_at"].is_string(), "{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");
|
||||
assert_eq!(rig.trace.rows.borrow().len(), 1, "the line stays decided by its one record");
|
||||
}
|
||||
|
||||
/// Soul's p8: the post landed and its receipt rewrite died; a start past the window finds her own line in the room, and the line is
|
||||
/// recorded as posted, never as refused.
|
||||
/// Soul's q1: words in the room's tail are never proof that a send posted. Her later line whose words are a prefix of the owed
|
||||
/// send's, the same words, a bare ellipsis or a clipped real line each leave the send unknown, never posted, never sent again.
|
||||
#[test]
|
||||
fn t_l3_a_send_that_landed_is_never_recorded_refused() {
|
||||
fn t_l3_words_in_the_room_are_never_a_receipt() {
|
||||
for (name, said, owed) in [("prefix", "Thanks!", "Thanks! I will read the PR tonight."), ("identical", "On it.", "On it."), ("ellipsis-only", "\u{2026}", "Anything at all."), ("clipped-real", "Thanks! I will read\u{2026}", "Thanks! I will read the PR tonight.")] {
|
||||
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
|
||||
let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap();
|
||||
rig.trace.rows.borrow_mut().push(("n0-t0".into(), json!({ "key": "n0-t0", "room": room(1), "held": ["$e1"], "owed": [{ "id": "l$e1:s0", "room": room(1), "text": owed }], "posted": [], "refused_sends": [], "at": at.to_rfc3339() })));
|
||||
rig.mouth.tail.borrow_mut().push(crate::chat_client::TailLine { room: room(1), event_id: "$later".into(), at_unix_ms: BASE_MS + 600_000, sender: "@eureka:gamecult.org".into(), form: Form::Message, basis: None, body: said.into(), reply_to: Default::default() });
|
||||
rig.mouth.forgot.set(true);
|
||||
rig.ticks.set(3600);
|
||||
rig.run(Never);
|
||||
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_at"].is_string(), "{name}: {record}");
|
||||
assert!(rig.mouth.sent.borrow().is_empty(), "{name}: past the window nothing is sent");
|
||||
}
|
||||
}
|
||||
|
||||
/// Within the window a retry goes out under the recorded id, and the homeserver's answer to it, the event the first try made, is the
|
||||
/// receipt: posted with that event id, and nothing posted twice.
|
||||
#[test]
|
||||
fn t_l3_a_retry_under_the_recorded_id_is_receipted_by_the_event_the_mouth_answers_with() {
|
||||
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
|
||||
rig.trace.allow.set(1);
|
||||
rig.mouth.answer_lost.set(true);
|
||||
rig.run(scripted(false));
|
||||
assert_eq!(rig.mouth.sent.borrow().len(), 1);
|
||||
rig.trace.allow.set(usize::MAX);
|
||||
rig.mouth.forgot.set(true);
|
||||
rig.ticks.set(rig.ticks.get() + 1900);
|
||||
rig.run(Never);
|
||||
let rows = rig.trace.rows.borrow();
|
||||
let record = &rows[0].1;
|
||||
assert!(record["refused_sends"].as_array().is_some_and(Vec::is_empty), "{record}");
|
||||
assert_eq!(record["posted"].as_array().map(Vec::len), Some(1), "{record}");
|
||||
assert_eq!(rig.mouth.sent.borrow().len(), 1);
|
||||
let record = rig.trace.rows.borrow()[0].1.clone();
|
||||
assert_eq!(record["posted"][0]["event"], "$sent-1", "{record}");
|
||||
assert_eq!(rig.mouth.sent.borrow().len(), 1, "one post");
|
||||
assert_eq!(rig.mouth.attempts.borrow().len(), 2, "tried twice");
|
||||
assert!(record.get("owed").is_none() && record.get("unknown_sends").is_none(), "{record}");
|
||||
}
|
||||
|
||||
/// Soul's q2: a send that is unknown is told at her next real turn exactly once, even when a start set a struck line aside before
|
||||
/// that turn, and after failed wakes.
|
||||
#[test]
|
||||
fn t_l3_an_unknown_send_is_told_at_her_next_real_turn_exactly_once_though_a_line_was_set_aside_between() {
|
||||
for aside in [false, true] {
|
||||
let rig = Rig::new(vec![line(1, MINDS, "@deru:gamecult.org", "hello all")]);
|
||||
rig.mouth.answer_lost.set(true);
|
||||
rig.run_woken(scripted(false), &["$e1"]);
|
||||
rig.mouth.forgot.set(true);
|
||||
rig.ticks.set(rig.ticks.get() + 3600);
|
||||
rig.run_woken(Never, &["$e1"]);
|
||||
let records = |rig: &Rig| rig.trace.rows.borrow().iter().map(|(_, record)| record.clone()).collect::<Vec<Value>>();
|
||||
if aside {
|
||||
rig.mouth.held.borrow_mut().push(line(2, &room(2), META, "FAILME x"));
|
||||
rig.run(failing(REFUSED));
|
||||
rig.run(failing(REFUSED));
|
||||
}
|
||||
rig.mouth.held.borrow_mut().push(line(3, &room(3), META, "hi"));
|
||||
rig.run(failing(REFUSED));
|
||||
assert_eq!(set_aside(&rig), aside, "the struck line was set aside before the turn");
|
||||
let all = records(&rig);
|
||||
let before_turn: Vec<Value> = all.iter().filter(|record| record["room"] != json!(room(3))).cloned().collect();
|
||||
let told = |records: &[Value]| crate::projection::history(records).last_outcome.map(|last| last["unknown"].clone());
|
||||
assert_eq!(told(&before_turn), Some(json!([{ "room": MINDS, "text": rig.mouth.sent.borrow()[0].text }])), "aside={aside}: told at her next turn");
|
||||
rig.run(scripted(false));
|
||||
assert_eq!(told(&records(&rig)), Some(Value::Null), "aside={aside}: told once");
|
||||
}
|
||||
}
|
||||
|
||||
/// A send that got no answer holds back every later send into its room for the rest of the start, so her lines never arrive out of
|
||||
/// order; another room's sends are not held.
|
||||
#[test]
|
||||
fn t_l3_a_send_with_no_answer_holds_back_what_is_newer_in_its_room_only() {
|
||||
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
|
||||
rig.mouth.down.borrow_mut().push(room(1));
|
||||
rig.run(varying());
|
||||
assert_eq!(owed_of(&rig).len(), 1, "the first send is owed");
|
||||
rig.mouth.held.borrow_mut().push(line(2, &room(1), META, "again"));
|
||||
rig.mouth.held.borrow_mut().push(line(3, &room(2), META, "elsewhere"));
|
||||
rig.run(varying());
|
||||
assert_eq!(texts(&rig, &room(2)).len(), 1, "another room's send is not held");
|
||||
assert!(texts(&rig, &room(1)).is_empty(), "nothing newer than the lost send reached its room");
|
||||
let ids = rig.mouth.attempts.borrow().clone();
|
||||
assert_eq!(ids.iter().filter(|id| id.starts_with("l$e1")).count(), 2, "the owed send was retried once: {ids:?}");
|
||||
assert!(!ids.iter().any(|id| id.starts_with("l$e2")), "the newer send was not even tried in her room: {ids:?}");
|
||||
rig.mouth.down.borrow_mut().clear();
|
||||
rig.run(Never);
|
||||
let order: Vec<String> = rig.mouth.sent.borrow().iter().filter(|request| request.room_alias == room(1)).map(|request| request.request_id.clone()).collect();
|
||||
assert_eq!(order.len(), 2, "both arrive once the homeserver answers: {order:?}");
|
||||
assert!(order[0].starts_with("l$e1") && order[1].starts_with("l$e2"), "in the order she decided them: {order:?}");
|
||||
}
|
||||
|
||||
/// A start that only pays a send owed takes no beat turn on top of it.
|
||||
#[test]
|
||||
fn t_l3_a_start_that_paid_a_send_owed_takes_no_beat_turn() {
|
||||
let rig = Rig::new(vec![]);
|
||||
let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap();
|
||||
rig.trace.rows.borrow_mut().push(("n0-t0".into(), json!({ "key": "n0-t0", "room": room(1), "held": [], "owed": [{ "id": "b1-t0:s0", "room": room(1), "text": "good morning" }], "posted": [], "refused_sends": [], "at": at.to_rfc3339() })));
|
||||
rig.run(Never);
|
||||
assert_eq!(texts(&rig, &room(1)), ["good morning"]);
|
||||
assert_eq!(rig.trace.rows.borrow().len(), 1, "no new record: the model was not asked");
|
||||
}
|
||||
|
||||
/// Soul's p9: a record that cannot be written puts nothing; the retry applies her memory of the turn once.
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ pub use narrate::{Answer, Continued, Failed, KitModel, Model, Reasoning, Spent,
|
|||
pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource};
|
||||
pub use select::TurnKind;
|
||||
pub(crate) use commit::apply as apply_commit;
|
||||
pub(crate) use turn::{Landed, Mouth, Taken, decide, decided, deliver, failed_run, history, owing};
|
||||
pub(crate) use turn::{Mouth, Taken, decide, decided, deliver, failed_run, history, owes, owing};
|
||||
pub use tuning::{TUNING_FILE, TUNING_ROOT};
|
||||
|
||||
use narrate::{cap_prose, cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words};
|
||||
|
|
|
|||
|
|
@ -232,6 +232,9 @@ enum Part {
|
|||
/// tells it, it was neither said, added nor left for Self, and it is no unfinished draft; or a line she said that the
|
||||
/// actuator refused (`refused_sends`, T6). No label says why: she knows her own reason. `reach` as on `Refused`.
|
||||
Unsent { room: Option<String>, text: Words, reach: bool },
|
||||
/// A line of hers whose send got no answer within the time the homeserver remembers it: it may or may not have gone out (derived
|
||||
/// from the trace's `unknown_sends`, never from the room's tail).
|
||||
Unknown { room: Option<String>, text: Words },
|
||||
/// An edited receipt with no refusal: her words were added after a line of hers; `unbacked` when a
|
||||
/// `missing_affordance` gap names the addition's draft (map 16.21).
|
||||
Amended { room: String, added: Words, unbacked: bool },
|
||||
|
|
@ -300,10 +303,11 @@ pub(crate) fn outcome_of(record: &Value) -> Option<Outcome> {
|
|||
}
|
||||
let mut outcome = Outcome::default();
|
||||
let decision = &record["interpreter"];
|
||||
// Sends the drain gave up (too old to repeat) since her last wake: told as lines that did not go out, whatever record they sit in.
|
||||
for given_up in record["given_up"].as_array().into_iter().flatten() {
|
||||
if let Some(text) = words_of(&given_up["text"]) {
|
||||
outcome.parts.push(Part::Unsent { room: words(&given_up["room"]), text, reach: false });
|
||||
// Sends no answer was got for within the homeserver's memory of their ids, since her last real turn: told as lines that may or may not
|
||||
// have gone out, whatever record they sit in.
|
||||
for unknown in record["unknown"].as_array().into_iter().flatten() {
|
||||
if let Some(text) = words_of(&unknown["text"]) {
|
||||
outcome.parts.push(Part::Unknown { room: words(&unknown["room"]), text });
|
||||
}
|
||||
}
|
||||
let failed = record.get("failed").is_some() || decision.get("failed").is_some();
|
||||
|
|
@ -344,6 +348,8 @@ pub(crate) fn outcome_of(record: &Value) -> Option<Outcome> {
|
|||
// A said line is told by its receipt; one the actuator refused (T6) by the row of a line that did not go out, which
|
||||
// `settle` holds to the receipts; one with neither is not told, and reported.
|
||||
let refused_send = |line: &Value| record["refused_sends"].as_array().into_iter().flatten().any(|refused| refused["room"] == line["room"] && refused["text"] == line["text"]);
|
||||
// A line whose send is unknown is told by `unknown`, from the record that settled it; its own record shows no receipt and no refusal.
|
||||
let unknown_send = |line: &Value| record["unknown_sends"].as_array().into_iter().flatten().any(|sent| sent["room"] == line["room"] && sent["text"] == line["text"]);
|
||||
for line in decision["said"].as_array().into_iter().flatten() {
|
||||
let went = receipts.iter().any(|posted| Some(posted.room.as_str()) == line["room"].as_str() && Some(posted.text.as_str()) == line["text"].as_str());
|
||||
match (went, words_of(&line["text"])) {
|
||||
|
|
@ -352,6 +358,7 @@ pub(crate) fn outcome_of(record: &Value) -> Option<Outcome> {
|
|||
rows.push((&line["rests_on"]["draft"], outcome.parts.len()));
|
||||
outcome.parts.push(Part::Unsent { room: words(&line["room"]), text, reach: false });
|
||||
}
|
||||
(false, _) if unknown_send(line) => {}
|
||||
(false, _) => outcome.omitted.push(format!("a line said with no receipt that it went out: {}", line["text"])),
|
||||
}
|
||||
}
|
||||
|
|
@ -566,6 +573,7 @@ impl Part {
|
|||
Self::Gap { .. } => "gap",
|
||||
Self::Unfinished { .. } => "unfinished draft",
|
||||
Self::Unsent { .. } => "draft that did not go out",
|
||||
Self::Unknown { .. } => "line that may not have gone out",
|
||||
Self::NotAmended { .. } => "unmade addition",
|
||||
_ => "row",
|
||||
}
|
||||
|
|
@ -577,7 +585,7 @@ impl Part {
|
|||
match self {
|
||||
Self::Failed => 0,
|
||||
Self::SetAside { .. } | Self::NotKept => 1,
|
||||
Self::Refused { .. } | Self::Gap { .. } | Self::Unfinished { .. } | Self::Unsent { .. } | Self::NotAmended { .. } | Self::NoteRefused(_) | Self::ReadFailed { .. } | Self::ReadRefused { .. } => 1,
|
||||
Self::Refused { .. } | Self::Gap { .. } | Self::Unfinished { .. } | Self::Unsent { .. } | Self::Unknown { .. } | Self::NotAmended { .. } | Self::NoteRefused(_) | Self::ReadFailed { .. } | Self::ReadRefused { .. } => 1,
|
||||
Self::SaidUnbacked { .. } | Self::Amended { unbacked: true, .. } => 2,
|
||||
Self::Said { .. } | Self::Amended { .. } | Self::NoteLeft(_) | Self::Read { .. } => 3,
|
||||
Self::BrokeAfter { .. } => 4,
|
||||
|
|
@ -613,6 +621,10 @@ impl Part {
|
|||
Some(quote) => format!("{cap_subj} had drafted {quote}, and it did not go out."),
|
||||
None => format!("{cap_subj} had drafted a line, and it did not go out."),
|
||||
},
|
||||
Self::Unknown { room, text } => match form.words(text) {
|
||||
Some(quote) => format!("{cap_subj} said {quote} in {}, and it may or may not have gone out.", place(room)),
|
||||
None => format!("{cap_subj} said a line in {}, and it may or may not have gone out.", place(room)),
|
||||
},
|
||||
Self::Gap { kind: GapKind::Addressee | GapKind::Elsewhere, .. } => "Nothing reached anyone.".to_owned(),
|
||||
Self::Gap { kind: GapKind::MissingAffordance, .. } => "Nothing happened.".to_owned(),
|
||||
Self::NotAmended { refusal: None, room, .. } => format!("Nothing changed, and nothing reached {}:", place(room)),
|
||||
|
|
@ -654,6 +666,7 @@ impl Part {
|
|||
match self {
|
||||
Self::Said { .. } => String::new(),
|
||||
Self::Unsent { .. } => reach.clone(),
|
||||
Self::Unknown { .. } => String::new(),
|
||||
Self::Amended { unbacked: false, .. } => " The rest of the line is as it was.".to_owned(),
|
||||
Self::Amended { unbacked: true, .. } => format!(" The rest of the line is as it was. What {subj} added promises something {subj} {has} no way to do, now or later, and it will not happen by itself."),
|
||||
Self::SaidUnbacked { .. } => format!(" It promises something {subj} {has} no way to do, now or later, and it will not happen by itself. The line stands as {subj} wrote it; {subj} can add to it."),
|
||||
|
|
|
|||
|
|
@ -250,7 +250,7 @@ fn i16_10_every_lines_first_clause_is_what_its_receipt_says_reached_the_room() {
|
|||
// "{Room} has" only on a receipt that a line went out or was added to.
|
||||
let receipt = matches!(part, Part::Said { .. } | Part::SaidUnbacked { .. } | Part::Amended { .. });
|
||||
assert_eq!(reached.starts_with("#minds:gamecult.org has"), receipt, "{form}: {part:?}: {reached}");
|
||||
let unsent = matches!(part, Part::Unsent { .. }) && reached.ends_with(", and it did not go out.");
|
||||
let unsent = (matches!(part, Part::Unsent { .. }) && reached.ends_with(", and it did not go out.")) || (matches!(part, Part::Unknown { .. }) && reached.ends_with(", and it may or may not have gone out."));
|
||||
assert!(receipt || unsent || matches!(part, Part::NoteLeft(_)) || reached.starts_with("Nothing") || reached.starts_with("No "), "{form}: {part:?}: {reached}");
|
||||
for claim in ["Nothing reached", "reached the room", "reached anyone", " has, from", " has a line", "now ending with", "now added to", "went out"] {
|
||||
assert!(!rest.contains(claim), "{form}: {part:?}: only the first clause says what reached the room: {rest}");
|
||||
|
|
@ -414,6 +414,7 @@ fn variant(part: &Part) -> &'static str {
|
|||
Part::Gap { .. } => "gap",
|
||||
Part::Unfinished { .. } => "unfinished",
|
||||
Part::Unsent { .. } => "not_sent",
|
||||
Part::Unknown { .. } => "unknown",
|
||||
Part::Amended { .. } => "amended",
|
||||
Part::NotAmended { .. } => "not_amended",
|
||||
Part::NoteLeft(_) => "note_left",
|
||||
|
|
@ -428,7 +429,7 @@ fn variant(part: &Part) -> &'static str {
|
|||
}
|
||||
}
|
||||
|
||||
const VARIANTS: usize = 17;
|
||||
const VARIANTS: usize = 18;
|
||||
|
||||
/// Every row kind, and every arm that renders a different sentence, with `s` in every text of a record it carries and in
|
||||
/// every read's target; and whether her told form shows those words (an echo, a held
|
||||
|
|
@ -461,6 +462,7 @@ fn fixtures(s: &str) -> Vec<(Part, bool)> {
|
|||
for refusal in [None, Some(EditRefusal::NotFound), Some(EditRefusal::NotHers), Some(EditRefusal::TooLong)] {
|
||||
out.push((Part::NotAmended { refusal, room: room(), added: w(), reach: false }, true));
|
||||
}
|
||||
out.push((Part::Unknown { room: room(), text: w() }, true));
|
||||
out.push((Part::NoteLeft(w()), true));
|
||||
out.push((Part::NoteRefused(Refusal::Private), false));
|
||||
out.push((Part::NoteRefused(Refusal::SecondNote), false));
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ pub(crate) struct Taken {
|
|||
/// One turn: `decide`, then `deliver`.
|
||||
pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, key: &str, now: DateTime<Utc>) -> Taken {
|
||||
let mut taken = decide(organs, request, key, now);
|
||||
deliver(actuator, &mut taken.record, None);
|
||||
deliver(actuator, &mut taken.record, false, &mut BTreeSet::new());
|
||||
taken
|
||||
}
|
||||
|
||||
|
|
@ -135,16 +135,15 @@ pub(crate) fn decide(organs: &Organs, request: &Request, key: &str, now: DateTim
|
|||
Taken { report, record, state }
|
||||
}
|
||||
|
||||
/// Answers, for one owed send, the event of her own line already in the room: that send's receipt.
|
||||
pub(crate) type Landed<'a> = &'a dyn Fn(&Value) -> Option<String>;
|
||||
|
||||
/// Settles what `record` owes through `actuator`: each owed send is posted, refused (a refusal is an answer) or, when no answer
|
||||
/// came, still owed. The amendments follow once nothing
|
||||
/// is owed. A record that owes nothing is the shape the simulator and the mouth share.
|
||||
/// came, still owed. The only receipt is the mouth's answer to a send, an event id; her lines in the room's tail are never one. The
|
||||
/// amendments follow once nothing is owed. A record that owes nothing is the shape the simulator and the mouth share.
|
||||
///
|
||||
/// With `give_up` (a record older than the homeserver remembers its ids) nothing is sent: `give_up` answers, for each owed send, the
|
||||
/// event of her own line already in the room, which is that send's receipt; a send with none is refused `owed_too_old`.
|
||||
pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, give_up: Option<Landed>) {
|
||||
/// A send is made under its recorded id, so the homeserver answers a repeat with the original event. `window_passed` (the record is older
|
||||
/// than the homeserver remembers an id) sends nothing: each owed send is recorded in `unknown_sends`, neither posted nor refused, and
|
||||
/// she is told it may or may not have gone out. `stalled` holds the rooms whose earlier send got no answer in this start: nothing is
|
||||
/// sent into them after it, so her lines never arrive out of order, and a send not sent stays owed.
|
||||
pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, window_passed: bool, stalled: &mut BTreeSet<String>) {
|
||||
let owed: Vec<Value> = record["owed"].as_array().cloned().unwrap_or_default();
|
||||
let mut still = Vec::new();
|
||||
for send in owed {
|
||||
|
|
@ -154,11 +153,25 @@ pub(crate) fn deliver(actuator: &dyn Actuator, record: &mut Value, give_up: Opti
|
|||
None => json!({ "room": room, "text": text, "refusal": why }),
|
||||
};
|
||||
let mentions: Vec<String> = send["mentions"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
|
||||
let sent = if let Some(landed) = give_up { landed(&send).map_or_else(|| Sent::Refused("owed_too_old".to_owned()), Sent::Posted) } else { actuator.send(send["id"].as_str().unwrap_or_default(), room, text, send["in_reply_to"].as_str(), &mentions) };
|
||||
match sent {
|
||||
if window_passed {
|
||||
let unknown = json!({ "room": room, "text": text });
|
||||
match record["unknown_sends"].as_array_mut() {
|
||||
Some(unknowns) => unknowns.push(unknown),
|
||||
None => record["unknown_sends"] = json!([unknown]),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if stalled.contains(room) {
|
||||
still.push(send);
|
||||
continue;
|
||||
}
|
||||
match actuator.send(send["id"].as_str().unwrap_or_default(), room, text, send["in_reply_to"].as_str(), &mentions) {
|
||||
Sent::Posted(event) => record["posted"].as_array_mut().into_iter().for_each(|posted| posted.push(json!({ "event": event, "room": room, "text": text }))),
|
||||
Sent::Refused(why) => record["refused_sends"].as_array_mut().into_iter().for_each(|refused| refused.push(refusal(&why))),
|
||||
Sent::Lost => still.push(send),
|
||||
Sent::Lost => {
|
||||
stalled.insert(room.to_owned());
|
||||
still.push(send);
|
||||
}
|
||||
}
|
||||
}
|
||||
if still.is_empty() {
|
||||
|
|
@ -220,15 +233,22 @@ pub(crate) struct Past {
|
|||
pub last_wake: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// The sends her trace shows given up (`owed_too_old`) that no wake of hers has followed since: each a `{room, text}`, told once, at her next
|
||||
/// wake. A record gives up when it is rewritten, so it is told by when it gave up (`gave_up_at`), not by where it sits in the trace.
|
||||
fn given_up(records: &[Value]) -> Vec<Value> {
|
||||
/// Whether any record of hers still owes a send.
|
||||
pub(crate) fn owes(records: &[Value]) -> bool {
|
||||
records.iter().any(|record| record.get("failed").is_none() && record["owed"].as_array().is_some_and(|owed| !owed.is_empty()))
|
||||
}
|
||||
|
||||
/// The sends her trace shows unknown (`unknown_sends`) that no real turn of hers has followed since: each a `{room, text}`, told once, at her
|
||||
/// next real turn. A record is rewritten when its sends are settled, so it is told by when it was (`unknown_at`), not by where it sits in the
|
||||
/// trace. A real turn is a record that decided something: a failed turn, a record that only set lines aside and a rewrite that settled a
|
||||
/// send are none.
|
||||
fn unknown(records: &[Value]) -> Vec<Value> {
|
||||
let at = |record: &Value, field: &str| record[field].as_str().and_then(|at| DateTime::parse_from_rfc3339(at).ok());
|
||||
let last_wake = records.iter().filter(|record| record.get("failed").is_none() && record.get("gave_up_at").is_none()).filter_map(|record| at(record, "at")).max();
|
||||
let last_wake = records.iter().filter(|record| record.get("failed").is_none() && record.get("set_aside").is_none()).filter_map(|record| at(record, "at")).max();
|
||||
let mut told = Vec::new();
|
||||
for record in records.iter().filter(|record| record.get("failed").is_none()) {
|
||||
if at(record, "gave_up_at").is_some_and(|gave| last_wake.is_none_or(|wake| wake < gave)) {
|
||||
told.extend(record["refused_sends"].as_array().into_iter().flatten().filter(|refused| refused["refusal"] == "owed_too_old").map(|refused| json!({ "room": refused["room"], "text": refused["text"] })));
|
||||
if at(record, "unknown_at").is_some_and(|gave| last_wake.is_none_or(|wake| wake < gave)) {
|
||||
told.extend(record["unknown_sends"].as_array().into_iter().flatten().map(|sent| json!({ "room": sent["room"], "text": sent["text"] })));
|
||||
}
|
||||
}
|
||||
told
|
||||
|
|
@ -242,9 +262,9 @@ pub(crate) fn history(records: &[Value]) -> Past {
|
|||
recent.drain(..recent.len().saturating_sub(RECENT));
|
||||
Past {
|
||||
last_outcome: records.last().cloned().map(|mut last| {
|
||||
let given_up = given_up(records);
|
||||
if !given_up.is_empty() {
|
||||
last["given_up"] = json!(given_up);
|
||||
let unknown = unknown(records);
|
||||
if !unknown.is_empty() {
|
||||
last["unknown"] = json!(unknown);
|
||||
}
|
||||
last
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -198,19 +198,31 @@ fn t_l2_a_line_is_decided_by_the_record_that_holds_it() {
|
|||
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$a", "$b", "$d"]);
|
||||
}
|
||||
|
||||
/// A send the drain gave up is told to her at her next wake, by her words, whether or not its record is her newest; once a wake of hers
|
||||
/// follows it, it is told no more.
|
||||
/// A send whose answer never came, past the time a repeat is safe, is told to her at her next real turn as a line that may or may not
|
||||
/// have gone out, by room and her words, whether or not its record is her newest. A failed turn, a record that only set lines aside and
|
||||
/// 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_a_send_given_up_is_told_at_her_next_wake_and_once() {
|
||||
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 given_up = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "refused_sends": [{ "room": "#minds", "text": "welcome aboard", "refusal": "owed_too_old" }], "at": "2026-11-28T00:00:00Z", "gave_up_at": "2026-11-28T02:00:00Z" });
|
||||
let records = vec![given_up.clone(), wake("2026-11-28T00:30:00Z")];
|
||||
let last = history(&records).last_outcome.expect("her last record");
|
||||
let told = outcome_of(&last).expect("an outcome").lines(forms(&json!({})));
|
||||
assert!(told.iter().any(|line| line.contains("welcome aboard")), "{told:?}");
|
||||
let records = vec![given_up, wake("2026-11-28T00:30:00Z"), wake("2026-11-28T03:00:00Z")];
|
||||
let last = history(&records).last_outcome.expect("her last record");
|
||||
assert!(last.get("given_up").is_none(), "a wake after it has told it");
|
||||
let unknown = json!({ "held": ["$e1"], "posted": [], "interpreter": { "said": [] }, "unknown_sends": [{ "room": "#minds", "text": "welcome aboard" }], "at": "2026-11-28T00:00:00Z", "unknown_at": "2026-11-28T02:00:00Z" });
|
||||
let told_at = |records: Vec<Value>| history(&records).last_outcome.map(|last| (last.get("unknown").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");
|
||||
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");
|
||||
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");
|
||||
assert!(list.is_none(), "a real turn after it has told it");
|
||||
}
|
||||
|
||||
/// A trace that holds an owed send says so; a failed record's owed send and a settled one are not owed.
|
||||
#[test]
|
||||
fn t_l3_a_trace_owes_a_send_only_while_a_record_holds_it_owed() {
|
||||
let owed = json!({ "held": [], "owed": [{ "id": "b1-t0:s0", "room": "#a", "text": "hi" }] });
|
||||
assert!(owes(std::slice::from_ref(&owed)), "a beat's send holds no line and is owed all the same");
|
||||
assert!(!owes(&[json!({ "held": ["$e1"], "owed": [{ "id": "x", "room": "#a", "text": "hi" }], "failed": "x" }), json!({ "held": ["$e2"], "posted": [] })]));
|
||||
}
|
||||
|
||||
/// An owed record holds its lines decided; the ack alone reads `owing`.
|
||||
|
|
@ -220,3 +232,12 @@ fn t_l3_an_owed_record_decides_its_lines_and_owes_them_to_the_ack() {
|
|||
assert_eq!(decided(&records).into_iter().collect::<Vec<_>>(), ["$e1"]);
|
||||
assert_eq!(owing(&records).into_iter().collect::<Vec<_>>(), ["$e1"]);
|
||||
}
|
||||
|
||||
/// The record that settled a send as unknown holds its said line with no receipt and no refusal: the line is told by `unknown`, and is
|
||||
/// not also reported as a said line with nothing to show it went out.
|
||||
#[test]
|
||||
fn t_l3_an_unknown_sends_own_record_reports_no_line_missing_its_receipt() {
|
||||
let record = json!({ "held": ["$e1"], "posted": [], "refused_sends": [], "unknown_sends": [{ "room": "#minds", "text": "welcome aboard" }], "interpreter": { "said": [{ "room": "#minds", "text": "welcome aboard" }] }, "at": "2026-11-28T00:00:00Z", "unknown_at": "2026-11-28T02:00:00Z" });
|
||||
let outcome = outcome_of(&record).expect("an outcome");
|
||||
assert!(outcome.omitted.is_empty(), "{:?}", outcome.omitted);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue