Skip to content

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

feat(agent): deliver background task results to the originating session

Steven Enamakeld5271492e112
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
index d6f6d38e21..dda2b82b47 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
@@ -1,30 +1,41 @@
//! Delivery subsystem for finished detached background sub-agents.
//!
-//! Surfaces results recorded in [`super::background_completions`] back into the
-//! originating chat as a single **system-injected** turn:
+//! Surfaces completions held by the harness `CompletionRouter`
+//! ([`super::background_completions`]) back into the originating chat as a
+//! single **system-injected** turn:
//! * **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,
-//! * **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.
+//! * **at-least-once** — a claimed batch stays leased until the turn has
+//! landed (`mark_delivered`); a failed turn releases it for the next drain,
+//! and a completion that was never delivered (a restart in between) is
+//! claimed again on boot ([`recover_on_boot`]),
+//! * **bounded** — the router counts attempts per record and returns the ones
+//! that gave up after [`DEFAULT_MAX_ATTEMPTS`] (`mark_failed`); a turn that
+//! can never succeed would otherwise retry forever, because a failed turn
+//! re-triggers this module,
+//! * **never silently lost** — a record that gave up is written into the
+//! thread verbatim, with an explicit notice that delivery failed and why.
+//!
+//! The queue, dedupe, tombstones and attempt counting are the router's. What
+//! stays here is the host policy: when a thread is idle, the delivery turn and
+//! the web_chat events, and the give-up writer.
//!
//! 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::{HashMap, HashSet};
+use std::collections::HashSet;
use std::future::Future;
+use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use async_trait::async_trait;
use serde_json::json;
+use tinyagents_tasks::{CompletionFormatter, CompletionRecord, CompletionRouter};
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
@@ -32,52 +43,14 @@ use tinybus::EventHandler;
use tinybus::SubscriptionHandle;
use super::background_completions;
+use super::completion_notice::build_undelivered_notice;
/// 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);
-}
+/// How long after boot a recovered, never-delivered completion waits before its
+/// delivery turn, so providers and the session store are up first.
+const RECOVERY_DELAY: Duration = Duration::from_secs(15);
/// Sessions with a user turn currently in flight — delivery defers while busy.
fn busy() -> &'static Mutex<HashSet<String>> {
@@ -85,17 +58,19 @@ fn busy() -> &'static Mutex<HashSet<String>> {
BUSY.get_or_init(|| Mutex::new(HashSet::new()))
}
-/// Sessions whose delivery turn is in flight — prevents two concurrent turns.
+/// Threads whose delivery turn is in flight — prevents two concurrent turns.
fn delivering() -> &'static Mutex<HashSet<String>> {
static D: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
D.get_or_init(|| Mutex::new(HashSet::new()))
}
-fn is_busy(session: &str) -> bool {
+/// Is any in-flight turn running on `thread_id`?
+fn is_busy(thread_id: &str) -> bool {
busy()
.lock()
.expect("background_delivery busy poisoned")
- .contains(session)
+ .iter()
+ .any(|session| background_completions::thread_for_session(session).as_deref() == Some(thread_id))
}
struct BackgroundDeliveryHandler;
@@ -117,13 +92,13 @@ impl EventHandler<DomainEvent> for BackgroundDeliveryHandler {
DomainEvent::AgentTurnCompleted { session_id, .. } => {
busy().lock().expect("busy poisoned").remove(session_id);
// A user turn just ended — drain anything that finished while it ran.
- schedule_delivery(session_id.clone(), Duration::from_millis(300));
+ schedule_for_session(session_id, Duration::from_millis(300));
}
DomainEvent::AgentError { session_id, .. } => {
// A failed turn may not emit AgentTurnCompleted — clear busy so
// delivery isn't stuck, then try to drain.
busy().lock().expect("busy poisoned").remove(session_id);
- schedule_delivery(session_id.clone(), Duration::from_millis(300));
+ schedule_for_session(session_id, Duration::from_millis(300));
}
// Any subagent terminal state — completed, failed, or awaiting-user —
// can arrive after the parent turn already went idle. Schedule a
@@ -136,66 +111,93 @@ impl EventHandler<DomainEvent> for BackgroundDeliveryHandler {
DomainEvent::SubagentCompleted { parent_session, .. }
| DomainEvent::SubagentFailed { parent_session, .. }
| DomainEvent::SubagentAwaitingUser { parent_session, .. } => {
- schedule_delivery(parent_session.clone(), DEBOUNCE);
+ schedule_for_session(parent_session, DEBOUNCE);
}
_ => {}
}
}
}
-/// Schedule a debounced delivery attempt for a session.
-fn schedule_delivery(session: String, delay: Duration) {
+/// Schedule a drain for the thread a session belongs to. A session that maps to
+/// no thread (cron, voice, skills) has nothing to deliver into.
+fn schedule_for_session(session_id: &str, delay: Duration) {
+ match background_completions::thread_for_session(session_id) {
+ Some(thread_id) => schedule_delivery(thread_id, delay),
+ None => log::trace!(
+ "[background_delivery] session has no delivery thread; not scheduling session={session_id}"
+ ),
+ }
+}
+
+/// Schedule a debounced delivery attempt for a thread.
+fn schedule_delivery(thread_id: String, delay: Duration) {
tokio::spawn(async move {
tokio::time::sleep(delay).await;
- try_deliver(session).await;
+ try_deliver(thread_id).await;
});
}
-/// Snapshot the ready batch for a session **right now** (sync, testable): if the
-/// session is idle, drain all ready results. Returns `None` (queue untouched)
-/// when busy or nothing is pending. Headless filtering + delivery happen in the
-/// caller, which can requeue the batch if the turn fails.
-fn plan_delivery(session: &str) -> Option<Vec<background_completions::CompletedBackgroundAgent>> {
- if is_busy(session) {
- return None;
- }
- let batch = background_completions::take_pending(session);
- if batch.is_empty() {
- None
- } else {
- Some(batch)
+/// Boot recovery: redeliver completions a previous process finished but never
+/// delivered. Each thread holding undelivered results gets one delivery attempt
+/// after [`RECOVERY_DELAY`], through the normal idle-gated path. Returns the
+/// number of threads scheduled.
+pub(crate) fn recover_on_boot(workspace_dir: &Path) -> usize {
+ let threads = background_completions::recover_pending_threads(workspace_dir);
+ let Ok(_runtime) = tokio::runtime::Handle::try_current() else {
+ log::warn!(
+ "[background_delivery] no async runtime at boot; {} thread(s) with undelivered \
+ completions will deliver on their next subagent event",
+ threads.len()
+ );
+ return 0;
+ };
+ for thread_id in &threads {
+ log::info!(
+ "[background_delivery] scheduling redelivery of undelivered completions after restart \
+ thread_id={thread_id}"
+ );
+ schedule_delivery(thread_id.clone(), RECOVERY_DELAY);
}
+ threads.len()
}
-/// Re-queue a drained batch (after a failed delivery) so it retries on the next
-/// idle drain rather than being lost.
-fn requeue(session: &str, batch: Vec<background_completions::CompletedBackgroundAgent>) {
- for c in batch {
- // Preserve the terminal outcome on requeue so a failed / awaiting-input
- // result isn't downgraded to a success when a delivery turn fails (#4896).
- background_completions::record_outcome(
- session,
- c.task_id,
- c.agent_id,
- c.summary,
- c.parent_thread_id,
- c.outcome,
- );
+/// Claim everything ready for a thread **right now** (sync, testable): `None`
+/// (queue untouched) when the thread is busy or nothing is pending. A claimed
+/// batch stays leased until the caller settles it with `mark_delivered` /
+/// `mark_failed` / `release`.
+fn claim_ready(router: &CompletionRouter, thread_id: &str) -> Option<Vec<CompletionRecord>> {
+ if is_busy(thread_id) {
+ return None;
+ }
+ match router.claim_pending(thread_id, usize::MAX) {
+ Ok(batch) if !batch.is_empty() => Some(batch),
+ Ok(_) => None,
+ Err(error) => {
+ log::error!(
+ "[background_delivery] claim failed thread_id={thread_id} error={error}"
+ );
+ None
+ }
}
}
-/// Drain + deliver pending completions for a session — if idle and not already
+/// Drain + deliver pending completions for a thread — if idle and not already
/// delivering. Batches everything ready at this instant into one system turn.
-async fn try_deliver(session: String) {
+async fn try_deliver(thread_id: String) {
+ let Some(router) = background_completions::router_for_thread(&thread_id) else {
+ log::debug!("[background_delivery] no router for thread_id={thread_id}");
+ return;
+ };
try_deliver_with(
- session,
+ thread_id,
+ router,
|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;
}
-/// Last resort when the delivery turn has failed [`MAX_DELIVERY_ATTEMPTS`]
+/// Last resort when the delivery turn has failed [`DEFAULT_MAX_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
@@ -233,19 +235,23 @@ async fn persist_undelivered(thread_id: String, notice: String) {
}
}
-/// 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)
-where
+/// Delivery-loop core with an injected router, turn executor and give-up
+/// sink. Keeping the queue and retry boundary independent from host execution
+/// lets tests prove a failed durable append releases the batch before any
+/// terminal announcement is observable, and that a record which exhausts its
+/// attempts is handed to `on_undeliverable` rather than dropped.
+async fn try_deliver_with<F, Fut, G, GFut>(
+ thread_id: String,
+ router: Arc<CompletionRouter>,
+ mut deliver: F,
+ on_undeliverable: G,
+) where
F: 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) {
+ if is_busy(&thread_id) {
return;
}
// Claim the delivery slot — held for the WHOLE delivery (including the
@@ -253,91 +259,79 @@ where
// turn on the same thread. Skip if a delivery is already in flight.
{
let mut d = delivering().lock().expect("delivering poisoned");
- if !d.insert(session.clone()) {
+ if !d.insert(thread_id.clone()) {
return;
}
}
- if let Some(batch) = plan_delivery(&session) {
- // A user turn can start (AgentTurnStarted -> busy) between plan_delivery's
- // gate and the awaited turn below. Re-check here so we don't stream a
- // *system* turn concurrently with a freshly-started user turn on the same
- // thread — requeue the drained batch and let the next idle drain retry.
- // (Narrows the window; a turn starting mid-await is still possible, but
- // both append into the thread and delivery is keyed to its own run id.)
- if is_busy(&session) {
- requeue(&session, batch);
- delivering()
- .lock()
- .expect("delivering poisoned")
- .remove(&session);
- return;
- }
- if let (Some(thread_id), Some(notice)) = (
- background_completions::batch_thread_id(&batch),
- background_completions::build_batched_notice(&batch),
- ) {
- log::info!(
- "[background_delivery] delivering {} batched background result(s) \
- session={session} thread_id={thread_id}",
- batch.len()
- );
- 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 {
+ // A busy thread defers *before* the claim: the claim counts a delivery
+ // attempt, and a user who keeps typing must not burn a record's budget.
+ if let Some(batch) = claim_ready(&router, &thread_id) {
+ let task_ids: Vec<String> = batch.iter().map(|c| c.task_id.clone()).collect();
+ let notice = router.formatter().format_batch(&batch);
+ log::info!(
+ "[background_delivery] delivering {} batched background result(s) thread_id={thread_id}",
+ batch.len()
+ );
+ match deliver(thread_id.clone(), notice).await {
+ Ok(_) => {
+ if let Err(error) = router.mark_delivered(&task_ids) {
+ // The reply is already in the thread; the record stays
+ // pending and is re-delivered after a restart (at-least-once).
+ log::error!(
+ "[background_delivery] delivered but could not settle records \
+ thread_id={thread_id} tasks=[{}] error={error}",
+ task_ids.join(",")
+ );
+ }
+ }
+ Err(e) => {
+ // 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 not lossy — the record is written
+ // into the thread rather than discarded. A checkout failure
+ // publishes no `AgentError`, so it cannot drive the self-retrigger
+ // loop on its own; it only ever spends the budget.
+ match router.mark_failed(&task_ids) {
+ Ok(gave_up) if !gave_up.is_empty() => {
// 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.
+ let attempts = gave_up.iter().map(|r| r.attempts).max().unwrap_or(0);
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
+ {attempts} attempts; writing {} result(s) into the thread \
+ instead thread_id={thread_id} tasks=[{}] error={e}",
+ gave_up.len(),
+ gave_up
.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)
+ if let Some(undelivered) = build_undelivered_notice(&gave_up, attempts, &e)
{
- on_undeliverable(thread_id, undelivered).await;
+ on_undeliverable(thread_id.clone(), undelivered).await;
}
- } else {
- log::warn!(
- "[background_delivery] delivery turn failed session={session} \
- attempt={attempt}/{MAX_DELIVERY_ATTEMPTS} error={e}"
+ }
+ Ok(_) => log::warn!(
+ "[background_delivery] delivery turn failed thread_id={thread_id} \
+ tasks=[{}] max_attempts={} error={e}",
+ task_ids.join(","),
+ router.max_attempts()
+ ),
+ Err(error) => {
+ log::error!(
+ "[background_delivery] could not record the failed delivery \
+ thread_id={thread_id} error={error}"
);
- requeue(&session, batch); // don't lose results on a failed turn
+ router.release(&task_ids);
}
}
}
- } else {
- log::warn!(
- "[background_delivery] dropping headless batch session={session} count={}",
- batch.len()
- );
}
}
@@ -345,12 +339,12 @@ where
delivering()
.lock()
.expect("delivering poisoned")
- .remove(&session);
+ .remove(&thread_id);
}
/// Run one system-authored delivery turn on an existing conversation thread.
/// It only delivers a detached sub-agent result already produced by
-/// `background_completions`.
+/// the completion router.
///
/// The turn runs on the thread's own session (`web_chat::run_system_turn_on_thread`),
/// never on a throwaway host: the model presents the result in the context of