Skip to content

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

fix(agent): no stale or unscrubbed slot errors; in-band 401 starts re-auth (#6724)

M3gA-Mind9047ac8b8395
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
index bb20a34b6a..162dd5f0f4 100644
--- a/crates/openhuman-core/src/agent/tinyagents/error_slot_model_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/error_slot_model_tests.rs
@@ -106,3 +106,45 @@ async fn an_invoke_error_fills_the_slot() {
.expect_err("scripted invoke fails");
assert!(slot_text(&slot).is_some_and(|text| text.contains(REJECTION)));
}
+
+#[tokio::test]
+async fn an_attempt_that_is_dropped_after_a_failed_one_leaves_no_stale_error() {
+ // In-band 503, then the retry hangs and the harness drops it on a call
+ // timeout: the 503 must not be re-surfaced as the cause.
+ let slot: ModelErrorSlot = Arc::new(Mutex::new(None));
+ let model = ErrorSlotModel::new(
+ Arc::new(ScriptedStreamModel(Mutex::new(vec![
+ ModelStreamItem::ProviderFailed(ProviderError {
+ status: Some(503),
+ ..rejection()
+ }),
+ ModelStreamItem::Completed(completed()),
+ ]))),
+ slot.clone(),
+ );
+ drain(&model).await;
+ assert!(slot_text(&slot).is_some());
+
+ let retry = model.stream(&(), ModelRequest::default()).await.unwrap();
+ drop(retry);
+ assert_eq!(slot_text(&slot), None, "a new attempt clears the old error");
+}
+
+#[tokio::test]
+async fn the_recorded_error_is_secret_scrubbed() {
+ // The slot's error reaches logs and Sentry via the run failure.
+ let slot: ModelErrorSlot = Arc::new(Mutex::new(None));
+ let model = ErrorSlotModel::new(
+ Arc::new(ScriptedStreamModel(Mutex::new(vec![
+ ModelStreamItem::ProviderFailed(ProviderError {
+ message: "bad key sk-live0123456789abcdefghij in request".to_string(),
+ ..rejection()
+ }),
+ ]))),
+ slot.clone(),
+ );
+ drain(&model).await;
+ let recorded = slot_text(&slot).expect("recorded");
+ assert!(!recorded.contains("sk-live0123456789"), "{recorded}");
+ assert!(recorded.contains("[REDACTED]"), "{recorded}");
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/model.rs b/crates/openhuman-core/src/agent/tinyagents/model.rs
index 7d11a91fd2..f9a7074347 100644
--- a/crates/openhuman-core/src/agent/tinyagents/model.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/model.rs
@@ -409,9 +409,12 @@ pub(crate) fn forward_provider_delta(tx: &UnboundedSender<ModelStreamItem>, delt
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).
+/// model call, so the runner re-surfaces the real failure instead of the
+/// harness's sanitized "hosted agent invocation failed" (#6724).
+///
+/// The slot is emptied when each attempt *starts*, not only when one succeeds:
+/// an attempt that is dropped (call timeout), cancelled, or ends without a
+/// terminal item must not leave the previous attempt's error behind.
///
/// Covers both an `Err` from `invoke`/`stream` and a failure reported *inside*
/// a stream (`ProviderFailed`, e.g. an HTTP 200 SSE `{"error":…}` payload).
@@ -434,12 +437,23 @@ fn store_model_error(slot: &ModelErrorSlot, error: Option<anyhow::Error>) {
.unwrap_or_else(std::sync::PoisonError::into_inner) = error;
}
+/// The slot's error flows into logs, Sentry and classification, and a provider
+/// message can echo request content, so it is secret-scrubbed and truncated
+/// here, once, before any of them sees it.
+fn slot_provider_error(error: &tinyinference_llm::model::ProviderError) -> anyhow::Error {
+ let mut error = error.clone();
+ error.message = tinyinference_core::sanitize::sanitize_api_error(&error.message);
+ error.raw = None;
+ anyhow::Error::new(tinyinference_llm::Error::Provider(Box::new(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}"),
+ tinyinference_llm::Error::Provider(provider_error) => slot_provider_error(provider_error),
+ other => anyhow::anyhow!(
+ "{}",
+ tinyinference_core::sanitize::sanitize_api_error(&other.to_string())
+ ),
}
}
@@ -458,6 +472,7 @@ impl ChatModel<()> for ErrorSlotModel {
state: &(),
request: ModelRequest,
) -> tinyinference_llm::Result<ModelResponse> {
+ store_model_error(&self.slot, None);
let result = self.inner.invoke(state, request).await;
store_model_error(&self.slot, result.as_ref().err().map(slot_error));
result
@@ -468,17 +483,15 @@ impl ChatModel<()> for ErrorSlotModel {
state: &(),
request: ModelRequest,
) -> tinyinference_llm::Result<ModelStream> {
+ store_model_error(&self.slot, None);
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::ProviderFailed(error) => {
+ store_model_error(&slot, Some(slot_provider_error(error)))
+ }
ModelStreamItem::Completed(_) => store_model_error(&slot, None),
_ => {}
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_run_error.rs b/crates/openhuman-core/src/agent/tinyagents/turn_run_error.rs
index 0b92cd550d..9cbbf3be24 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_run_error.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_run_error.rs
@@ -50,6 +50,21 @@ pub(super) async fn map_turn_run_error(
if let Some(depth_err) = tinyagents_depth_error(&e) {
return anyhow::Error::new(depth_err);
}
+ // A timeout or cancellation is the run's own failure, not a provider's: a
+ // provider error left in the slot by an earlier attempt must not be
+ // re-surfaced as its cause (#6724).
+ if matches!(
+ e,
+ tinyagents_harness::TinyAgentsError::Timeout(_)
+ | tinyagents_harness::TinyAgentsError::CallTimeout(_)
+ | tinyagents_harness::TinyAgentsError::Cancelled
+ ) {
+ error_slot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take();
+ return anyhow::anyhow!("tinyagents harness run failed: {e}");
+ }
// Otherwise prefer the original typed provider error (preserves
// `AgentError` downcasts the caller relies on) over the harness's
// string wrap — this is where a genuine model/provider failure that
@@ -70,3 +85,7 @@ pub(super) async fn map_turn_run_error(
}
anyhow::anyhow!("tinyagents harness run failed: {e}")
}
+
+#[cfg(test)]
+#[path = "turn_run_error_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_run_error_tests.rs b/crates/openhuman-core/src/agent/tinyagents/turn_run_error_tests.rs
new file mode 100644
index 0000000000..652b7beed3
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_run_error_tests.rs
@@ -0,0 +1,21 @@
+use super::*;
+
+#[tokio::test]
+async fn a_timeout_is_not_reported_as_a_provider_error_left_in_the_slot() {
+ // #6724: a provider error from an earlier attempt must not be re-surfaced
+ // as the cause of a run that timed out or was cancelled.
+ for error in [
+ tinyagents_harness::TinyAgentsError::CallTimeout("model call".to_string()),
+ tinyagents_harness::TinyAgentsError::Timeout("run".to_string()),
+ tinyagents_harness::TinyAgentsError::Cancelled,
+ ] {
+ let slot: ModelErrorSlot = std::sync::Arc::new(std::sync::Mutex::new(Some(
+ anyhow::anyhow!("OpenHuman returned HTTP 503: upstream unavailable"),
+ )));
+ let mapped = map_turn_run_error(error, "m", 10, &slot, None).await;
+ assert!(
+ !mapped.to_string().contains("503"),
+ "stale provider error re-surfaced: {mapped}"
+ );
+ }
+}
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 9f9c206fde..62ca57abd6 100644
--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs
+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs
@@ -525,17 +525,21 @@ fn maybe_publish_local_session_expiry() {
/// crate-native path bypasses.
fn maybe_publish_session_expired(err: &TiError, operation: &str) {
if let TiError::Provider(pe) = err {
- if pe.provider.as_str() == "OpenHuman" && matches!(pe.status, Some(401 | 403)) {
- let reason = tinyinference_core::sanitize::sanitize_api_error(&pe.message);
- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {
- source: format!(
- "openhuman_backend_model.{}({})",
- operation,
- pe.status.unwrap_or(0)
- ),
- reason,
- });
- }
+ maybe_publish_provider_session_expired(pe, operation);
+ }
+}
+
+fn maybe_publish_provider_session_expired(pe: &ProviderError, operation: &str) {
+ if pe.provider.as_str() == "OpenHuman" && matches!(pe.status, Some(401 | 403)) {
+ let reason = tinyinference_core::sanitize::sanitize_api_error(&pe.message);
+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {
+ source: format!(
+ "openhuman_backend_model.{}({})",
+ operation,
+ pe.status.unwrap_or(0)
+ ),
+ reason,
+ });
}
}
@@ -573,6 +577,15 @@ fn log_managed_provider_error(pe: &ProviderError, operation: &str) {
);
}
+/// Gives a failure reported inside a stream the same handling as a failed
+/// `stream()` call: logged, and an expired session starts re-authentication.
+fn observe_in_band_failure(item: &ModelStreamItem) {
+ if let ModelStreamItem::ProviderFailed(pe) = item {
+ log_managed_provider_error(pe, "stream (in-band)");
+ maybe_publish_provider_session_expired(pe, "stream");
+ }
+}
+
#[async_trait]
impl ChatModel<()> for OpenHumanBackendModel {
fn profile(&self) -> Option<&ModelProfile> {
@@ -630,9 +643,7 @@ impl ChatModel<()> for OpenHumanBackendModel {
// 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)");
- }
+ observe_in_band_failure(&item);
item
})),
Err(e) => {
diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs
index e958153bdf..dedd68f65a 100644
--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs
+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs
@@ -555,3 +555,42 @@ fn api_key_endpoint_is_bound_to_tinyhumans_or_loopback() {
"http://api.tinyhumans.ai/openai/v1"
));
}
+
+/// #6724 (review): a 401 reported *inside* a stream must start re-auth just
+/// like a failed `stream()` call does.
+#[tokio::test]
+async fn an_in_band_401_publishes_session_expired() {
+ use crate::core::events::DomainEvent;
+
+ crate::core::bus::init().await.expect("bus init");
+ let mut rx = crate::core::bus::BUS
+ .get()
+ .expect("event bus initialized")
+ .receiver();
+
+ observe_in_band_failure(&ModelStreamItem::ProviderFailed(ProviderError {
+ provider: PROVIDER_LABEL.to_string(),
+ status: Some(401),
+ message: "TEST_MARKER_IN_BAND token expired".to_string(),
+ ..ProviderError::default()
+ }));
+
+ let mut source_seen = None;
+ loop {
+ match rx.try_recv() {
+ Ok(DomainEvent::SessionExpired { source, reason })
+ if reason.contains("TEST_MARKER_IN_BAND") =>
+ {
+ source_seen = Some(source);
+ break;
+ }
+ Ok(_) | Err(tinybus::TryRecvError::Lagged(_)) => continue,
+ Err(_) => break,
+ }
+ }
+ assert_eq!(
+ source_seen.as_deref(),
+ Some("openhuman_backend_model.stream(401)"),
+ "an in-band 401 must publish SessionExpired"
+ );
+}