Skip to content

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

test(cron): cover the bus host, handler registry, and cutover

Steven Enamakelcad0b791fec3
diff --git a/crates/openhuman-core/src/cron/bus_host_tests.rs b/crates/openhuman-core/src/cron/bus_host_tests.rs
index 4563e55b7b..860d253422 100644
--- a/crates/openhuman-core/src/cron/bus_host_tests.rs
+++ b/crates/openhuman-core/src/cron/bus_host_tests.rs
@@ -1 +1,269 @@
+//! The callback adapter, driven the way the module drives it: over the bus, on
+//! the contract's `ScheduleHost` interface, against the real (linked) module.
+
use super::*;
+use crate::cron::handlers::{kind_handler, register_kind, JobKindHandler, JobOutcome, JobRunContext};
+use async_trait::async_trait;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use tempfile::TempDir;
+use tinyflows_bus::schedule::types::Schedule;
+use tinyflows_bus::schedule::{callbacks, CALLBACK_INTERFACE};
+
+fn config(tmp: &TempDir) -> Config {
+ let config = Config {
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Config::default()
+ };
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ config
+}
+
+async fn host(config: &Config, agent_only: bool) -> (HostRegistration, tinybus::Proxy) {
+ module::proxy(config).await.expect("module attaches");
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ let mut binding = Binding::new(&DispatchCtx::ambient(), config, security);
+ if agent_only {
+ binding = binding.agent_only();
+ }
+ let registration = register(binding).await.expect("host object is served");
+ let address = registration.address();
+ let proxy = crate::modules::runtime::runtime()
+ .await
+ .unwrap()
+ .connection()
+ .proxy(&address.destination, &address.object_path, CALLBACK_INTERFACE)
+ .expect("the contract's callback interface is the one served");
+ (registration, proxy)
+}
+
+fn shell_job(config: &Config, command: &str) -> CronJob {
+ crate::cron::add_shell_job(
+ config,
+ None,
+ Schedule::Every {
+ every_ms: 3_600_000,
+ },
+ command,
+ )
+ .unwrap()
+}
+
+/// Runs jobs whose command starts with `bus-host-test:` itself and hands every
+/// other job to the handler it replaced, so tests running in parallel keep
+/// their real shell/flow behaviour.
+struct Marker {
+ inner: Arc<dyn JobKindHandler>,
+ calls: Arc<AtomicUsize>,
+ permanent: bool,
+}
+
+#[async_trait]
+impl JobKindHandler for Marker {
+ async fn run(&self, cx: &JobRunContext, job: &CronJob, run_id: &str) -> JobOutcome {
+ if !job.command.starts_with("bus-host-test:") {
+ return self.inner.run(cx, job, run_id).await;
+ }
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ let outcome = JobOutcome::failed(format!("marker ran {run_id}"));
+ if self.permanent {
+ outcome.permanent()
+ } else {
+ outcome
+ }
+ }
+}
+
+#[tokio::test]
+async fn execute_runs_the_registered_handler_and_reports_a_retryable_failure() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let (_host, proxy) = host(&config, false).await;
+ let calls = Arc::new(AtomicUsize::new(0));
+ let _registration = register_kind(
+ JobType::Shell,
+ Arc::new(Marker {
+ inner: kind_handler(&JobType::Shell).unwrap(),
+ calls: Arc::clone(&calls),
+ permanent: false,
+ }),
+ );
+ let job = shell_job(&config, "bus-host-test:retryable");
+ let attempt: Attempt = proxy
+ .call(callbacks::EXECUTE, (&job, "run-a"))
+ .await
+ .unwrap();
+ assert!(!attempt.success);
+ assert!(attempt.retryable, "an ordinary failure may be retried");
+ assert_eq!(attempt.output, "marker ran run-a");
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn a_permanent_handler_outcome_stops_the_retry_loop() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let (_host, proxy) = host(&config, false).await;
+ let _registration = register_kind(
+ JobType::Shell,
+ Arc::new(Marker {
+ inner: kind_handler(&JobType::Shell).unwrap(),
+ calls: Arc::new(AtomicUsize::new(0)),
+ permanent: true,
+ }),
+ );
+ let job = shell_job(&config, "bus-host-test:permanent");
+ let attempt: Attempt = proxy
+ .call(callbacks::EXECUTE, (&job, "run-b"))
+ .await
+ .unwrap();
+ assert!(!attempt.success);
+ assert!(!attempt.retryable);
+}
+
+#[tokio::test]
+async fn an_agent_only_scheduler_refuses_shell_jobs_before_running_anything() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let (_host, proxy) = host(&config, true).await;
+ let calls = Arc::new(AtomicUsize::new(0));
+ let _registration = register_kind(
+ JobType::Shell,
+ Arc::new(Marker {
+ inner: kind_handler(&JobType::Shell).unwrap(),
+ calls: Arc::clone(&calls),
+ permanent: false,
+ }),
+ );
+ let job = shell_job(&config, "bus-host-test:refused");
+ let attempt: Attempt = proxy
+ .call(callbacks::EXECUTE, (&job, "run-c"))
+ .await
+ .unwrap();
+ assert!(!attempt.success);
+ assert!(!attempt.retryable);
+ assert!(attempt.output.contains("only agent cron jobs"), "{}", attempt.output);
+ assert_eq!(calls.load(Ordering::SeqCst), 0, "the handler never ran");
+ let trigger: Attempt = proxy
+ .call(callbacks::SCHEDULE_TRIGGER, ("some-flow", "run-d"))
+ .await
+ .unwrap();
+ assert!(!trigger.success, "flow ticks are refused too");
+}
+
+#[tokio::test]
+async fn failed_is_accepted_for_any_job() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let (_host, proxy) = host(&config, false).await;
+ let job = shell_job(&config, "echo nothing");
+ let attempt = Attempt {
+ success: false,
+ output: "boom".into(),
+ retryable: false,
+ };
+ proxy
+ .call::<()>(callbacks::FAILED, (&job, "run-e", &attempt))
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn deliver_answers_with_the_delivery_status_string() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let (_host, proxy) = host(&config, false).await;
+ let job = shell_job(&config, "echo nothing");
+ let attempt = Attempt {
+ success: true,
+ output: "result".into(),
+ retryable: true,
+ };
+ let status: String = proxy
+ .call(callbacks::DELIVER, (&job, "run-f", &attempt))
+ .await
+ .unwrap();
+ assert_eq!(status, "not_requested", "delivery mode `none` sends nothing");
+ assert!(DeliveryStatus::parse(&status).is_some());
+}
+
+#[tokio::test]
+async fn schedule_trigger_runs_a_system_job_and_records_the_handler_result() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let (_host, proxy) = host(&config, false).await;
+ let calls = Arc::new(AtomicUsize::new(0));
+ let seen = Arc::clone(&calls);
+ let _handler = crate::cron::system_job_handlers::register(
+ "bus-host-system",
+ Arc::new(move |ctx| {
+ seen.fetch_add(1, Ordering::SeqCst);
+ Box::pin(async move {
+ assert_eq!(ctx.name, "bus-host-system");
+ Ok(())
+ })
+ }),
+ );
+ let row = crate::cron::system_jobs::ensure_system_job(
+ &config,
+ "bus-host-system",
+ Schedule::Every {
+ every_ms: 3_600_000,
+ },
+ )
+ .unwrap();
+ let attempt: Attempt = proxy
+ .call(callbacks::SCHEDULE_TRIGGER, (&row.command, "run-g"))
+ .await
+ .unwrap();
+ assert!(attempt.success, "{}", attempt.output);
+ assert!(attempt.output.contains("completed"), "{}", attempt.output);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+}
+
+#[cfg(feature = "flows")]
+#[tokio::test]
+async fn schedule_trigger_for_an_unknown_flow_is_answered_not_failed() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let (_host, proxy) = host(&config, false).await;
+ let attempt: Attempt = proxy
+ .call(callbacks::SCHEDULE_TRIGGER, ("flow-never-saved", "run-h"))
+ .await
+ .unwrap();
+ assert!(attempt.success, "{}", attempt.output);
+ assert!(
+ attempt.output.contains("flow schedule tick emitted"),
+ "{}",
+ attempt.output
+ );
+}
+
+#[tokio::test]
+async fn dropping_the_registration_stops_serving_the_object() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let (registration, proxy) = host(&config, false).await;
+ let job = shell_job(&config, "echo nothing");
+ let attempt = Attempt {
+ success: true,
+ output: String::new(),
+ retryable: true,
+ };
+ drop(registration);
+ for _ in 0..100 {
+ let reply: Result<(), _> = proxy
+ .call(callbacks::FAILED, (&job, "run-i", &attempt))
+ .await;
+ if reply.is_err() {
+ return;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ panic!("the host object kept answering after its registration dropped");
+}
diff --git a/crates/openhuman-core/src/cron/cutover_tests.rs b/crates/openhuman-core/src/cron/cutover_tests.rs
new file mode 100644
index 0000000000..bce2dc4c0e
--- /dev/null
+++ b/crates/openhuman-core/src/cron/cutover_tests.rs
@@ -0,0 +1,114 @@
+//! Jobs that existed before the cutover to the `tinyflows` module keep firing
+//! through it: host-owned system jobs, the seeded briefing, flow schedule rows
+//! and rows imported from the old `jobs.db`. The module owns when they run;
+//! these pin that the host's callbacks answer for each kind.
+
+use super::*;
+use crate::config::Config;
+use crate::memory::lifecycle::jobs::BACKGROUND_JOB;
+use crate::security::SecurityPolicy;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use tempfile::TempDir;
+
+fn config(tmp: &TempDir) -> Config {
+ let config = Config {
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Config::default()
+ };
+ std::fs::create_dir_all(&config.workspace_dir).unwrap();
+ config
+}
+
+fn dispatcher(config: &Config) -> scheduler::JobDispatcher {
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ scheduler::JobDispatcher::new(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ config,
+ &security,
+ )
+}
+
+#[tokio::test]
+async fn a_seeded_system_job_fires_through_the_module_and_records_its_handler() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let calls = Arc::new(AtomicUsize::new(0));
+ let seen = Arc::clone(&calls);
+ let _handler = system_job_handlers::register(
+ BACKGROUND_JOB,
+ Arc::new(move |_ctx| {
+ seen.fetch_add(1, Ordering::SeqCst);
+ Box::pin(async { Ok(()) })
+ }),
+ );
+ system_jobs::ensure_memory_jobs(&config).unwrap();
+ let job = list_jobs(&config)
+ .unwrap()
+ .into_iter()
+ .find(|job| system_jobs::system_job_name(job) == Some(BACKGROUND_JOB))
+ .expect("the memory background job is seeded");
+ store::force_next_run_for_test(&config, &job.id, chrono::Utc::now() - chrono::Duration::seconds(1))
+ .unwrap();
+
+ let mut dispatcher = dispatcher(&config);
+ assert!(dispatcher.tick(&config).await.unwrap() >= 1);
+ dispatcher.drain().await;
+
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ let after = get_job(&config, &job.id).unwrap();
+ assert_eq!(after.last_status.as_deref(), Some("ok"));
+ assert!(after.next_run > chrono::Utc::now(), "the recurrence moved on");
+}
+
+#[tokio::test]
+async fn the_seeded_morning_briefing_stays_dormant_until_enabled() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ seed::seed_proactive_agents(&config).unwrap();
+ let briefing = list_jobs(&config)
+ .unwrap()
+ .into_iter()
+ .find(|job| job.name.as_deref() == Some("morning_briefing"))
+ .expect("seeded");
+ assert!(!briefing.enabled, "opt-in: seeded disabled");
+ let mut dispatcher = dispatcher(&config);
+ assert_eq!(dispatcher.tick(&config).await.unwrap(), 0);
+ // Seeding twice neither duplicates nor changes it.
+ seed::seed_proactive_agents(&config).unwrap();
+ assert_eq!(
+ list_jobs(&config)
+ .unwrap()
+ .iter()
+ .filter(|job| job.name.as_deref() == Some("morning_briefing"))
+ .count(),
+ 1
+ );
+}
+
+#[tokio::test]
+async fn a_flow_schedule_row_is_answered_by_the_flow_handler_on_a_tick() {
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let row = add_flow_schedule_job(
+ &config,
+ "flow-cutover",
+ Schedule::Every {
+ every_ms: 3_600_000,
+ },
+ )
+ .unwrap();
+ store::force_next_run_for_test(&config, &row.id, chrono::Utc::now() - chrono::Duration::seconds(1))
+ .unwrap();
+ let mut dispatcher = dispatcher(&config);
+ assert_eq!(dispatcher.tick(&config).await.unwrap(), 1);
+ dispatcher.drain().await;
+ let after = get_job(&config, &row.id).unwrap();
+ assert_eq!(after.last_status.as_deref(), Some("ok"));
+}
diff --git a/crates/openhuman-core/src/cron/handlers_tests.rs b/crates/openhuman-core/src/cron/handlers_tests.rs
index 4563e55b7b..cb3a50d97b 100644
--- a/crates/openhuman-core/src/cron/handlers_tests.rs
+++ b/crates/openhuman-core/src/cron/handlers_tests.rs
@@ -1 +1,101 @@
use super::*;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+/// Answers jobs whose command starts with `handlers-test:` and hands every
+/// other job to the handler it replaced, so parallel tests keep the defaults.
+struct Tagged {
+ tag: &'static str,
+ inner: Option<Arc<dyn JobKindHandler>>,
+ calls: Arc<AtomicUsize>,
+}
+
+#[async_trait]
+impl JobKindHandler for Tagged {
+ async fn run(&self, cx: &JobRunContext, job: &CronJob, run_id: &str) -> JobOutcome {
+ if job.command.starts_with("handlers-test:") {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ return JobOutcome::ok(self.tag);
+ }
+ match &self.inner {
+ Some(inner) => inner.run(cx, job, run_id).await,
+ None => JobOutcome::failed("no inner handler"),
+ }
+ }
+}
+
+fn tagged(tag: &'static str) -> Arc<Tagged> {
+ Arc::new(Tagged {
+ tag,
+ inner: kind_handler(&JobType::Flow),
+ calls: Arc::new(AtomicUsize::new(0)),
+ })
+}
+
+fn same(a: &Option<Arc<dyn JobKindHandler>>, b: &Arc<dyn JobKindHandler>) -> bool {
+ a.as_ref().is_some_and(|a| Arc::ptr_eq(a, b))
+}
+
+#[test]
+fn every_job_kind_has_a_default_handler() {
+ for kind in [JobType::Shell, JobType::Agent, JobType::Flow] {
+ assert!(kind_handler(&kind).is_some(), "{}", kind.as_str());
+ }
+}
+
+#[test]
+fn a_later_registration_wins_and_dropping_restores_in_order() {
+ let default = kind_handler(&JobType::Flow).unwrap();
+ let first: Arc<dyn JobKindHandler> = tagged("first");
+ let second: Arc<dyn JobKindHandler> = tagged("second");
+ let one = register_kind(JobType::Flow, Arc::clone(&first));
+ assert!(same(&kind_handler(&JobType::Flow), &first));
+ let two = register_kind(JobType::Flow, Arc::clone(&second));
+ assert!(same(&kind_handler(&JobType::Flow), &second));
+ // Dropping the older guard leaves the newer handler in place.
+ drop(one);
+ assert!(same(&kind_handler(&JobType::Flow), &second));
+ // Dropping the newer one restores what it replaced (the first), which its
+ // own guard already gave up; the registry never resurrects a dropped one.
+ drop(two);
+ let current = kind_handler(&JobType::Flow);
+ assert!(
+ same(&current, &first) || same(&current, &default),
+ "restored to a handler that was current before"
+ );
+}
+
+#[tokio::test]
+async fn the_registered_handler_decides_the_outcome() {
+ let handler = tagged("custom");
+ let calls = Arc::clone(&handler.calls);
+ let _guard = register_kind(JobType::Flow, handler);
+ let registry = kind_handler(&JobType::Flow).unwrap();
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = Config {
+ workspace_dir: tmp.path().into(),
+ ..Config::default()
+ };
+ let binding = Binding::new(
+ &DispatchCtx::ambient(),
+ &config,
+ Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ )),
+ );
+ let job = crate::cron::scheduler::run_delivery::stand_in_for_test("handlers-test:x");
+ let outcome = registry
+ .run(&JobRunContext::new(binding), &job, "run-1")
+ .await;
+ assert_eq!(outcome, JobOutcome::ok("custom"));
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn outcome_builders_set_success_and_permanence() {
+ assert!(JobOutcome::ok("x").success);
+ let failed = JobOutcome::failed("x");
+ assert!(!failed.success && !failed.permanent);
+ assert!(failed.permanent().permanent);
+}
diff --git a/crates/openhuman-core/src/cron/mod.rs b/crates/openhuman-core/src/cron/mod.rs
index 07c1116254..9dc5377245 100644
--- a/crates/openhuman-core/src/cron/mod.rs
+++ b/crates/openhuman-core/src/cron/mod.rs
@@ -33,6 +33,10 @@ pub mod tools;
pub mod scheduler;
+#[cfg(test)]
+#[path = "cutover_tests.rs"]
+mod cutover_tests;
+
pub use ops as rpc;
#[cfg(test)]
pub use ops::update_cron_job;
diff --git a/crates/openhuman-core/src/cron/scheduler/run_delivery.rs b/crates/openhuman-core/src/cron/scheduler/run_delivery.rs
index a6ce57bb8d..1c4aefb86d 100644
--- a/crates/openhuman-core/src/cron/scheduler/run_delivery.rs
+++ b/crates/openhuman-core/src/cron/scheduler/run_delivery.rs
@@ -95,6 +95,12 @@ fn stand_in(flow_id: &str) -> CronJob {
}
}
+/// A stand-in `flow` row with `command`, for tests of handlers.
+#[cfg(test)]
+pub(crate) fn stand_in_for_test(command: &str) -> CronJob {
+ stand_in(command)
+}
+
/// Fire the `flow` row bound to `flow_id` through the registered `flow`
/// handler.
pub(crate) async fn trigger(binding: &Binding, flow_id: &str, run_id: &str) -> Attempt {