The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
test(cron): cover durable admission and lost ack reply handling
Steven Enamakel707f402f6e5c
diff --git a/crates/openhuman-core/src/cron/documents_port.rs b/crates/openhuman-core/src/cron/documents_port.rsindex dbd80eab44..1c80d31d24 100644--- a/crates/openhuman-core/src/cron/documents_port.rs+++ b/crates/openhuman-core/src/cron/documents_port.rs@@ -288,6 +288,8 @@ impl DocumentsPort {}}}+ #[cfg(test)]+ pause_manual_claim_if_armed(&ops).await;encode(documents.atomic_batch(ops).await?)}_ => Err(StorageError::invalid_input("unexpected document request")),@@ -295,6 +297,73 @@ impl DocumentsPort {}}+#[cfg(test)]+struct ManualClaimTestGate {+ entered: std::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>,+ release: tokio::sync::Mutex<Option<tokio::sync::oneshot::Receiver<()>>>,+}++#[cfg(test)]+static MANUAL_CLAIM_TEST_GATES: LazyLock<+ std::sync::Mutex<HashMap<String, Arc<ManualClaimTestGate>>>,+> = LazyLock::new(Default::default);++#[cfg(test)]+pub(crate) fn pause_manual_claim_for_test(+ job_id: &str,+) -> (tokio::sync::oneshot::Receiver<()>, tokio::sync::oneshot::Sender<()>) {+ let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();+ MANUAL_CLAIM_TEST_GATES+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(+ job_id.to_string(),+ Arc::new(ManualClaimTestGate {+ entered: std::sync::Mutex::new(Some(entered_tx)),+ release: tokio::sync::Mutex::new(Some(release_rx)),+ }),+ );+ (entered_rx, release_tx)+}++#[cfg(test)]+async fn pause_manual_claim_if_armed(ops: &[WriteOp]) {+ let job_id = ops.iter().find_map(|operation| match operation {+ WriteOp::Put { collection, id, .. }+ if collection == "cron.jobs"+ && MANUAL_CLAIM_TEST_GATES+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .contains_key(id) =>+ {+ Some(id.clone())+ }+ _ => None,+ });+ let Some(job_id) = job_id else {+ return;+ };+ let gate = MANUAL_CLAIM_TEST_GATES+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .remove(&job_id);+ let Some(gate) = gate else {+ return;+ };+ if let Some(entered) = gate+ .entered+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .take()+ {+ let _ = entered.send(());+ }+ if let Some(release) = gate.release.lock().await.take() {+ let _ = release.await;+ }+}+#[tinybus::interface(name = "ai.tinyhumans.tinyflows.ScheduleDocuments")]impl DocumentsPort {/// One mechanical document request; see the module docs for the shapes.diff --git a/crates/openhuman-core/src/cron/ops_delivery_tests.rs b/crates/openhuman-core/src/cron/ops_delivery_tests.rsindex 0cc09374c0..821b7813c9 100644--- a/crates/openhuman-core/src/cron/ops_delivery_tests.rs+++ b/crates/openhuman-core/src/cron/ops_delivery_tests.rs@@ -296,7 +296,7 @@ async fn manual_run_projects_its_captured_job_after_the_saved_job_is_deleted() {}#[tokio::test]-async fn detached_manual_run_returns_only_after_the_worker_is_running() {+async fn detached_manual_run_waits_for_durable_admission_after_starting() {use tokio::sync::oneshot;crate::core::bus::init().await.unwrap();@@ -324,6 +324,8 @@ async fn detached_manual_run_returns_only_after_the_worker_is_running() {}),);let job = tests::single_flight_system_job(&config, &name);+ let (claim_entered, claim_release) =+ crate::cron::documents_port::pause_manual_claim_for_test(&job.id);let run_id = format!("detached-{}", uuid::Uuid::new_v4());let dispatch = crate::core::runtime::DispatchCtx::ambient();let task_config = config.clone();@@ -341,14 +343,19 @@ async fn detached_manual_run_returns_only_after_the_worker_is_running() {.await});- tokio::time::timeout(std::time::Duration::from_secs(3), async {- tokio::select! {- result = &mut call => panic!("manual call returned before its handler started: {result:?}"),- started = started_rx => started.expect("handler start signal remains open"),- }- })- .await- .expect("the manual worker reaches its running state");+ tokio::time::timeout(std::time::Duration::from_secs(3), claim_entered)+ .await+ .expect("manual claim reaches the controlled storage boundary")+ .expect("claim gate remains open");+ assert!(+ !call.is_finished(),+ "Starting is not admission while the durable claim is blocked"+ );+ let _ = claim_release.send(());+ tokio::time::timeout(std::time::Duration::from_secs(3), started_rx)+ .await+ .expect("the worker proceeds after durable claim")+ .expect("handler start signal remains open");let reply = tokio::time::timeout(std::time::Duration::from_secs(3), call).await.expect("confirmed running is returned promptly")@@ -499,6 +506,73 @@ async fn manual_run_claims_are_shared_within_a_scope_and_isolated_between_agentsassert_eq!(beta_runs[0].run_id.as_deref(), Some(beta_id.as_str()));}+#[tokio::test]+async fn manual_owner_reconciles_a_lost_committed_ack_before_releasing_context() {+ use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};++ crate::core::bus::init().await.unwrap();+ let tmp = TempDir::new().unwrap();+ let config = tests::test_config(&tmp);+ let agent = format!("ack-retention-{}", uuid::Uuid::new_v4().simple());+ let context = CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(+ ContextOverlay::new(+ config.clone(),+ DomainSet::full(),+ crate::tools::toolpacks::ToolGroups::none(),+ )+ .session_agent(agent),+ );+ let weak = Arc::downgrade(&context);+ let name = format!("ack-retention-job-{}", uuid::Uuid::new_v4().simple());+ let job = CoreContext::scope(Arc::clone(&context), async {+ tests::single_flight_system_job(&config, &name)+ })+ .await;+ let _handler = crate::cron::system_job_handlers::register(+ &name,+ Arc::new(|_| Box::pin(async { Ok(()) })),+ );+ let (ack_committed, allow_lost_reply) =+ crate::cron::scheduler::lose_next_ack_reply_after_commit_for_test(+ config.workspace_dir.clone(),+ );+ let dispatch = DispatchCtx::new(Arc::clone(&context));+ drop(context);++ let result = crate::cron::scheduler::run_job_now(+ &dispatch,+ &config,+ job,+ format!("ack-run-{}", uuid::Uuid::new_v4()),+ true,+ tinyflows_bus::schedule::ManualDelivery::NotRequested,+ )+ .await+ .expect("the completed result is delivered independently from acknowledgement");+ assert!(matches!(+ result,+ tinyflows_bus::schedule::RunJobReply::Completed { success: true, .. }+ ));+ drop(dispatch);+ tokio::time::timeout(std::time::Duration::from_secs(3), ack_committed)+ .await+ .expect("the first acknowledgement committed before its response was lost")+ .expect("ack response loss gate remains open");+ assert!(+ weak.upgrade().is_some(),+ "the callback owner retains its bound context until Ack is reconciled"+ );++ let _ = allow_lost_reply.send(());+ tokio::time::timeout(std::time::Duration::from_secs(3), async {+ while weak.upgrade().is_some() {+ tokio::task::yield_now().await;+ }+ })+ .await+ .expect("the invocation context is released after Ack reconciliation");+}+#[tokio::test]async fn cancelled_waiting_caller_keeps_manual_run_callback_served_until_completion() {use crate::core::events::DomainEvent;diff --git a/crates/openhuman-core/src/cron/scheduler/dispatcher.rs b/crates/openhuman-core/src/cron/scheduler/dispatcher.rsindex 9ddf7c0afd..d88709da35 100644--- a/crates/openhuman-core/src/cron/scheduler/dispatcher.rs+++ b/crates/openhuman-core/src/cron/scheduler/dispatcher.rs@@ -1,4 +1,6 @@use super::*;+#[cfg(test)]+use std::path::PathBuf;use tinyflows_bus::schedule::{AcknowledgeManualRun, ManualRunHandle, ManualRunOutcome, ManualRunRequest, ManualRunState,PrepareManualRun, StartManualRun, WaitManualRun,@@ -259,11 +261,10 @@ async fn own_manual_run(let mut retry_delay = Duration::from_millis(20);loop {let result = match module::proxy(&config).await {- Ok(proxy) => {- proxy- .call::<bool>(members::ACKNOWLEDGE_MANUAL_RUN, (&ack,))- .await- }+ Ok(proxy) => proxy+ .call::<bool>(members::ACKNOWLEDGE_MANUAL_RUN, (&ack,))+ .await+ .map_err(|error| error.wire_message()),Err(error) => {tracing::debug!(%error, "[cron:scheduler] retrying AcknowledgeManualRun");tokio::time::sleep(retry_delay).await;@@ -271,6 +272,14 @@ async fn own_manual_run(continue;}};+ #[cfg(test)]+ let result = if result.as_ref().is_ok_and(|acknowledged| *acknowledged)+ && wait_for_ack_reply_loss_test_gate(&config.workspace_dir).await+ {+ Err("simulated lost AcknowledgeManualRun reply after commit".to_string())+ } else {+ result+ };match result {Ok(true) => break,Ok(false) => {@@ -297,7 +306,7 @@ async fn own_manual_run(}}Err(error) => {- tracing::debug!(error = %error.wire_message(), "[cron:scheduler] retrying ambiguous AcknowledgeManualRun")+ tracing::debug!(%error, "[cron:scheduler] retrying ambiguous AcknowledgeManualRun")}}tokio::time::sleep(retry_delay).await;@@ -307,6 +316,59 @@ async fn own_manual_run(Ok(())}+#[cfg(test)]+struct AckReplyLossTestGate {+ entered: std::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>,+ release: tokio::sync::Mutex<Option<tokio::sync::oneshot::Receiver<()>>>,+}++#[cfg(test)]+static ACK_REPLY_LOSS_TEST_GATES: std::sync::LazyLock<+ std::sync::Mutex<std::collections::HashMap<PathBuf, Arc<AckReplyLossTestGate>>>,+> = std::sync::LazyLock::new(Default::default);++#[cfg(test)]+pub(crate) fn lose_next_ack_reply_after_commit_for_test(+ workspace: PathBuf,+) -> (tokio::sync::oneshot::Receiver<()>, tokio::sync::oneshot::Sender<()>) {+ let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();+ ACK_REPLY_LOSS_TEST_GATES+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .insert(+ workspace,+ Arc::new(AckReplyLossTestGate {+ entered: std::sync::Mutex::new(Some(entered_tx)),+ release: tokio::sync::Mutex::new(Some(release_rx)),+ }),+ );+ (entered_rx, release_tx)+}++#[cfg(test)]+async fn wait_for_ack_reply_loss_test_gate(workspace: &std::path::Path) -> bool {+ let gate = ACK_REPLY_LOSS_TEST_GATES+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .remove(workspace);+ let Some(gate) = gate else {+ return false;+ };+ if let Some(entered) = gate+ .entered+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .take()+ {+ let _ = entered.send(());+ }+ if let Some(release) = gate.release.lock().await.take() {+ let _ = release.await;+ }+ true+}+/// Single poll cycle of the scheduler loop, extracted so tests can drive/// it without owning `tokio::time::interval`.///diff --git a/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs b/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rsindex 1ed0929e34..28f14d85ce 100644--- a/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs+++ b/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs@@ -232,7 +232,7 @@ async fn module_scheduler_slot_is_per_store_scope_and_refuses_a_duplicate() {}#[tokio::test]-async fn started_agent_scheduler_pins_its_context_only_until_stop_is_confirmed() {+async fn started_agent_scheduler_releases_its_context_after_stop_is_confirmed() {use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};let tmp = TempDir::new().unwrap();