Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(agent): re-surface in-stream provider failures past the hosted sanitizer (#6724)

M3gA-Mind3129347d8444
diff --git a/crates/openhuman-core/src/agent/tinyagents/error_slot_model_tests.rs b/crates/openhuman-core/src/agent/tinyagents/error_slot_model_tests.rs
new file mode 100644
index 0000000000..bb20a34b6a
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/error_slot_model_tests.rs
@@ -0,0 +1,108 @@
+//! #6724: `ErrorSlotModel` keeps the turn's error slot filled with the provider
+//! failure that ended a model call, including one reported inside a stream.
+use super::*;
+use futures::StreamExt;
+use tinyinference_llm::model::ProviderError;
+
+const REJECTION: &str = "Message at index 2 has role 'tool' but is not preceded by an \
+ assistant message with a matching tool_call";
+
+/// Streams one terminal item per call, in order; `invoke` fails with the
+/// same provider error.
+struct ScriptedStreamModel(Mutex<Vec<ModelStreamItem>>);
+
+fn completed() -> ModelResponse {
+ ModelResponse {
+ message: AssistantMessage {
+ id: None,
+ content: vec![ContentBlock::Text("ok".to_string())],
+ tool_calls: Vec::new(),
+ usage: None,
+ origin: None,
+ },
+ usage: None,
+ finish_reason: Some("stop".to_string()),
+ raw: None,
+ resolved_model: None,
+ continue_turn: None,
+ served_from_cache: false,
+ correlation: None,
+ resolved_route: None,
+ }
+}
+
+fn rejection() -> ProviderError {
+ ProviderError {
+ provider: "OpenHuman".to_string(),
+ status: Some(400),
+ message: REJECTION.to_string(),
+ ..ProviderError::default()
+ }
+}
+
+#[async_trait]
+impl ChatModel<()> for ScriptedStreamModel {
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ Err(tinyinference_llm::Error::Provider(Box::new(rejection())))
+ }
+
+ async fn stream(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelStream> {
+ let item = self.0.lock().unwrap().remove(0);
+ Ok(ModelStream::new(Box::pin(futures::stream::iter(vec![
+ item,
+ ]))))
+ }
+}
+
+async fn drain(model: &ErrorSlotModel) {
+ let mut stream = model.stream(&(), ModelRequest::default()).await.unwrap();
+ while stream.next().await.is_some() {}
+}
+
+fn slot_text(slot: &ModelErrorSlot) -> Option<String> {
+ slot.lock().unwrap().as_ref().map(|error| error.to_string())
+}
+
+#[tokio::test]
+async fn an_in_stream_provider_failure_fills_the_slot_and_a_later_success_clears_it() {
+ let slot: ModelErrorSlot = Arc::new(Mutex::new(None));
+ let model = ErrorSlotModel::new(
+ Arc::new(ScriptedStreamModel(Mutex::new(vec![
+ ModelStreamItem::ProviderFailed(rejection()),
+ ModelStreamItem::Completed(completed()),
+ ]))),
+ slot.clone(),
+ );
+
+ drain(&model).await;
+ let recorded = slot_text(&slot).expect("an in-stream failure is recorded");
+ assert!(recorded.contains(REJECTION), "{recorded}");
+ assert!(recorded.contains("HTTP 400"), "{recorded}");
+
+ // A retry or fallback that succeeds must not leave a stale failure behind
+ // for an unrelated later error to re-surface.
+ drain(&model).await;
+ assert_eq!(slot_text(&slot), None);
+}
+
+#[tokio::test]
+async fn an_invoke_error_fills_the_slot() {
+ let slot: ModelErrorSlot = Arc::new(Mutex::new(None));
+ let model = ErrorSlotModel::new(
+ Arc::new(ScriptedStreamModel(Mutex::new(Vec::new()))),
+ slot.clone(),
+ );
+ model
+ .invoke(&(), ModelRequest::default())
+ .await
+ .expect_err("scripted invoke fails");
+ assert!(slot_text(&slot).is_some_and(|text| text.contains(REJECTION)));
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/model.rs b/crates/openhuman-core/src/agent/tinyagents/model.rs
index c010be6024..7d11a91fd2 100644
--- a/crates/openhuman-core/src/agent/tinyagents/model.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/model.rs
@@ -408,6 +408,91 @@ pub(crate) fn forward_provider_delta(tx: &UnboundedSender<ModelStreamItem>, delt
/// the runner can re-surface the downcastable error after the run fails.
pub(super) type ModelErrorSlot = Arc<Mutex<Option<anyhow::Error>>>;
+/// Fills the turn's [`ModelErrorSlot`] with the provider failure that ended a
+/// model call, and empties it again when a later call succeeds, so the runner
+/// re-surfaces the real failure instead of the harness's sanitized
+/// "hosted agent invocation failed" (#6724).
+///
+/// Covers both an `Err` from `invoke`/`stream` and a failure reported *inside*
+/// a stream (`ProviderFailed`, e.g. an HTTP 200 SSE `{"error":…}` payload).
+/// The recorded error only feeds `web_errors` classification, which picks the
+/// user-facing copy; it is never rendered verbatim.
+pub(super) struct ErrorSlotModel {
+ inner: Arc<dyn ChatModel<()>>,
+ slot: ModelErrorSlot,
+}
+
+impl ErrorSlotModel {
+ pub(super) fn new(inner: Arc<dyn ChatModel<()>>, slot: ModelErrorSlot) -> Self {
+ Self { inner, slot }
+ }
+}
+
+fn store_model_error(slot: &ModelErrorSlot, error: Option<anyhow::Error>) {
+ *slot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = error;
+}
+
+fn slot_error(error: &tinyinference_llm::Error) -> anyhow::Error {
+ match error {
+ tinyinference_llm::Error::Provider(provider_error) => {
+ anyhow::Error::new(tinyinference_llm::Error::Provider(provider_error.clone()))
+ }
+ other => anyhow::anyhow!("{other}"),
+ }
+}
+
+#[async_trait]
+impl ChatModel<()> for ErrorSlotModel {
+ fn profile(&self) -> Option<&ModelProfile> {
+ self.inner.profile()
+ }
+
+ fn cache_identity(&self) -> Option<String> {
+ self.inner.cache_identity()
+ }
+
+ async fn invoke(
+ &self,
+ state: &(),
+ request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ let result = self.inner.invoke(state, request).await;
+ store_model_error(&self.slot, result.as_ref().err().map(slot_error));
+ result
+ }
+
+ async fn stream(
+ &self,
+ state: &(),
+ request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelStream> {
+ match self.inner.stream(state, request).await {
+ Ok(stream) => {
+ let slot = self.slot.clone();
+ Ok(stream.map_items(move |item| {
+ match &item {
+ ModelStreamItem::ProviderFailed(error) => store_model_error(
+ &slot,
+ Some(anyhow::Error::new(tinyinference_llm::Error::Provider(
+ Box::new(error.clone()),
+ ))),
+ ),
+ ModelStreamItem::Completed(_) => store_model_error(&slot, None),
+ _ => {}
+ }
+ item
+ }))
+ }
+ Err(error) => {
+ store_model_error(&self.slot, Some(slot_error(&error)));
+ Err(error)
+ }
+ }
+ }
+}
+
pub(super) struct MaxTokensModel {
inner: Arc<dyn ChatModel<()>>,
max_tokens: u32,
@@ -539,3 +624,7 @@ impl ChatModel<()> for MaxTokensModel {
#[cfg(test)]
#[path = "model_g1_usage_tests_tests.rs"]
mod g1_usage_tests;
+
+#[cfg(test)]
+#[path = "error_slot_model_tests.rs"]
+mod error_slot_model_tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
index 728c6b37e2..a72ae7f372 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
@@ -6,7 +6,7 @@ use std::sync::Arc;
use async_trait::async_trait;
use crate::agent::tinyagents::model::{
- BuiltTurnModels, ProfileOverrideModel, TierRoutes, TurnChatModel,
+ BuiltTurnModels, ErrorSlotModel, ProfileOverrideModel, TierRoutes, TurnChatModel,
};
use crate::agent::tinyagents::routes;
use tinyagents_harness::host::{ModelResolveRequest, ModelResolver};
@@ -291,11 +291,24 @@ fn build_turn_models_crate(
anyhow::Ok((primary, routes, summarizer))
})?;
+ // The primary and every tier route share one slot: a failure on one and a
+ // successful fallback on another must leave the slot empty.
+ let error_slot: crate::agent::tinyagents::model::ModelErrorSlot =
+ Arc::new(std::sync::Mutex::new(None));
+ let primary: TurnChatModel = Arc::new(ErrorSlotModel::new(primary, error_slot.clone()));
+ let routes = routes
+ .into_iter()
+ .map(|(tier, route)| {
+ let route: TurnChatModel = Arc::new(ErrorSlotModel::new(route, error_slot.clone()));
+ (tier, route)
+ })
+ .collect();
+
Ok(TurnModels {
primary,
routes,
summarizer,
- error_slot: Arc::new(std::sync::Mutex::new(None)),
+ error_slot,
provider_id,
context_window,
native_tools,
@@ -482,16 +495,21 @@ impl TurnModelSource {
let native_tools = profile.tool_calling;
let supports_vision = profile.modalities.image_in;
let context_window = context_window.or(profile.max_input_tokens);
- let primary: TurnChatModel = Arc::new(
- ProfileOverrideModel::new(direct.clone(), profile)
- .with_request_model(model)
- .with_request_temperature(temperature),
- );
+ let error_slot: crate::agent::tinyagents::model::ModelErrorSlot =
+ Arc::new(std::sync::Mutex::new(None));
+ let primary: TurnChatModel = Arc::new(ErrorSlotModel::new(
+ Arc::new(
+ ProfileOverrideModel::new(direct.clone(), profile)
+ .with_request_model(model)
+ .with_request_temperature(temperature),
+ ),
+ error_slot.clone(),
+ ));
return Ok(TurnModels {
primary,
routes: Vec::new(),
summarizer: direct.clone(),
- error_slot: Arc::new(std::sync::Mutex::new(None)),
+ error_slot,
provider_id,
context_window,
native_tools,
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner_tests.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner_tests.rs
index e850abea77..3c72091b1a 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner_tests.rs
@@ -223,3 +223,79 @@ async fn a_streamed_delta_reaches_the_progress_channel_exactly_once() {
"the deferring seam must emit no TurnCompleted — the caller owns it"
);
}
+
+/// A model whose every stream ends in a provider failure reported inside the
+/// stream, the shape of an HTTP 200 SSE `{"error":{"code":400,…}}` (#6724).
+struct InStreamRejectionModel;
+
+const IN_STREAM_REJECTION: &str = "Message at index 2 has role 'tool' but is not preceded \
+ by an assistant message with a matching tool_call";
+
+#[async_trait::async_trait]
+impl tinyinference_llm::model::ChatModel<()> for InStreamRejectionModel {
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: tinyinference_llm::model::ModelRequest,
+ ) -> tinyinference_llm::Result<tinyinference_llm::model::ModelResponse> {
+ unreachable!("the hosted root streams")
+ }
+
+ async fn stream(
+ &self,
+ _state: &(),
+ _request: tinyinference_llm::model::ModelRequest,
+ ) -> tinyinference_llm::Result<tinyinference_llm::model::ModelStream> {
+ let failure = tinyinference_llm::model::ProviderError {
+ provider: "OpenHuman".to_string(),
+ status: Some(400),
+ message: IN_STREAM_REJECTION.to_string(),
+ retryable: false,
+ ..Default::default()
+ };
+ Ok(tinyinference_llm::model::ModelStream::new(Box::pin(
+ futures::stream::iter(vec![
+ tinyinference_llm::model::ModelStreamItem::ProviderFailed(failure),
+ ]),
+ )))
+ }
+}
+
+/// The harness sanitizes a failed stream to "hosted agent invocation failed";
+/// the turn's error slot must carry the real provider failure past it so
+/// `web_errors` can classify it (#6724).
+#[tokio::test]
+async fn an_in_stream_provider_failure_is_re_surfaced_past_the_hosted_sanitizer() {
+ let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> = Arc::new(InStreamRejectionModel);
+ let models = TurnModelSource::from_model(model)
+ .build("root-test-model", 0.0, None, None)
+ .expect("turn models build");
+ let (tx, _rx) = tokio::sync::mpsc::channel(8);
+ let error = run_root_turn_via_hosted_agent(
+ root_context("in-stream", "/tmp/in-stream", tx),
+ hosted_base(),
+ "main".to_string(),
+ models,
+ "test".to_string(),
+ "root-test-model",
+ root_messages("in-stream"),
+ vec![Arc::new(Vec::new())],
+ Some(Default::default()),
+ 2,
+ None,
+ None,
+ &[],
+ false,
+ None,
+ TurnContextMiddleware::default(),
+ None,
+ true,
+ )
+ .await
+ .expect_err("the provider rejected the request");
+ let text = error.to_string();
+ assert!(
+ text.contains(IN_STREAM_REJECTION),
+ "the run failure must be the provider's, not the sanitized one: {text}"
+ );
+}
diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs
index 3237007c91..9f9c206fde 100644
--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs
+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs
@@ -30,7 +30,8 @@ use std::time::Duration;
use tinyinference_llm::message::Message;
use tinyinference_llm::model::{
- ChatModel, Modalities, ModelProfile, ModelRequest, ModelResponse, ModelStream, ProviderError,
+ ChatModel, Modalities, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
+ ProviderError,
};
use tinyinference_llm::providers::openai::OpenAiModel;
use tinyinference_llm::Error as TiError;
@@ -549,16 +550,7 @@ fn maybe_publish_session_expired(err: &TiError, operation: &str) {
/// by [`sanitize_api_error`] before it's logged — no tokens, no full PII.
fn log_managed_dispatch_error(err: &TiError, operation: &str) {
match err {
- TiError::Provider(pe) => {
- log::warn!(
- "[providers][openhuman-backend] managed {operation} failed: status={:?} code={:?} provider={} retryable={} detail={}",
- pe.status,
- pe.code,
- pe.provider,
- pe.retryable,
- tinyinference_core::sanitize::sanitize_api_error(&pe.message),
- );
- }
+ TiError::Provider(pe) => log_managed_provider_error(pe, operation),
other => {
log::warn!(
"[providers][openhuman-backend] managed {operation} failed (non-provider error): {}",
@@ -568,6 +560,19 @@ fn log_managed_dispatch_error(err: &TiError, operation: &str) {
}
}
+/// Logs a structured provider failure; the detail is secret-scrubbed and
+/// truncated because a provider error can echo request content.
+fn log_managed_provider_error(pe: &ProviderError, operation: &str) {
+ log::warn!(
+ "[providers][openhuman-backend] managed {operation} failed: status={:?} code={:?} provider={} retryable={} detail={}",
+ pe.status,
+ pe.code,
+ pe.provider,
+ pe.retryable,
+ tinyinference_core::sanitize::sanitize_api_error(&pe.message),
+ );
+}
+
#[async_trait]
impl ChatModel<()> for OpenHumanBackendModel {
fn profile(&self) -> Option<&ModelProfile> {
@@ -622,7 +627,14 @@ impl ChatModel<()> for OpenHumanBackendModel {
.stream(state, with_thread_id(request, self.thread_id.as_deref()))
.await
{
- Ok(stream) => Ok(stream),
+ // A failure can also arrive *inside* an HTTP 200 stream as an SSE
+ // `{"error":…}` payload; it never reaches the `Err` arm (#6724).
+ Ok(stream) => Ok(stream.map_items(|item| {
+ if let ModelStreamItem::ProviderFailed(pe) = &item {
+ log_managed_provider_error(pe, "stream (in-band)");
+ }
+ item
+ })),
Err(e) => {
log_managed_dispatch_error(&e, "stream");
maybe_publish_session_expired(&e, "stream");
diff --git a/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rs b/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rs
index 26462d5f8d..f8df65933c 100644
--- a/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rs
+++ b/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rs
@@ -88,12 +88,18 @@ pub(crate) fn is_provider_request_rejected_text(lower: &str) -> bool {
// `inference::provider::ops::api_error`). Matching a bare "400"/"404"
// anywhere would misclassify unrelated errors that merely contain those
// digits (token counts, byte offsets, timestamps). Per CodeRabbit review
- // on PR #3199.
+ // on PR #3199. The `returned http 4xx` forms are tinyinference's
+ // `ProviderError` Display (`<provider> returned HTTP 400: …`), which is
+ // how a failure reported inside a stream reaches classification (#6724).
const PROVIDER_4XX_MARKERS: &[&str] = &[
"api error (400",
"api error (404",
"api error (409",
"api error (422",
+ "returned http 400",
+ "returned http 404",
+ "returned http 409",
+ "returned http 422",
];
PROVIDER_4XX_MARKERS
.iter()
diff --git a/crates/openhuman-core/src/web_chat/web_tests_error_code_classification_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_error_code_classification_tests.rs
index beeedb98fa..04418747d5 100644
--- a/crates/openhuman-core/src/web_chat/web_tests_error_code_classification_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests_error_code_classification_tests.rs
@@ -608,3 +608,26 @@ fn fingerprint_identical_inputs_are_cache_hit() {
"identical fingerprints must compare equal (cache hit)"
);
}
+
+#[test]
+fn classify_inference_error_in_stream_tool_history_rejection_uses_malformed_history_copy() {
+ // #6724: a provider failure delivered inside an HTTP 200 stream reaches
+ // classification as the session driver wraps the re-surfaced
+ // `ProviderError`, whose status comes from the stream's numeric `code`
+ // (tinyinference#37). It must land on the purpose-built canned copy, and
+ // the raw provider text must not be shown.
+ let raw = "driver failed: OpenHuman returned HTTP 400: Message at index 2 has role 'tool' \
+ but is not preceded by an assistant message with a matching tool_call";
+ let classified = classify_inference_error(raw);
+ assert_eq!(classified.error_type, "provider_request_rejected");
+ assert!(
+ classified.message.contains("we've cleared it"),
+ "{}",
+ classified.message
+ );
+ assert!(
+ !classified.message.contains("index 2"),
+ "{}",
+ classified.message
+ );
+}