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 job runs from stale claims

Steven Enamakel1a1ff6b37075
diff --git a/crates/openhuman-core/src/cron/claims.rs b/crates/openhuman-core/src/cron/claims.rs
deleted file mode 100644
index 6d59ff21c1..0000000000
--- a/crates/openhuman-core/src/cron/claims.rs
+++ /dev/null
@@ -1,89 +0,0 @@
-//! Occurrence claims: at most one process runs a job's scheduled occurrence.
-//!
-//! Several nodes can sweep the same shared store. Each (job, `next_run`) pair
-//! is claimed by creating one document with an absent-only write, so exactly
-//! one sweeper wins it. A claim carries a lease: if its holder dies, another
-//! sweeper may take the occurrence over once the lease has lapsed, by a
-//! compare-and-swap on the claim's version.
-
-use anyhow::{Context, Result};
-use chrono::{DateTime, Utc};
-use serde_json::{json, Value};
-use tinystoragedrivers::{CollectionSpec, DocumentStore, ErrorKind, Filter, Precondition};
-
-use crate::cron::CronJob;
-
-/// Collection holding one claim per claimed occurrence.
-pub const CLAIMS: &str = "cron_occurrence_claims";
-
-/// How long a claim holds an occurrence before another sweeper may retake it.
-pub const CLAIM_LEASE_MS: i64 = 10 * 60 * 1000;
-
-/// Claims older than this are pruned.
-const KEEP_MS: i64 = 24 * 60 * 60 * 1000;
-
-/// The claim id of `job`'s current occurrence.
-fn claim_id(job: &CronJob) -> String {
- format!("{}:{}", job.id, job.next_run.timestamp_millis())
-}
-
-/// Claim `job`'s occurrence for `holder`. `Ok(true)` when this caller now owns
-/// it; `Ok(false)` when another holder has it.
-///
-/// # Errors
-///
-/// When the store fails.
-pub async fn claim_occurrence(
- docs: &dyn DocumentStore,
- job: &CronJob,
- holder: &str,
- now: DateTime<Utc>,
-) -> Result<bool> {
- docs.ensure_collection(&CollectionSpec::new(CLAIMS))
- .await
- .context("declaring the occurrence claims")?;
- let now_ms = now.timestamp_millis();
- let id = claim_id(job);
- let doc = json!({
- "job_id": job.id,
- "holder": holder,
- "claimed_at_ms": now_ms,
- "lease_until_ms": now_ms + CLAIM_LEASE_MS,
- });
- match docs
- .put(CLAIMS, &id, doc.clone(), Precondition::Absent)
- .await
- {
- Ok(_) => return Ok(true),
- Err(error) if error.kind() == ErrorKind::Conflict => {}
- Err(error) => return Err(error).context("claiming the occurrence"),
- }
- let Some(held) = docs.get(CLAIMS, &id).await.context("reading the claim")? else {
- return Ok(false);
- };
- let lapsed = held.doc.get("lease_until_ms").and_then(Value::as_i64) < Some(now_ms);
- if !lapsed {
- return Ok(false);
- }
- match docs.put(CLAIMS, &id, doc, held.unchanged()).await {
- Ok(_) => Ok(true),
- Err(error) if error.kind() == ErrorKind::Conflict => Ok(false),
- Err(error) => Err(error).context("retaking the lapsed claim"),
- }
-}
-
-/// Drop claims whose lease ended more than a day ago.
-///
-/// # Errors
-///
-/// When the store fails.
-pub async fn prune(docs: &dyn DocumentStore, now: DateTime<Utc>) -> Result<u64> {
- let cutoff = now.timestamp_millis() - KEEP_MS;
- docs.delete_where(CLAIMS, &Filter::lt("lease_until_ms", cutoff))
- .await
- .context("pruning old claims")
-}
-
-#[cfg(test)]
-#[path = "claims_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/cron/claims_tests.rs b/crates/openhuman-core/src/cron/claims_tests.rs
deleted file mode 100644
index 3ad219cecd..0000000000
--- a/crates/openhuman-core/src/cron/claims_tests.rs
+++ /dev/null
@@ -1,88 +0,0 @@
-use super::*;
-use crate::cron::{Schedule, SessionTarget};
-use crate::storage::{MemoryStorage, Scope, StorageBackend};
-use chrono::Duration;
-use std::sync::Arc;
-use tinyflows_drivers::schedule::CronDocuments;
-
-async fn job(docs: &Arc<dyn DocumentStore>) -> CronJob {
- CronDocuments::new(Arc::clone(docs))
- .add_agent_job(
- None,
- Schedule::Every {
- every_ms: 3_600_000,
- },
- "ping",
- SessionTarget::Isolated,
- None,
- None,
- false,
- )
- .await
- .unwrap()
-}
-
-fn docs() -> Arc<dyn DocumentStore> {
- let scoped = MemoryStorage::new()
- .for_scope(&Scope::new("claims").unwrap())
- .unwrap();
- Arc::clone(scoped.documents())
-}
-
-#[tokio::test]
-async fn competing_holders_claim_an_occurrence_once() {
- let docs = docs();
- let job = job(&docs).await;
- let now = Utc::now();
- let (a, b) = tokio::join!(
- claim_occurrence(docs.as_ref(), &job, "node-a", now),
- claim_occurrence(docs.as_ref(), &job, "node-b", now),
- );
- assert_eq!(
- [a.unwrap(), b.unwrap()].iter().filter(|won| **won).count(),
- 1
- );
- let again = claim_occurrence(docs.as_ref(), &job, "node-a", now).await;
- assert!(
- !again.unwrap(),
- "a holder cannot claim the same occurrence twice"
- );
-}
-
-#[tokio::test]
-async fn a_lapsed_claim_is_retaken_by_one_holder() {
- let docs = docs();
- let job = job(&docs).await;
- let now = Utc::now();
- assert!(claim_occurrence(docs.as_ref(), &job, "dead", now)
- .await
- .unwrap());
- let later = now + Duration::milliseconds(CLAIM_LEASE_MS + 1);
- let (a, b) = tokio::join!(
- claim_occurrence(docs.as_ref(), &job, "node-a", later),
- claim_occurrence(docs.as_ref(), &job, "node-b", later),
- );
- assert_eq!(
- [a.unwrap(), b.unwrap()].iter().filter(|won| **won).count(),
- 1
- );
-}
-
-#[tokio::test]
-async fn each_occurrence_has_its_own_claim_and_old_claims_are_pruned() {
- let docs = docs();
- let mut job = job(&docs).await;
- let now = Utc::now();
- assert!(claim_occurrence(docs.as_ref(), &job, "node-a", now)
- .await
- .unwrap());
- job.next_run += Duration::hours(1);
- assert!(claim_occurrence(docs.as_ref(), &job, "node-a", now)
- .await
- .unwrap());
- assert_eq!(prune(docs.as_ref(), now).await.unwrap(), 0);
- assert_eq!(
- prune(docs.as_ref(), now + Duration::days(2)).await.unwrap(),
- 2
- );
-}
diff --git a/crates/openhuman-core/src/cron/scheduler/run_record.rs b/crates/openhuman-core/src/cron/scheduler/run_record.rs
deleted file mode 100644
index 013e501208..0000000000
--- a/crates/openhuman-core/src/cron/scheduler/run_record.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-//! The high-frequency agent-job warning. Persisting a finished run (history,
-//! one-shot termination, rescheduling) is the schedule runtime's
-//! (`tinyflows_schedule::runtime`).
-
-use chrono::Utc;
-use {
- tinyflows_schedule::schedule::runs_closer_than, tinyflows_schedule::schedule::TooFrequent,
- tinyflows_schedule::schedule::MIN_AGENT_JOB_INTERVAL, tinyflows_schedule::types::CronJob,
- tinyflows_schedule::types::JobType,
-};
-
-/// 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
-/// that cannot be read (that is not evidence of anything).
-///
-/// Returns the verdict rather than only logging it, because the verdict is
-/// the part worth testing: the `Schedule::Cron` arm used to measure the gap
-/// between the next run after now and the next run after now plus one
-/// second — the same instant unless a run fell inside that second — so every
-/// cron-scheduled agent job warned, and no test could see it because a
-/// function that only warns has nothing to assert. The gap is now the
-/// shortest one between consecutive runs (`runs_closer_than`), so an
-/// irregular expression is judged by its tightest pair and not by whichever
-/// pair happens to follow the instant of the check.
-pub(super) fn agent_job_too_frequent(job: &CronJob) -> Option<TooFrequent> {
- if !matches!(job.job_type, JobType::Agent) {
- return None;
- }
- runs_closer_than(&job.schedule, Utc::now(), MIN_AGENT_JOB_INTERVAL)
-}
-
-/// New agent jobs cannot be created below the floor (`validate_agent_schedule`
-/// rejects them), so a job that trips this predates the rule. It keeps
-/// running — silently skipping runs would turn its schedule into a lie — and
-/// this line is the operator's signal to edit it.
-pub(super) fn warn_if_high_frequency_agent_job(job: &CronJob) {
- if let Some(too_frequent) = agent_job_too_frequent(job) {
- tracing::warn!(
- "Cron agent job '{}' is scheduled more frequently than every 5 minutes: it \
- {too_frequent}. It was created before that floor was enforced; edit its \
- schedule to silence this.",
- job.id
- );
- }
-}