Skip to content

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

refactor(orchestration): use registry wait_many for agent waits

Steven Enamakel4d22722378b2
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
index a556dcdd6c..271fbe02a4 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
@@ -421,8 +421,6 @@ async fn try_deliver(
let turn_workspace = workspace_dir.clone();
let give_up_ctx = busy_ctx.clone();
let format_router = router.clone();
- let last_delivery_error = Arc::new(std::sync::Mutex::new(None::<String>));
- let delivery_error_sink = Arc::clone(&last_delivery_error);
let turn_thread_id = thread_id.clone();
let give_up_thread_id = thread_id.clone();
let give_up_log_thread_id = thread_id.clone();
@@ -435,31 +433,21 @@ async fn try_deliver(
let ctx = ctx.clone();
let workspace_dir = turn_workspace.clone();
let thread_id = turn_thread_id.clone();
- let delivery_error_sink = Arc::clone(&delivery_error_sink);
async move {
let result = run_system_turn_on_thread(&ctx, workspace_dir, thread_id, notice)
.await
- .map(|_| ());
- if let Err(error) = &result {
- if let Ok(mut last_error) = delivery_error_sink.lock() {
- *last_error = Some(error.clone());
- }
- }
+ .map(|_| ())
+ .map_err(|error| error.to_string());
result
}
};
- let write_undelivered = move |records: &[CompletionRecord]| {
+ let write_undelivered = move |records: &[CompletionRecord], error: &str| {
let attempts = records
.iter()
.map(|record| record.attempts)
.max()
.unwrap_or(1);
- let error = last_delivery_error
- .lock()
- .ok()
- .and_then(|error| error.clone())
- .unwrap_or_else(|| "the background delivery turn failed".to_string());
- let notice = build_undelivered_notice(records, attempts, &error);
+ let notice = build_undelivered_notice(records, attempts, error);
if let Some(notice) = notice {
let run_id = format!("bgdeliver-undelivered-{}", uuid::Uuid::new_v4());
if let Err(error) = persist_delivery_reply(
@@ -483,7 +471,7 @@ async fn try_deliver(
};
let outcome = if recovering {
delivery
- .recover_on_boot(
+ .recover_on_boot_with_error(
target,
|| is_busy(&busy_ctx, &thread_id),
fence.clone(),
@@ -493,7 +481,7 @@ async fn try_deliver(
.await
} else {
delivery
- .deliver_once(
+ .deliver_once_with_error(
target,
|| is_busy(&busy_ctx, &thread_id),
fence.clone(),
diff --git a/crates/openhuman-core/src/agent/orchestration/ops.rs b/crates/openhuman-core/src/agent/orchestration/ops.rs
index 4a2ddcccaf..acbe495326 100644
--- a/crates/openhuman-core/src/agent/orchestration/ops.rs
+++ b/crates/openhuman-core/src/agent/orchestration/ops.rs
@@ -44,7 +44,7 @@ use tinyagents_tasks::{
OrchestrationTaskStatus,
};
use tokio::sync::{mpsc, watch};
-use tokio::time::{Duration, Instant};
+use tokio::time::Duration;
#[derive(Debug, Error)]
pub enum OrchestrationError {
@@ -66,12 +66,6 @@ pub enum OrchestrationError {
/// the table grows past this, matching [`super::running_subagents`].
const REGISTRY_SOFT_CAP: usize = 256;
-/// Chunk length for an unbounded `wait_agents`. The crate's `wait` takes a
-/// concrete deadline, so a `timeout_ms: None` request loops over these until a
-/// terminal status lands — which preserves the old "wait forever" contract
-/// without inventing a fake far-future instant.
-const UNBOUNDED_WAIT_CHUNK: Duration = Duration::from_secs(3600);
-
/// Product metadata retained alongside each detached child's executor handles.
///
/// `status_tx` rides in the metadata deliberately: it is what lets
@@ -193,27 +187,34 @@ impl AgentOrchestrationSession {
});
}
- let deadline = options
- .timeout_ms
- .map(|ms| Instant::now() + Duration::from_millis(ms));
+ let timeout = options.timeout_ms.map(Duration::from_millis);
+ let task_ids: Vec<_> = options
+ .orchestration_ids
+ .iter()
+ .cloned()
+ .map(TaskId::new)
+ .collect();
+ let items = self
+ .registry
+ .wait_many(&task_ids, &self.session_id, timeout)
+ .await
+ .map_err(|failure| self.lookup_error(failure.task_id.as_str(), failure.error))?;
let mut agents = Vec::with_capacity(options.orchestration_ids.len());
let mut completed = true;
- for id in &options.orchestration_ids {
- let task_id = TaskId::new(id.clone());
- // Metadata is only retained while the entry is live, so capture it
- // before `wait` prunes a terminal child.
- let metadata = self
- .registry
- .snapshot(&task_id, &self.session_id)
- .map_err(|err| self.lookup_error(id, err))?
- .metadata;
-
- let state = self.wait_one(&task_id, deadline).await?;
+ for item in items {
+ let state = match item.outcome {
+ DetachedTaskWaitOutcome::Terminal(state)
+ | DetachedTaskWaitOutcome::TimedOut(state) => state,
+ };
if !state.is_terminal() {
completed = false;
}
- agents.push(snapshot_of(id, &metadata, &state));
+ agents.push(snapshot_of(
+ item.task_id.as_str(),
+ &item.metadata,
+ &state,
+ ));
}
Ok(WaitAgentResponse { completed, agents })
@@ -253,34 +254,6 @@ impl AgentOrchestrationSession {
);
}
- /// Wait one child to a terminal status, honouring the shared `deadline`.
- async fn wait_one(
- &self,
- task_id: &TaskId,
- deadline: Option<Instant>,
- ) -> Result<ChildState, OrchestrationError> {
- loop {
- let slice = match deadline {
- Some(deadline) => deadline.saturating_duration_since(Instant::now()),
- None => UNBOUNDED_WAIT_CHUNK,
- };
- let outcome = self
- .registry
- .wait(task_id, &self.session_id, slice)
- .await
- .map_err(|err| self.lookup_error(task_id.as_str(), err))?;
- match outcome {
- DetachedTaskWaitOutcome::Terminal(state) => return Ok(state),
- DetachedTaskWaitOutcome::TimedOut(state) => {
- if deadline.is_some() {
- return Ok(state);
- }
- // Unbounded wait: the chunk expired, keep waiting.
- }
- }
- }
- }
-
/// Every child snapshot still live in this session's registry, ordered by
/// creation time.
fn all_snapshots(&self) -> Result<Vec<AgentSnapshot>, OrchestrationError> {