Skip to content

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

feat(orchestration): drain queued deliveries while the agent is busy

Steven Enamakele0106c8e218c
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
index 67a9ab06d4..1e16c07651 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
@@ -251,15 +251,18 @@ fn schedule_delivery_inner(thread_id: String, delay: Duration, wait_idle: bool,
// Scoped: the thread -> workspace table is keyed per profile, so the
// delayed task must run under the profile that scheduled it.
crate::core::runtime::spawn_scoped(async move {
+ // Inside the owner's scope: the context this drain acts for.
+ let ctx = crate::core::runtime::DispatchCtx::ambient();
let turn_fence = fence.clone();
let turn_thread = thread_id.clone();
let outcome = run_drain(
+ &ctx,
&thread_id,
delay,
wait_idle,
&fence,
RECOVERY_BUSY_POLL,
- || try_deliver(turn_thread, turn_fence),
+ || try_deliver(ctx.clone(), turn_thread, turn_fence),
)
.await;
if outcome == DrainOutcome::StillBusy {
@@ -337,8 +340,12 @@ pub(crate) fn recover_on_open(workspace_dir: &Path, fence: DrainFence) -> usize
/// (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) {
+fn claim_ready(
+ ctx: &crate::core::runtime::DispatchCtx,
+ router: &CompletionRouter,
+ thread_id: &str,
+) -> Option<Vec<CompletionRecord>> {
+ if is_busy(ctx, thread_id) {
return None;
}
match router.claim_pending(thread_id, usize::MAX) {
@@ -353,7 +360,11 @@ fn claim_ready(router: &CompletionRouter, thread_id: &str) -> Option<Vec<Complet
/// 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(thread_id: String, fence: DrainFence) {
+async fn try_deliver(
+ busy_ctx: crate::core::runtime::DispatchCtx,
+ thread_id: String,
+ fence: DrainFence,
+) {
if !fence.admits() {
log::info!(
"[background_delivery] profile lease lost; not delivering thread_id={thread_id}"
@@ -369,6 +380,7 @@ async fn try_deliver(thread_id: String, fence: DrainFence) {
// A drain is event-driven and carries no context of its own.
let ctx = crate::core::runtime::DispatchCtx::host_default();
let retry_after = try_deliver_with(
+ &busy_ctx,
thread_id.clone(),
router,
move |thread_id, notice| {
@@ -400,11 +412,13 @@ async fn try_deliver(thread_id: String, fence: DrainFence) {
/// outside this module.
#[cfg(test)]
pub(super) async fn try_deliver_for_test(
+ ctx: &crate::core::runtime::DispatchCtx,
thread_id: String,
router: Arc<CompletionRouter>,
turns: Arc<std::sync::atomic::AtomicU32>,
) -> Option<Duration> {
try_deliver_with(
+ ctx,
thread_id,
router,
move |_, _| {
@@ -449,6 +463,7 @@ async fn persist_undelivered(workspace_dir: PathBuf, thread_id: String, notice:
/// 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>(
+ ctx: &crate::core::runtime::DispatchCtx,
thread_id: String,
router: Arc<CompletionRouter>,
mut deliver: F,
@@ -461,7 +476,7 @@ where
GFut: Future<Output = ()>,
{
let mut retry_after = None;
- if is_busy(&thread_id) {
+ if is_busy(ctx, &thread_id) {
return None;
}
// Claim the delivery slot — held for the WHOLE delivery (including the
@@ -469,19 +484,19 @@ where
// turn on the same thread. Skip if a delivery is already in flight. The
// guard frees the slot, and any lease still held, even if this future is
// dropped mid-turn.
- let mut slot = DeliverySlot::claim(&thread_id, router.clone())?;
+ let mut slot = DeliverySlot::claim(ctx, &thread_id, router.clone())?;
// 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) {
+ if let Some(batch) = claim_ready(ctx, &router, &thread_id) {
let task_ids: Vec<String> = batch.iter().map(|c| c.task_id.clone()).collect();
slot.hold(&task_ids);
// A user turn can start between the idle check inside `claim_ready` and
// the awaited turn below; re-check so a system turn is never streamed
// concurrently with it. Dropping the slot releases the lease (the claim
// already counted one attempt; this window is narrow).
- if is_busy(&thread_id) {
- log::debug!(
+ if is_busy(ctx, &thread_id) {
+ log::debug!
"[background_delivery] thread became busy after the claim; deferring \
thread_id={thread_id}"
);
@@ -593,8 +608,8 @@ struct DeliverySlot {
impl DeliverySlot {
/// `None` when a delivery is already in flight for the thread.
- fn claim(thread_id: &str, router: Arc<CompletionRouter>) -> Option<Self> {
- let key = tenant::profile_key(thread_id);
+ fn claim(ctx: &crate::core::runtime::DispatchCtx, thread_id: &str, router: Arc<CompletionRouter>) -> Option<Self> {
+ let key = tenant::profile_key_in(&super::busy_guard::caller(ctx), thread_id);
let mut d = delivering().lock().expect("delivering poisoned");
if !d.insert(key.clone()) {
return None;
diff --git a/crates/openhuman-core/src/agent/orchestration/busy_guard.rs b/crates/openhuman-core/src/agent/orchestration/busy_guard.rs
index 02feb723e0..5f31e0a976 100644
--- a/crates/openhuman-core/src/agent/orchestration/busy_guard.rs
+++ b/crates/openhuman-core/src/agent/orchestration/busy_guard.rs
@@ -20,8 +20,8 @@ pub(super) fn busy() -> &'static Mutex<HashMap<String, HashSet<u64>>> {
}
/// The calling task's profile, as the tenant its busy/slot keys carry.
-pub(super) fn caller() -> Tenant {
- tenant::current_tenant_or_isolated("background_delivery").profile_only()
+pub(super) fn caller(ctx: &crate::core::runtime::DispatchCtx) -> Tenant {
+ tenant::isolated_unless_tenant(ctx.tenant(), "background_delivery").profile_only()
}
/// The session id of a busy key, when the key belongs to `me`.
@@ -40,9 +40,9 @@ pub(crate) struct TurnBusy {
}
impl TurnBusy {
- pub(crate) fn start(session_id: &str) -> Self {
+ pub(crate) fn start(ctx: &crate::core::runtime::DispatchCtx, session_id: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
- let key = tenant::profile_key(session_id);
+ let key = tenant::profile_key_in(&caller(ctx), session_id);
let id = NEXT.fetch_add(1, Ordering::Relaxed);
busy()
.lock()
@@ -57,8 +57,8 @@ impl TurnBusy {
/// not map to its thread: a relayed channel turn runs under the channel
/// pipeline's own session id, which [`background_completions`] never
/// learns, so marking that session would leave the thread looking idle.
- pub(crate) fn start_on_thread(thread_id: &str) -> Self {
- Self::start(&format!("{THREAD_MARK}{thread_id}"))
+ pub(crate) fn start_on_thread(ctx: &crate::core::runtime::DispatchCtx, thread_id: &str) -> Self {
+ Self::start(ctx, &format!("{THREAD_MARK}{thread_id}"))
}
}
@@ -88,8 +88,8 @@ impl Drop for TurnBusy {
}
/// Is any in-flight turn of the calling profile running on `thread_id`?
-pub(crate) fn is_busy(thread_id: &str) -> bool {
- let me = caller();
+pub(crate) fn is_busy(ctx: &crate::core::runtime::DispatchCtx, thread_id: &str) -> bool {
+ let me = caller(ctx);
busy()
.lock()
.expect("background_delivery busy poisoned")
@@ -103,8 +103,8 @@ pub(crate) fn is_busy(thread_id: &str) -> bool {
/// or `AgentError`, and its session would otherwise stay "busy" and defer this
/// thread's deliveries until restart. Another profile's turn on a thread with
/// the same id is left alone. Returns how many sessions were cleared.
-pub(crate) fn clear_busy_for_thread(thread_id: &str) -> usize {
- let me = caller();
+pub(crate) fn clear_busy_for_thread(ctx: &crate::core::runtime::DispatchCtx, thread_id: &str) -> usize {
+ let me = caller(ctx);
let mut busy = busy().lock().expect("background_delivery busy poisoned");
let before = busy.len();
busy.retain(|key, _| {
diff --git a/crates/openhuman-core/src/agent/orchestration/delivery_drain.rs b/crates/openhuman-core/src/agent/orchestration/delivery_drain.rs
index d73992eaef..baac589084 100644
--- a/crates/openhuman-core/src/agent/orchestration/delivery_drain.rs
+++ b/crates/openhuman-core/src/agent/orchestration/delivery_drain.rs
@@ -93,6 +93,7 @@ pub(super) enum DrainOutcome {
/// `wait_idle` serves a recovered record: it has no owner noted (that table is
/// process-local), so the busy turn's completion event would not wake it.
pub(super) async fn run_drain<F, Fut>(
+ ctx: &crate::core::runtime::DispatchCtx,
thread_id: &str,
delay: Duration,
wait_idle: bool,
@@ -112,7 +113,7 @@ where
}
if wait_idle {
let mut polls = 0;
- while is_busy(thread_id) && polls < RECOVERY_BUSY_POLLS {
+ while is_busy(ctx, thread_id) && polls < RECOVERY_BUSY_POLLS {
polls += 1;
if !fence.sleep(poll).await {
log::info!(
@@ -122,7 +123,7 @@ where
return DrainOutcome::Fenced;
}
}
- if is_busy(thread_id) {
+ if is_busy(ctx, thread_id) {
return DrainOutcome::StillBusy;
}
}
diff --git a/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs b/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
index 300973d762..88a6bd75f7 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
@@ -92,7 +92,10 @@ impl OpenHumanSessionHost {
// turn's own (profile) scope; the bus subscriber runs off-task.
// A guard, so a turn dropped mid-flight does not leave it busy.
let busy =
- crate::agent::orchestration::busy_guard::TurnBusy::start(self.event_session_id());
+ crate::agent::orchestration::busy_guard::TurnBusy::start(
+ &self.dispatch_ctx(),
+ self.event_session_id(),
+ );
BUS.publish(DomainEvent::AgentTurnStarted {
session_id: self.event_session_id().to_string(),
channel: self.event_channel().to_string(),
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rs
index 12f661cf69..a1588fbc3f 100644
--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs
@@ -112,7 +112,7 @@ pub(crate) async fn run_relay_turn(
// waits instead of landing mid-turn. The pipeline's session id does not
// name the thread, so the guard is taken on the thread itself; this task
// runs in the caller's scope, which keys it to the caller's profile.
- let busy = crate::agent::orchestration::busy_guard::TurnBusy::start_on_thread(&thread_id);
+ let busy = crate::agent::orchestration::busy_guard::TurnBusy::start_on_thread(&dispatch_ctx, &thread_id);
let channel = Arc::new(RelayChannel::new(
params.channel.clone(),
params.client_id(),
diff --git a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
index 54c7a08200..ff16f2c778 100644
--- a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
+++ b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
@@ -150,7 +150,7 @@ async fn cancel_chat_inner(
// Only once nothing is left running on the thread: a scoped cancel can leave
// the primary or a parallel turn alive, and those still owe a terminal event.
if cancelled_any.is_some() && !thread_has_live_turn(thread_id, &map_key).await {
- crate::agent::orchestration::busy_guard::clear_busy_for_thread(thread_id);
+ crate::agent::orchestration::busy_guard::clear_busy_for_thread(ctx, thread_id);
// A drain that fired while the cancelled turn counted as busy returned
// without claiming anything; ask for another.
crate::agent::orchestration::background_delivery::kick_delivery(thread_id);