diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index e3333c9..a2fbae7 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -41,7 +41,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::{belongs_to_the_line, DomainSource, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, history, own_addressee as heard_as, take}; +use crate::projection::{is_transient, DomainSource, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, history, own_addressee as heard_as, take}; /// 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"; @@ -281,10 +281,10 @@ fn done_events(records: &[Value]) -> BTreeSet<&str> { done } -/// How many of her turns that held `event` failed for a reason that is the line's (`belongs_to_the_line`): an outage, quota stop or -/// connector failure is the body's, retried, and no strike. +/// How many strikes her trace charges `event`: a failed turn that was not an outage (`is_transient`) charged one to the +/// oldest line it was waking on, the room's held turn, and to no other line it happened to share the room with. fn strikes(records: &[Value], event: &str) -> usize { - records.iter().filter(|record| record["failed"].as_str().is_some_and(belongs_to_the_line) && record["held"].as_array().is_some_and(|held| held.iter().any(|id| id == event))).count() + records.iter().filter(|record| record["strike"] == event).count() } fn drain(instance: &Slug, start: &Start) -> Outcome { @@ -321,21 +321,15 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { .map(|(delivery, _)| Waking { seq: delivery.seq, room: delivery.room_alias.as_str(), event: delivery.event_id.as_str() }) .collect(); let woken = !waking_all.is_empty(); - // A line her trace shows decided is not waking again, whatever else in the queue is still stuck; one whose turns failed - // twice is set aside, acked past with no third turn. + // A line her trace shows decided is not waking again, whatever else in the queue is still stuck. The oldest line of a + // room with two strikes is set aside and acked past, that line only: the room's later lines are tried without it. let done = done_events(&trace); - let (aside, waking): (Vec, Vec) = waking_all.into_iter().filter(|line| !done.contains(line.event)).partition(|line| strikes(&trace, line.event) >= STRIKES); + let mut oldest_of_room = BTreeSet::new(); + let (aside, waking): (Vec, Vec) = waking_all.into_iter().filter(|line| !done.contains(line.event)).partition(|line| oldest_of_room.insert(line.room) && strikes(&trace, line.event) >= STRIKES); // The key of every record and send of this start: the newest seq the mouth holds and how long her trace is, so no clock // names a turn. A start that leaves neither changed re-sends its turns under the same ids, which the mouth answers as the // sends they already were. let stem = format!("s{}-n{}", deliveries.last().map_or(0, |delivery| delivery.seq), trace.len()); - if !aside.is_empty() { - let lines: Vec = aside.iter().map(|line| json!({ "room": line.room, "event": line.event })).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() })) { - eprintln!("mind-persona: the record of the lines set aside was not appended: {fault:#}"); - } - } // 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 { @@ -374,7 +368,15 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { } } }; - if rooms.is_empty() { + // A line set aside is recorded, then acked past before the room's turn, so that turn reads the room without it. + if !aside.is_empty() { + let lines: Vec = aside.iter().map(|line| json!({ "room": line.room, "event": line.event })).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() })) { + eprintln!("mind-persona: the record of the lines set aside was not appended: {fault:#}"); + } + } + if rooms.is_empty() || !aside.is_empty() { settle(&taken, &mut acked); } for (index, room) in rooms.iter().enumerate() { @@ -408,6 +410,12 @@ 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["held"] = json!(deliveries.iter().filter(|delivery| delivery.room_alias == **room).map(|delivery| delivery.event_id.as_str()).collect::>()); + // A failure that is no outage is a strike against the oldest line this turn was waking on, and no other. + if turn.record["failed"].as_str().is_some_and(|reason| !is_transient(reason)) + && let Some(line) = waking.iter().find(|line| line.room == *room) + { + turn.record["strike"] = json!(line.event); + } let mut put_refused = false; if turn.record.get("failed").is_none() && turn.state != state { match put_applied(start.persona.as_ref(), &state, &turn, &key, now, start.clock.as_ref()) { diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 86a8fae..ca1aecb 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -541,13 +541,63 @@ fn t_l2_an_outage_and_a_refusal_are_one_strike() { assert!(set_aside(&rig) && rig.held_seqs().is_empty(), "the second refusal is the second strike"); } +/// The outages are one list; every other reason, named or not, is a strike. #[test] -fn t_l2_only_the_lines_own_failures_are_strikes() { - use crate::projection::belongs_to_the_line as line_own; - for reason in ["the answer is not the speech contract", "the model's turn ended early: Refusal", "the model's turn ended early: ContextWindow", "the provider failed the call: InvalidRequest", "the provider failed the call: ResultSize"] { - assert!(line_own(reason), "{reason}"); +fn t_l2_the_outages_are_one_list_and_every_other_failure_is_a_strike() { + use crate::projection::is_transient; + for reason in ["the provider failed the call: RateLimited", "the provider failed the call: Unavailable", "the provider failed the call: Timeout", "the provider failed the call: Authentication", "the connector did not answer: x", "the connector refused the call: Y"] { + assert!(is_transient(reason), "{reason}"); } - for reason in ["the provider failed the call: RateLimited", "the provider failed the call: Unavailable", "the provider failed the call: Timeout", "the provider failed the call: Authentication", "the provider failed the call: Provider", "the connector did not answer: x", "the connector refused the call: Y", "something new"] { - assert!(!line_own(reason), "{reason}"); + for reason in [ + "the answer is not the speech contract", + "the model's turn ended early: Refusal", + "the model's turn ended early: ContextWindow", + "the model's turn ended early: MaxOutputTokens", + "the provider failed the call: InvalidRequest", + "the provider failed the call: ResultSize", + "the provider failed the call: Provider", + "the request is not a valid connector request", + "something nobody has named yet", + ] { + assert!(!is_transient(reason), "{reason}"); } } + +/// Soul's probe: a later line that shares the room with a poison line is not struck for it. +#[test] +fn t_l2_a_line_that_arrived_after_the_poison_line_is_not_set_aside_for_sharing_its_room() { + let rig = Rig::new(vec![line(1, &room(1), META, "FAILME one")]); + rig.run(failing(REFUSED)); + rig.mouth.held.borrow_mut().push(line(2, &room(1), META, "two")); + rig.run(failing(REFUSED)); + rig.run(failing(REFUSED)); + let aside: Vec = rig.trace.rows.borrow().iter().filter_map(|(_, record)| record.get("set_aside").cloned()).collect(); + assert_eq!(aside.len(), 1, "one set-aside record: {aside:?}"); + assert_eq!(aside[0][0]["event"], "$e1", "the poison line, and only it"); + assert_eq!(sends_to(&rig, &room(1)), 1, "start 3 answered the second line, which no longer reads the first"); + assert!(rig.held_seqs().is_empty()); +} + +/// A room of poison lines is peeled one at a time, two failed turns each, oldest first; a good line behind them is answered. +#[test] +fn t_l2_a_room_of_poison_lines_is_peeled_one_at_a_time_oldest_first() { + let rig = Rig::new(vec![line(1, &room(1), META, "FAILME one"), line(2, &room(1), META, "FAILME two"), line(3, &room(1), META, "FAILME three")]); + for _ in 0..7 { + rig.run(failing(REFUSED)); + } + let aside: Vec = rig.trace.rows.borrow().iter().filter_map(|(_, record)| record.get("set_aside").map(|lines| lines[0]["event"].clone())).collect(); + assert_eq!(aside, [json!("$e1"), json!("$e2"), json!("$e3")]); + assert_eq!(rig.trace.rows.borrow().iter().filter(|(_, record)| record.get("failed").is_some()).count(), 6, "two failed turns for each line, never more"); + assert!(rig.held_seqs().is_empty()); +} + +/// A failure nobody has named is a strike too: a room that fails for a reason of its own cannot hold the ack forever. +#[test] +fn t_l2_a_failure_nobody_named_cannot_hold_the_ack_forever() { + let rig = Rig::new(vec![line(1, &room(1), META, "FAILME one"), line(2, &room(2), META, "fine")]); + for _ in 0..3 { + rig.run(failing("her room could not be read")); + } + assert!(set_aside(&rig)); + assert!(rig.held_seqs().is_empty(), "the ack passed the line: {:?}", rig.held_seqs()); +} diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 9078f8d..f9084ba 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -47,7 +47,7 @@ use crate::heartbeat::HeartbeatView; pub use domain::{DomainFacts, DomainSource, HttpForge, MindDomain}; pub use narrate::{Answer, Continued, Failed, KitModel, Model, Reasoning, Spent, Turn, connector_key}; -pub(crate) use narrate::belongs_to_the_line; +pub(crate) use narrate::is_transient; pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource}; pub use select::TurnKind; pub(crate) use commit::apply as apply_commit; diff --git a/crates/mind-body/src/projection/narrate.rs b/crates/mind-body/src/projection/narrate.rs index d3da9fb..616cd3d 100644 --- a/crates/mind-body/src/projection/narrate.rs +++ b/crates/mind-body/src/projection/narrate.rs @@ -78,14 +78,15 @@ impl std::fmt::Display for Failed { } } -/// Whether a failed turn's reason (the `failed` of its record) belongs to the line it held: the model answered and the answer, or -/// the input, was the fault (an answer that is not the speech contract, a refusal, an over-long input or output). Transport, -/// connector, quota, timeout and unavailability are the body's, not the line's: that turn is retried, never counted. The -/// reasons are the ones this module and the Interpreter write; one not named here is the body's. -pub(crate) fn belongs_to_the_line(reason: &str) -> bool { - reason == "the answer is not the speech contract" - || ["Refusal", "ContextWindow", "MaxOutputTokens"].iter().any(|stop| reason == format!("the model's turn ended early: {stop}")) - || ["ResultSize", "InvalidRequest"].iter().any(|kind| reason == format!("the provider failed the call: {kind}")) +/// The failures that are outages: the turn's reason (the `failed` of its record) says no answer could be had, not that the +/// answer was bad. One list, and the only one: a turn that fails this way is retried on every start and never counts as a +/// strike against a line; every other reason, named anywhere or not at all, does. The reasons are the ones this module +/// writes: the connector did not answer or refused the call, or the provider failed the call with one of these kinds. +const OUTAGE_PREFIXES: [&str; 2] = ["the connector did not answer", "the connector refused the call"]; +const OUTAGE_KINDS: [&str; 4] = ["RateLimited", "Unavailable", "Timeout", "Authentication"]; + +pub(crate) fn is_transient(reason: &str) -> bool { + OUTAGE_PREFIXES.iter().any(|prefix| reason.starts_with(prefix)) || OUTAGE_KINDS.iter().any(|kind| reason == format!("the provider failed the call: {kind}")) } impl Failed {