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 Enamakel6d6f6b4043b5
diff --git a/crates/openhuman-core/src/cron/scheduler.rs b/crates/openhuman-core/src/cron/scheduler.rs
index 2eb85dec73..21989581de 100644
--- a/crates/openhuman-core/src/cron/scheduler.rs
+++ b/crates/openhuman-core/src/cron/scheduler.rs
@@ -95,14 +95,14 @@ pub async fn run(config: Config) -> Result<()> {
/// - Poll itself failed (DB read) → `healthy: false` with the DB error.
/// - Poll succeeded, queue empty or not → `healthy: true` (#3312
/// recovery signal). Without this, a single transient job failure
-/// that flipped the component to `error` via [`process_due_jobs`]
+/// that flipped the component to `error` by a dispatched job (`dispatch.rs`)
/// would stay there indefinitely while the queue was idle — no later
/// event would clear it, the health endpoint would keep returning
/// 503, and Docker would mark the container `unhealthy` for hours
/// until a manual restart. Tick-level "still polling" beats
/// job-level success as the recovery signal because the queue is
/// empty most of the time.
-/// - Per-job results (handled inside `process_due_jobs`) continue to
+/// - Per-job results (published by each dispatched job) continue to
/// flip the component back to `healthy: false` on a failure; the
/// next tick that survives the DB read will re-flip it to
/// `healthy: true`, exactly the auto-recovery behaviour the Docker
@@ -166,7 +166,7 @@ pub(crate) async fn tick_once(
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
+ // A dispatched job may have published `healthy: false` on
// a job failure, but it does so directly on the bus without
// touching our local tracker. Reset so the next successful tick
// is again treated as a transition and re-emits `healthy: true` —
diff --git a/crates/openhuman-core/src/cron/scheduler/agent_run.rs b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
index a05b815350..95b0f17c4e 100644
--- a/crates/openhuman-core/src/cron/scheduler/agent_run.rs
+++ b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
@@ -211,7 +211,10 @@ pub(super) async fn run_agent_job(
}
/// Fires a `JobType::Flow` job. A system job (`system:<name>`, see
-/// [`crate::cron::system_jobs`]) publishes `DomainEvent::CronSystemJobDue`;
+/// [`crate::cron::system_jobs`]) publishes `DomainEvent::CronSystemJobDue` and,
+/// when a handler is registered for it
+/// ([`crate::cron::system_job_handlers`]), awaits that handler and returns its
+/// result;
/// any other publishes `DomainEvent::FlowScheduleTick` for
/// the bound flow id (stored in `job.command`, see `JobType::Flow`'s doc) and
/// returns immediately. This job type does no work itself — dispatching the
@@ -224,7 +227,17 @@ pub(super) async fn run_flow_schedule_job(job: &CronJob) -> (bool, String) {
BUS.publish(DomainEvent::CronSystemJobDue {
job: name.to_string(),
});
- return (true, format!("system job {name} dispatched"));
+ // A host-registered handler is awaited and its result is the run's
+ // result; without one the job is announce-only and `ok` on dispatch.
+ let ctx = crate::cron::system_job_handlers::SystemJobContext {
+ job_id: job.id.clone(),
+ name: name.to_string(),
+ };
+ return match crate::cron::system_job_handlers::dispatch(ctx).await {
+ Some(Ok(())) => (true, format!("system job {name} completed")),
+ Some(Err(error)) => (false, format!("system job {name} failed: {error}")),
+ None => (true, format!("system job {name} dispatched")),
+ };
}
let flow_id = job.command.clone();
tracing::info!(
diff --git a/crates/openhuman-core/src/cron/scheduler/dispatch.rs b/crates/openhuman-core/src/cron/scheduler/dispatch.rs
new file mode 100644
index 0000000000..240a2a573b
--- /dev/null
+++ b/crates/openhuman-core/src/cron/scheduler/dispatch.rs
@@ -0,0 +1,161 @@
+//! Dispatching due jobs without holding the poll loop.
+//!
+//! The poll loop used to await its whole batch (`buffer_unordered`), so one
+//! long agent turn kept every other job — including ones that came due during
+//! it — waiting for the next poll that could only happen once it finished.
+//! Now each due job is spawned onto the [`JobDispatcher`]'s task set and the
+//! poll returns at once; a semaphore keeps at most `scheduler.max_concurrent`
+//! jobs executing. Dropping the dispatcher (the loop's task is aborted on
+//! shutdown) aborts the jobs it still owns.
+//!
+//! Because the loop no longer waits, two guards replace the old implicit one:
+//!
+//! - **In flight**: a job is marked running from dispatch until its run is
+//! persisted ([`super::in_flight`]), and a running job is never dispatched
+//! again.
+//! - **Claimed slot**: a recurring job's `next_run` is advanced to its next
+//! occurrence at dispatch, so a running job is not "due" on every poll. When
+//! it finishes, the usual reschedule recomputes `next_run` from that moment,
+//! exactly as before. A job that comes due again while still running has
+//! genuinely missed a slot: a default job skips it silently (the historical
+//! behaviour, when such slots were swallowed by the blocked loop); a
+//! single-flight job ([`crate::cron::policy::JobPolicy::single_flight`])
+//! records it as a `skipped` run.
+
+use std::sync::Arc;
+
+use chrono::Utc;
+use tokio::sync::Semaphore;
+use tokio::task::JoinSet;
+
+use super::in_flight;
+use crate::config::Config;
+use crate::core::bus::BUS;
+use crate::core::events::DomainEvent;
+use crate::core::runtime::CoreContext;
+use crate::cron::policy::policy_or_default;
+use crate::cron::{next_run_for_schedule, record_run, update_job, CronJob, CronJobPatch, Schedule};
+use crate::security::SecurityPolicy;
+
+/// Output recorded for a single-flight slot missed while a run was in flight.
+pub(crate) const SKIPPED_OUTPUT: &str = "skipped: the previous run was still in flight";
+
+/// Owns the tasks of the jobs the poll loop dispatched.
+pub(crate) struct JobDispatcher {
+ tasks: JoinSet<()>,
+ permits: Arc<Semaphore>,
+}
+
+impl JobDispatcher {
+ /// A dispatcher running at most `max_concurrent` jobs at once.
+ pub(crate) fn new(max_concurrent: usize) -> Self {
+ Self {
+ tasks: JoinSet::new(),
+ permits: Arc::new(Semaphore::new(max_concurrent.max(1))),
+ }
+ }
+
+ /// Start every job in `jobs` that is not already running and return.
+ pub(crate) async fn dispatch(
+ &mut self,
+ config: &Config,
+ security: &Arc<SecurityPolicy>,
+ jobs: Vec<CronJob>,
+ ) {
+ self.reap();
+ for job in jobs {
+ if in_flight::is_running(&job.id) {
+ skip_in_flight(config, &job);
+ continue;
+ }
+ let guard = in_flight::enter(&job.id);
+ claim_slot(config, &job);
+ let config = config.clone();
+ let security = Arc::clone(security);
+ let permits = Arc::clone(&self.permits);
+ tracing::debug!(job_id = %job.id, "[cron:dispatch] job dispatched");
+ self.tasks.spawn(CoreContext::propagate(async move {
+ let _guard = guard;
+ let Ok(_permit) = permits.acquire_owned().await else {
+ return;
+ };
+ let (job_id, success, failure_message) =
+ super::execute_and_persist_job(&config, security.as_ref(), &job).await;
+ BUS.publish(DomainEvent::HealthChanged {
+ component: "scheduler".to_string(),
+ healthy: success,
+ message: (!success).then(|| {
+ failure_message.unwrap_or_else(|| format!("job {job_id} failed"))
+ }),
+ });
+ }));
+ }
+ }
+
+ /// Wait for every dispatched job to finish.
+ pub(crate) async fn drain(&mut self) {
+ while let Some(result) = self.tasks.join_next().await {
+ log_join(result);
+ }
+ }
+
+ /// Collect the jobs that already finished, so the set does not grow.
+ fn reap(&mut self) {
+ while let Some(result) = self.tasks.try_join_next() {
+ log_join(result);
+ }
+ }
+}
+
+fn log_join(result: Result<(), tokio::task::JoinError>) {
+ if let Err(error) = result {
+ if error.is_panic() {
+ tracing::error!("[cron:dispatch] a dispatched job panicked: {error}");
+ }
+ }
+}
+
+/// Advance a recurring job's `next_run` past now, so it is not due again
+/// while it runs. Best effort: on failure the in-flight guard still keeps the
+/// job from being dispatched twice.
+fn claim_slot(config: &Config, job: &CronJob) {
+ if matches!(job.schedule, Schedule::At { .. }) {
+ return;
+ }
+ match update_job(
+ config,
+ &job.id,
+ CronJobPatch {
+ schedule: Some(job.schedule.clone()),
+ ..CronJobPatch::default()
+ },
+ ) {
+ Ok(claimed) => tracing::trace!(
+ job_id = %job.id,
+ next_run = %claimed.next_run,
+ "[cron:dispatch] slot claimed"
+ ),
+ Err(error) => tracing::debug!(
+ job_id = %job.id,
+ %error,
+ "[cron:dispatch] could not claim the slot; relying on the in-flight guard"
+ ),
+ }
+}
+
+/// A due job whose previous run is still going.
+fn skip_in_flight(config: &Config, job: &CronJob) {
+ let policy = policy_or_default(config, &job.id);
+ if !policy.single_flight || matches!(job.schedule, Schedule::At { .. }) {
+ tracing::trace!(job_id = %job.id, "[cron:dispatch] still running; not dispatched again");
+ return;
+ }
+ tracing::info!(job_id = %job.id, "[cron:dispatch] single-flight job still running; slot skipped");
+ let now = Utc::now();
+ if let Err(error) = record_run(config, &job.id, now, now, "skipped", Some(SKIPPED_OUTPUT), 0) {
+ tracing::warn!(job_id = %job.id, %error, "[cron:dispatch] recording the skipped run failed");
+ }
+ if next_run_for_schedule(&job.schedule, now).is_ok() {
+ claim_slot(config, job);
+ }
+}
diff --git a/crates/openhuman-core/src/cron/scheduler/retry.rs b/crates/openhuman-core/src/cron/scheduler/retry.rs
index ff80e78d15..dd8a42c378 100644
--- a/crates/openhuman-core/src/cron/scheduler/retry.rs
+++ b/crates/openhuman-core/src/cron/scheduler/retry.rs
@@ -33,7 +33,11 @@ pub(super) async fn execute_job_with_retry(
) -> (bool, String) {
let mut last_output = String::new();
let mut last_agent_error: Option<String> = None;
- let retries = config.reliability.scheduler_retries;
+ // A per-job override (`cron::policy`) wins; `Some(0)` is one attempt.
+ let retries = crate::cron::policy::effective_retries(
+ config,
+ &crate::cron::policy::policy_or_default(config, &job.id),
+ );
let mut backoff_ms = config.reliability.provider_backoff_ms.max(200);
let mut session_expired = false;
let mut credits_exhausted = false;
diff --git a/crates/openhuman-core/src/cron/scheduler/slot.rs b/crates/openhuman-core/src/cron/scheduler/slot.rs
new file mode 100644
index 0000000000..e5ce16d1ce
--- /dev/null
+++ b/crates/openhuman-core/src/cron/scheduler/slot.rs
@@ -0,0 +1,37 @@
+//! The process-wide claim on the cron poll loop.
+//!
+//! Two loops in one process would each read the same due rows and run every
+//! job twice. A runtime that is dropped and rebuilt in the same process (an
+//! embedder, a test) must also be able to start a fresh loop once the old one
+//! is gone, so the claim is a guard released on drop — including when the
+//! loop's task is aborted.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+
+static LIVE: AtomicBool = AtomicBool::new(false);
+
+/// Held by the running poll loop.
+#[must_use = "the slot is released when the guard drops"]
+pub(crate) struct SchedulerSlot(());
+
+impl SchedulerSlot {
+ /// Claim the slot; `None` when another loop holds it.
+ pub(crate) fn acquire() -> Option<Self> {
+ (!LIVE.swap(true, Ordering::AcqRel)).then(|| {
+ tracing::debug!("[cron:scheduler] poll loop slot acquired");
+ Self(())
+ })
+ }
+}
+
+impl Drop for SchedulerSlot {
+ fn drop(&mut self) {
+ LIVE.store(false, Ordering::Release);
+ tracing::debug!("[cron:scheduler] poll loop slot released");
+ }
+}
+
+/// Whether a cron poll loop is running in this process.
+pub fn is_running() -> bool {
+ LIVE.load(Ordering::Acquire)
+}