Skip to content

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

feat(agent): add background delivery for orchestration

Steven Enamakel17c18fbc31de
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
index efe77deb34..215a863ec7 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
@@ -48,6 +48,7 @@ use super::busy_guard::is_busy;
use super::busy_guard::{busy, clear_busy_for_thread, TurnBusy};
use super::completion_notice::build_undelivered_notice;
use super::completion_owners;
+use super::delivery_drain::{run_drain, DrainFence, DrainOutcome, RECOVERY_BUSY_POLL};
use crate::core::runtime::tenant;
use crate::core::runtime::CoreContext;
@@ -232,19 +233,16 @@ pub(super) fn drain_schedule_in(
.collect()
}
-/// Schedule a debounced delivery attempt for a thread.
+/// Schedule a debounced delivery attempt for a thread, fenced by the calling
+/// profile's lease ([`DrainFence::current`]).
fn schedule_delivery(thread_id: String, delay: Duration) {
- schedule_delivery_inner(thread_id, delay, false);
+ schedule_delivery_inner(thread_id, delay, false, DrainFence::current());
}
-/// Poll interval and ceiling while a recovered drain waits for a busy thread.
-const RECOVERY_BUSY_POLL: Duration = Duration::from_secs(5);
-const RECOVERY_BUSY_POLLS: u32 = 360;
-
/// `wait_idle`: after the delay, keep waiting while the thread's user turn is in
-/// flight instead of giving up. A recovered record has no owner noted (the table
-/// is process-local), so the turn's completion event would not wake the drain.
-fn schedule_delivery_inner(thread_id: String, delay: Duration, wait_idle: bool) {
+/// flight instead of giving up (see [`run_drain`]). `fence` drops the drain
+/// once this node loses the owning profile's lease.
+fn schedule_delivery_inner(thread_id: String, delay: Duration, wait_idle: bool, fence: DrainFence) {
#[cfg(test)]
scheduled_for_test()
.lock()
@@ -253,25 +251,26 @@ 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 {
- tokio::time::sleep(delay).await;
- if wait_idle {
- let mut polls = 0;
- while is_busy(&thread_id) && polls < RECOVERY_BUSY_POLLS {
- polls += 1;
- tokio::time::sleep(RECOVERY_BUSY_POLL).await;
- }
- if is_busy(&thread_id) {
- // Still running past the ceiling: leave the record pending and
- // wait again rather than overlap the user's turn.
- log::debug!(
- "[background_delivery] recovered drain still busy; waiting again \
- thread_id={thread_id}"
- );
- schedule_delivery_inner(thread_id, RECOVERY_BUSY_POLL, true);
- return;
- }
+ let turn_fence = fence.clone();
+ let turn_thread = thread_id.clone();
+ let outcome = run_drain(
+ &thread_id,
+ delay,
+ wait_idle,
+ &fence,
+ RECOVERY_BUSY_POLL,
+ || try_deliver(turn_thread, turn_fence),
+ )
+ .await;
+ if outcome == DrainOutcome::StillBusy {
+ // Still running past the ceiling: leave the record pending and
+ // wait again rather than overlap the user's turn.
+ log::debug!(
+ "[background_delivery] recovered drain still busy; waiting again \
+ thread_id={thread_id}"
+ );
+ schedule_delivery_inner(thread_id, RECOVERY_BUSY_POLL, true, fence);
}
- try_deliver(thread_id).await;
});
}
@@ -285,9 +284,14 @@ fn scheduled_for_test() -> &'static Mutex<Vec<(String, Duration)>> {
/// 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.
+/// after [`RECOVERY_DELAY`], through the normal idle-gated path, fenced by the
+/// calling profile's lease when there is one. Returns the number of threads
+/// scheduled.
pub(crate) fn recover_on_boot(workspace_dir: &Path) -> usize {
+ recover_fenced(workspace_dir, DrainFence::current())
+}
+
+fn recover_fenced(workspace_dir: &Path, fence: DrainFence) -> usize {
// Scheduling needs a runtime; check before claiming so a later call retries.
if tokio::runtime::Handle::try_current().is_err() {
log::warn!(
@@ -306,7 +310,7 @@ pub(crate) fn recover_on_boot(workspace_dir: &Path) -> usize {
"[background_delivery] scheduling redelivery of undelivered completions after restart \
thread_id={thread_id}"
);
- schedule_delivery_inner(thread_id.clone(), RECOVERY_DELAY, true);
+ schedule_delivery_inner(thread_id.clone(), RECOVERY_DELAY, true, fence.clone());
}
threads.len()
}
@@ -314,10 +318,13 @@ pub(crate) fn recover_on_boot(workspace_dir: &Path) -> usize {
/// Recovery for a profile that was just opened: forget the workspace's earlier
/// claim (a profile released and re-leased may have results another node left
/// pending since), then recover. Duplicate drains are harmless: delivery is
-/// lease-claimed.
-pub(crate) fn recover_on_open(workspace_dir: &Path) -> usize {
+/// lease-claimed. `fence` is the grant the profile was just opened under (the
+/// host has not published the profile yet, so it cannot be looked up): a drain
+/// that comes due after this node lost that lease is dropped, and the records
+/// stay pending for the node that holds it now.
+pub(crate) fn recover_on_open(workspace_dir: &Path, fence: DrainFence) -> usize {
background_completions::forget_recovery(workspace_dir);
- let scheduled = recover_on_boot(workspace_dir);
+ let scheduled = recover_fenced(workspace_dir, fence);
if scheduled == 0 {
// Nothing pending: do not keep this profile's log handle cached for a
// workspace that may never complete anything on this node.
@@ -346,7 +353,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) {
+async fn try_deliver(thread_id: String, fence: DrainFence) {
+ if !fence.admits() {
+ log::info!("[background_delivery] profile lease lost; not delivering thread_id={thread_id}");
+ return;
+ }
let Some(workspace_dir) = background_completions::workspace_for_thread(&thread_id) else {
log::debug!("[background_delivery] no workspace for thread_id={thread_id}");
return;
@@ -376,7 +387,7 @@ async fn try_deliver(thread_id: String) {
delay_ms={}",
delay.as_millis()
);
- schedule_delivery(thread_id, delay);
+ schedule_delivery_inner(thread_id, delay, false, fence);
}
}
diff --git a/crates/openhuman-core/src/agent/orchestration/mod.rs b/crates/openhuman-core/src/agent/orchestration/mod.rs
index 696e667701..b4b4ff0304 100644
--- a/crates/openhuman-core/src/agent/orchestration/mod.rs
+++ b/crates/openhuman-core/src/agent/orchestration/mod.rs
@@ -23,6 +23,7 @@ pub mod command_center;
pub(crate) mod completion_notice;
pub(crate) mod completion_owners;
pub(crate) mod completion_target;
+pub(crate) mod delivery_drain;
pub(crate) mod delegation;
pub use delegation::open_delegation_checkpointer;
pub(crate) mod fleet_tools;