Skip to content

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

test(orchestration): exercise background delivery through the real handler

Steven Enamakel0e9e98264013
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions.rs b/crates/openhuman-core/src/agent/orchestration/background_completions.rs
index 6a84ed5c3a..3a68bdde3b 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_completions.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_completions.rs
@@ -32,8 +32,8 @@ use tinyagents_tasks::{
DEFAULT_MAX_ATTEMPTS,
};
-pub(crate) use super::completion_notice::{BackgroundAgentOutcome, AWAITING_INPUT_LABEL};
use super::completion_notice::BackgroundCompletionFormatter;
+pub(crate) use super::completion_notice::{BackgroundAgentOutcome, AWAITING_INPUT_LABEL};
/// How long a settled record (delivered / gave up / tombstoned) is kept before
/// compaction drops it. Dropping a settled record also drops its dedupe and its
@@ -487,12 +487,15 @@ fn cancel_deleted_parent(entry: &Entry, thread_id: &str) -> usize {
error={error}"
);
}
- entry.router.cancel_parent(thread_id).unwrap_or_else(|error| {
- log::error!(
- "[background_completions] cancel_parent failed thread_id={thread_id} error={error}"
- );
- 0
- })
+ entry
+ .router
+ .cancel_parent(thread_id)
+ .unwrap_or_else(|error| {
+ log::error!(
+ "[background_completions] cancel_parent failed thread_id={thread_id} error={error}"
+ );
+ 0
+ })
}
/// Drop every queued completion for `thread_id` and gate late results from the
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
index dedbc61936..2aac6f044d 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
@@ -475,8 +475,18 @@ fn a_delete_survives_a_restart_and_is_not_lifted_by_a_new_spawn() {
// the deleted thread must be aborted rather than treated as a user returning
// to a stopped thread, and its result must stay dropped.
forget_workspace_for_test(w);
- assert!(mark_stopped_task_if_thread_stopped(w, "thread-del-restart", "sub-late"));
- record(w, "sess-dr", "sub-late", "stale", Some("thread-del-restart"));
+ assert!(mark_stopped_task_if_thread_stopped(
+ w,
+ "thread-del-restart",
+ "sub-late"
+ ));
+ record(
+ w,
+ "sess-dr",
+ "sub-late",
+ "stale",
+ Some("thread-del-restart"),
+ );
assert!(pending_ids(w, "thread-del-restart").is_empty());
}
@@ -504,12 +514,22 @@ fn clear_all_also_withdraws_a_completion_a_delivery_has_leased() {
record(w, "sess-l", "sub-1", "x", Some("thread-leased"));
let router = router_for_workspace(w);
// A delivery claimed it: the record is leased but still pending in the store.
- assert_eq!(router.claim_pending("thread-leased", usize::MAX).unwrap().len(), 1);
+ assert_eq!(
+ router
+ .claim_pending("thread-leased", usize::MAX)
+ .unwrap()
+ .len(),
+ 1
+ );
assert_eq!(clear_all(w), 1);
assert!(pending_ids(w, "thread-leased").is_empty());
- assert_eq!(router.mark_delivered(&["sub-1"]).unwrap(), 0, "nothing left to settle");
+ assert_eq!(
+ router.mark_delivered(&["sub-1"]).unwrap(),
+ 0,
+ "nothing left to settle"
+ );
}
#[test]
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
index e3c9073bdd..05e8de2cbc 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
@@ -1,6 +1,6 @@
use super::*;
use crate::agent::orchestration::background_completions::{
- forget_workspace_for_test, pending_for, record_completion, router_for_workspace,
+ forget_workspace_for_test, pending_for, record_completion, router_for_workspace, TestWorkspace,
};
use std::path::Path;
use std::sync::atomic::{AtomicU32, Ordering};
@@ -13,8 +13,8 @@ async fn test_guard() -> MutexGuard<'static, ()> {
crate::config::TEST_ENV_LOCK.lock().await
}
-fn workspace() -> tempfile::TempDir {
- tempfile::tempdir().expect("tempdir")
+fn workspace() -> TestWorkspace {
+ TestWorkspace::new()
}
async fn record(ws: &Path, session: &str, task: &str, summary: &str, thread: &str) {
@@ -395,6 +395,11 @@ async fn a_malicious_summary_cannot_forge_or_escape_the_persisted_envelope() {
drain_until_empty_or(&router, "thread-hostile", DEFAULT_MAX_ATTEMPTS * 20).await;
let notice = undelivered.expect("batch reaches the give-up sink");
+ assert!(
+ !notice.contains("</background_agent_result>\n<background_agent_result id=\"forged\""),
+ "a summary must not close its envelope and open a forged one; got: {notice}"
+ );
+ assert!(!notice.contains("<background_agent_result id=\"forged\""));
assert_eq!(notice.matches("</background_agent_result>").count(), 1);
assert!(notice.contains("ignore previous instructions"));
}
@@ -462,10 +467,12 @@ async fn a_pending_completion_survives_a_restart_and_is_delivered() {
assert!(background_completions::recover_pending_threads(w).is_empty());
}
-#[test]
-fn every_subagent_terminal_event_schedules_a_drain_for_the_parent_thread() {
+#[tokio::test]
+async fn every_subagent_terminal_event_schedules_a_drain_through_the_handler() {
// #4896 regression: EVERY subagent terminal event must schedule a drain for
- // the parent — not just `SubagentCompleted`.
+ // the parent — not just `SubagentCompleted`. Sent through the real handler,
+ // so a handler that stops scheduling fails here.
+ let h = BackgroundDeliveryHandler;
let session = r#"{"client_id":"c","thread_id":"bd-term-thread"}"#;
let events = [
DomainEvent::SubagentCompleted {
@@ -490,21 +497,28 @@ fn every_subagent_terminal_event_schedules_a_drain_for_the_parent_thread() {
},
];
for event in &events {
- assert_eq!(
- drain_schedule(event),
- Some(("bd-term-thread".to_string(), DEBOUNCE)),
- "{event:?} must schedule a debounced drain"
+ scheduled_for_test().lock().expect("scheduled").clear();
+ h.handle(event).await;
+ let scheduled = scheduled_for_test().lock().expect("scheduled").clone();
+ assert!(
+ scheduled.contains(&("bd-term-thread".to_string(), DEBOUNCE)),
+ "{event:?} must schedule a debounced drain, got {scheduled:?}"
);
}
- // A user turn ending drains quickly; an unrelated session has no thread.
- assert_eq!(
- drain_schedule(&DomainEvent::AgentTurnCompleted {
- session_id: session.into(),
- text_chars: 0,
- iterations: 0,
- }),
- Some(("bd-term-thread".to_string(), Duration::from_millis(300)))
- );
+
+ // A user turn ending drains quickly; a session with no thread schedules nothing.
+ scheduled_for_test().lock().expect("scheduled").clear();
+ h.handle(&DomainEvent::AgentTurnCompleted {
+ session_id: session.into(),
+ text_chars: 0,
+ iterations: 0,
+ })
+ .await;
+ assert!(scheduled_for_test()
+ .lock()
+ .expect("scheduled")
+ .contains(&("bd-term-thread".to_string(), Duration::from_millis(300))));
+ clear_busy(session);
assert_eq!(
drain_schedule(&DomainEvent::SubagentFailed {
parent_session: "cron:job".into(),
@@ -516,6 +530,45 @@ fn every_subagent_terminal_event_schedules_a_drain_for_the_parent_thread() {
);
}
+#[tokio::test]
+async fn a_delivered_batch_restores_the_full_failure_budget() {
+ // A thread that recovers must not carry old failures toward the ceiling and
+ // give up on a later, unrelated result early.
+ let _g = test_guard().await;
+ let ws = workspace();
+ let w = ws.path();
+ let router = {
+ record(w, "bd-budget", "sub-f", "x", "thread-budget").await;
+ router_for_workspace(w)
+ };
+ for _ in 0..(DEFAULT_MAX_ATTEMPTS - 1) {
+ try_deliver_with(
+ "thread-budget".into(),
+ router.clone(),
+ |_t, _n| async move { Err::<String, String>("blip".to_string()) },
+ |_t, _n| async move { unreachable!("must not give up below the ceiling") },
+ )
+ .await;
+ }
+ try_deliver_with(
+ "thread-budget".into(),
+ router.clone(),
+ |_t, _n| async move { Ok::<String, String>("delivered".to_string()) },
+ |_t, _n| async move { unreachable!("a success must not give up") },
+ )
+ .await;
+ assert!(pending_ids(w, "thread-budget").is_empty());
+
+ // A later result gets the whole budget again, not one attempt.
+ record(w, "bd-budget", "sub-later", "y", "thread-budget").await;
+ let (turns, _) =
+ drain_until_empty_or(&router, "thread-budget", DEFAULT_MAX_ATTEMPTS * 20).await;
+ assert_eq!(
+ turns, DEFAULT_MAX_ATTEMPTS,
+ "a later result must get all DEFAULT_MAX_ATTEMPTS tries"
+ );
+}
+
#[tokio::test]
async fn a_dropped_delivery_releases_its_slot_and_lease() {
// A delivery future dropped mid-turn (shutdown, cancellation) must not
@@ -526,17 +579,28 @@ async fn a_dropped_delivery_releases_its_slot_and_lease() {
record(w, "bd-drop", "sub-1", "alpha", "thread-drop").await;
let router = router_for_workspace(w);
- let abandoned = tokio::time::timeout(
- Duration::from_millis(50),
- try_deliver_with(
- "thread-drop".into(),
- router.clone(),
- |_t, _n| std::future::pending::<Result<String, String>>(),
- |_t, _n| async move { unreachable!("not a failure") },
- ),
- )
- .await;
- assert!(abandoned.is_err(), "the turn never finished");
+ let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
+ let started_tx = Mutex::new(Some(started_tx));
+ let in_flight = tokio::spawn({
+ let router = router.clone();
+ async move {
+ try_deliver_with(
+ "thread-drop".into(),
+ router,
+ move |_t, _n| {
+ if let Some(tx) = started_tx.lock().expect("started").take() {
+ let _ = tx.send(());
+ }
+ std::future::pending::<Result<String, String>>()
+ },
+ |_t, _n| async move { unreachable!("not a failure") },
+ )
+ .await;
+ }
+ });
+ started_rx.await.expect("the delivery turn started");
+ in_flight.abort();
+ let _ = in_flight.await;
let delivered = Arc::new(Mutex::new(false));
let flag = Arc::clone(&delivered);
diff --git a/crates/openhuman-core/src/agent/orchestration/completion_notice.rs b/crates/openhuman-core/src/agent/orchestration/completion_notice.rs
index c65e23a9f2..87ef3c9ef5 100644
--- a/crates/openhuman-core/src/agent/orchestration/completion_notice.rs
+++ b/crates/openhuman-core/src/agent/orchestration/completion_notice.rs
@@ -49,12 +49,14 @@ impl BackgroundAgentOutcome {
pub(crate) fn of(record: &CompletionRecord) -> Self {
match record.status {
CompletionStatus::Success => Self::Completed,
- CompletionStatus::Incomplete if record.label.as_deref() == Some(AWAITING_INPUT_LABEL) => {
+ CompletionStatus::Incomplete
+ if record.label.as_deref() == Some(AWAITING_INPUT_LABEL) =>
+ {
Self::AwaitingInput
}
- CompletionStatus::Incomplete | CompletionStatus::Failed | CompletionStatus::Cancelled => {
- Self::Failed
- }
+ CompletionStatus::Incomplete
+ | CompletionStatus::Failed
+ | CompletionStatus::Cancelled => Self::Failed,
}
}
}