Skip to content

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

test(orchestration): cover thread purge cancelling live driver children

Steven Enamakel9e10a694b2ec
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_thread_delete_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_thread_delete_tests.rs
index e431306c94..1ee1b176f5 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_thread_delete_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_thread_delete_tests.rs
@@ -410,3 +410,213 @@ async fn thread_delete_closes_parent_when_driver_task_scope_cannot_be_resolved()
"stale-driver-task",
);
}
+
+#[tokio::test]
+async fn purging_threads_cancels_driver_children_and_discards_completions() {
+ use crate::agent::orchestration::background_completions::{self, BackgroundAgentOutcome};
+ use crate::agent::tinyagents::host::OpenHumanRunContext;
+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
+ use crate::threads::store::{blocking, CreateConversationThread};
+ use crate::tools::toolpacks::ToolGroups;
+ use tinyagents_harness::context::RunContext;
+ use tinyagents_harness_tools::subagents::SubAgentJobRegistry;
+ use tinyagents_orchestration::subagent::SubAgentJobStatus;
+
+ struct GatedModel {
+ started: tokio::sync::mpsc::Sender<()>,
+ release: Arc<tokio::sync::Notify>,
+ }
+
+ #[async_trait]
+ impl ChatModel<()> for GatedModel {
+ fn profile(&self) -> Option<&ModelProfile> {
+ static PROFILE: std::sync::OnceLock<ModelProfile> = std::sync::OnceLock::new();
+ Some(PROFILE.get_or_init(|| {
+ let mut profile = ModelProfile::default();
+ profile.tool_calling = true;
+ profile.parallel_tool_calls = true;
+ profile
+ }))
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ let _ = self.started.send(()).await;
+ self.release.notified().await;
+ Ok(ModelResponse::assistant("child released after purge"))
+ }
+ }
+
+ let scratch = tempfile::tempdir().expect("isolated thread-purge fixture");
+ let workspace = scratch.path().join("workspace");
+ std::fs::create_dir_all(&workspace).expect("create workspace");
+ let _env =
+ crate::config::test_env::EnvVarGuard::locked_set_async("OPENHUMAN_WORKSPACE", &workspace)
+ .await;
+ let thread_id = "purge-live-driver-parent-thread";
+ let parent_session = "purge-live-driver-parent-session";
+ let (started_tx, mut started_rx) = tokio::sync::mpsc::channel(1);
+ let release = Arc::new(tokio::sync::Notify::new());
+ let provider = Arc::new(GatedModel {
+ started: started_tx,
+ release: release.clone(),
+ });
+ let mut parent = parent_context(&workspace, provider, vec![]);
+ let workspace_descriptor = tinytools::WorkspaceDescriptor::new(workspace.clone());
+ parent.workspace_descriptor = Some(workspace_descriptor.clone());
+ parent.workspace_dir = workspace.clone();
+ parent.session_id = parent_session.into();
+
+ let definitions = Arc::new(AgentDefinitionRegistry::builtins_only());
+ let mut config = crate::config::Config::default();
+ config.workspace_dir = workspace.clone();
+ config.components.juice = false;
+ let core = CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(
+ ContextOverlay::new(config, DomainSet::full(), ToolGroups::none()).definitions(definitions),
+ );
+ let mut host_context = OpenHumanRunContext::new()
+ .with_core(Some(Arc::clone(&core)))
+ .with_parent(parent);
+ host_context.thread_id = Some(thread_id.into());
+ let live = RunContext::<OpenHumanRunContext>::new(
+ tinyagents_harness::context::RunConfig::new("purge-live-driver-parent")
+ .with_thread(thread_id),
+ host_context,
+ )
+ .with_workspace(workspace_descriptor.clone());
+ let dispatch = live.data.dispatch_ctx();
+ blocking::ensure_thread(
+ dispatch.clone(),
+ workspace.clone(),
+ CreateConversationThread {
+ id: thread_id.into(),
+ title: "Purge live driver parent".into(),
+ created_at: "2026-01-01T00:00:00Z".into(),
+ parent_thread_id: None,
+ labels: None,
+ personality_id: None,
+ working_dir: None,
+ },
+ )
+ .await
+ .expect("persist parent thread before spawning child");
+
+ let completion_store: Arc<dyn tinyagents_tasks::CompletionStore> =
+ Arc::new(tinyagents_tasks::InMemoryCompletionStore::new());
+ background_completions::install_store_for_test(&workspace, completion_store);
+ let detached_data = live.data.detached_child();
+ let detached = live
+ .child(
+ tinyagents_harness::context::RunConfig::new("purge-live-driver-child"),
+ detached_data.clone(),
+ )
+ .expect("detached child context")
+ .with_cancellation(detached_data.cancellation.clone());
+ let spawned = crate::agent::orchestration::tools::SpawnSubagentTool::new()
+ .execute_with_live_parent_context(
+ json!({
+ "agent_id": "task_manager_agent",
+ "prompt": "wait for the parent thread to be purged",
+ "model": "test-model"
+ }),
+ None,
+ live.data.child(),
+ detached,
+ )
+ .await
+ .expect("spawn tool execution");
+ assert!(!spawned.is_error, "{}", spawned.output());
+ let task_id = spawned
+ .output()
+ .split("[async_subagent_ref]\n")
+ .nth(1)
+ .and_then(|value| value.split("\n[/async_subagent_ref]").next())
+ .and_then(|value| serde_json::from_str::<serde_json::Value>(value).ok())
+ .and_then(|value| value["task_id"].as_str().map(str::to_owned))
+ .expect("accepted child envelope contains its task ID");
+ tokio::time::timeout(std::time::Duration::from_secs(5), started_rx.recv())
+ .await
+ .expect("child reaches its gated provider call")
+ .expect("provider start notification");
+
+ let jobs = crate::core::runtime::slot_for::<SubAgentJobRegistry>(&dispatch);
+ let job = jobs
+ .list()
+ .into_iter()
+ .find(|job| {
+ job.extensions
+ .get("task_id")
+ .and_then(serde_json::Value::as_str)
+ == Some(task_id.as_str())
+ })
+ .expect("spawned child is live in the TinyAgents job registry");
+ background_completions::record_outcome(
+ &dispatch,
+ &workspace,
+ parent_session,
+ task_id.clone(),
+ "task_manager_agent",
+ "queued child result",
+ Some(thread_id.into()),
+ BackgroundAgentOutcome::Completed,
+ )
+ .await;
+ assert_eq!(
+ background_completions::pending_for(&workspace, thread_id).len(),
+ 1,
+ "the purge starts with a queued child completion"
+ );
+ let release_after_cancel = {
+ let release = release.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ release.notify_one();
+ })
+ };
+
+ tokio::time::timeout(
+ std::time::Duration::from_secs(6),
+ crate::threads::ops::threads_purge(&dispatch, crate::threads::EmptyRequest {}),
+ )
+ .await
+ .expect("purge waits for cancellation-aware child settlement")
+ .expect("purge all threads");
+
+ assert_eq!(
+ jobs.get(job.id.as_str()).map(|job| job.status),
+ Some(SubAgentJobStatus::Cancelled),
+ "purging the parent thread cancels its live TinyAgents child"
+ );
+ assert!(
+ background_completions::pending_for(&workspace, thread_id).is_empty(),
+ "purge discards queued child completions"
+ );
+ background_completions::record_outcome(
+ &dispatch,
+ &workspace,
+ parent_session,
+ task_id,
+ "task_manager_agent",
+ "late child result after purge",
+ Some(thread_id.into()),
+ BackgroundAgentOutcome::Completed,
+ )
+ .await;
+ assert!(
+ background_completions::pending_for(&workspace, thread_id).is_empty(),
+ "a child completion racing after purge remains tombstoned"
+ );
+ assert!(
+ crate::agent::orchestration::completion_owners::driver_tasks_for_thread(
+ &dispatch, &workspace, thread_id,
+ )
+ .is_empty(),
+ "settled purge releases active child owner slots"
+ );
+ release_after_cancel
+ .await
+ .expect("child release task completes");
+}