The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(agent): stop the background-delivery retry storm without losing results
M3gA-Mindd7260b521616
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions.rs b/crates/openhuman-core/src/agent/orchestration/background_completions.rsindex 754db05ea0..5ce4725a32 100644--- a/crates/openhuman-core/src/agent/orchestration/background_completions.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_completions.rs@@ -376,6 +376,15 @@ pub(crate) fn build_batched_notice(completed: &[CompletedBackgroundAgent]) -> Optagged with its sub-agent process id.]\n",if n == 1 { "" } else { "s" },));+ out.push_str(&render_results(completed));+ Some(out)+}++/// Render each result with its outcome-specific tag. Shared by the normal+/// delivery notice and by the undelivered fallback, so a result reads the same+/// either way and a failure is never dressed up as a completion.+fn render_results(completed: &[CompletedBackgroundAgent]) -> String {+ let mut out = String::new();for c in completed {// Distinct tag per terminal outcome so a failure / awaiting-input result// is not presented as a normal completion (#4896).@@ -402,6 +411,39 @@ pub(crate) fn build_batched_notice(completed: &[CompletedBackgroundAgent]) -> Opc.task_id, c.agent_id, summary,));}+ out+}++/// Build the notice written **straight into the thread** when the delivery turn+/// has failed too many times to keep retrying.+///+/// Delivery normally runs a system turn so the agent can present a result in+/// context. When that turn cannot succeed, the results still exist and the user+/// is still owed them — so they are persisted verbatim instead, with an+/// `[BACKGROUND_DELIVERY_FAILED]` envelope saying plainly that this is a failed+/// delivery and why. The envelope follows the `[SUBAGENT_FAILED]` precedent+/// (#4896): the user learns the delegated work finished and could not be+/// delivered normally, rather than the result vanishing or arriving as an+/// unexplained raw dump.+pub(crate) fn build_undelivered_notice(+ completed: &[CompletedBackgroundAgent],+ attempts: u32,+ error: &str,+) -> Option<String> {+ if completed.is_empty() {+ return None;+ }+ let n = completed.len();+ let mut out = format!(+ "[BACKGROUND_DELIVERY_FAILED] {n} background sub-agent result{} finished, but \+ could not be delivered into this conversation after {attempts} attempts. \+ Last error: {error}\n\nThe {} shown verbatim below so nothing is lost — it has \+ not been reviewed or summarised, because the turn that would have done so is \+ the thing that failed.\n",+ if n == 1 { "" } else { "s" },+ if n == 1 { "result is" } else { "results are" },+ );+ out.push_str(&render_results(completed));Some(out)}diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rsindex 5b342490e2..1e29f3a097 100644--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs@@ -5,14 +5,20 @@//! * **idle-gated** — never mid-turn; defers while a user turn is in flight,//! * **debounced** — a burst of completions batches into one turn,//! * **batched** — every result ready at delivery time goes in one turn,-//! each tagged by its sub-agent process id.+//! each tagged by its sub-agent process id,+//! * **bounded** — a failed turn requeues its batch, but only+//! [`MAX_DELIVERY_ATTEMPTS`] times; a turn that can never succeed would+//! otherwise retry forever, because a failed turn re-triggers this module,+//! * **never silently lost** — once the retries are spent the results are+//! written into the thread verbatim, with an explicit notice that delivery+//! failed and why, instead of being discarded.//!//! The delivery turn runs on the originating thread's own chat session//! (`web_chat::run_system_turn_on_thread`) so it sees the conversation and//! appends to the thread's transcript. It persists its reply before announcing//! `chat_done`, so a reconnect cannot lose a completed delegated result.-use std::collections::HashSet;+use std::collections::{HashMap, HashSet};use std::future::Future;use std::sync::{Arc, Mutex, OnceLock};use std::time::Duration;@@ -30,6 +36,49 @@ use super::background_completions;/// Coalesce completions landing within this window into one delivery turn.const DEBOUNCE: Duration = Duration::from_secs(3);+/// Upper bound on consecutive failed delivery turns for one session before the+/// loop stops retrying and writes the results into the thread instead.+///+/// The requeue below exists so a *transient* failure doesn't lose a result+/// (#4896), but on its own it is unbounded — and this module re-triggers+/// itself: a failed delivery turn publishes `DomainEvent::AgentError`, which+/// our own handler turns straight back into a scheduled drain 300 ms later.+/// Against a turn that can *never* succeed (refused inference, expired+/// session, revoked integration, backend outage) that is a self-sustaining+/// loop, not a retry. Observed in production 2026-09-21: 178 delivery attempts+/// per minute against a single thread, 4,389 in one day, and a 432 MB log.+///+/// Five attempts keeps the transient case working. Past that the retries stop,+/// but the results are **not** discarded: they are handed to the give-up sink,+/// which persists them into the thread with an explicit failed-delivery notice.+/// Ending the storm must not cost the user the result that caused it.+const MAX_DELIVERY_ATTEMPTS: u32 = 5;++/// Consecutive failed delivery turns per session. Cleared on a delivered batch+/// and once a batch has been handed to the give-up sink, so the budget tracks a+/// single failure chain and a later batch always starts fresh.+fn attempts() -> &'static Mutex<HashMap<String, u32>> {+ static A: OnceLock<Mutex<HashMap<String, u32>>> = OnceLock::new();+ A.get_or_init(|| Mutex::new(HashMap::new()))+}++/// Record a failed delivery turn; returns the new consecutive-failure count.+fn note_failed_attempt(session: &str) -> u32 {+ let mut a = attempts().lock().expect("delivery attempts poisoned");+ let n = a.entry(session.to_string()).or_insert(0);+ *n += 1;+ *n+}++/// Reset a session's failure budget — on a delivered batch, or once a batch has+/// been handed to the give-up sink and the chain is over.+fn clear_attempts(session: &str) {+ attempts()+ .lock()+ .expect("delivery attempts poisoned")+ .remove(session);+}+/// Sessions with a user turn currently in flight — delivery defers while busy.fn busy() -> &'static Mutex<HashSet<String>> {static BUSY: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();@@ -138,19 +187,63 @@ fn requeue(session: &str, batch: Vec<background_completions::CompletedBackground/// Drain + deliver pending completions for a session — if idle and not already/// delivering. Batches everything ready at this instant into one system turn.async fn try_deliver(session: String) {- try_deliver_with(session, |thread_id, notice| async move {- run_system_turn_on_thread(thread_id, notice).await- })+ try_deliver_with(+ session,+ |thread_id, notice| async move { run_system_turn_on_thread(thread_id, notice).await },+ |thread_id, notice| async move { persist_undelivered(thread_id, notice).await },+ ).await;}-/// Delivery-loop core with an injected turn executor. Keeping the queue and-/// retry boundary independent from host execution lets tests prove a failed-/// durable append is requeued before any terminal announcement is observable.-async fn try_deliver_with<F, Fut>(session: String, mut deliver: F)+/// Last resort when the delivery turn has failed [`MAX_DELIVERY_ATTEMPTS`]+/// times: append the results to the thread directly, with no model turn.+///+/// This is the whole point of the ceiling — retries stop, but the user is still+/// told. If even this append fails there is nowhere left to put the result, so+/// it is logged at error and the chain ends; that is the one path on which a+/// result is genuinely lost, and it requires the conversation store to be+/// failing as well as the agent.+async fn persist_undelivered(thread_id: String, notice: String) {+ let run_id = format!("bgdeliver-undelivered-{}", uuid::Uuid::new_v4());+ let config = match crate::config::Config::load_or_init().await {+ Ok(config) => config,+ Err(error) => {+ log::error!(+ "[background_delivery] undelivered results LOST — could not load config to \+ persist them thread_id={thread_id} run_id={run_id} error={error:#}"+ );+ return;+ }+ };+ match persist_delivery_reply(+ config.workspace_dir.clone(),+ &thread_id,+ &run_id,+ notice,+ false,+ ) {+ Ok(()) => log::warn!(+ "[background_delivery] delivery turn gave up; wrote results into the thread \+ verbatim instead thread_id={thread_id} run_id={run_id}"+ ),+ Err(error) => log::error!(+ "[background_delivery] undelivered results LOST — could not append them to the \+ thread thread_id={thread_id} run_id={run_id} error={error}"+ ),+ }+}++/// Delivery-loop core with an injected turn executor and an injected+/// give-up sink. Keeping the queue and retry boundary independent from host+/// execution lets tests prove a failed durable append is requeued before any+/// terminal announcement is observable, and that a batch which exhausts its+/// retries is handed to `on_undeliverable` rather than dropped.+async fn try_deliver_with<F, Fut, G, GFut>(session: String, mut deliver: F, on_undeliverable: G)whereF: FnMut(String, String) -> Fut,Fut: Future<Output = Result<String, String>>,+ G: FnOnce(String, String) -> GFut,+ GFut: Future<Output = ()>,{if is_busy(&session) || !background_completions::has_pending(&session) {return;@@ -189,11 +282,56 @@ wheresession={session} thread_id={thread_id}",batch.len());- if let Err(e) = deliver(thread_id, notice).await {- log::warn!(- "[background_delivery] delivery turn failed session={session} error={e}"- );- requeue(&session, batch); // don't lose results on a failed turn+ match deliver(thread_id.clone(), notice).await {+ Ok(_) => clear_attempts(&session),+ Err(e) => {+ // Count only a failed *turn*. The busy re-check above also+ // requeues, but that is a deferral, not a failure — letting+ // it burn the budget would drop results just because the+ // user kept typing.+ //+ // A `SESSION_CHECKOUT_FAILURE`-prefixed error (the session+ // could not be checked out, so no turn ran at all) counts+ // the same as a turn that ran and failed. That is+ // deliberate: the budget measures "the result was not+ // delivered", which is equally true either way, and giving+ // up is no longer lossy — the batch is written into the+ // thread rather than discarded. Note a checkout failure+ // publishes no `AgentError`, so it cannot drive the+ // self-retrigger loop on its own; it only ever spends the+ // budget, never extends it.+ let attempt = note_failed_attempt(&session);+ if attempt >= MAX_DELIVERY_ATTEMPTS {+ // Stop retrying, but do NOT drop: the results exist and+ // the user is owed them. Hand them to the give-up sink,+ // which writes them into the thread verbatim along with+ // an explicit statement that delivery failed and why.+ log::warn!(+ "[background_delivery] giving up on the delivery turn after \+ {attempt} consecutive failures; writing {} result(s) into the \+ thread instead session={session} thread_id={thread_id} \+ tasks=[{}] error={e}",+ batch.len(),+ batch+ .iter()+ .map(|c| c.task_id.as_str())+ .collect::<Vec<_>>()+ .join(","),+ );+ clear_attempts(&session);+ if let Some(undelivered) =+ background_completions::build_undelivered_notice(&batch, attempt, &e)+ {+ on_undeliverable(thread_id, undelivered).await;+ }+ } else {+ log::warn!(+ "[background_delivery] delivery turn failed session={session} \+ attempt={attempt}/{MAX_DELIVERY_ATTEMPTS} error={e}"+ );+ requeue(&session, batch); // don't lose results on a failed turn+ }+ }}} else {log::warn!(diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rsindex 9b57a0405b..a1224e2d2e 100644--- a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs@@ -1,5 +1,6 @@use super::*;use crate::agent::orchestration::background_completions::record_completion;+use std::sync::atomic::{AtomicU32, Ordering};#[test]fn plan_drains_ready_batch_when_idle() {@@ -71,16 +72,20 @@ async fn persistence_failure_requeues_batch_without_terminal_announcement() {let announced = Arc::new(AtomicBool::new(false));let announced_for_delivery = Arc::clone(&announced);- try_deliver_with(session.to_string(), move |_thread_id, _notice| {- let announced = Arc::clone(&announced_for_delivery);- async move {- persist_then_announce(- Ok("delivery reply".to_string()),- |_content, _success| Err("append failed".to_string()),- |_| announced.store(true, Ordering::SeqCst),- )- }- })+ try_deliver_with(+ session.to_string(),+ move |_thread_id, _notice| {+ let announced = Arc::clone(&announced_for_delivery);+ async move {+ persist_then_announce(+ Ok("delivery reply".to_string()),+ |_content, _success| Err("append failed".to_string()),+ |_| announced.store(true, Ordering::SeqCst),+ )+ }+ },+ |_thread_id, _notice| async move { unreachable!("one failure must not exhaust retries") },+ ).await;assert!(@@ -147,6 +152,206 @@ async fn handler_tracks_busy_across_turn_and_error_events() {assert!(!is_busy(&sid));}+/// Drive the real delivery loop with a turn executor that always fails, the+/// way a refused inference call / expired session / revoked integration does.+/// Returns the number of delivery turns that actually ran, and whatever the+/// give-up sink was handed (`None` if it was never reached).+async fn drain_until_empty_or(session: &str, cap: u32) -> (u32, Option<String>) {+ let turns = Arc::new(AtomicU32::new(0));+ let undelivered: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));+ for _ in 0..cap {+ if !background_completions::has_pending(session) {+ break;+ }+ let turns_for_delivery = Arc::clone(&turns);+ let sink = Arc::clone(&undelivered);+ try_deliver_with(+ session.to_string(),+ move |_thread_id, _notice| {+ let turns = Arc::clone(&turns_for_delivery);+ async move {+ turns.fetch_add(1, Ordering::SeqCst);+ Err::<String, String>("hosted agent invocation failed".to_string())+ }+ },+ move |_thread_id, notice| async move {+ *sink.lock().expect("sink") = Some(notice);+ },+ )+ .await;+ }+ let captured = undelivered.lock().expect("sink").clone();+ (turns.load(Ordering::SeqCst), captured)+}++#[tokio::test]+async fn permanently_failing_delivery_stops_instead_of_requeueing_forever() {+ // STORM-0922: a failed delivery turn publishes AgentError, which this+ // module's own handler turns back into a scheduled drain — so an unbounded+ // requeue against a turn that can never succeed is a closed loop. In+ // production it ran 178 attempts/minute against one thread for hours.+ // Drive far past the ceiling: the queue must drain itself and STOP.+ let session = "bd-storm-permanent-failure";+ record_completion(session, "sub-1", "researcher", "alpha", Some("t".into()));+ record_completion(session, "sub-2", "researcher", "beta", Some("t".into()));++ let (turns, undelivered) = drain_until_empty_or(session, MAX_DELIVERY_ATTEMPTS * 20).await;++ assert!(+ !background_completions::has_pending(session),+ "a permanently failing delivery turn must stop requeueing its batch; the queue is \+ still pending after {turns} turns, so the retry loop never terminates"+ );+ assert_eq!(+ turns, MAX_DELIVERY_ATTEMPTS,+ "the batch must be retried exactly MAX_DELIVERY_ATTEMPTS times before giving up; \+ a count of 0 would mean the injected turn never ran and this test proved nothing"+ );+ assert!(+ undelivered.is_some(),+ "giving up must hand the batch to the give-up sink, never discard it"+ );+}++#[tokio::test]+async fn results_that_cannot_be_delivered_are_written_to_the_thread_and_say_so() {+ // The headline behaviour: the storm stops AND nothing is silently lost.+ // A user whose background task finished must be told it finished and that+ // delivery failed — not left with silence, and not handed a raw dump that+ // reads as if it were a normal reply.+ let session = "bd-storm-undelivered-notice";+ record_completion(+ session,+ "sub-7",+ "researcher",+ "the migration plan is ready",+ Some("thread-42".into()),+ );++ let (turns, undelivered) = drain_until_empty_or(session, MAX_DELIVERY_ATTEMPTS * 20).await;+ assert_eq!(turns, MAX_DELIVERY_ATTEMPTS, "sanity: the turns did run");++ let notice = undelivered.expect(+ "a batch that exhausted its delivery retries must reach the give-up sink so it can \+ be written into the thread; None means the result was silently lost",+ );+ assert!(+ notice.contains("[BACKGROUND_DELIVERY_FAILED]"),+ "the persisted notice must declare itself a failed delivery, not pose as a normal \+ reply; got: {notice}"+ );+ assert!(+ notice.contains("hosted agent invocation failed"),+ "the notice must name WHY delivery failed — an error the user cannot see is barely \+ better than silence; got: {notice}"+ );+ assert!(+ notice.contains("the migration plan is ready"),+ "the notice must carry the result that was actually received, verbatim; got: {notice}"+ );+ assert!(+ notice.contains("sub-7"),+ "the notice must tag which sub-agent produced the result; got: {notice}"+ );+}++#[tokio::test]+async fn transient_failure_under_the_ceiling_still_requeues() {+ // The ceiling must not undo #4896: a single failed turn keeps the result.+ let session = "bd-storm-transient";+ record_completion(session, "sub-1", "researcher", "alpha", Some("t".into()));++ try_deliver_with(+ session.to_string(),+ |_thread_id, _notice| async move { Err::<String, String>("blip".to_string()) },+ |_thread_id, _notice| async move {+ unreachable!("a single failure must not reach the give-up sink")+ },+ )+ .await;++ assert!(+ background_completions::has_pending(session),+ "one failed delivery turn must requeue the batch, not drop it (#4896)"+ );+ let _ = background_completions::take_pending(session);+ clear_attempts(session);+}++#[tokio::test]+async fn busy_deferral_does_not_consume_the_failure_budget() {+ // The busy re-check requeues too, but that is a deferral, not a failure.+ // If it burned an attempt, a user who keeps typing would lose results.+ let session = "bd-storm-busy-deferral";+ record_completion(session, "sub-1", "researcher", "alpha", Some("t".into()));++ for _ in 0..(MAX_DELIVERY_ATTEMPTS * 2) {+ busy().lock().expect("busy").insert(session.to_string());+ try_deliver_with(+ session.to_string(),+ |_thread_id, _notice| async move {+ unreachable!("must not run a delivery turn while the session is busy")+ },+ |_thread_id, _notice| async move {+ unreachable!("a busy deferral must never reach the give-up sink")+ },+ )+ .await;+ busy().lock().expect("busy").remove(session);+ }++ assert!(+ background_completions::has_pending(session),+ "deferring while busy must never drop the batch, however often it repeats"+ );+ assert_eq!(+ attempts()+ .lock()+ .expect("attempts")+ .get(session)+ .copied()+ .unwrap_or(0),+ 0,+ "a busy deferral must not count as a failed delivery attempt"+ );+ let _ = background_completions::take_pending(session);+ clear_attempts(session);+}++#[tokio::test]+async fn a_delivered_batch_restores_the_full_failure_budget() {+ // Failure chains are consecutive: a session that recovers must not carry+ // old failures toward the ceiling and drop a later, unrelated batch early.+ let session = "bd-storm-budget-reset";+ for _ in 0..(MAX_DELIVERY_ATTEMPTS - 1) {+ record_completion(session, "sub-f", "researcher", "x", Some("t".into()));+ try_deliver_with(+ session.to_string(),+ |_thread_id, _notice| async move { Err::<String, String>("blip".to_string()) },+ |_thread_id, _notice| async move { unreachable!("must not give up below the ceiling") },+ )+ .await;+ }+ // A turn finally succeeds.+ try_deliver_with(+ session.to_string(),+ |_thread_id, _notice| async move { Ok::<String, String>("delivered".to_string()) },+ |_thread_id, _notice| async move { unreachable!("a success must not give up") },+ )+ .await;+ assert!(!background_completions::has_pending(session));++ // A later batch must get the whole budget again, not one attempt.+ record_completion(session, "sub-later", "researcher", "y", Some("t".into()));+ let (turns, _) = drain_until_empty_or(session, MAX_DELIVERY_ATTEMPTS * 20).await;+ assert_eq!(+ turns, MAX_DELIVERY_ATTEMPTS,+ "a successful delivery must reset the budget so a later batch gets all \+ MAX_DELIVERY_ATTEMPTS tries"+ );+ clear_attempts(session);+}+#[tokio::test(start_paused = true)]async fn every_subagent_terminal_event_schedules_a_drain() {// #4896 regression: EVERY subagent terminal event must schedule a drain