Skip to content

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

test(saas_mode): add delivery recovery tests

Steven Enamakel53ed17aa227a
diff --git a/tests/saas_mode/delivery_recovery.rs b/tests/saas_mode/delivery_recovery.rs
index 19baada2e9..2bb5e7f5b0 100644
--- a/tests/saas_mode/delivery_recovery.rs
+++ b/tests/saas_mode/delivery_recovery.rs
@@ -1,38 +1,37 @@
//! A detached sub-agent's result survives a restart and reaches the profile
//! that spawned it, through the real binary.
//!
-//! `ann` spawns a detached sub-agent on a thread whose turn then stays in
-//! flight ([`HANG_AFTER_TOOL`]), so the finished result is recorded but
-//! held: delivery never runs into a busy thread. The core is then killed
-//! (SIGKILL: no shutdown hook, no delivery). `bob` has a thread with the same
-//! id on the same core.
+//! The state under test is what a core leaves when it dies between a
+//! sub-agent finishing and its result being delivered: a pending record in
+//! the profile's completion log (`<workspace>/.openhuman/
+//! background_completions.jsonl`), addressed by thread id. The SaaS user
+//! surface does not offer `spawn_async_subagent` (the `agent` domain is off
+//! for profiles), so the record is written here, through the harness's own
+//! store, while the core is down, exactly as `record_completion` would have
+//! written it.
//!
-//! After a restart nothing is delivered at boot: profiles are opened lazily.
-//! Opening `ann`'s profile (`ProfileHost::open` → `recover_on_open`) must
-//! deliver the result into `ann`'s thread, under `ann`'s credential; opening
-//! `bob`'s first, and the whole recovery, must leave `bob`'s thread of the
-//! same id untouched.
+//! `ann` and `bob` both hold a thread named [`THREAD`]. After the restart
+//! nothing is open: opening `bob` first must not deliver anything, and
+//! opening `ann` (`ProfileHost::open` → `recover_on_open`) must deliver the
+//! result into `ann`'s thread, under `ann`'s credential, and leave `bob`'s
+//! thread of the same id untouched.
-use std::path::Path;
+use std::sync::Arc;
+
+use openhuman_core::profiles::{ProfileId, ProfileIdMode, ProfileLayout};
+use tinyagents_tasks::{
+ CompletionRecord, CompletionResult, CompletionStatus, CompletionStore, JsonlCompletionStore,
+ NotifyMode,
+};
-use super::mock_llm::{mock_llm, MockLlm, HANG_AFTER_TOOL, PROBE};
use super::*;
const OWNER: &str = "ann";
const OTHER: &str = "bob";
const THREAD: &str = "shared-thread";
-/// Unique to the sub-agent's task. The mock answers the sub-agent with
-/// `ECHO: <its prompt>`, so [`result`] appears only once the sub-agent ran.
-const MARKER: &str = "delivery-ann-7c1e";
-
-fn task() -> String {
- format!("SUBTASK {MARKER}")
-}
-
-/// The sub-agent's answer, as the mock writes it.
-fn result() -> String {
- format!("ECHO: {}", task())
-}
+/// The sub-agent's result: unique, so it can be traced to every place it
+/// lands.
+const RESULT: &str = "subagent result delivery-ann-7c1e";
fn node_logging(d: &Deployment, backend: u16) -> Node {
start_node_logging(
@@ -45,127 +44,117 @@ fn node_logging(d: &Deployment, backend: u16) -> Node {
)
}
+fn rpc_ok(node: &Node, user: &str, method: &str, params: Value) -> Value {
+ let (status, _, body) = call(node, user, method, params);
+ assert_eq!(status, 200, "{user} {method}: {body}");
+ assert!(body.get("result").is_some(), "{user} {method}: {body}");
+ body
+}
+
fn messages(node: &Node, user: &str) -> String {
- let (status, _, body) = call(
+ rpc_ok(
node,
user,
"openhuman.threads_messages_list",
json!({ "thread_id": THREAD }),
- );
- assert_eq!(status, 200, "{user} lists {THREAD}: {body}");
- assert!(body.get("result").is_some(), "{user} lists {THREAD}: {body}");
- body.to_string()
+ )
+ .to_string()
}
-/// Whether some `background_completions.jsonl` under `root` holds `text`.
-fn completion_log_holds(root: &Path, text: &str) -> bool {
- let Ok(entries) = std::fs::read_dir(root) else {
- return false;
- };
- entries.flatten().any(|entry| {
- let path = entry.path();
- if path.is_dir() {
- completion_log_holds(&path, text)
- } else {
- path.file_name()
- .is_some_and(|name| name == "background_completions.jsonl")
- && std::fs::read_to_string(&path).is_ok_and(|log| log.contains(text))
- }
- })
+/// `user`'s thread [`THREAD`] with one message of their own.
+fn seed_thread(node: &Node, user: &str) {
+ rpc_ok(
+ node,
+ user,
+ "openhuman.threads_upsert",
+ json!({ "id": THREAD, "title": format!("{user}'s thread"),
+ "created_at": "2026-10-10T00:00:00Z" }),
+ );
+ rpc_ok(
+ node,
+ user,
+ "openhuman.threads_message_append",
+ json!({
+ "thread_id": THREAD,
+ "message": { "id": format!("{user}-msg-1"), "content": format!("{user}'s own words"),
+ "type": "text", "extraMetadata": {}, "sender": "user",
+ "createdAt": "2026-10-10T00:00:00Z" }
+ }),
+ );
}
-/// Inference requests carrying the sub-agent's result, by credential.
-fn result_requests(llm: &MockLlm) -> Vec<String> {
- llm.recorded()
- .into_iter()
- .filter(|r| r.is_inference() && r.body.contains(&result()))
- .map(|r| r.auth)
- .collect()
+/// The pending record a core killed before delivery leaves in `user`'s
+/// completion log.
+fn leave_undelivered_result(root: &std::path::Path, user: &str) {
+ let id = ProfileId::for_user(user, ProfileIdMode::Raw).unwrap();
+ let workspace = ProfileLayout::new(root, &id).workspace_dir;
+ let log = workspace.join(".openhuman").join("background_completions.jsonl");
+ std::fs::create_dir_all(log.parent().unwrap()).unwrap();
+ let store: Arc<dyn CompletionStore> =
+ Arc::new(JsonlCompletionStore::open(&log).expect("open the completion log"));
+ let record = CompletionRecord::new(
+ "task-delivery-recovery-1",
+ THREAD,
+ "researcher",
+ CompletionStatus::Success,
+ CompletionResult::text(RESULT),
+ )
+ .with_notify_mode(NotifyMode::Followup);
+ store.put(&record).expect("write the pending record");
}
#[test]
-fn a_held_subagent_result_reaches_its_own_profile_after_a_restart() {
+fn an_undelivered_subagent_result_reaches_its_own_profile_after_a_restart() {
let d = deployment(true);
- let llm = mock_llm();
+ let llm = mock_llm::mock_llm();
let mut node = node_logging(&d, llm.port);
provision_with_credential(&node, OWNER);
provision_with_credential(&node, OTHER);
+ seed_thread(&node, OWNER);
+ seed_thread(&node, OTHER);
+ assert!(!messages(&node, OWNER).contains(RESULT));
- // bob holds a thread with the same id, with a finished turn of his own.
- let (status, _, body) = call(
- &node,
- OTHER,
- "openhuman.channel_web_chat",
- json!({ "client_id": "c1", "thread_id": THREAD, "message": "bob's own words" }),
- );
- assert_eq!(status, 200, "{body}");
- wait_until("bob's turn", &node, Duration::from_secs(60), || {
- messages(&node, OTHER).contains("ECHO: bob's own words")
- });
-
- // ann's turn spawns a detached sub-agent, then stays in flight.
- let args = json!({ "agent_id": "task_manager_agent", "prompt": task() });
- let message = format!("{PROBE} spawn_async_subagent {args}\n{HANG_AFTER_TOOL}");
- let (status, _, body) = call(
- &node,
- OWNER,
- "openhuman.channel_web_chat",
- json!({ "client_id": "c1", "thread_id": THREAD, "message": message }),
- );
- assert_eq!(status, 200, "{body}");
- assert!(body.get("result").is_some(), "{body}");
-
- // The sub-agent finishes and its result is recorded, but not delivered:
- // ann's turn on the thread is still running.
- wait_until(
- "the sub-agent's recorded result",
- &node,
- Duration::from_secs(90),
- || completion_log_holds(&d.root, &result()),
- );
- assert!(
- active(&node, OWNER, THREAD),
- "ann's turn stays in flight while the result is held"
- );
- assert!(
- !messages(&node, OWNER).contains(&result()),
- "the result is held while ann's turn runs"
- );
- let before = node.log_tail();
+ // The core dies with ann's sub-agent result recorded but undelivered.
node.kill();
+ leave_undelivered_result(&d.root, OWNER);
- // Restart. Nothing is open until a user calls.
+ // Restart. Opening bob, whose thread has the same id, delivers nothing.
let node = node_logging(&d, llm.port);
let bob_before = messages(&node, OTHER);
- assert!(!bob_before.contains(MARKER), "{bob_before}");
+ assert!(bob_before.contains("bob's own words"), "{bob_before}");
+ assert!(!bob_before.contains(RESULT), "{bob_before}");
- // Opening ann's profile recovers the held result into ann's thread.
+ // Opening ann recovers the result into ann's thread.
wait_until(
"the recovered delivery into ann's thread",
&node,
Duration::from_secs(120),
- || messages(&node, OWNER).contains(&result()),
+ || messages(&node, OWNER).contains(RESULT),
);
+ let ann = messages(&node, OWNER);
+ assert!(ann.contains("ann's own words"), "{ann}");
- // Give any stray drain time to land, then check bob is untouched.
+ // Let any stray drain land, then check bob's thread is as it was.
std::thread::sleep(Duration::from_secs(5));
let bob_after = messages(&node, OTHER);
assert!(
- !bob_after.contains(MARKER),
+ !bob_after.contains(RESULT),
"ann's result reached bob's thread of the same id: {bob_after}"
);
- assert_eq!(
- bob_before, bob_after,
- "recovery changed bob's thread of the same id"
- );
+ assert_eq!(bob_before, bob_after, "recovery changed bob's thread");
// Every inference request that carried the result ran as ann.
- let carriers = result_requests(&llm);
- assert!(!carriers.is_empty(), "the result went through inference");
+ let carriers: Vec<String> = llm
+ .recorded()
+ .into_iter()
+ .filter(|r| r.is_inference() && r.body.contains(RESULT))
+ .map(|r| r.auth)
+ .collect();
+ assert!(!carriers.is_empty(), "the delivery turn reached inference");
for auth in &carriers {
assert!(
auth.contains(&format!("{OWNER}-jwt")),
- "ann's result was sent under another credential (before kill:\n{before}\n)"
+ "ann's result went to inference under another credential"
);
}
}