Skip to content

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

feat(cron): add job enable/disable and manual run support

Steven Enamakel1211084d1edc
diff --git a/crates/openhuman-core/src/cron/ops.rs b/crates/openhuman-core/src/cron/ops.rs
index 41bb461b10..4a724a1340 100644
--- a/crates/openhuman-core/src/cron/ops.rs
+++ b/crates/openhuman-core/src/cron/ops.rs
@@ -2,46 +2,18 @@ use crate::config::Config;
use crate::core::Outcome;
use crate::security::SecurityPolicy;
use anyhow::Result;
-use once_cell::sync::Lazy;
use serde_json::json;
-use std::collections::HashSet;
-use std::sync::Mutex;
use {
crate::cron, crate::cron::add_shell_job, crate::cron::update_job,
tinyflows_schedule::types::CronJob, tinyflows_schedule::types::CronJobPatch,
tinyflows_schedule::types::CronRun, tinyflows_schedule::types::Schedule,
};
-/// Guard against duplicate concurrent "Run Now" executions per job.
-/// Entries are inserted before spawning and removed when the task completes.
-static ACTIVE_RUNS: Lazy<Mutex<HashSet<String>>> = Lazy::new(|| Mutex::new(HashSet::new()));
-
-/// RAII guard that removes a job ID from `ACTIVE_RUNS` when dropped.
-///
-/// Ensures cleanup runs on normal completion, panic, or future cancellation —
-/// so a hung or aborted background task can never permanently lock a job_id.
-pub(crate) struct ActiveRunGuard {
- job_id: String,
-}
-
-impl Drop for ActiveRunGuard {
- fn drop(&mut self) {
- if let Ok(mut active) = ACTIVE_RUNS.lock() {
- active.remove(&self.job_id);
- }
- }
-}
-
/// Claim `job_id` as running. `None` when a run (scheduled or Run Now) already
-/// holds it; the claim is released when the guard drops.
-pub(crate) fn try_acquire_run(job_id: &str) -> Option<ActiveRunGuard> {
- let mut active = ACTIVE_RUNS.lock().ok()?;
- if !active.insert(job_id.to_string()) {
- return None;
- }
- Some(ActiveRunGuard {
- job_id: job_id.to_string(),
- })
+/// holds it; the claim is released when the guard drops, including on panic or
+/// future cancellation, so an aborted task can never lock a job id.
+pub(crate) fn try_acquire_run(job_id: &str) -> Option<tinyflows_schedule::runtime::RunClaim> {
+ crate::cron::scheduler::try_acquire_run(job_id)
}
pub fn add_once(config: &Config, delay: &str, command: &str) -> Result<CronJob> {
@@ -213,27 +185,13 @@ pub async fn cron_run(config: &Config, job_id: &str) -> Result<Outcome<serde_jso
)
.map_err(|e| e.to_string())?;
- // Guard against duplicate concurrent executions for the same job.
- {
- let mut active = ACTIVE_RUNS
- .lock()
- .map_err(|_| "ACTIVE_RUNS lock poisoned".to_string())?;
- if active.contains(job_id) {
- tracing::debug!(job_id, "[cron_run] rejected duplicate concurrent execution");
- return Err(format!("cron job '{job_id}' is already running"));
- }
- active.insert(job_id.to_string());
- }
-
- let job = match cron::get_job(config, job_id) {
- Ok(j) => j,
- Err(e) => {
- if let Ok(mut active) = ACTIVE_RUNS.lock() {
- active.remove(job_id);
- }
- return Err(e.to_string());
- }
+ // Guard against duplicate concurrent executions for the same job. The
+ // claim is taken before the job is loaded and moves into the task.
+ let Some(run_guard) = try_acquire_run(job_id) else {
+ tracing::debug!(job_id, "[cron_run] rejected duplicate concurrent execution");
+ return Err(format!("cron job '{job_id}' is already running"));
};
+ let job = cron::get_job(config, job_id).map_err(|e| e.to_string())?;
// Insert a "queued" placeholder run record immediately so the frontend
// poller can observe the run as soon as the RPC returns — otherwise the
@@ -249,11 +207,8 @@ pub async fn cron_run(config: &Config, job_id: &str) -> Result<Outcome<serde_jso
// Spawn the execution as a background task so the RPC handler returns
// immediately instead of blocking for the full job duration.
tokio::spawn(async move {
- // Drop guard ensures job_id is removed from ACTIVE_RUNS even on panic
- // or future cancellation, not just on the normal completion path.
- let _guard = ActiveRunGuard {
- job_id: job_id_owned.clone(),
- };
+ // The claim is released even on panic or future cancellation.
+ let _guard = run_guard;
tracing::debug!(job_id = %job_id_owned, "[cron_run] background task started");
run_and_record(&config_owned, &job).await;
diff --git a/crates/openhuman-core/src/cron/scheduler.rs b/crates/openhuman-core/src/cron/scheduler.rs
index e7447a6705..9a57a041ae 100644
--- a/crates/openhuman-core/src/cron/scheduler.rs
+++ b/crates/openhuman-core/src/cron/scheduler.rs
@@ -1,19 +1,24 @@
-//! Background scheduler loop for cron jobs: polls the store for due jobs,
-//! 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.
+//! The host side of the cron scheduler.
+//!
+//! The runtime — poll pass, bounded concurrency, process-wide run claims,
+//! retry with backoff, rescheduling and single-flight skips — is
+//! `tinyflows_schedule::runtime::Scheduler`. This module builds it from config
+//! and supplies the ports (see [`host`]): the document store, the shell/agent
+//! executor with its failure classification ([`executor`]), delivery and the
+//! flow trigger sink ([`run_delivery`]). It owns the loop that drives one
+//! scheduler for the operator and one for every live embedded agent, and the
+//! health signals the loop emits.
mod agent_run;
mod delivery;
-mod dispatch;
+mod executor;
mod failure_classification;
+mod host;
mod origin_context;
mod origin_delivery;
-mod retry;
+mod run_delivery;
mod run_record;
pub(crate) mod shell_job;
-mod slot;
#[cfg(test)]
#[path = "scheduler_tests.rs"]
@@ -24,35 +29,41 @@ use agent_run::*;
#[allow(unused_imports)]
use delivery::*;
#[allow(unused_imports)]
-use failure_classification::*;
+use executor::*;
#[allow(unused_imports)]
-use retry::*;
+use failure_classification::*;
#[allow(unused_imports)]
use run_record::*;
#[allow(unused_imports)]
use shell_job::*;
pub use delivery::deliver_job;
-pub(crate) use dispatch::JobDispatcher;
-pub use retry::execute_job_now;
-pub use slot::is_running;
-pub(crate) use slot::SchedulerSlot;
+pub(crate) use host::{is_run_active, try_acquire_run, JobDispatcher};
use crate::config::Config;
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
use crate::security::SecurityPolicy;
use anyhow::Result;
-use chrono::Utc;
+use std::collections::HashMap;
use std::sync::Arc;
+use tinyflows_schedule::runtime::{execute_with_retry, SchedulerSlot};
+use tinyflows_schedule::types::CronJob;
use tokio::time::{self, Duration};
-use {crate::cron::due_jobs, tinyflows_schedule::types::CronJob};
const MIN_POLL_SECONDS: u64 = 5;
+/// The poll-loop slot: one loop per process, or two would each see the same
+/// due rows.
+const LOOP_SCOPE: &str = "openhuman:cron-loop";
+
+/// Whether a cron poll loop is running in this process.
+pub fn is_running() -> bool {
+ SchedulerSlot::is_running(LOOP_SCOPE)
+}
+
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 {
+ let Some(_slot) = SchedulerSlot::acquire(LOOP_SCOPE) else {
tracing::warn!(
"[cron:scheduler] a scheduler loop is already running; not starting another"
);
@@ -78,65 +89,76 @@ pub async fn run(config: Config) -> Result<()> {
// Track the most recently *emitted* scheduler health so we only
// publish `HealthChanged` on a state transition. Without this the
// bus would carry a steady `healthy: true` event every poll
- // interval — typically 30 s, forever — churn for any subscriber
- // that logs / persists / reacts to health events. `None` means
- // "nothing emitted yet for this run", so the first successful tick
- // is treated as a transition and emits.
+ // interval, forever. `None` means "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);
+ let mut dispatcher = JobDispatcher::new(&config, &security);
+ let mut agents = LiveAgentSchedulers::default();
loop {
interval.tick().await;
- tick_once(
- &config,
- &security,
- &mut last_emitted_health,
- &mut dispatcher,
- )
- .await;
- tick_live_agents(&mut dispatcher).await;
+ tick_once(&config, &mut last_emitted_health, &mut dispatcher).await;
+ agents.tick().await;
}
}
-/// Runs the due jobs of every live embedded agent, each under that agent's
-/// own context: its config, provider route, policy and job store. An agent
-/// that is not live has no context to run under — no host tools or prompt
-/// for its agent jobs — so its jobs stay dormant until it is instantiated
-/// again, including when a storage backend still records it
-/// (`crate::storage::agents`).
-pub(crate) async fn tick_live_agents(dispatcher: &mut JobDispatcher) {
- for (agent_id, ctx) in crate::core::runtime::AgentContextRegistry::live() {
- let agent = agent_id.clone();
- let dispatcher = &mut *dispatcher;
- crate::core::runtime::CoreContext::scope(ctx, async move {
- let config = match crate::config::ops::load_current_or_init().await {
- Ok(config) => config,
- Err(error) => {
- tracing::debug!(agent = %agent, %error, "[cron:scheduler] agent config unavailable");
+/// The schedulers of the live embedded agents, one per agent id.
+#[derive(Default)]
+pub(crate) struct LiveAgentSchedulers {
+ by_agent: HashMap<String, JobDispatcher>,
+}
+
+impl LiveAgentSchedulers {
+ /// Runs the due jobs of every live embedded agent, each under that agent's
+ /// own context: its config, provider route, policy and job store. An agent
+ /// that is not live has no context to run under — no host tools or prompt
+ /// for its agent jobs — so its jobs stay dormant until it is instantiated
+ /// again, including when a storage backend still records it
+ /// (`crate::storage::agents`).
+ pub(crate) async fn tick(&mut self) {
+ let live = crate::core::runtime::AgentContextRegistry::live();
+ // A scheduler whose agent is gone aborts the jobs it still owns.
+ self.by_agent
+ .retain(|id, _| live.iter().any(|(live_id, _)| live_id == id));
+ for (agent_id, ctx) in live {
+ let scheduler = &mut self.by_agent;
+ crate::core::runtime::CoreContext::scope(ctx, async move {
+ let config = match crate::config::ops::load_current_or_init().await {
+ Ok(config) => config,
+ Err(error) => {
+ tracing::debug!(agent = %agent_id, %error, "[cron:scheduler] agent config unavailable");
+ return;
+ }
+ };
+ if !agent_jobs_may_exist(&config) {
return;
}
- };
- if !agent_jobs_may_exist(&config) {
- return;
- }
- let jobs = match due_jobs(&config, Utc::now()) {
- Ok(jobs) => jobs,
- Err(error) => {
- tracing::warn!(agent = %agent, "[cron:scheduler] agent poll db_error: {error}");
+ let Some(security) = crate::security::live_policy::effective() else {
+ tracing::warn!(agent = %agent_id, "[cron:scheduler] agent has no policy; jobs skipped");
return;
+ };
+ let dispatcher = scheduler
+ .entry(agent_id.clone())
+ .or_insert_with(|| JobDispatcher::new(&config, &security));
+ match dispatcher.tick(&config).await {
+ Ok(0) => {}
+ Ok(count) => {
+ tracing::debug!(agent = %agent_id, count, "[cron:scheduler] agent jobs dispatched");
+ }
+ Err(error) => {
+ tracing::warn!(agent = %agent_id, "[cron:scheduler] agent poll failed: {error}");
+ }
}
- };
- if jobs.is_empty() {
- return;
- }
- let Some(security) = crate::security::live_policy::effective() else {
- tracing::warn!(agent = %agent, "[cron:scheduler] agent has no policy; jobs skipped");
- return;
- };
- tracing::debug!(agent = %agent, due_count = jobs.len(), "[cron:scheduler] running agent jobs");
- dispatcher.dispatch(&config, &security, jobs).await;
- })
- .await;
+ })
+ .await;
+ }
+ }
+
+ /// Wait for every dispatched agent job to finish.
+ pub(crate) async fn drain(&mut self) {
+ for dispatcher in self.by_agent.values_mut() {
+ dispatcher.drain().await;
+ }
}
}
@@ -145,9 +167,9 @@ pub(crate) async fn tick_live_agents(dispatcher: &mut JobDispatcher) {
/// tests that drive the agent pass without owning the loop's interval.
pub async fn run_live_agent_pass(max_concurrent: usize) {
tracing::debug!(max_concurrent, "[cron:scheduler] live agent pass begin");
- let mut dispatcher = JobDispatcher::new(max_concurrent.max(1));
- tick_live_agents(&mut dispatcher).await;
- dispatcher.drain().await;
+ let mut agents = LiveAgentSchedulers::default();
+ agents.tick().await;
+ agents.drain().await;
}
/// Whether an agent can have jobs to poll: with a storage backend its jobs
@@ -160,40 +182,49 @@ pub(crate) fn agent_jobs_may_exist(config: &Config) -> bool {
|| crate::cron::store::legacy_db_path(config).exists()
}
+/// Run `job` now under the caller's `run_id` (also the id its delivery and
+/// run record use), with the same executor, retry budget and failure
+/// classification as a scheduled run. The caller holds the job's run claim.
+pub async fn execute_job_now(config: &Config, job: &CronJob, run_id: &str) -> (bool, String) {
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ let binding = host::Binding::current(config, security);
+ let ports = host::ports(&binding);
+ match execute_with_retry(&ports, &host::scheduler_config(config), job, run_id).await {
+ Ok(attempt) => (attempt.success, attempt.output),
+ Err(error) => (false, error.to_string()),
+ }
+}
+
/// Single poll cycle of the scheduler loop, extracted so tests can drive
/// it without owning `tokio::time::interval`.
///
-/// Emits a `scheduler` health signal in three cases:
+/// Emits a `scheduler` health signal in two cases:
/// - 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` 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 (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
-/// health check needs.
+/// that flipped the component to `error` by a dispatched job would stay
+/// there indefinitely while the queue was idle — the health endpoint would
+/// keep returning 503 and Docker would mark the container `unhealthy` for
+/// hours until a manual restart.
+/// - Per-job results (published by each job's delivery) 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`.
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()) {
- Ok(jobs) => jobs,
+ let dispatched = match dispatcher.tick(config).await {
+ Ok(count) => count,
Err(e) => {
- tracing::warn!("[cron:scheduler] tick poll db_error: {e}");
- // Transition-only emission: only publish on the first
- // failure after a previous healthy (or unknown) state.
- // Repeat DB failures stay quiet so subscribers don't see
- // an event-storm during a long outage.
+ tracing::warn!("[cron:scheduler] tick poll failed: {e}");
+ // Transition-only emission: repeat failures stay quiet so
+ // subscribers don't see an event-storm during a long outage.
if *last_emitted_health != Some(false) {
BUS.publish(DomainEvent::HealthChanged {
component: "scheduler".to_string(),
@@ -206,17 +237,12 @@ pub(crate) async fn tick_once(
}
};
- let due_count = jobs.len();
- // Transition-only emission for the recovery / healthy signal: a
- // long idle stretch with no transitions stays silent on the bus,
- // so subscribers don't pay per-poll work for a steady `healthy:
- // true` event every poll interval — the nit oxoxDev caught on
- // #3329. The very first successful tick after boot (or after a
- // failure) is the one that fires; subsequent successful ticks
- // are no-ops on the wire.
+ // Transition-only emission for the recovery signal: the very first
+ // successful tick after boot (or after a failure) fires; later successful
+ // ticks are no-ops on the wire.
if *last_emitted_health != Some(true) {
tracing::debug!(
- "[cron:scheduler] tick poll ok due_count={due_count} (recovery signal: healthy=true)"
+ "[cron:scheduler] tick poll ok dispatched={dispatched} (recovery signal: healthy=true)"
);
BUS.publish(DomainEvent::HealthChanged {
component: "scheduler".to_string(),
@@ -226,65 +252,14 @@ pub(crate) async fn tick_once(
*last_emitted_health = Some(true);
} else {
tracing::trace!(
- "[cron:scheduler] tick poll ok due_count={due_count} (steady state, no event)"
+ "[cron:scheduler] tick poll ok dispatched={dispatched} (steady state, no event)"
);
}
- if due_count == 0 {
- tracing::trace!("[cron:scheduler] tick end (no due jobs)");
- return;
+ if dispatched > 0 {
+ // A dispatched job publishes `healthy: false` on failure directly on
+ // the bus, without touching this tracker. Reset so the next
+ // successful tick is again a transition and re-emits `healthy: true`.
+ *last_emitted_health = None;
}
-
- dispatcher.dispatch(config, security, jobs).await;
- tracing::debug!("[cron:scheduler] tick end due_count={due_count} (jobs processed)");
-
- // 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` —
- // exactly the auto-recovery behaviour #3312 requires.
- *last_emitted_health = None;
-}
-
-pub(super) async fn execute_and_persist_job(
- config: &Config,
- security: &SecurityPolicy,
- job: &CronJob,
-) -> (String, bool, Option<String>) {
- warn_if_high_frequency_agent_job(job);
-
- let started_at = Utc::now();
-
- BUS.publish(DomainEvent::CronJobTriggered {
- job_id: job.id.clone(),
- job_name: job.name.clone().unwrap_or_default(),
- job_type: format!("{:?}", job.job_type),
- });
-
- let run_id = uuid::Uuid::new_v4().to_string();
- let (execution_success, output) =
- execute_job_with_retry_for_run(config, security, job, &run_id).await;
- let finished_at = Utc::now();
- let success = persist_job_result_for_run(
- config,
- job,
- &run_id,
- execution_success,
- &output,
- started_at,
- finished_at,
- )
- .await;
-
- // The job ran as its agent (when it had one); a one-shot job is already
- // deleted, so subscribers learn the owner here, not from the store.
- crate::cron::completion_owner::note(&job.id);
- BUS.publish(DomainEvent::CronJobCompleted {
- job_id: job.id.clone(),
- success,
- output: crate::util::truncate_with_ellipsis(&output, 512),
- });
- let failure_message = (!success).then(|| crate::util::truncate_with_ellipsis(&output, 256));
-
- (job.id.clone(), success, failure_message)
}