Skip to content

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

chore: files changed crates/openhuman-core/src/cron/scheduler.rs,crates/openhuman-core/src/cron/sche

Steven Enamakel119094c40761
diff --git a/crates/openhuman-core/src/cron/scheduler.rs b/crates/openhuman-core/src/cron/scheduler.rs
index 93f2a0667f..2eb85dec73 100644
--- a/crates/openhuman-core/src/cron/scheduler.rs
+++ b/crates/openhuman-core/src/cron/scheduler.rs
@@ -1,15 +1,18 @@
//! Background scheduler loop for cron jobs: polls the store for due jobs,
-//! runs them with bounded concurrency, persists results, and emits health
+//! dispatches each onto its own task with bounded concurrency (so a long job
+//! never holds up the next poll), persists results, and emits health
//! signals. Job-type execution, retry, delivery, and persistence live in the
//! submodules below.
mod agent_run;
mod delivery;
+mod dispatch;
mod failure_classification;
pub(crate) mod in_flight;
mod retry;
mod run_record;
mod shell_job;
+mod slot;
#[cfg(test)]
#[path = "scheduler_tests.rs"]
@@ -28,7 +31,10 @@ use run_record::*;
#[allow(unused_imports)]
use shell_job::*;
+pub(crate) use dispatch::JobDispatcher;
pub use delivery::deliver_job;
+pub use slot::is_running;
+pub(crate) use slot::SchedulerSlot;
pub use retry::execute_job_now;
use crate::config::Config;
@@ -38,13 +44,17 @@ use crate::cron::{due_jobs, CronJob};
use crate::security::SecurityPolicy;
use anyhow::Result;
use chrono::Utc;
-use futures_util::{stream, StreamExt};
use std::sync::Arc;
use tokio::time::{self, Duration};
const MIN_POLL_SECONDS: u64 = 5;
pub async fn run(config: Config) -> Result<()> {
+ // One poll loop per process: two would each see the same due rows.
+ let Some(_slot) = SchedulerSlot::acquire() else {
+ tracing::warn!("[cron:scheduler] a scheduler loop is already running; not starting another");
+ return Ok(());
+ };
// Ensure the global event bus is initialized so cron delivery events
// are not silently dropped. This is a no-op if already initialized.
crate::core::bus::init().await.expect("bus init");
@@ -70,10 +80,11 @@ pub async fn run(config: Config) -> Result<()> {
// "nothing emitted yet for this run", so the first successful tick
// is treated as a transition and emits.
let mut last_emitted_health: Option<bool> = None;
+ let mut dispatcher = JobDispatcher::new(config.scheduler.max_concurrent);
loop {
interval.tick().await;
- tick_once(&config, &security, &mut last_emitted_health).await;
+ tick_once(&config, &security, &mut last_emitted_health, &mut dispatcher).await;
}
}
@@ -100,6 +111,7 @@ pub(crate) async fn tick_once(
config: &Config,
security: &Arc<SecurityPolicy>,
last_emitted_health: &mut Option<bool>,
+ dispatcher: &mut JobDispatcher,
) {
tracing::debug!("[cron:scheduler] tick poll begin");
let jobs = match due_jobs(config, Utc::now()) {
@@ -151,7 +163,7 @@ pub(crate) async fn tick_once(
return;
}
- process_due_jobs(config, security, jobs).await;
+ dispatcher.dispatch(config, security, jobs).await;
tracing::debug!("[cron:scheduler] tick end due_count={due_count} (jobs processed)");
// `process_due_jobs` itself may have published `healthy: false` on
@@ -162,33 +174,7 @@ pub(crate) async fn tick_once(
*last_emitted_health = None;
}
-async fn process_due_jobs(config: &Config, security: &Arc<SecurityPolicy>, jobs: Vec<CronJob>) {
- let max_concurrent = config.scheduler.max_concurrent.max(1);
- let mut in_flight = stream::iter(jobs.into_iter().map(|job| {
- let config = config.clone();
- let security = Arc::clone(security);
- async move { execute_and_persist_job(&config, security.as_ref(), &job).await }
- }))
- .buffer_unordered(max_concurrent);
-
- while let Some((job_id, success, failure_message)) = in_flight.next().await {
- if success {
- BUS.publish(DomainEvent::HealthChanged {
- component: "scheduler".to_string(),
- healthy: true,
- message: None,
- });
- } else {
- BUS.publish(DomainEvent::HealthChanged {
- component: "scheduler".to_string(),
- healthy: false,
- message: Some(failure_message.unwrap_or_else(|| format!("job {job_id} failed"))),
- });
- }
- }
-}
-
-async fn execute_and_persist_job(
+pub(super) async fn execute_and_persist_job(
config: &Config,
security: &SecurityPolicy,
job: &CronJob,
@@ -224,3 +210,4 @@ async fn execute_and_persist_job(
(job.id.clone(), success, failure_message)
}
+
diff --git a/crates/openhuman-core/src/cron/scheduler/agent_run.rs b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
index 24c030eea0..a05b815350 100644
--- a/crates/openhuman-core/src/cron/scheduler/agent_run.rs
+++ b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
@@ -218,7 +218,7 @@ pub(super) async fn run_agent_job(
/// actual `flows::ops::flows_run` happens asynchronously in
/// `flows::bus::FlowTriggerSubscriber`, which is the sole consumer of this
/// event (kept out of the cron domain so cron stays flow-agnostic).
-pub(super) fn run_flow_schedule_job(job: &CronJob) -> (bool, String) {
+pub(super) async fn run_flow_schedule_job(job: &CronJob) -> (bool, String) {
if let Some(name) = crate::cron::system_jobs::system_job_name(job) {
tracing::info!(job_id = %job.id, job = %name, "[cron] system job due — publishing CronSystemJobDue");
BUS.publish(DomainEvent::CronSystemJobDue {
diff --git a/crates/openhuman-core/src/cron/scheduler/retry.rs b/crates/openhuman-core/src/cron/scheduler/retry.rs
index 2d9f180f88..ff80e78d15 100644
--- a/crates/openhuman-core/src/cron/scheduler/retry.rs
+++ b/crates/openhuman-core/src/cron/scheduler/retry.rs
@@ -49,7 +49,7 @@ pub(super) async fn execute_job_with_retry(
}
JobType::Agent => run_agent_job(config, job).await,
JobType::Flow => {
- let (success, output) = run_flow_schedule_job(job);
+ let (success, output) = run_flow_schedule_job(job).await;
(success, output, None)
}
};
diff --git a/crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rs b/crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rs
index 1f4f792d0c..c501d5204e 100644
--- a/crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_classifier_and_delivery_tests.rs
@@ -459,7 +459,7 @@ async fn scheduler_tick_once_publishes_health_recovery_signal_on_empty_queue() {
// transition and fires the recovery event — same shape as `run()`
// immediately after boot.
let mut last_emitted_health: Option<bool> = None;
- tick_once(&config, &security, &mut last_emitted_health).await;
+ tick_once(&config, &security, &mut last_emitted_health, &mut JobDispatcher::new(1)).await;
// Bus delivery is async — wait briefly for the subscriber to drain.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
@@ -517,7 +517,7 @@ async fn scheduler_tick_once_does_not_re_emit_recovery_signal_on_steady_state()
let mut last_emitted_health: Option<bool> = None;
// First tick: transition from None → Some(true), publishes once.
- tick_once(&config, &security, &mut last_emitted_health).await;
+ tick_once(&config, &security, &mut last_emitted_health, &mut JobDispatcher::new(1)).await;
assert_eq!(
last_emitted_health,
Some(true),
@@ -530,7 +530,7 @@ async fn scheduler_tick_once_does_not_re_emit_recovery_signal_on_steady_state()
// Some(true)` guard inside `tick_once` short-circuited and no
// `publish_global` call ran on those ticks.
for tick in 2..=5 {
- tick_once(&config, &security, &mut last_emitted_health).await;
+ tick_once(&config, &security, &mut last_emitted_health, &mut JobDispatcher::new(1)).await;
assert_eq!(
last_emitted_health,
Some(true),
diff --git a/crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rs b/crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rs
index fe7a6e0439..926c24a47b 100644
--- a/crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_halt_and_persist_tests.rs
@@ -396,7 +396,9 @@ async fn scheduler_flow_runs_active_hours_job_and_reschedules_inside_window() {
&config.workspace_dir,
&config.workspace_dir,
));
- process_due_jobs(&config, &security, vec![job.clone()]).await;
+ let mut dispatcher = JobDispatcher::new(1);
+ dispatcher.dispatch(&config, &security, vec![job.clone()]).await;
+ dispatcher.drain().await;
let stored = cron::get_job(&config, &job.id).unwrap();
assert_eq!(stored.last_status.as_deref(), Some("ok"));