diff --git a/codex-rs/app-server/src/request_processors/automation_dispatch.rs b/codex-rs/app-server/src/request_processors/automation_dispatch.rs index c5a96d3a6d..95c3674d96 100644 --- a/codex-rs/app-server/src/request_processors/automation_dispatch.rs +++ b/codex-rs/app-server/src/request_processors/automation_dispatch.rs @@ -286,6 +286,14 @@ impl ThreadRequestProcessor { claim: &AutomationDispatchClaim, thread_id: ThreadId, ) -> Result { + let deferred_for_cooldown = state_db + .defer_scheduled_heartbeat_for_cooldown(claim, thread_id) + .await + .map_err(|err| internal_error(format!("failed to defer automation: {err}")))?; + if deferred_for_cooldown { + return Ok(AutomationDispatchResult::Deferred); + } + let loaded_status = self .thread_watch_manager .loaded_status_for_thread(&thread_id.to_string()) diff --git a/codex-rs/state/src/runtime/automation_schedule.rs b/codex-rs/state/src/runtime/automation_schedule.rs index 94dbc2e90e..3330276642 100644 --- a/codex-rs/state/src/runtime/automation_schedule.rs +++ b/codex-rs/state/src/runtime/automation_schedule.rs @@ -151,6 +151,38 @@ pub(super) fn compute_next_run_at( Ok(Some(scheduled + Duration::seconds(jitter_seconds))) } +pub(super) fn compute_next_heartbeat_cooldown_at( + rrule: &str, + last_run_at: Option>, + thread_updated_at: Option>, + now: DateTime, + automation_id: &str, +) -> anyhow::Result>> { + let schedule = AutomationSchedule::parse(rrule)?; + if schedule.one_shot && last_run_at.is_some() { + return Ok(None); + } + let Some(interval) = heartbeat_interval_duration(&schedule) else { + return compute_next_run_at( + AutomationKind::Heartbeat, + automation_id, + &schedule, + last_run_at, + now, + ); + }; + let baseline = [last_run_at, thread_updated_at].into_iter().flatten().max(); + Ok(baseline.map(|value| value + interval)) +} + +fn heartbeat_interval_duration(schedule: &AutomationSchedule) -> Option { + match schedule.frequency { + ScheduleFrequency::Minutely => Some(Duration::minutes(i64::from(schedule.interval))), + ScheduleFrequency::Hourly => Some(Duration::hours(i64::from(schedule.interval))), + ScheduleFrequency::Daily | ScheduleFrequency::Weekly => None, + } +} + fn parse_optional_u32(value: Option<&String>, key: &str, max: u32) -> anyhow::Result> { let Some(value) = value else { return Ok(None); diff --git a/codex-rs/state/src/runtime/automations.rs b/codex-rs/state/src/runtime/automations.rs index 1c5d9cdb1b..391bfa69c4 100644 --- a/codex-rs/state/src/runtime/automations.rs +++ b/codex-rs/state/src/runtime/automations.rs @@ -1,4 +1,5 @@ use super::automation_schedule::AutomationSchedule; +use super::automation_schedule::compute_next_heartbeat_cooldown_at; use super::automation_schedule::compute_next_run_at; use super::*; use crate::AUTOMATION_CLAIM_LEASE_SECS; @@ -527,12 +528,67 @@ WHERE id = ? claim.dispatch_mode == AutomationDispatchMode::Scheduled, "only scheduled automation dispatches can be deferred", ); - let now = Utc::now().timestamp(); let retry_at_ts = retry_at.timestamp(); let next_run_at = claim .next_run_at_after_claim .map(|value| value.timestamp().min(retry_at_ts)) .unwrap_or(retry_at_ts); + self.defer_scheduled_automation_dispatch_until(claim, next_run_at, reason) + .await + } + + pub async fn defer_scheduled_heartbeat_for_cooldown( + &self, + claim: &AutomationDispatchClaim, + thread_id: ThreadId, + ) -> anyhow::Result { + self.defer_scheduled_heartbeat_for_cooldown_at(claim, thread_id, Utc::now()) + .await + } + + async fn defer_scheduled_heartbeat_for_cooldown_at( + &self, + claim: &AutomationDispatchClaim, + thread_id: ThreadId, + now: DateTime, + ) -> anyhow::Result { + anyhow::ensure!( + claim.dispatch_mode == AutomationDispatchMode::Scheduled, + "only scheduled heartbeat dispatches can be deferred", + ); + anyhow::ensure!( + matches!(&claim.automation.target, AutomationTarget::Heartbeat { .. }), + "only heartbeat dispatches can use heartbeat cooldown", + ); + let thread_updated_at = self + .get_thread(thread_id) + .await? + .map(|thread| thread.updated_at); + let Some(cooldown_at) = compute_next_heartbeat_cooldown_at( + claim.automation.rrule.as_str(), + claim.automation.last_run_at, + thread_updated_at, + now, + claim.automation.id.as_str(), + )? + .filter(|cooldown_at| *cooldown_at > now) else { + return Ok(false); + }; + self.defer_scheduled_automation_dispatch_until( + claim, + cooldown_at.timestamp(), + "heartbeat target thread is in cooldown", + ) + .await + } + + async fn defer_scheduled_automation_dispatch_until( + &self, + claim: &AutomationDispatchClaim, + next_run_at: i64, + reason: &str, + ) -> anyhow::Result { + let now = Utc::now().timestamp(); let result = sqlx::query( r#" UPDATE automations diff --git a/codex-rs/state/src/runtime/automations_tests.rs b/codex-rs/state/src/runtime/automations_tests.rs index 1e2298ecce..6c0a641714 100644 --- a/codex-rs/state/src/runtime/automations_tests.rs +++ b/codex-rs/state/src/runtime/automations_tests.rs @@ -7,6 +7,7 @@ use crate::AutomationDispatchRetryOutcome; use crate::AutomationStatus; use crate::AutomationTarget; use crate::AutomationUpdateParams; +use crate::runtime::test_support::test_thread_metadata; use crate::runtime::test_support::unique_temp_dir; use chrono::Duration; use chrono::Utc; @@ -369,6 +370,80 @@ async fn deferred_scheduled_heartbeat_reopens_next_run_without_consuming() { let _ = tokio::fs::remove_dir_all(codex_home).await; } +#[tokio::test] +async fn scheduled_heartbeat_cooldown_defers_after_recent_thread_activity() { + let codex_home = unique_temp_dir(); + let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string()) + .await + .expect("state runtime should initialize"); + let now = Utc::now(); + let target_thread_id = thread_id(); + let thread_updated_at = now - Duration::minutes(5); + let mut metadata = + test_thread_metadata(&codex_home, target_thread_id, codex_home.join("workspace")); + metadata.updated_at = thread_updated_at; + runtime + .upsert_thread(&metadata) + .await + .expect("store target thread metadata"); + + let automation = runtime + .create_automation(&heartbeat_create_params(target_thread_id)) + .await + .expect("create automation"); + sqlx::query("UPDATE automations SET next_run_at = ? WHERE id = ?") + .bind((now - Duration::seconds(1)).timestamp()) + .bind(automation.id.as_str()) + .execute(runtime.automations_pool.as_ref()) + .await + .expect("force due automation"); + + let claim = runtime + .claim_due_automation_dispatch("worker-a") + .await + .expect("claim due automation") + .expect("automation should be due"); + assert!( + runtime + .mark_automation_dispatch_started( + claim.automation.id.as_str(), + claim.ownership_token.as_str(), + ) + .await + .expect("mark started") + ); + + assert!( + runtime + .defer_scheduled_heartbeat_for_cooldown_at(&claim, target_thread_id, now) + .await + .expect("defer heartbeat for cooldown") + ); + + let reloaded = runtime + .get_automation(automation.id.as_str()) + .await + .expect("load automation") + .expect("automation should exist"); + assert_eq!(reloaded.last_run_at, None); + assert_eq!( + reloaded + .next_run_at + .expect("cooldown should set next run") + .timestamp(), + (thread_updated_at + Duration::minutes(30)).timestamp() + ); + assert_eq!( + runtime + .claim_due_automation_dispatch("worker-b") + .await + .expect("cooldown heartbeat should not be immediately due"), + None + ); + + let _ = tokio::fs::remove_dir_all(codex_home).await; +} + #[tokio::test] async fn run_now_dispatches_paused_automation_once() { let codex_home = unique_temp_dir();