Skip to content

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

fix(cron): prevent duplicate agent runs for the same slot

Steven Enamakela5fd2b8c2758
diff --git a/crates/openhuman-core/src/cron/scheduler/agent_run.rs b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
index a2a12c94db..fc5c1707af 100644
--- a/crates/openhuman-core/src/cron/scheduler/agent_run.rs
+++ b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
@@ -245,51 +245,6 @@ pub(super) async fn run_agent_job_for_run(
}
}
-/// Fires a `JobType::Flow` job. A system job (`system:<name>`, see
-/// [`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
-/// 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) 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 {
- job: name.to_string(),
- });
- // 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!(
- target: "flows",
- job_id = %job.id,
- %flow_id,
- "[cron] flow schedule tick — publishing FlowScheduleTick"
- );
- BUS.publish(DomainEvent::FlowScheduleTick {
- flow_id: flow_id.clone(),
- });
- (
- true,
- format!("flow schedule tick emitted for flow {flow_id}"),
- )
-}
-
/// Placeholder recorded in run history when an agent job succeeds but returns
/// no text. Never delivered to chat — used only for the run-history record.
pub(super) const EMPTY_AGENT_OUTPUT: &str = "agent job executed";
diff --git a/crates/openhuman-core/src/cron/scheduler/dispatch.rs b/crates/openhuman-core/src/cron/scheduler/dispatch.rs
deleted file mode 100644
index c85f3f0222..0000000000
--- a/crates/openhuman-core/src/cron/scheduler/dispatch.rs
+++ /dev/null
@@ -1,182 +0,0 @@
-//! 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:
-//!
-//! - **Run claim**: a job is claimed (`cron::ops::try_acquire_run`, the same
-//! claim Run Now and the run tool take) from dispatch until its run is
-//! persisted, and a claimed 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 crate::config::Config;
-use crate::core::bus::BUS;
-use crate::core::events::DomainEvent;
-use crate::core::runtime::CoreContext;
-use crate::cron::policy::get_policy;
-use crate::security::SecurityPolicy;
-use {
- crate::cron::record_run, crate::cron::update_job,
- tinyflows_schedule::schedule::next_run_for_schedule, tinyflows_schedule::types::CronJob,
- tinyflows_schedule::types::CronJobPatch, tinyflows_schedule::types::Schedule,
-};
-
-/// 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 {
- // One run per job at a time, shared with Run Now and the run tool.
- let Some(guard) = crate::cron::ops::try_acquire_run(&job.id) else {
- skip_in_flight(config, &job);
- continue;
- };
- // Fail closed: an unreadable policy refuses the job before its slot
- // is advanced, so the occurrence is retried once the read recovers.
- if get_policy(config, &job.id).is_err() {
- continue;
- }
- // Operator limits (`cron::limits`) also bind rows stored before
- // they were switched on.
- if let Err(error) = crate::cron::limits::check_run(config, &job) {
- tracing::warn!(job_id = %job.id, %error, "[cron:dispatch] job refused by operator limits");
- continue;
- }
- 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 run claim"
- ),
- }
-}
-
-/// A due job whose previous run is still going.
-fn skip_in_flight(config: &Config, job: &CronJob) {
- let single_flight = get_policy(config, &job.id).is_ok_and(|policy| policy.single_flight);
- if !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
deleted file mode 100644
index d9fbfe0d18..0000000000
--- a/crates/openhuman-core/src/cron/scheduler/retry.rs
+++ /dev/null
@@ -1,301 +0,0 @@
-//! The per-job retry loop with exponential backoff, its permanent-halt
-//! short-circuits, and the retries-exhausted observability report.
-
-use super::agent_run::{run_agent_job_for_run, run_flow_schedule_job};
-use super::failure_classification::{
- is_api_key_unset_failure, is_budget_exhausted_failure, is_insufficient_credits_failure,
- is_local_provider_unreachable_failure, is_session_expired_failure, permanent_halt_message,
-};
-use super::shell_job::run_job_command;
-use crate::config::Config;
-use crate::security::SecurityPolicy;
-use chrono::Utc;
-use tokio::time::{self, Duration};
-use {
- tinyflows_schedule::types::CronJob, tinyflows_schedule::types::JobType,
- tinyflows_schedule::types::SessionTarget,
-};
-
-pub(super) fn agent_session_target_tag(target: &SessionTarget) -> &'static str {
- match target {
- SessionTarget::Main => "main",
- SessionTarget::Isolated => "isolated",
- SessionTarget::Current => "current",
- }
-}
-
-/// Run `job` now under the caller's `run_id` (also the id its delivery and
-/// run record use).
-pub async fn execute_job_now(config: &Config, job: &CronJob, run_id: &str) -> (bool, String) {
- let security =
- SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir);
- execute_job_with_retry_for_run(config, &security, job, run_id).await
-}
-
-/// [`execute_job_with_retry_for_run`] under a fresh run id.
-#[cfg(test)]
-pub(super) async fn execute_job_with_retry(
- config: &Config,
- security: &SecurityPolicy,
- job: &CronJob,
-) -> (bool, String) {
- let run_id = uuid::Uuid::new_v4().to_string();
- execute_job_with_retry_for_run(config, security, job, &run_id).await
-}
-
-pub(super) async fn execute_job_with_retry_for_run(
- config: &Config,
- security: &SecurityPolicy,
- job: &CronJob,
- run_id: &str,
-) -> (bool, String) {
- let mut last_output = String::new();
- let mut last_agent_error: Option<String> = None;
- // A per-job override (`cron::policy`) wins; `Some(0)` is one attempt. An
- // unreadable policy refuses the run (and any later attempt) outright.
- if let Err(error) = crate::cron::limits::check_run(config, job) {
- return (false, error.to_string());
- }
- let policy = match crate::cron::policy::get_policy(config, &job.id) {
- Ok(policy) => policy,
- Err(error) => return (false, error.to_string()),
- };
- let retries = crate::cron::policy::effective_retries(config, &policy);
- let mut backoff_ms = config.reliability.provider_backoff_ms.max(200);
- let mut session_expired = false;
- let mut credits_exhausted = false;
- let mut budget_exhausted = false;
- let mut key_unset = false;
- let mut local_unreachable = false;
-
- for attempt in 0..=retries {
- if attempt > 0 {
- if let Err(error) = crate::cron::policy::get_policy(config, &job.id) {
- return (false, error.to_string());
- }
- }
- let (success, output, agent_error) = match job.job_type {
- JobType::Shell => {
- let (success, output) = run_job_command(config, security, job).await;
- (success, output, None)
- }
- JobType::Agent => run_agent_job_for_run(config, job, run_id).await,
- JobType::Flow => {
- let (success, output) = run_flow_schedule_job(job).await;
- (success, output, None)
- }
- };
- last_output = output;
- if agent_error.is_some() {
- last_agent_error = agent_error;
- }
-
- if success {
- return (true, last_output);
- }
-
- if last_output.starts_with("blocked by security policy:") {
- // Deterministic policy violations are not retryable.
- return (false, last_output);
- }
-
- if is_session_expired_failure(
- &job.job_type,
- last_agent_error.as_deref(),
- last_output.as_str(),
- ) {
- // Halt on the first occurrence — the inference layer already
- // published `SessionExpired`, retries cannot recover until the
- // user re-auths, and the classifier considers this expected
- // user state (TAURI-RUST-N). See `is_session_expired_failure`
- // for the full rationale.
- session_expired = true;
- break;
- }
-
- if is_insufficient_credits_failure(
- &job.job_type,
- last_agent_error.as_deref(),
- last_output.as_str(),
- ) {
- // Halt on the first occurrence — a BYO provider 402 (out of
- // balance) is permanent across the backoff loop, and the
- // provider emit site already demoted it from Sentry. Skipping
- // the retries-exhausted `report_error` below keeps the residual
- // off Sentry at source, independent of the `before_send` chain
- // (TAURI-RUST-514). See `is_insufficient_credits_failure`.
- // Metadata-only log (no raw provider body — see CLAUDE.md).
- log::debug!(
- "[cron] action=halt_on_insufficient_credits_402 job_id={} attempt={} retries={}",
- job.id.as_str(),
- attempt,
- retries
- );
- credits_exhausted = true;
- break;
- }
-
- if is_budget_exhausted_failure(
- &job.job_type,
- last_agent_error.as_deref(),
- last_output.as_str(),
- ) {
- // Halt on the first occurrence — a managed-backend budget 400
- // (USER_INSUFFICIENT_CREDITS) is permanent across the backoff
- // loop. The tag-gated `is_budget_event` before_send filter never
- // matches this cron re-report, so suppressing the report here
- // keeps it off Sentry at source (TAURI-RUST-BMW). See
- // `is_budget_exhausted_failure`. Metadata-only log (no raw body).
- log::debug!(
- "[cron] action=halt_on_budget_exhausted_400 job_id={} attempt={} retries={}",
- job.id.as_str(),
- attempt,
- retries
- );
- budget_exhausted = true;
- break;
- }
-
- if is_api_key_unset_failure(
- &job.job_type,
- last_agent_error.as_deref(),
- last_output.as_str(),
- ) {
- // Halt on the first occurrence — a configured provider with no
- // API key fails deterministically at the credential guard before
- // any HTTP, so the missing key is permanent across the backoff
- // loop. The bare cron `report_error` below bypasses the
- // `ApiKeyMissing` `expected_error_kind` demotion, so suppressing
- // here keeps the residual off Sentry at source (TAURI-RUST-HCK).
- // The failure stays visible to the user via the alerts tab
- // (`push_cron_alert`) + run history. See `is_api_key_unset_failure`.
- // Metadata-only log (no raw provider body — see CLAUDE.md).
- log::debug!(
- "[cron] action=halt_on_api_key_unset job_id={} attempt={} retries={}",
- job.id.as_str(),
- attempt,
- retries
- );
- key_unset = true;
- break;
- }
-
- if is_local_provider_unreachable_failure(
- &job.job_type,
- last_agent_error.as_deref(),
- last_output.as_str(),
- ) {
- // Halt on the first occurrence — a local LLM provider refusing the
- // loopback connection (LM Studio / Ollama not running) cannot
- // recover across the backoff loop, and the provider/agent emit
- // sites already demoted it from Sentry (`LoopbackUnavailable`).
- // The bare cron `report_error` below bypasses that demotion, so
- // suppressing here keeps the residual off Sentry at source
- // (TAURI-RUST-12K). The failure stays visible via the run history
- // + cron alert. See `is_local_provider_unreachable_failure`.
- // Metadata-only log (no raw provider body — see CLAUDE.md).
- log::debug!(
- "[cron] action=halt_on_local_provider_unreachable job_id={} attempt={} retries={}",
- job.id.as_str(),
- attempt,
- retries
- );
- local_unreachable = true;
- break;
- }
-
- if attempt < retries {
- let jitter_ms = u64::from(Utc::now().timestamp_subsec_millis() % 250);
- time::sleep(Duration::from_millis(backoff_ms + jitter_ms)).await;
- backoff_ms = (backoff_ms.saturating_mul(2)).min(30_000);
- }
- }
-
- // Permanent user-config / billing states are demoted at source: halt the
- // loop and skip the retries-exhausted report, independent of the tag-gated
- // before_send filters that the cron re-report does not match. Covers BYO
- // 402 out-of-credit + managed-backend 400 out-of-budget (TAURI-RUST-514 /
- // -BMW) and a configured provider with no API key (TAURI-RUST-HCK). The
- // `session_expired` (TAURI-RUST-N) and `local_unreachable` (a local LLM
- // server refusing the loopback connection, TAURI-RUST-12K) halts are the
- // same shape — suppress the bypassing bare report — but carry no
- // user-config remediation surface, so they gate the report directly rather
- // than routing through `permanent_config_halt`'s UserErrorCenter swap.
- let permanent_config_halt = credits_exhausted || budget_exhausted || key_unset;
- if matches!(job.job_type, JobType::Agent)
- && !session_expired
- && !local_unreachable
- && !permanent_config_halt
- {
- let report_message = last_agent_error.as_deref().unwrap_or(last_output.as_str());
- crate::core::observability::report_error(
- report_message,
- "cron",
- "agent_job",
- &[
- ("job_id", job.id.as_str()),
- ("agent_id", job.agent_id.as_deref().unwrap_or("none")),
- (
- "session_target",
- agent_session_target_tag(&job.session_target),
- ),
- ("failure", "retries_exhausted"),
- ],
- );
- } else if matches!(job.job_type, JobType::Agent) && permanent_config_halt {
- // Suppressed the retries-exhausted Sentry report for a permanent
- // user-config / billing state. Metadata-only breadcrumb so the
- // suppression is diagnosable in production without the raw provider body.
- let (reason, user_error_kind) = if credits_exhausted {
- ("insufficient_credits_402", "insufficient_credits")
- } else if budget_exhausted {
- ("budget_exhausted_400", "budget_exceeded")
- } else {
- ("api_key_unset", "api_key_missing")
- };
- log::debug!(
- "[cron] action=suppress_retries_exhausted_report reason={reason} job_id={} retries={}",
- job.id.as_str(),
- retries
- );
- // Replace the generic agent-failure copy with the specific, actionable
- // (static, leak-safe) reason so the hoisted /notifications alert + run
- // history tell the user the exact next step rather than "Something went
- // wrong" (CodeRabbit #4169). The raw `last_agent_error` chain is NEVER
- // surfaced here — only the `&'static str` constants from
- // `permanent_halt_message`.
- last_output = permanent_halt_message(credits_exhausted, budget_exhausted).to_string();
- // Also surface the actionable state to the UserErrorCenter so the user
- // can fix it (add an API key / top up credits / raise the budget) even
- // with no chat thread open. Broadcast-only + metadata-only — see
- // `publish_cron_user_error` (#4165 / TAURI-RUST-HCK follow-up).
- publish_cron_user_error(user_error_kind);
- }
-
- (false, last_output)
-}
-
-/// Surface a permanent cron user-config / billing halt to every connected
-/// client's UserErrorCenter.
-///
-/// Broadcasts a metadata-only `user_error` web-channel event to the `"system"`
-/// room (which every socket auto-joins). The payload carries only the stable
-/// `kind` token in `error_type` — one of `api_key_missing` / `insufficient_credits`
-/// / `budget_exceeded`, mirroring the frontend `UserErrorKind` discriminator —
-/// plus `error_source = "cron"`. It NEVER carries the raw provider body (see the
-/// metadata-only rule in CLAUDE.md), so no secrets / PII leave the core.
-///
-/// The frontend `socketService` listens for `user_error` and routes it through
-/// the same classifier the chat runtime uses, so a background (no-delivery) job
-/// failure is no longer silent — it lands in the shell's UserErrorCenter with a
-/// deep-link action even though no chat thread is active.
-pub(super) fn publish_cron_user_error(kind: &str) {
- log::debug!("[cron] action=surface_user_error kind={kind}");
- crate::web_chat::publish_web_channel_event(crate::web_chat::WebChannelEvent {
- event: "user_error".to_string(),
- client_id: "system".to_string(),
- error_type: Some(kind.to_string()),
- error_source: Some("cron".to_string()),
- ..Default::default()
- });
-}
diff --git a/crates/openhuman-core/src/cron/scheduler/run_record.rs b/crates/openhuman-core/src/cron/scheduler/run_record.rs
index ef03bbd3d6..013e501208 100644
--- a/crates/openhuman-core/src/cron/scheduler/run_record.rs
+++ b/crates/openhuman-core/src/cron/scheduler/run_record.rs
@@ -1,116 +1,14 @@
-//! Persisting a finished run: delivery, run history, one-shot termination,
-//! rescheduling, and the high-frequency agent-job warning.
+//! The high-frequency agent-job warning. Persisting a finished run (history,
+//! one-shot termination, rescheduling) is the schedule runtime's
+//! (`tinyflows_schedule::runtime`).
-use super::delivery::deliver_run;
-use crate::config::Config;
-use chrono::{DateTime, Utc};
+use chrono::Utc;
use {
- crate::cron::record_last_run, crate::cron::record_run_with_delivery, crate::cron::remove_job,
- crate::cron::reschedule_after_run, crate::cron::update_job,
tinyflows_schedule::schedule::runs_closer_than, tinyflows_schedule::schedule::TooFrequent,
tinyflows_schedule::schedule::MIN_AGENT_JOB_INTERVAL, tinyflows_schedule::types::CronJob,
- tinyflows_schedule::types::CronJobPatch, tinyflows_schedule::types::DeliveryStatus,
- tinyflows_schedule::types::JobType, tinyflows_schedule::types::Schedule,
+ tinyflows_schedule::types::JobType,
};
-/// [`persist_job_result_for_run`] under a fresh run id.
-#[cfg(test)]
-pub(super) async fn persist_job_result(
- config: &Config,
- job: &CronJob,
- success: bool,
- output: &str,
- started_at: DateTime<Utc>,
- finished_at: DateTime<Utc>,
-) -> bool {
- let run_id = uuid::Uuid::new_v4().to_string();
- persist_job_result_for_run(
- config,
- job,
- &run_id,
- success,
- output,
- started_at,
- finished_at,
- )
- .await
-}
-
-pub(super) async fn persist_job_result_for_run(
- config: &Config,
- job: &CronJob,
- run_id: &str,
- mut success: bool,
- output: &str,
- started_at: DateTime<Utc>,
- finished_at: DateTime<Utc>,
-) -> bool {
- let duration_ms = (finished_at - started_at).num_milliseconds();
-
- let delivery_status = match deliver_run(config, job, run_id, output, success).await {
- Ok(status) => status,
- Err(e) => {
- if job.delivery.best_effort {
- tracing::warn!("Cron delivery failed (best_effort): {e}");
- } else {
- success = false;
- tracing::warn!("Cron delivery failed: {e}");
- }
- DeliveryStatus::Failed
- }
- };
-
- let _ = record_run_with_delivery(
- config,
- &job.id,
- started_at,
- finished_at,
- if success { "ok" } else { "error" },
- Some(output),
- duration_ms,
- Some(delivery_status),
- );
-
- // A fixed-instant (`Schedule::At`) job is inherently one-shot: its `at` is in
- // the past the moment it runs, so `reschedule_after_run` (which writes
- // next_run = at for an `At` schedule) leaves next_run <= now and the job is
- // re-selected by `due_jobs` on every poll, re-executing forever. Terminate
- // every `At` job after a single run, regardless of `delete_after_run`. Only an
- // auto-delete job that succeeded is removed; everything else is kept disabled
- // so its run history stays inspectable. (Inside this `At` branch
- // `is_one_shot_auto_delete` reduces to `job.delete_after_run`.)
- if matches!(job.schedule, Schedule::At { .. }) {
- if is_one_shot_auto_delete(job) && success {
- if let Err(e) = remove_job(config, &job.id) {
- tracing::warn!("Failed to remove one-shot cron job after success: {e}");
- }
- } else {
- let _ = record_last_run(config, &job.id, finished_at, success, output);
- if let Err(e) = update_job(
- config,
- &job.id,
- CronJobPatch {
- enabled: Some(false),
- ..CronJobPatch::default()
- },
- ) {
- tracing::warn!("Failed to disable one-shot cron job: {e}");
- }
- }
- return success;
- }
-
- if let Err(e) = reschedule_after_run(config, job, success, output) {
- tracing::warn!("Failed to persist scheduler run result: {e}");
- }
-
- success
-}
-
-pub(super) fn is_one_shot_auto_delete(job: &CronJob) -> bool {
- job.delete_after_run && matches!(job.schedule, Schedule::At { .. })
-}
-
/// Why an agent job counts as scheduled more often than every five minutes,
/// if it does. `None` for shell and flow jobs, for one-shot `At` schedules,
/// for anything at or above [`MIN_AGENT_JOB_INTERVAL`], and for an expression
diff --git a/crates/openhuman-core/src/cron/scheduler/slot.rs b/crates/openhuman-core/src/cron/scheduler/slot.rs
deleted file mode 100644
index e5ce16d1ce..0000000000
--- a/crates/openhuman-core/src/cron/scheduler/slot.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-//! 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)
-}