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 host delivery claims

Steven Enamakel6f89d5cc215c
diff --git a/crates/openhuman-core/src/cron/claims.rs b/crates/openhuman-core/src/cron/claims.rs
new file mode 100644
index 0000000000..babdf534a1
--- /dev/null
+++ b/crates/openhuman-core/src/cron/claims.rs
@@ -0,0 +1,86 @@
+//! 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/host_delivery.rs b/crates/openhuman-core/src/cron/host_delivery.rs
new file mode 100644
index 0000000000..8b909cbedd
--- /dev/null
+++ b/crates/openhuman-core/src/cron/host_delivery.rs
@@ -0,0 +1,61 @@
+//! Host-routed delivery of a hosted profile's scheduled output.
+//!
+//! A host that embeds profiles (`profiles::ProfileHost`) owns the conversations
+//! its users talk in, so it can route a scheduled reply better than the core
+//! can. With a [`CronDelivery`] installed, an `origin`-mode run of a profile's
+//! job hands its output to the host instead of writing into a local thread or
+//! channel: the host is told which profile, which conversation the job was
+//! created in, and the job's recorded origin. A run with nothing to say (blank
+//! or `NO_REPLY`) never reaches it.
+
+use std::sync::{Arc, RwLock};
+
+use async_trait::async_trait;
+
+use crate::cron::JobOrigin;
+
+/// One scheduled reply for the host to route.
+#[derive(Debug, Clone, PartialEq)]
+pub struct CronReply {
+ /// The profile whose job produced the reply.
+ pub profile_id: String,
+ /// The job that ran.
+ pub job_id: String,
+ /// This run; stable across redelivery of the same reply.
+ pub run_id: String,
+ /// The thread the job was created in, when it records one.
+ pub thread_id: Option<String>,
+ /// The conversation snapshot the job was created with.
+ pub origin: Option<JobOrigin>,
+ /// What the job said.
+ pub text: String,
+}
+
+/// The host's delivery callback.
+#[async_trait]
+pub trait CronDelivery: Send + Sync {
+ /// Route `reply` to the user. An error is recorded on the run as a failed
+ /// delivery.
+ ///
+ /// # Errors
+ ///
+ /// The host's reason the reply could not be routed.
+ async fn deliver(&self, reply: CronReply) -> Result<(), String>;
+}
+
+static SINK: RwLock<Option<Arc<dyn CronDelivery>>> = RwLock::new(None);
+
+/// Install the process's host delivery, returning the one it replaces.
+pub fn install(sink: Arc<dyn CronDelivery>) -> Option<Arc<dyn CronDelivery>> {
+ SINK.write().unwrap_or_else(|e| e.into_inner()).replace(sink)
+}
+
+/// Remove the installed delivery. Returns whether there was one.
+pub fn clear() -> bool {
+ SINK.write().unwrap_or_else(|e| e.into_inner()).take().is_some()
+}
+
+/// The installed delivery, if any.
+pub fn installed() -> Option<Arc<dyn CronDelivery>> {
+ SINK.read().unwrap_or_else(|e| e.into_inner()).clone()
+}