diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index 17cb6a7..77d621b 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::{is_transient, DomainSource, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, history, own_addressee as heard_as, take}; +use crate::projection::{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"; @@ -284,7 +284,7 @@ fn done_events(records: &[Value]) -> BTreeSet<&str> { done } -/// How many strikes her trace charges `event`: a failed turn that was not an outage (`is_transient`) charged one to the +/// How many strikes her trace charges `event`: a failed turn that was not an outage (the connector's typed kind, `Failed::outage`) 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["strike"] == event).count() @@ -425,8 +425,13 @@ 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 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. + if let Some(fault) = turn.report.get("error") { + return failed("the turn could not be set up", anyhow!("{}", fault.as_str().unwrap_or_default())); + } // 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)) + if turn.record.get("failed").is_some() && turn.record["outage"] != true && let Some(line) = waking.iter().find(|line| line.room == *room) { turn.record["strike"] = json!(line.event); diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 7a237fd..99fbd3a 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -165,7 +165,7 @@ struct Flaky { impl Model for Flaky { fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { if prompt.contains(self.marker) { - return Err(Failed { reason: self.reason.into(), usage: None }); + return Err(Failed { reason: self.reason.into(), outage: self.reason == OUTAGE, usage: None }); } self.inner.ask(request_id, model, prompt, schema) } @@ -566,26 +566,33 @@ 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. +/// A turn is an outage by the typed kind the failure carries, not by what its reason reads like: a connector refusal of the +/// request itself (`PayloadBound`, `Malformed`, `ModelNotAllowed`) is the line's, and two of them set it aside. #[test] -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 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}"); +fn t_l2_a_connector_refusal_of_the_request_is_a_strike_whatever_its_reason_reads_like() { + let rig = Rig::new(vec![line(1, &room(1), META, "FAILME hello")]); + rig.run(failing("the connector refused the call: PayloadBound")); + assert!(!set_aside(&rig) && rig.held_seqs() == [1], "one strike so far"); + rig.run(failing("the connector refused the call: Malformed")); + assert!(!set_aside(&rig) && rig.held_seqs() == [1], "two strikes, set aside by the next start"); + rig.run(failing(OUTAGE)); + assert!(set_aside(&rig) && rig.held_seqs().is_empty(), "the third start sets it aside"); +} + +/// A tuning file that cannot be read is the body's fault, not a member's line: the start fails loudly on it, sets nothing +/// aside however many starts it lasts, and answers the line once the file is mended. +#[test] +fn t_l2_a_bad_tuning_file_fails_the_start_and_strikes_no_line() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + std::fs::write(rig.dir.path().join("persona-tuning.toml"), "this is = not [valid").unwrap(); + for _ in 0..4 { + assert!(matches!(rig.run(scripted(false)), Outcome::Failed(why) if why.contains("could not be set up"))); } + assert!(!set_aside(&rig) && rig.held_seqs() == [1] && rig.mouth.sent.borrow().is_empty(), "nothing set aside, acked or sent"); + assert!(rig.trace.rows.borrow().iter().all(|(_, record)| record.get("strike").is_none()), "no strike was charged"); + std::fs::remove_file(rig.dir.path().join("persona-tuning.toml")).unwrap(); + rig.run(scripted(false)); + assert_eq!(sends_to(&rig, &room(1)), 1, "mended, she answers it"); } /// The model refusing a turn whose input holds the poison line. Her being told of a line set aside quotes it, which is not @@ -595,7 +602,7 @@ struct RefusesThePoisonLine(Scripted); impl Model for RefusesThePoisonLine { fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { if prompt.contains("FAILME") && !prompt.contains("so it was set aside") { - return Err(Failed { reason: REFUSED.into(), usage: None }); + return Err(Failed { reason: REFUSED.into(), outage: false, usage: None }); } self.0.ask(request_id, model, prompt, schema) } diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 8f2d244..4af9bce 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -47,7 +47,6 @@ 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::is_transient; pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource}; pub use select::TurnKind; pub(crate) use commit::apply as apply_commit; @@ -425,7 +424,7 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni let wake_id = wake_id(instance, tag, packet.seed); let answer = match model.ask(&call_id(&wake_id, "projector", 0), &tuning.projector.model, &projector_prompt(packet, tuning), None) { Ok(answer) => answer, - Err(failed) => return json!({ "seed": packet.seed, "lens": packet.lens, "selected": ids, "failed": failed.reason, "usage": failed.usage }), + Err(failed) => return json!({ "seed": packet.seed, "lens": packet.lens, "selected": ids, "failed": failed.reason, "outage": failed.outage, "usage": failed.usage }), }; let raw = answer.text; let budget = word_budget(packet.kind, tuning); @@ -450,7 +449,7 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni let first = match model.converse(&call_id(&wake_id, "persona", 0), &tuning.persona.model, &turns) { Ok(spoke) => spoke, Err(failed) => { - render["persona"] = json!({ "failed": failed.reason, "usage": failed.usage }); + render["persona"] = json!({ "failed": failed.reason, "outage": failed.outage, "usage": failed.usage }); return render; } }; diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index 24aa4a1..ea24ea7 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -83,7 +83,7 @@ impl Model for Replaying<'_> { fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { self.ids.borrow_mut().push(request_id.to_owned()); if let Some((sent, answer)) = self.bound.borrow().get(request_id) { - return if sent == prompt { Ok(answer.clone()) } else { Err(Failed { reason: "the connector refused the call: ReplayConflict".into(), usage: None }) }; + return if sent == prompt { Ok(answer.clone()) } else { Err(Failed { reason: "the connector refused the call: ReplayConflict".into(), outage: false, usage: None }) }; } let answer = self.inner.ask(request_id, model, prompt, schema)?; self.bound.borrow_mut().insert(request_id.to_owned(), (prompt.to_owned(), answer.clone())); diff --git a/crates/mind-body/src/projection/interpret.rs b/crates/mind-body/src/projection/interpret.rs index 44706b3..e2d8756 100644 --- a/crates/mind-body/src/projection/interpret.rs +++ b/crates/mind-body/src/projection/interpret.rs @@ -629,7 +629,7 @@ pub(crate) fn decide_in(model: &dyn Model, segment_id: &str, packet: &Packet, na // A failed call names why, as the connector said it (K66): a turn cut at the output cap reads "the model's // turn ended early: MaxOutputTokens". calls.push(json!({ "usage": failed.usage, "retry": false, "failed": failed.reason })); - return json!({ "failed": failed.reason, "calls": calls, "retried": retried }); + return json!({ "failed": failed.reason, "outage": failed.outage, "calls": calls, "retried": retried }); } }; match serde_json::from_str::(&answer.text) { diff --git a/crates/mind-body/src/projection/interpret/tests.rs b/crates/mind-body/src/projection/interpret/tests.rs index d6f2fff..2fe4d2f 100644 --- a/crates/mind-body/src/projection/interpret/tests.rs +++ b/crates/mind-body/src/projection/interpret/tests.rs @@ -1734,7 +1734,7 @@ struct CutAtCap; impl crate::projection::Model for CutAtCap { fn ask(&self, _request_id: &str, model: &str, _prompt: &str, _schema: Option<&str>) -> std::result::Result { - Err(crate::projection::Failed { reason: "the model's turn ended early: MaxOutputTokens".into(), usage: Some(crate::projection::Spent { model: model.into(), input_tokens: 8, output_tokens: 4096, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) }) + Err(crate::projection::Failed { reason: "the model's turn ended early: MaxOutputTokens".into(), outage: false, usage: Some(crate::projection::Spent { model: model.into(), input_tokens: 8, output_tokens: 4096, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) }) } } @@ -2141,7 +2141,7 @@ struct FailsTheRetry(Scripted); impl Model for FailsTheRetry { fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> Result { if prompt.contains("notes in an earlier answer to this were refused") { - return Err(crate::projection::Failed { reason: "the model's turn ended early: MaxOutputTokens".into(), usage: None }); + return Err(crate::projection::Failed { reason: "the model's turn ended early: MaxOutputTokens".into(), outage: false, usage: None }); } self.0.ask(request_id, model, prompt, schema) } diff --git a/crates/mind-body/src/projection/narrate.rs b/crates/mind-body/src/projection/narrate.rs index 616cd3d..087977a 100644 --- a/crates/mind-body/src/projection/narrate.rs +++ b/crates/mind-body/src/projection/narrate.rs @@ -12,7 +12,7 @@ use std::time::Duration; use anyhow::{Result, anyhow, bail}; use chrono::Utc; use ghostlight_persona_projection::{PersonaPrompt, build_persona_prompt}; -use model_connector::{ConnectorClient, InputItem, ProviderRequest, ReasoningEffort, StopReason, TransportDisposition, TransportEventPayload, TransportInvocation, TransportOutcome}; +use model_connector::{ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, ReasoningEffort, Refusal, StopReason, TransportDisposition, TransportEventPayload, TransportInvocation, TransportOutcome}; use serde::Serialize; use sha2::{Digest, Sha256}; @@ -69,6 +69,10 @@ pub struct Continued { #[derive(Clone, Debug, PartialEq, Eq)] pub struct Failed { pub reason: String, + /// No answer could be had, by the connector's typed kind (`client_outage`, `refusal_outage`, `failure_outage`): not that the + /// request or the answer was bad. A turn that fails this way is retried on every start and charges no line a strike; every + /// other failure, set wherever it is made or not at all, is a strike. + pub outage: bool, pub usage: Option, } @@ -78,20 +82,33 @@ impl std::fmt::Display for Failed { } } -/// 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"]; +/// The failures that are outages, by the connector's own typed kinds, each match naming every variant so a kind the connector adds +/// is a compile error here, not a silent default. The deterministic ones (the request or its answer is what the connector +/// refused, or its own frame bound) are strikes against the line, as is every failure that names no kind. +pub(crate) fn client_outage(fault: &ConnectorClientError) -> bool { + match fault { + ConnectorClientError::Connection(_) | ConnectorClientError::Transport(_) => true, + ConnectorClientError::InvalidConfig | ConnectorClientError::FrameSize | ConnectorClientError::RequestIdTooLong => false, + } +} -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}")) +pub(crate) fn refusal_outage(refusal: &Refusal) -> bool { + match refusal { + Refusal::Expired | Refusal::Capacity | Refusal::InFlight | Refusal::Indeterminate | Refusal::ProviderRejected => true, + Refusal::IdentitySubstitution | Refusal::ProviderDigestSubstitution | Refusal::ModelNotAllowed | Refusal::OutputBound | Refusal::PayloadBound | Refusal::ReplayConflict | Refusal::Malformed | Refusal::ForeignReasoningState => false, + } +} + +pub(crate) fn failure_outage(kind: &FailureKind) -> bool { + match kind { + FailureKind::RateLimited | FailureKind::Unavailable | FailureKind::Timeout | FailureKind::Authentication => true, + FailureKind::ResultSize | FailureKind::InvalidRequest | FailureKind::Provider => false, + } } impl Failed { fn without_usage(reason: impl Into) -> Self { - Self { reason: reason.into(), usage: None } + Self { reason: reason.into(), outage: false, usage: None } } } @@ -169,9 +186,9 @@ impl KitModel { request.reasoning_effort = Some(ReasoningEffort::Low); let expires = u64::try_from(Utc::now().timestamp_millis()).unwrap_or_default() + INVOCATION_LIFE_MS; let invocation = TransportInvocation::new(&self.caller, expires, Sha256::digest(&native).into(), request).map_err(|_| Failed::without_usage("the request is not a valid connector request"))?; - let result = self.client.execute(&invocation).map_err(|fault| Failed::without_usage(format!("the connector did not answer: {fault}")))?; + let result = self.client.execute(&invocation).map_err(|fault| Failed { reason: format!("the connector did not answer: {fault}"), outage: client_outage(&fault), usage: None })?; match result.disposition { - TransportDisposition::Refused(reason) => Err(Failed::without_usage(format!("the connector refused the call: {reason:?}"))), + TransportDisposition::Refused(reason) => Err(Failed { reason: format!("the connector refused the call: {reason:?}"), outage: refusal_outage(&reason), usage: None }), TransportDisposition::Transported { events, receipt } => match receipt.outcome { TransportOutcome::Completed { stop_reason: StopReason::EndTurn, usage, .. } => { let (mut text, mut states) = (String::new(), Vec::new()); @@ -184,8 +201,8 @@ impl KitModel { } Ok(Continued { answer: Answer { text, usage: Some(spent(model, &usage)) }, states }) } - TransportOutcome::Completed { stop_reason, usage, .. } => Err(Failed { reason: format!("the model's turn ended early: {stop_reason:?}"), usage: Some(spent(model, &usage)) }), - TransportOutcome::Failed { kind, usage, .. } => Err(Failed { reason: format!("the provider failed the call: {kind:?}"), usage: usage.as_ref().map(|usage| spent(model, usage)) }), + TransportOutcome::Completed { stop_reason, usage, .. } => Err(Failed { reason: format!("the model's turn ended early: {stop_reason:?}"), outage: false, usage: Some(spent(model, &usage)) }), + TransportOutcome::Failed { kind, usage, .. } => Err(Failed { reason: format!("the provider failed the call: {kind:?}"), outage: failure_outage(&kind), usage: usage.as_ref().map(|usage| spent(model, usage)) }), }, } } diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 73a82db..8c659b0 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -251,7 +251,7 @@ impl Model for FailingPersona { if prompt.starts_with(PROJECTOR_OPENING) { Ok(Answer { text: "The room is slow.".into(), usage: None }) } else { - Err(Failed { reason: "the provider failed the call: Overloaded".into(), usage: Some(Spent { model: model.into(), input_tokens: 5, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) }) + Err(Failed { reason: "the provider failed the call: Overloaded".into(), outage: false, usage: Some(Spent { model: model.into(), input_tokens: 5, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) }) } } } @@ -940,7 +940,7 @@ impl Model for X5Model { fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { if self.failing && self.failed.get() == 0 && is_libby_speech(prompt) && prompt.contains(X5_HEIMDALL) { self.failed.set(1); - return Err(Failed { reason: "the provider failed the call: Provider".into(), usage: Some(Spent { model: model.into(), input_tokens: 8, output_tokens: 4096, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) }); + return Err(Failed { reason: "the provider failed the call: Provider".into(), outage: false, usage: Some(Spent { model: model.into(), input_tokens: 8, output_tokens: 4096, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) }); } self.inner.ask(request_id, model, prompt, schema) } @@ -1050,7 +1050,7 @@ says = "Tobiah, what changed in GameCult/Lodur#12?" impl Model for BreaksLater<'_> { fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { if prompt.starts_with(crate::projection::interpret::SPEECH_OPENING) && prompt.contains("Earlier in his moment") { - return Err(Failed { reason: "the provider failed the call: Provider".into(), usage: None }); + return Err(Failed { reason: "the provider failed the call: Provider".into(), outage: false, usage: None }); } self.0.ask(request_id, model, prompt, schema) } diff --git a/crates/mind-body/src/projection/tests.rs b/crates/mind-body/src/projection/tests.rs index 66afa51..a2a324a 100644 --- a/crates/mind-body/src/projection/tests.rs +++ b/crates/mind-body/src/projection/tests.rs @@ -1244,6 +1244,49 @@ fn a_kit_refusal_or_a_cut_short_turn_is_a_fault() { } } +/// The outage is the connector's typed kind: a refusal of the request itself, over a real kit, is not one. +#[test] +fn a_kit_refusal_of_the_request_is_no_outage_and_a_provider_failure_is_by_its_kind() { + let (model, _root) = kit(Scripted::ending(StopReason::EndTurn, &["x"]), "some-other-model"); + let refused = model.ask("id-r1", KIT_MODEL, "p", None).unwrap_err(); + assert!(refused.reason.contains("ModelNotAllowed") && !refused.outage, "{refused:?}"); + for (kind, outage) in [(model_connector::FailureKind::Unavailable, true), (model_connector::FailureKind::RateLimited, true), (model_connector::FailureKind::InvalidRequest, false), (model_connector::FailureKind::ResultSize, false)] { + let backend = Arc::new(Scripted { outcome: TransportOutcome::Failed { kind, message: "failed".into(), usage: None }, words: vec![], seen: Mutex::default() }); + let (model, _root) = kit(backend, KIT_MODEL); + let failed = model.ask("id-r2", KIT_MODEL, "p", None).unwrap_err(); + assert_eq!(failed.outage, outage, "{kind:?}: {failed:?}"); + } +} + +/// A connector that cannot be reached is an outage. +#[test] +fn an_unreachable_connector_is_an_outage() { + let free = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap(); + let model = KitModel::open(free, KIT_KEY.into(), INSTANCE, Duration::from_secs(1)).unwrap(); + let failed = model.ask("id-r3", KIT_MODEL, "p", None).unwrap_err(); + assert!(failed.reason.starts_with("the connector did not answer") && failed.outage, "{failed:?}"); +} + +/// Every kind the connector names, by its own type: the deterministic refusals and the frame bound are the line's. +#[test] +fn the_connectors_kinds_split_into_outages_and_the_lines_own_faults() { + use model_connector::{ConnectorClientError, FailureKind, Refusal}; + let refusals = [ + (Refusal::Expired, true), (Refusal::Capacity, true), (Refusal::InFlight, true), (Refusal::Indeterminate, true), (Refusal::ProviderRejected, true), + (Refusal::PayloadBound, false), (Refusal::OutputBound, false), (Refusal::Malformed, false), (Refusal::ModelNotAllowed, false), (Refusal::ReplayConflict, false), + (Refusal::IdentitySubstitution, false), (Refusal::ProviderDigestSubstitution, false), (Refusal::ForeignReasoningState, false), + ]; + for (refusal, outage) in refusals { + assert_eq!(super::narrate::refusal_outage(&refusal), outage, "{refusal:?}"); + } + let failures = [(FailureKind::RateLimited, true), (FailureKind::Unavailable, true), (FailureKind::Timeout, true), (FailureKind::Authentication, true), (FailureKind::ResultSize, false), (FailureKind::InvalidRequest, false), (FailureKind::Provider, false)]; + for (kind, outage) in failures { + assert_eq!(super::narrate::failure_outage(&kind), outage, "{kind:?}"); + } + assert!(super::narrate::client_outage(&ConnectorClientError::Connection(std::io::Error::other("down")))); + assert!(!super::narrate::client_outage(&ConnectorClientError::FrameSize) && !super::narrate::client_outage(&ConnectorClientError::RequestIdTooLong)); +} + #[test] fn the_kit_must_be_loopback_and_no_error_carries_the_key() { let key = "zq7Kx-9wVtm3Pd"; @@ -1639,8 +1682,8 @@ fn a_failed_call_keeps_the_report_and_its_usage() { self.0.set(self.0.get() + 1); let usage = Some(Spent { model: model.into(), input_tokens: 100, output_tokens: 20, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }); match self.0.get() { - 3 => Err(Failed { reason: "the model's turn ended early: MaxOutputTokens".into(), usage }), - 5 => Err(Failed { reason: "the connector did not answer".into(), usage: None }), + 3 => Err(Failed { reason: "the model's turn ended early: MaxOutputTokens".into(), outage: false, usage }), + 5 => Err(Failed { reason: "the connector did not answer".into(), outage: true, usage: None }), _ => Ok(Answer { text: if prompt.starts_with(PROJECTOR_OPENING) { "I am here. The room is quiet.".into() } else { "A".into() }, usage }), } } diff --git a/crates/mind-body/src/projection/turn.rs b/crates/mind-body/src/projection/turn.rs index 03f3214..18dbb54 100644 --- a/crates/mind-body/src/projection/turn.rs +++ b/crates/mind-body/src/projection/turn.rs @@ -79,9 +79,14 @@ pub(crate) struct Taken { pub(crate) fn take(organs: &Organs, request: &Request, actuator: &dyn Actuator, key: &str, now: DateTime) -> Taken { let report = project(organs, request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") })); let render = &report["renders"][0]; - let failed = report.get("error").or_else(|| render.get("failed")).or_else(|| render["persona"].get("failed")).or_else(|| render["interpreter"].get("failed")).map(|fault| fault.as_str().unwrap_or_default().to_owned()); + // Which stage's failure ended the turn, and whether the connector's typed kind made it an outage. A `project` error is no stage's: + // it is the setup that is wrong (her tuning, her own id), and is no outage either. + let stage = [render, &render["persona"], &render["interpreter"]].into_iter().find(|part| part.get("failed").is_some()); + let failed = report.get("error").or_else(|| stage.map(|part| &part["failed"])).map(|fault| fault.as_str().unwrap_or_default().to_owned()); + let outage = report.get("error").is_none() && stage.is_some_and(|part| part["outage"] == true); let here = request.room.clone().unwrap_or_default(); let mut record = match &failed { + Some(failed) if outage => json!({ "failed": failed, "outage": true }), Some(failed) => json!({ "failed": failed }), None => { // What she says is the Interpreter's decision alone. diff --git a/crates/mind-body/src/projection/turn/tests.rs b/crates/mind-body/src/projection/turn/tests.rs index 29078be..a2ed4cf 100644 --- a/crates/mind-body/src/projection/turn/tests.rs +++ b/crates/mind-body/src/projection/turn/tests.rs @@ -125,7 +125,7 @@ struct FailingPersona; impl Model for FailingPersona { fn ask(&self, _request_id: &str, _model: &str, prompt: &str, _schema: Option<&str>) -> std::result::Result { - if prompt.starts_with(PROJECTOR_OPENING) { Ok(Answer { text: "The room is slow.".into(), usage: None }) } else { Err(Failed { reason: "the provider failed the call: Overloaded".into(), usage: None }) } + if prompt.starts_with(PROJECTOR_OPENING) { Ok(Answer { text: "The room is slow.".into(), usage: None }) } else { Err(Failed { reason: "the provider failed the call: Overloaded".into(), outage: false, usage: None }) } } }