Skip to content

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

refactor(orchestration): route test dispatch through a shared cx helper

Steven Enamakel750f03827d06
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 e141528e55..b2576aca74 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
@@ -1,4 +1,10 @@
use super::*;
+
+/// The context these tests dispatch under: the calling task's own.
+fn cx() -> crate::core::runtime::DispatchCtx {
+ crate::core::runtime::DispatchCtx::ambient()
+}
+
use crate::core::runtime::DispatchCtx;
use tinyagents_tasks::CompletionStatus;
use tokio::sync::MutexGuard;
@@ -18,7 +24,7 @@ fn workspace() -> TestWorkspace {
fn record(ws: &Path, session: &str, task: &str, summary: &str, thread: Option<&str>) {
futures::executor::block_on(record_completion(
- &DispatchCtx::ambient(),
+ &cx(),
ws,
session,
task,
@@ -78,7 +84,7 @@ fn headless_completion_is_dropped() {
.claim_pending("", usize::MAX)
.unwrap()
.is_empty());
- assert!(recover_pending_threads(&DispatchCtx::ambient(), ws.path()).is_empty());
+ assert!(recover_pending_threads(&cx(), ws.path()).is_empty());
}
#[test]
@@ -87,19 +93,16 @@ fn the_session_is_mapped_to_its_thread_for_the_idle_gate() {
let ws = workspace();
record(ws.path(), "sess-map", "sub-1", "x", Some("thread-map"));
assert_eq!(
- thread_for_session(&DispatchCtx::ambient(), "sess-map").as_deref(),
+ thread_for_session(&cx(), "sess-map").as_deref(),
Some("thread-map")
);
// A web-channel session id carries its thread in the JSON body.
let web = r#"{"client_id":"c","thread_id":"thread-json"}"#;
assert_eq!(
- thread_for_session(&DispatchCtx::ambient(), web).as_deref(),
+ thread_for_session(&cx(), web).as_deref(),
Some("thread-json")
);
- assert_eq!(
- thread_for_session(&DispatchCtx::ambient(), "cron:job-1"),
- None
- );
+ assert_eq!(thread_for_session(&cx(), "cron:job-1"), None);
}
#[test]
@@ -111,10 +114,7 @@ fn discard_for_thread_removes_matching_and_drops_stragglers() {
record(w, "sess-d1", "sub-b", "y", Some("thread-KEEP"));
record(w, "sess-d2", "sub-c", "z", Some("thread-DEL"));
- assert_eq!(
- discard_for_thread(&DispatchCtx::ambient(), w, "thread-DEL"),
- 2
- );
+ assert_eq!(discard_for_thread(&cx(), w, "thread-DEL"), 2);
assert!(pending_ids(w, "thread-DEL").is_empty());
assert_eq!(pending_ids(w, "thread-KEEP"), ["sub-b"]);
}
@@ -126,7 +126,7 @@ fn record_after_discard_is_dropped_by_the_cancelled_parent() {
let w = ws.path();
// The thread is deleted before this process ever saw a child of it: the
// delete still writes the cancelled-parent marker in the caller's workspace.
- discard_for_thread(&DispatchCtx::ambient(), w, "thread-race");
+ discard_for_thread(&cx(), w, "thread-race");
// A straggler that records after the sweep (the cooperative-abort race) is
// dropped rather than queued.
record(w, "sess-race", "sub-late", "stale", Some("thread-race"));
@@ -142,18 +142,18 @@ fn a_child_registering_after_its_thread_was_deleted_is_aborted_and_stays_dropped
let ws = workspace();
let w = ws.path();
assert!(!mark_stopped_task_if_thread_stopped(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"thread-del-reg",
"sub-a"
));
- discard_for_thread(&DispatchCtx::ambient(), w, "thread-del-reg");
+ discard_for_thread(&cx(), w, "thread-del-reg");
// A child spawned before the delete registers after it: it must be aborted,
// and registering must not lift the delete (unlike a stopped thread, a
// deleted one never reopens).
assert!(mark_stopped_task_if_thread_stopped(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"thread-del-reg",
"sub-b"
@@ -171,11 +171,11 @@ fn clear_all_withdraws_every_pending_completion() {
record(w, "sess-c1", "sub-1", "a", Some("t1"));
record(w, "sess-c2", "sub-2", "b", Some("t2"));
- let removed = clear_all(&DispatchCtx::ambient(), w);
+ let removed = clear_all(&cx(), w);
assert_eq!(removed, 2);
assert!(pending_ids(w, "t1").is_empty());
assert!(pending_ids(w, "t2").is_empty());
- assert_eq!(clear_all(&DispatchCtx::ambient(), w), 0);
+ assert_eq!(clear_all(&cx(), w), 0);
}
#[test]
@@ -186,7 +186,7 @@ fn clear_all_is_scoped_to_its_workspace() {
record(purged.path(), "sess-p", "sub-1", "a", Some("t-purged"));
record(other.path(), "sess-o", "sub-2", "b", Some("t-other"));
- assert_eq!(clear_all(&DispatchCtx::ambient(), purged.path()), 1);
+ assert_eq!(clear_all(&cx(), purged.path()), 1);
assert!(pending_ids(purged.path(), "t-purged").is_empty());
assert_eq!(
@@ -267,7 +267,7 @@ fn record_failure_queues_a_framed_failure_for_delivery() {
let ws = workspace();
let w = ws.path();
futures::executor::block_on(record_failure(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"sess-fail",
"sub-bad",
@@ -288,7 +288,7 @@ fn record_awaiting_input_queues_a_framed_needs_input_for_delivery() {
let ws = workspace();
let w = ws.path();
futures::executor::block_on(record_awaiting_input(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"sess-ask",
"sub-ask",
@@ -312,7 +312,7 @@ fn the_outcome_survives_a_claim() {
let ws = workspace();
let w = ws.path();
futures::executor::block_on(record_outcome(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"sess-out",
"sub-1",
@@ -351,10 +351,7 @@ fn discard_pending_for_thread_blocks_late_results_until_the_next_turn() {
);
// Stop drops the undelivered result so it can't start a delivery turn...
- assert_eq!(
- discard_pending_for_thread(&DispatchCtx::ambient(), "thread-stop-live"),
- 1
- );
+ assert_eq!(discard_pending_for_thread(&cx(), "thread-stop-live"), 1);
assert!(pending_ids(w, "thread-stop-live").is_empty());
assert_eq!(pending_ids(w, "thread-stop-other"), ["sub-stop-keep"]);
@@ -371,11 +368,7 @@ fn discard_pending_for_thread_blocks_late_results_until_the_next_turn() {
// Completing Stop keeps the thread gate until a new user turn begins, so a
// child that registers after the cancellation sweep is still rejected.
- finish_stop_for_thread(
- &DispatchCtx::ambient(),
- "thread-stop-live",
- &["sub-stop-later".into()],
- );
+ finish_stop_for_thread(&cx(), "thread-stop-live", &["sub-stop-later".into()]);
record(
w,
"sess-stop",
@@ -388,13 +381,13 @@ fn discard_pending_for_thread_blocks_late_results_until_the_next_turn() {
// A child that was spawned before Stop but registers after the registry
// sweep gets its own tombstone before the thread can be reopened.
assert!(mark_stopped_task_if_thread_stopped(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"thread-stop-live",
"sub-stop-registered-late"
));
- resume_stopped_thread(&DispatchCtx::ambient(), "thread-stop-live");
+ resume_stopped_thread(&cx(), "thread-stop-live");
record(
w,
"sess-stop",
@@ -422,16 +415,13 @@ fn a_stop_before_a_restart_is_lifted_by_the_first_new_spawn() {
let ws = workspace();
let w = ws.path();
record(w, "sess-rs", "sub-1", "x", Some("thread-restart-stop"));
- assert_eq!(
- discard_pending_for_thread(&DispatchCtx::ambient(), "thread-restart-stop"),
- 1
- );
+ assert_eq!(discard_pending_for_thread(&cx(), "thread-restart-stop"), 1);
// A restart: the in-memory gate is gone, the durable cancelled-parent
// marker is not.
forget_workspace_for_test(w);
assert!(!mark_stopped_task_if_thread_stopped(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"thread-restart-stop",
"sub-new"
@@ -477,7 +467,7 @@ fn undelivered_completions_are_found_again_after_a_restart() {
drop(router);
forget_workspace_for_test(w);
- let threads = recover_pending_threads(&DispatchCtx::ambient(), w);
+ let threads = recover_pending_threads(&cx(), w);
assert_eq!(
threads,
@@ -488,7 +478,7 @@ fn undelivered_completions_are_found_again_after_a_restart() {
pending_for(w, "thread-boot")[0].result.text,
"unseen result"
);
- assert!(router_for_thread(&DispatchCtx::ambient(), "thread-boot").is_some());
+ assert!(router_for_thread(&cx(), "thread-boot").is_some());
}
#[test]
@@ -497,17 +487,14 @@ fn a_delete_survives_a_restart_and_is_not_lifted_by_a_new_spawn() {
let ws = workspace();
let w = ws.path();
record(w, "sess-dr", "sub-1", "x", Some("thread-del-restart"));
- assert_eq!(
- discard_for_thread(&DispatchCtx::ambient(), w, "thread-del-restart"),
- 1
- );
+ assert_eq!(discard_for_thread(&cx(), w, "thread-del-restart"), 1);
// A restart: memory is gone, the durable markers are not. A late child for
// 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(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"thread-del-restart",
"sub-late"
@@ -554,7 +541,7 @@ fn clear_all_also_withdraws_a_completion_a_delivery_has_leased() {
1
);
- assert_eq!(clear_all(&DispatchCtx::ambient(), w), 1);
+ assert_eq!(clear_all(&cx(), w), 1);
assert!(pending_ids(w, "thread-leased").is_empty());
assert_eq!(
@@ -569,20 +556,19 @@ fn the_session_cache_evicts_its_oldest_mapping_only() {
let _guard = test_guard();
for i in 0..(SESSION_THREADS_CAP + 5) {
note_session_thread(
- &DispatchCtx::ambient(),
+ &cx(),
&format!("evict-sess-{i}"),
&format!("evict-thread-{i}"),
);
}
assert_eq!(
- thread_for_session(&DispatchCtx::ambient(), "evict-sess-0"),
+ thread_for_session(&cx(), "evict-sess-0"),
None,
"oldest evicted"
);
for survivor in [5, SESSION_THREADS_CAP / 2, SESSION_THREADS_CAP + 4] {
assert_eq!(
- thread_for_session(&DispatchCtx::ambient(), &format!("evict-sess-{survivor}"))
- .as_deref(),
+ thread_for_session(&cx(), &format!("evict-sess-{survivor}")).as_deref(),
Some(format!("evict-thread-{survivor}").as_str()),
"a surviving session still resolves to its own thread"
);
@@ -595,7 +581,7 @@ fn a_delete_marker_outlives_compaction() {
let ws = workspace();
let w = ws.path();
record(w, "sess-cm", "sub-1", "x", Some("thread-compact"));
- discard_for_thread(&DispatchCtx::ambient(), w, "thread-compact");
+ discard_for_thread(&cx(), w, "thread-compact");
// Settled records expire; the deletion must not.
router_for_workspace(w)
@@ -603,7 +589,7 @@ fn a_delete_marker_outlives_compaction() {
.unwrap();
forget_workspace_for_test(w);
assert!(mark_stopped_task_if_thread_stopped(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"thread-compact",
"sub-late"
@@ -615,10 +601,7 @@ fn deleting_a_thread_that_never_used_background_work_writes_nothing() {
let _guard = test_guard();
let ws = workspace();
let w = ws.path();
- assert_eq!(
- discard_for_thread(&DispatchCtx::ambient(), w, "thread-plain"),
- 0
- );
+ assert_eq!(discard_for_thread(&cx(), w, "thread-plain"), 0);
assert!(
entry_for(w).store.list(None).is_empty(),
"no marker is persisted for an ordinary thread"
@@ -634,7 +617,7 @@ fn a_late_record_for_a_deleted_thread_is_dropped_by_the_durable_marker_alone() {
let ws = workspace();
let w = ws.path();
record(w, "sess-dm", "sub-1", "x", Some("thread-dm"));
- discard_for_thread(&DispatchCtx::ambient(), w, "thread-dm");
+ discard_for_thread(&cx(), w, "thread-dm");
// A restart empties the in-memory gates; the marker on disk still decides.
forget_workspace_for_test(w);
record(w, "sess-dm", "sub-late", "stale", Some("thread-dm"));
@@ -647,7 +630,7 @@ async fn release_all_closes_every_router_and_the_log_stays_replayable() {
let ws = workspace();
let w = ws.path();
record_completion(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"sess-rel",
"sub-1",
@@ -663,15 +646,12 @@ async fn release_all_closes_every_router_and_the_log_stays_replayable() {
"the router (and its log handle) is dropped"
);
assert!(
- workspace_for_thread(&DispatchCtx::ambient(), "thread-rel").is_none(),
+ workspace_for_thread(&cx(), "thread-rel").is_none(),
"process-local maps are cleared"
);
// The next boot finds the undelivered completion from the log alone.
- assert_eq!(
- recover_pending_threads(&DispatchCtx::ambient(), w),
- ["thread-rel"]
- );
+ assert_eq!(recover_pending_threads(&cx(), w), ["thread-rel"]);
}
#[tokio::test(start_paused = true)]
@@ -711,13 +691,13 @@ async fn release_all_keeps_the_stop_and_delete_gates() {
let _guard = crate::config::TEST_ENV_LOCK.lock().await;
let ws = workspace();
let w = ws.path();
- discard_pending_for_thread(&DispatchCtx::ambient(), "thread-keep-stop");
+ discard_pending_for_thread(&cx(), "thread-keep-stop");
state().deleted_threads.insert("thread-keep-del".into());
release_all().await;
// A detached child finishing after the release is still refused.
record_completion(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"s",
"sub-1",
@@ -727,7 +707,7 @@ async fn release_all_keeps_the_stop_and_delete_gates() {
)
.await;
record_completion(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"s",
"sub-2",
@@ -738,7 +718,7 @@ async fn release_all_keeps_the_stop_and_delete_gates() {
.await;
assert!(pending_ids(w, "thread-keep-stop").is_empty());
assert!(pending_ids(w, "thread-keep-del").is_empty());
- resume_stopped_thread(&DispatchCtx::ambient(), "thread-keep-stop");
+ resume_stopped_thread(&cx(), "thread-keep-stop");
state().deleted_threads.remove("thread-keep-del");
}
@@ -776,7 +756,7 @@ async fn a_store_that_keeps_failing_degrades_to_memory_instead_of_losing_the_res
install_store_for_test(w, Arc::new(FullDisk(InMemoryCompletionStore::new())));
record_completion(
- &DispatchCtx::ambient(),
+ &cx(),
w,
"sess-fd",
"sub-1",
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 2227815bd2..597232f9ac 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
@@ -1,4 +1,10 @@
use super::*;
+
+/// The context these tests dispatch under: the calling task's own.
+fn cx() -> crate::core::runtime::DispatchCtx {
+ crate::core::runtime::DispatchCtx::ambient()
+}
+
use crate::agent::orchestration::background_completions::{
forget_workspace_for_test, pending_for, record_completion, router_for_workspace, TestWorkspace,
};
@@ -17,16 +23,7 @@ fn workspace() -> TestWorkspace {
}
async fn record(ws: &Path, session: &str, task: &str, summary: &str, thread: &str) {
let thread = Some(thread.to_owned());
- record_completion(
- &DispatchCtx::ambient(),
- ws,
- session,
- task,
- "researcher",
- summary,
- thread,
- )
- .await;
+ record_completion(&cx(), ws, session, task, "researcher", summary, thread).await;
}
fn pending_ids(ws: &Path, thread: &str) -> Vec<String> {
pending_for(ws, thread)
@@ -57,15 +54,14 @@ async fn claim_takes_the_ready_batch_when_idle() {
record(w, "bd-ready", "sub-2", "beta", "thread-ready").await;
let router = router_for_workspace(w);
- let batch =
- claim_ready(&DispatchCtx::ambient(), &router, "thread-ready").expect("claims a batch");
+ let batch = claim_ready(&cx(), &router, "thread-ready").expect("claims a batch");
assert_eq!(batch.len(), 2);
let notice = router.formatter().format_batch(&batch);
assert!(notice.contains("sub-1") && notice.contains("sub-2"));
// The records stay pending (leased) until the turn lands.
assert_eq!(pending_ids(w, "thread-ready").len(), 2);
assert!(
- claim_ready(&DispatchCtx::ambient(), &router, "thread-ready").is_none(),
+ claim_ready(&cx(), &router, "thread-ready").is_none(),
"a held lease is not claimed twice"
);
}
@@ -79,10 +75,10 @@ async fn claim_skips_a_busy_thread_and_leaves_the_queue_intact() {
let router = router_for_workspace(w);
mark_busy("bd-busy");
- assert!(claim_ready(&DispatchCtx::ambient(), &router, "thread-busy").is_none());
+ assert!(claim_ready(&cx(), &router, "thread-busy").is_none());
clear_busy("bd-busy");
assert!(
- claim_ready(&DispatchCtx::ambient(), &router, "thread-busy").is_some(),
+ claim_ready(&cx(), &router, "thread-busy").is_some(),
"a deferral leaves the record claimable"
);
assert_eq!(
@@ -97,7 +93,7 @@ async fn claim_is_none_when_nothing_is_pending() {
let _g = test_guard().await;
let ws = workspace();
let router = router_for_workspace(ws.path());
- assert!(claim_ready(&DispatchCtx::ambient(), &router, "bd-empty-unique").is_none());
+ assert!(claim_ready(&cx(), &router, "bd-empty-unique").is_none());
}
#[tokio::test]
@@ -111,7 +107,7 @@ async fn a_delivered_batch_is_settled_and_not_redelivered() {
let seen = Arc::clone(&turns);
try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-ok".into(),
router.clone(),
move |thread, notice| {
@@ -146,7 +142,7 @@ async fn persistence_failure_releases_batch_without_terminal_announcement() {
let announced_for_delivery = Arc::clone(&announced);
try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-persist".into(),
router.clone(),
move |_thread_id, _notice| {
@@ -186,10 +182,10 @@ async fn persistence_failure_releases_batch_without_terminal_announcement() {
async fn a_turn_is_busy_until_its_guard_drops() {
let sid = r#"{"client_id":"c","thread_id":"bd-turn-thread"}"#.to_string();
- let turn = TurnBusy::start(&DispatchCtx::ambient(), &sid);
- assert!(is_busy(&DispatchCtx::ambient(), "bd-turn-thread"));
+ let turn = TurnBusy::start(&cx(), &sid);
+ assert!(is_busy(&cx(), "bd-turn-thread"));
drop(turn);
- assert!(!is_busy(&DispatchCtx::ambient(), "bd-turn-thread"));
+ assert!(!is_busy(&cx(), "bd-turn-thread"));
// The bus events no longer mark busy: the subscriber runs off-task and
// cannot tell which profile a session belongs to.
@@ -199,7 +195,7 @@ async fn a_turn_is_busy_until_its_guard_drops() {
channel: "test".into(),
})
.await;
- assert!(!is_busy(&DispatchCtx::ambient(), "bd-turn-thread"));
+ assert!(!is_busy(&cx(), "bd-turn-thread"));
}
/// Drive the real delivery loop with a turn executor that always fails, the
@@ -220,7 +216,7 @@ async fn drain_until_empty_or(
let turns_for_delivery = Arc::clone(&turns);
let sink = Arc::clone(&undelivered);
try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
thread.to_string(),
router.clone(),
move |_thread_id, _notice| {
@@ -322,7 +318,7 @@ async fn transient_failure_under_the_ceiling_keeps_the_result() {
let router = router_for_workspace(w);
try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-transient".into(),
router.clone(),
|_t, _n| async move { Err::<String, String>("blip".to_string()) },
@@ -357,7 +353,7 @@ async fn busy_deferral_does_not_consume_the_failure_budget() {
for _ in 0..(DEFAULT_MAX_ATTEMPTS * 2) {
mark_busy("bd-busy-defer");
try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-busy-defer".into(),
router.clone(),
|_t, _n| async move { unreachable!("must not run a delivery turn while busy") },
@@ -431,16 +427,15 @@ async fn a_pending_completion_survives_a_restart_and_is_delivered() {
drop(router);
forget_workspace_for_test(w);
- let threads = background_completions::recover_pending_threads(&DispatchCtx::ambient(), w);
+ let threads = background_completions::recover_pending_threads(&cx(), w);
assert_eq!(threads, ["thread-restart"]);
let router =
- background_completions::router_for_thread(&DispatchCtx::ambient(), "thread-restart")
- .expect("recovered");
+ background_completions::router_for_thread(&cx(), "thread-restart").expect("recovered");
let delivered = Arc::new(Mutex::new(Vec::<String>::new()));
let sink = Arc::clone(&delivered);
try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-restart".into(),
router,
move |thread, notice| {
@@ -466,7 +461,7 @@ async fn a_pending_completion_survives_a_restart_and_is_delivered() {
);
forget_workspace_for_test(w);
- assert!(background_completions::recover_pending_threads(&DispatchCtx::ambient(), w).is_empty());
+ assert!(background_completions::recover_pending_threads(&cx(), w).is_empty());
}
#[tokio::test]
@@ -545,7 +540,7 @@ async fn a_delivered_batch_restores_the_full_failure_budget() {
};
for _ in 0..(DEFAULT_MAX_ATTEMPTS - 1) {
try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-budget".into(),
router.clone(),
|_t, _n| async move { Err::<String, String>("blip".to_string()) },
@@ -554,7 +549,7 @@ async fn a_delivered_batch_restores_the_full_failure_budget() {
.await;
}
try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-budget".into(),
router.clone(),
|_t, _n| async move { Ok::<String, String>("delivered".to_string()) },
@@ -589,7 +584,7 @@ async fn a_dropped_delivery_releases_its_slot_and_lease() {
let router = router.clone();
async move {
try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-drop".into(),
router,
move |_t, _n| {
@@ -610,7 +605,7 @@ async fn a_dropped_delivery_releases_its_slot_and_lease() {
let delivered = Arc::new(Mutex::new(false));
let flag = Arc::clone(&delivered);
try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-drop".into(),
router,
move |_t, _n| {
@@ -641,7 +636,7 @@ async fn a_failed_turn_under_the_ceiling_asks_for_a_backoff_retry() {
let router = router_for_workspace(w);
let retry = try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-retry".into(),
router.clone(),
|_t, _n| async move { Err::<String, String>("session checkout failed".to_string()) },
@@ -651,7 +646,7 @@ async fn a_failed_turn_under_the_ceiling_asks_for_a_backoff_retry() {
assert_eq!(retry, Some(retry_backoff(1)));
let delivered = try_deliver_with(
- &DispatchCtx::ambient(),
+ &cx(),
"thread-retry".into(),
router,
|_t, _n| async move { Ok::<String, String>("presented".to_string()) },
@@ -683,13 +678,13 @@ async fn boot_recovery_schedules_a_delivery_for_every_thread_with_undelivered_re
forget_workspace_for_test(w);
scheduled_for_test().lock().expect("scheduled").clear();
- assert_eq!(recover_on_boot(&DispatchCtx::ambient(), w), 1);
+ assert_eq!(recover_on_boot(&cx(), w), 1);
assert!(scheduled_for_test()
.lock()
.expect("scheduled")
.contains(&("thread-boot-sched".to_string(), RECOVERY_DELAY)));
assert_eq!(
- recover_on_boot(&DispatchCtx::ambient(), w),
+ recover_on_boot(&cx(), w),
0,
"a workspace is scanned once per process"
);
@@ -702,14 +697,10 @@ async fn recover_on_open_rescans_a_workspace_already_recovered() {
let w = ws.path();
record(w, "bd-open", "sub-1", "left pending", "thread-open-resc").await;
forget_workspace_for_test(w);
- assert_eq!(recover_on_boot(&DispatchCtx::ambient(), w), 1);
+ assert_eq!(recover_on_boot(&cx(), w), 1);
+ assert_eq!(recover_on_boot(&cx(), w), 0, "boot recovery claims once");
assert_eq!(
- recover_on_boot(&DispatchCtx::ambient(), w),
- 0,
- "boot recovery claims once"
- );
- assert_eq!(
- recover_on_open(&DispatchCtx::ambient(), w, DrainFence::none()),
+ recover_on_open(&cx(), w, DrainFence::none()),
1,
"a re-open scans again"
);
@@ -723,16 +714,13 @@ async fn a_cancelled_turn_does_not_leave_the_thread_busy() {
let other = r#"{"client_id":"c","thread_id":"bd-other-thread"}"#;
mark_busy(session);
mark_busy(other);
- assert!(is_busy(&DispatchCtx::ambient(), "bd-stale-thread"));
+ assert!(is_busy(&cx(), "bd-stale-thread"));
- assert_eq!(
- clear_busy_for_thread(&DispatchCtx::ambient(), "bd-stale-thread"),
- 1
- );
+ assert_eq!(clear_busy_for_thread(&cx(), "bd-stale-thread"), 1);
- assert!(!is_busy(&DispatchCtx::ambient(), "bd-stale-thread"));
+ assert!(!is_busy(&cx(), "bd-stale-thread"));
assert!(
- is_busy(&DispatchCtx::ambient(), "bd-other-thread"),
+ is_busy(&cx(), "bd-other-thread"),
"other threads are untouched"
);
clear_busy(other);
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs
index 433e62287f..cae3925a8b 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs
@@ -1,4 +1,10 @@
use super::*;
+
+/// The context these tests dispatch under: the calling task's own.
+fn cx() -> crate::core::runtime::DispatchCtx {
+ crate::core::runtime::DispatchCtx::ambient()
+}
+
use crate::agent::orchestration::fleet_tools::FleetToolSet;
use crate::agent::orchestration::running_subagents::resolve::resume_ref_for_task;
use crate::agent::orchestration::running_subagents::resolve::task_id_for_session;
@@ -89,7 +95,7 @@ fn register_test_with_thread(
) -> watch::Sender<DetachedSubagentStatus> {
let (tx, rx) = status_channel();
register(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
task_id.into(),
"researcher".into(),
parent_session.into(),
@@ -147,11 +153,7 @@ async fn task_store_records_spawn_complete_and_cancel() {
// A second sub-agent that gets cancelled is recorded Cancelled.
let _tx2 = register_test("task-ledger-2", "ledger-parent", run_queue());
- assert!(cancel_by_task(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-ledger-2"
- )
- .is_some());
+ assert!(cancel_by_task(&cx(), "task-ledger-2").is_some());
let cancelled = task_records(None)
.into_iter()
.find(|r| r.spec.task_id.as_str() == "task-ledger-2")
@@ -167,7 +169,7 @@ async fn task_id_for_session_enforces_parent_ownership() {
let rq = run_queue();
let (tx, rx) = status_channel();
register(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-session".into(),
"researcher".into(),
"session-owner".into(),
@@ -182,20 +184,11 @@ async fn task_id_for_session_enforces_parent_ownership() {
.expect("fixture registration admitted");
assert_eq!(
- task_id_for_session(
- &crate::core::runtime::DispatchCtx::ambient(),
- "subsess-1",
- "session-owner"
- )
- .unwrap(),
+ task_id_for_session(&cx(), "subsess-1", "session-owner").unwrap(),
"task-session"
);
assert!(matches!(
- task_id_for_session(
- &crate::core::runtime::DispatchCtx::ambient(),
- "subsess-1",
- "session-other"
- ),
+ task_id_for_session(&cx(), "subsess-1", "session-other"),
Err(WaitError::NotOwned)
));
let _ = tx.send(DetachedSubagentStatus::Completed {
@@ -210,7 +203,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
let _guard = test_guard_async().await;
let (tx_a, rx_a) = status_channel();
register(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-fleet-a".into(),
"researcher".into(),
"fleet-parent".into(),
@@ -225,7 +218,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
.expect("fixture registration admitted");
let (tx_b, rx_b) = status_channel();
register(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-fleet-b".into(),
"code_executor".into(),
"fleet-parent".into(),
@@ -241,7 +234,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
// A worker owned by a different parent must not leak into the snapshot.
let (tx_other, rx_other) = status_channel();
register(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-fleet-other".into(),
"researcher".into(),
"other-parent".into(),
@@ -261,10 +254,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
})
.unwrap();
- let snap = snapshot_for_parent(
- &crate::core::runtime::DispatchCtx::ambient(),
- "fleet-parent",
- );
+ let snap = snapshot_for_parent(&cx(), "fleet-parent");
assert_eq!(snap.len(), 2, "only this parent's workers: {snap:?}");
// Ordered by agent_id then task_id → code_executor before researcher.
assert_eq!(snap[0].agent_id, "code_executor");
@@ -273,7 +263,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
assert_eq!(snap[1].status, "running");
let block = active_subagents_context_block(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"fleet-parent",
&test_workspace(),
&FleetToolSet::all(),
@@ -288,7 +278,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
// A parent with no registered workers gets no block (no perturbation).
assert!(active_subagents_context_block(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"nobody-here",
&test_workspace(),
&FleetToolSet::all()
@@ -302,13 +292,9 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
let registry = AgentDefinitionRegistry::builtins_only();
let def = registry.get("orchestrator").expect("built-in orchestrator");
let fleet = FleetToolSet::from_scope(&def.tools, &def.disallowed_tools);
- let block = active_subagents_context_block(
- &crate::core::runtime::DispatchCtx::ambient(),
- "fleet-parent",
- &test_workspace(),
- &fleet,
- )
- .expect("block present");
+ let block =
+ active_subagents_context_block(&cx(), "fleet-parent", &test_workspace(), &fleet)
+ .expect("block present");
for name in [
"wait_subagent",
"steer_subagent",
@@ -368,7 +354,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
.expect("mark idle");
let block = active_subagents_context_block(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"cold-parent",
durable_ws.path(),
&FleetToolSet::all(),
@@ -379,7 +365,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
assert!(block.contains("about: Daily X trending email workflow"));
// Other parents' durable sessions must not leak in.
assert!(active_subagents_context_block(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"unrelated-parent",
durable_ws.path(),
&FleetToolSet::all()
@@ -405,7 +391,7 @@ async fn resume_ref_for_task_includes_resume_fields_and_enforces_ownership() {
let _guard = test_guard_async().await;
let (tx, rx) = status_channel();
register(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-resume".into(),
"researcher".into(),
"session-owner".into(),
@@ -419,12 +405,8 @@ async fn resume_ref_for_task_includes_resume_fields_and_enforces_ownership() {
)
.expect("fixture registration admitted");
- let reference = resume_ref_for_task(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-resume",
- "session-owner",
- )
- .expect("resume reference");
+ let reference =
+ resume_ref_for_task(&cx(), "task-resume", "session-owner").expect("resume reference");
assert_eq!(reference.task_id, "task-resume");
assert_eq!(reference.agent_id, "researcher");
assert_eq!(
@@ -432,11 +414,7 @@ async fn resume_ref_for_task_includes_resume_fields_and_enforces_ownership() {
Some("subsess-resume")
);
assert!(matches!(
- resume_ref_for_task(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-resume",
- "session-other"
- ),
+ resume_ref_for_task(&cx(), "task-resume", "session-other"),
Err(WaitError::NotOwned)
));
@@ -452,7 +430,7 @@ async fn task_id_for_session_prefers_live_task_over_terminal_task() {
let _guard = test_guard_async().await;
let (old_tx, old_rx) = status_channel();
register(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-old".into(),
"researcher".into(),
"session-owner".into(),
@@ -471,7 +449,7 @@ async fn task_id_for_session_prefers_live_task_over_terminal_task() {
});
let (_new_tx, new_rx) = status_channel();
register(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-new".into(),
"researcher".into(),
"session-owner".into(),
@@ -486,12 +464,7 @@ async fn task_id_for_session_prefers_live_task_over_terminal_task() {
.expect("fixture registration admitted");
assert_eq!(
- task_id_for_session(
- &crate::core::runtime::DispatchCtx::ambient(),
- "subsess-live",
- "session-owner"
- )
- .unwrap(),
+ task_id_for_session(&cx(), "subsess-live", "session-owner").unwrap(),
"task-new"
);
prune("task-old");
@@ -513,14 +486,9 @@ async fn wait_returns_completion_once_published() {
drop(tx);
});
- let outcome = wait(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-wait",
- "session-A",
- Duration::from_secs(5),
- )
- .await
- .expect("wait should resolve");
+ let outcome = wait(&cx(), "task-wait", "session-A", Duration::from_secs(5))
+ .await
+ .expect("wait should resolve");
match outcome {
WaitOutcome::Terminal(DetachedSubagentStatus::Completed { output, iterations }) => {
assert_eq!(output, "the answer");
@@ -531,13 +499,7 @@ async fn wait_returns_completion_once_published() {
// pruned after a terminal wait
assert!(matches!(
- wait(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-wait",
- "session-A",
- Duration::from_millis(10)
- )
- .await,
+ wait(&cx(), "task-wait", "session-A", Duration::from_millis(10)).await,
Err(WaitError::Unknown)
));
}
@@ -548,14 +510,9 @@ async fn wait_times_out_and_leaves_entry_intact() {
let rq = run_queue();
let _tx = register_test("task-slow", "session-A", rq);
- let outcome = wait(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-slow",
- "session-A",
- Duration::from_millis(20),
- )
- .await
- .expect("wait should resolve");
+ let outcome = wait(&cx(), "task-slow", "session-A", Duration::from_millis(20))
+ .await
+ .expect("wait should resolve");
assert!(matches!(
outcome,
WaitOutcome::TimedOut(DetachedSubagentStatus::Running)
@@ -563,7 +520,7 @@ async fn wait_times_out_and_leaves_entry_intact() {
// still steerable after a timed-out wait
assert!(steer(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-slow",
"session-A",
"still here".into(),
@@ -585,13 +542,13 @@ async fn cancel_for_thread_aborts_only_matching_entries() {
// Headless (no parent thread) — must survive.
let _d = register_test_with_thread("task-headless", "session-A", None, rq);
- let cancelled = cancel_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-X");
+ let cancelled = cancel_for_thread(&cx(), "thread-X");
assert_eq!(cancelled, 2, "both thread-X entries should be cancelled");
// The two cancelled entries are gone (steer can't find them).
assert_eq!(
steer(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-tA-1",
"session-A",
"x".into(),
@@ -602,7 +559,7 @@ async fn cancel_for_thread_aborts_only_matching_entries() {
);
assert_eq!(
steer(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-tA-2",
"session-A",
"x".into(),
@@ -613,17 +570,13 @@ async fn cancel_for_thread_aborts_only_matching_entries() {
);
// Non-matching entries stay live and steerable.
+ assert!(
+ steer(&cx(), "task-tB", "session-A", "x".into(), QueueLane::Steer)
+ .await
+ .is_ok()
+ );
assert!(steer(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-tB",
- "session-A",
- "x".into(),
- QueueLane::Steer
- )
- .await
- .is_ok());
- assert!(steer(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-headless",
"session-A",
"x".into(),
@@ -633,10 +586,7 @@ async fn cancel_for_thread_aborts_only_matching_entries() {
.is_ok());
// Idempotent: a second pass cancels nothing.
- assert_eq!(
- cancel_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-X"),
- 0
- );
+ assert_eq!(cancel_for_thread(&cx(), "thread-X"), 0);
prune("task-tB");
prune("task-headless");
@@ -650,8 +600,7 @@ async fn cancel_by_task_returns_metadata_and_removes_entry() {
let task_id = TaskId::new("task-cbt");
shared_steering_registry().register(task_id.clone(), SteeringHandle::allow_all());
- let meta = cancel_by_task(&crate::core::runtime::DispatchCtx::ambient(), "task-cbt")
- .expect("known task should cancel");
+ let meta = cancel_by_task(&cx(), "task-cbt").expect("known task should cancel");
assert_eq!(
meta.already_finished, None,
"a running task is a real cancel"
@@ -666,23 +615,12 @@ async fn cancel_by_task_returns_metadata_and_removes_entry() {
// Entry is gone — steer can no longer find it, and a second cancel is a no-op.
assert_eq!(
- steer(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-cbt",
- "session-Z",
- "x".into(),
- QueueLane::Steer
- )
- .await,
+ steer(&cx(), "task-cbt", "session-Z", "x".into(), QueueLane::Steer).await,
Err(SteerError::Unknown)
);
- assert!(cancel_by_task(&crate::core::runtime::DispatchCtx::ambient(), "task-cbt").is_none());
+ assert!(cancel_by_task(&cx(), "task-cbt").is_none());
// Unknown ids are simply None.
- assert!(cancel_by_task(
- &crate::core::runtime::DispatchCtx::ambient(),
- "never-existed"
- )
- .is_none());
+ assert!(cancel_by_task(&cx(), "never-existed").is_none());
}
/// A finished run stays registered until the terminal sweep, so a late
@@ -719,8 +657,7 @@ async fn cancel_by_task_flags_a_run_that_already_finished() {
for (task_id, status, finished) in cases {
let tx = register_test(task_id, "session-F", run_queue());
tx.send(status).expect("status channel open");
- let meta = cancel_by_task(&crate::core::runtime::DispatchCtx::ambient(), task_id)
- .expect("registered task is found");
+ let meta = cancel_by_task(&cx(), task_id).expect("registered task is found");
assert_eq!(meta.already_finished, finished, "{task_id}");
}
}
@@ -733,7 +670,7 @@ async fn cancel_all_clears_everything() {
// Headless (no parent thread) — aborted, but contributes no thread id.
let _b = register_test_with_thread("task-all-2", "session-B", None, rq);
- let cancelled_threads = cancel_all(&crate::core::runtime::DispatchCtx::ambient());
+ let cancelled_threads = cancel_all(&cx());
assert!(
cancelled_threads.contains(&"thread-1".to_string()),
"cancel_all should report the parent thread of the cancelled sub-agent"
@@ -745,7 +682,7 @@ async fn cancel_all_clears_everything() {
assert_eq!(
steer(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-all-1",
"session-A",
"x".into(),
@@ -756,7 +693,7 @@ async fn cancel_all_clears_everything() {
);
assert_eq!(
steer(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-all-2",
"session-B",
"x".into(),
@@ -766,7 +703,7 @@ async fn cancel_all_clears_everything() {
Err(SteerError::Unknown)
);
// Registry is empty now.
- assert!(cancel_all(&crate::core::runtime::DispatchCtx::ambient(),).is_empty());
+ assert!(cancel_all(&cx(),).is_empty());
}
#[tokio::test]
@@ -778,7 +715,7 @@ async fn stop_for_thread_aborts_the_threads_running_children() {
let child = tokio::spawn(std::future::pending::<()>());
let (_tx, rx) = status_channel();
register(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-stop-1".into(),
"researcher".into(),
"session-stop".into(),
@@ -795,7 +732,7 @@ async fn stop_for_thread_aborts_the_threads_running_children() {
let _other =
register_test_with_thread("task-stop-other", "session-stop", Some("thread-keep"), rq);
- let stopped = stop_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-stop");
+ let stopped = stop_for_thread(&cx(), "thread-stop");
assert_eq!(stopped, vec!["task-stop-1".to_string()]);
let joined = tokio::time::timeout(Duration::from_secs(2), child)
@@ -807,7 +744,7 @@ async fn stop_for_thread_aborts_the_threads_running_children() {
);
assert_eq!(
steer(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-stop-1",
"session-stop",
"x".into(),
@@ -818,7 +755,7 @@ async fn stop_for_thread_aborts_the_threads_running_children() {
);
assert!(
steer(
- &crate::core::runtime::DispatchCtx::ambient(),
+ &cx(),
"task-stop-other",
"session-stop",
"x".into(),
@@ -829,7 +766,7 @@ async fn stop_for_thread_aborts_the_threads_running_children() {
"a different thread's sub-agent is untouched"
);
assert!(
- stop_for_thread(&crate::core::runtime::DispatchCtx::ambient(), "thread-stop").is_empty(),
+ stop_for_thread(&cx(), "thread-stop").is_empty(),
"idempotent"
);