1pub mod expr;
30pub mod schedule;
31pub mod start;
32
33pub use start::{ActionOutcome, ActionRunner};
34
35use agentmux_common::AUTH_KEY_HEADER;
36use std::collections::HashMap;
37use std::sync::{Arc, Mutex};
38
39use agentmux_common::api_types::InjectRequest;
40use chrono::{DateTime, Utc};
41
42use crate::backend::jobs::admission::Admission;
43use crate::backend::jobs::{self, RunLedger};
44use crate::backend::storage::store::Store;
45use crate::backend::storage::cron::{CronJob, FireProof, WRITER_OPERATOR};
46use crate::backend::mps::Broker;
47use crate::backend::reactive::types::{InjectionRequest, SchedulerFire, SCHEDULER_SENDER};
48
49type HandleMap = Mutex<HashMap<String, tokio::task::AbortHandle>>;
51
52const MISSED_SLOTS_CAP: usize = 100_000;
54
55const PENDING_SWEEP_EVERY: std::time::Duration = std::time::Duration::from_secs(30);
57
58pub type FireDelivery = Arc<
66 dyn Fn(
67 InjectionRequest,
68 String,
69 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = serde_json::Value> + Send>>
70 + Send
71 + Sync,
72>;
73
74pub type AgentPresence = Arc<dyn Fn(&str) -> bool + Send + Sync>;
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub(crate) enum MissReason {
81 TargetStopped,
85 TargetMissing,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum FireOutcome {
92 Delivered { block_id: Option<String> },
93 Missed { reason: MissReason },
94 Failed { error: String },
95}
96
97impl FireOutcome {
98 pub(crate) fn delivered(&self) -> bool {
99 matches!(self, FireOutcome::Delivered { .. })
100 }
101
102 pub(crate) fn miss_reason(&self) -> Option<String> {
105 match self {
106 FireOutcome::Delivered { .. } => None,
107 FireOutcome::Missed { reason: MissReason::TargetStopped } => Some("target_stopped".into()),
108 FireOutcome::Missed { reason: MissReason::TargetMissing } => Some("target_missing".into()),
109 FireOutcome::Failed { error } => Some(format!("failed: {error}")),
110 }
111 }
112}
113
114pub(crate) fn fire_outcome(body: Option<&serde_json::Value>) -> FireOutcome {
118 let Some(body) = body else {
119 return FireOutcome::Failed { error: "inject request failed".to_string() };
120 };
121 if body.get("success").and_then(|v| v.as_bool()) == Some(true) {
122 let block_id = body.get("block_id").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(str::to_string);
123 return FireOutcome::Delivered { block_id };
124 }
125 let error = body.get("error").and_then(|v| v.as_str()).unwrap_or("").to_string();
126 if error.starts_with("agent not found") {
127 return FireOutcome::Missed { reason: MissReason::TargetStopped };
128 }
129 FireOutcome::Failed { error }
130}
131
132pub(crate) fn fire_message(prompt: &str, run_id: Option<&str>, late_for: Option<i64>) -> String {
137 match run_id {
138 Some(run_id) if !prompt.trim_start().starts_with('/') => {
139 format!("{prompt}\n\n{}", jobs::brief_line(run_id, late_for, agentmux_common::time::now_ms()))
140 }
141 _ => prompt.to_string(),
142 }
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
147pub enum Slot {
148 Scheduled(i64),
150 CatchUp(i64),
152 Manual { triggered_by: String },
155}
156
157#[derive(Debug, Clone)]
159pub struct JobEvent {
160 pub id: String,
162 pub source: String,
164 pub input: serde_json::Value,
166}
167
168#[derive(Debug, Clone, PartialEq, Eq)]
170pub struct Fired {
171 pub run_id: Option<String>,
173 pub outcome: Option<FireOutcome>,
176 pub waiting: Option<&'static str>,
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184struct Missed {
185 newest_ms: i64,
186 earlier: Option<(i64, i64)>,
187}
188
189pub struct CronScheduler {
190 handles: HandleMap,
191 jobs_store: Option<Arc<Store>>,
193 http_client: reqwest::Client,
194 local_url: String,
195 auth_key: String,
196 broker: Arc<Broker>,
197 delivery: std::sync::OnceLock<FireDelivery>,
198 presence: std::sync::OnceLock<AgentPresence>,
199 runs: std::sync::OnceLock<Arc<RunLedger>>,
200 actions: std::sync::OnceLock<ActionRunner>,
202 aged_out: Mutex<std::collections::HashSet<String>>,
208}
209
210impl CronScheduler {
211 pub fn new(
212 jobs_store: Option<Arc<Store>>,
213 http_client: reqwest::Client,
214 local_url: String,
215 auth_key: String,
216 broker: Arc<Broker>,
217 ) -> Arc<Self> {
218 Arc::new(Self {
219 handles: Mutex::new(HashMap::new()),
220 jobs_store,
221 http_client,
222 local_url,
223 auth_key,
224 broker,
225 delivery: std::sync::OnceLock::new(),
226 presence: std::sync::OnceLock::new(),
227 runs: std::sync::OnceLock::new(),
228 actions: std::sync::OnceLock::new(),
229 aged_out: Mutex::default(),
230 })
231 }
232
233 pub fn install_delivery(&self, delivery: FireDelivery) {
236 let _ = self.delivery.set(delivery);
237 }
238
239 pub fn install_presence(&self, presence: AgentPresence) {
241 let _ = self.presence.set(presence);
242 }
243
244 pub fn install_runs(&self, ledger: Arc<RunLedger>) {
247 let _ = self.runs.set(ledger);
248 }
249
250 pub fn runs(&self) -> Option<&Arc<RunLedger>> {
252 self.runs.get()
253 }
254
255 fn publish_changed(&self) {
256 self.broker.publish_event::<crate::backend::mps_events::CronChanged>(&(), vec![], 0);
257 }
258
259 pub async fn start(self: &Arc<Self>) {
261 self.start_at(Utc::now()).await;
262 }
263
264 pub(crate) async fn start_at(self: &Arc<Self>, now_dt: DateTime<Utc>) {
267 let store = match &self.jobs_store {
268 Some(s) => s.clone(),
269 None => {
270 tracing::warn!("cron: no job store — cron scheduler disabled");
271 return;
272 }
273 };
274
275 let jobs = match store.cron_list_enabled() {
276 Ok(j) => j,
277 Err(e) => {
278 tracing::error!(error = %e, "cron: failed to load jobs on startup");
279 return;
280 }
281 };
282
283 let count = jobs.len();
284
285 for job in jobs {
286 let missed = self.missed_while_off(&job, now_dt);
287 self.schedule_job_inner(&job, missed);
288 }
289
290 self.spawn_pending_delivery();
291 tracing::info!(count, "cron: scheduled {} job(s) from DB", count);
292 }
293
294 fn missed_while_off(&self, job: &CronJob, now_dt: DateTime<Utc>) -> Option<Missed> {
300 if !should_catchup(job, now_dt) {
301 return None;
302 }
303 let mut base_ms = catch_up_base_secs(job).saturating_mul(1000);
304 if let Some(last) = self.runs().and_then(|r| r.store().job_run_last(&job.id).ok().flatten()) {
305 let seen = last.last_skip_at_ms.or(last.scheduled_for_ms).unwrap_or(last.started_at_ms);
306 base_ms = base_ms.max(seen);
307 }
308 let schedule = schedule::JobSchedule::of(job).ok()?;
309 let (newest_ms, earlier) = jobs::missed_slots(&schedule, base_ms, now_dt.timestamp_millis(), MISSED_SLOTS_CAP)?;
310 Some(Missed { newest_ms, earlier })
311 }
312
313 pub fn schedule_job(self: &Arc<Self>, job: &CronJob) {
316 self.schedule_job_inner(job, None);
317 }
318
319 fn schedule_job_inner(self: &Arc<Self>, job: &CronJob, missed: Option<Missed>) {
320 self.cancel_job(&job.id);
321
322 let schedule = match schedule::JobSchedule::of(job) {
323 Ok(schedule::JobSchedule::Manual) => return,
324 Ok(s) => s,
325 Err(e) => {
326 tracing::warn!(id = %job.id, expr = %job.expression, error = %e, "cron: invalid trigger — skipping job");
327 return;
328 }
329 };
330 let jitter = if matches!(schedule, schedule::JobSchedule::Once { .. }) { 0 } else { schedule::jitter_ms(&job.id) };
332
333 let sched = self.clone();
334 let job = job.clone();
335 let job_id = job.id.clone();
336
337 let handle = tokio::spawn(async move {
338 let mut fires: i64 = job.fire_count;
341 let mut last_slot: Option<i64> = None;
345 if let Some(m) = missed {
346 let latest = job.catch_up == jobs::CATCH_UP_LATEST;
349 let skipped = match (latest, m.earlier) {
350 (true, earlier) => earlier,
351 (false, Some((first, n))) => Some((first, n + 1)),
352 (false, None) => Some((m.newest_ms, 1)),
353 };
354 if let (Some(runs), Some((first, n))) = (sched.runs(), skipped) {
355 let (runs, job) = (runs.clone(), job.clone());
356 let _ = tokio::task::spawn_blocking(move || runs.record_missed_while_off(&job, first, n)).await;
357 }
358 if latest && sched.fire(&job, Slot::CatchUp(m.newest_ms)).await.outcome.is_some_and(|o| o.delivered()) {
361 fires += 1;
362 }
363 }
364 loop {
365 if let Some(max) = job.max_fires {
373 if fires >= max {
374 sched.disable_job(&job.id, "max_fires reached");
375 break;
376 }
377 }
378 if is_expired_by_age(job.created_at, job.max_age_secs, Utc::now().timestamp()) {
379 sched.disable_job(&job.id, "max_age_secs reached");
380 break;
381 }
382 let now_ms = agentmux_common::time::now_ms();
383 let from = last_slot.map_or(now_ms, |l| l.max(now_ms - jitter));
384 let Some(next_ms) = schedule.next_after(from) else {
385 if matches!(schedule, schedule::JobSchedule::Once { .. }) {
387 sched.disable_job(&job.id, "once fired");
388 }
389 break;
390 };
391 let Some(next) = DateTime::from_timestamp_millis(next_ms) else { break };
392 if is_expired_by_age(job.created_at, job.max_age_secs, next.timestamp()) {
402 sched.disable_job(&job.id, "max_age_secs would be reached before the next scheduled fire");
403 break;
404 }
405 let due = next_ms + jitter - agentmux_common::time::now_ms();
406 tokio::time::sleep(std::time::Duration::from_millis(due.max(0) as u64)).await;
407 last_slot = Some(next_ms);
408 if let Some(n) = sched.persisted_fire_count(&job.id) {
411 fires = fires.max(n);
412 }
413 if job.max_fires.is_some_and(|max| fires >= max) {
414 sched.disable_job(&job.id, "max_fires reached");
415 break;
416 }
417 if sched.fire(&job, Slot::Scheduled(next_ms)).await.outcome.is_some_and(|o| o.delivered()) {
418 fires += 1;
419 }
420 if let Some(max) = job.max_fires {
424 if fires >= max {
425 sched.disable_job(&job.id, "max_fires reached");
426 break;
427 }
428 }
429 }
430 });
431
432 self.handles.lock().unwrap().insert(job_id, handle.abort_handle());
433 }
434
435 #[cfg(any(test, feature = "test-support"))]
437 pub fn is_scheduled(&self, id: &str) -> bool {
438 self.handles.lock().unwrap().contains_key(id)
439 }
440
441 pub fn cancel_job(&self, id: &str) {
443 self.aged_out.lock().unwrap().remove(id);
444 if let Some(handle) = self.handles.lock().unwrap().remove(id) {
445 handle.abort();
446 }
447 }
448
449 fn disable_job(&self, job_id: &str, reason: &str) {
455 tracing::info!(id = job_id, reason, "cron: disabling job");
456 if reason.starts_with("max_age_secs") {
457 self.aged_out.lock().unwrap().insert(job_id.to_string());
458 }
459 if let Some(store) = &self.jobs_store {
460 let _ = store.cron_set_enabled(job_id, false);
461 }
462 self.handles.lock().unwrap().remove(job_id);
463 self.publish_changed();
464 }
465
466 pub async fn run_now(&self, job: &CronJob, triggered_by: &str) -> Fired {
469 self.fire(job, Slot::Manual { triggered_by: triggered_by.to_string() }).await
470 }
471
472 pub async fn fire_event(&self, job: &CronJob, event: JobEvent) -> Fired {
476 let none = Fired { run_id: None, outcome: None, waiting: None };
477 if !job.enabled || job.trigger_kind != crate::backend::jobs::definition::trigger_kind::EVENT {
478 return none;
479 }
480 let Some(runs) = self.runs().cloned() else { return none };
481 let admitted = {
482 let (runs, owned, id, source, input) = (runs.clone(), job.clone(), event.id.clone(), event.source.clone(), event.input.clone());
483 tokio::task::spawn_blocking(move || runs.admit_event(&owned, &id, &source, &input)).await.unwrap_or(Admission::Unrecorded)
484 };
485 match admitted {
486 Admission::Run(run_id) => {
487 let fired = self.start_run(job, Some(run_id), true, None).await;
488 if matches!(fired.outcome, Some(FireOutcome::Delivered { .. })) {
489 self.stop_at_max_fires(&job.id);
490 }
491 fired
492 }
493 Admission::Waiting(run_id, why) => {
494 self.publish_changed();
495 Fired { run_id: Some(run_id), outcome: None, waiting: Some(why) }
496 }
497 Admission::Unrecorded | Admission::Taken | Admission::Skipped | Admission::Refused | Admission::Capped(_) => none,
499 }
500 }
501
502 pub async fn fire(&self, job: &CronJob, slot: Slot) -> Fired {
521 let id = job.id.as_str();
522 let (trigger, scheduled_for, by) = match &slot {
523 Slot::Scheduled(ms) => (jobs::TRIGGER_SCHEDULE, Some(*ms), jobs::BY_SCHEDULER.to_string()),
524 Slot::CatchUp(ms) => (jobs::TRIGGER_CATCH_UP, Some(*ms), jobs::BY_SCHEDULER.to_string()),
525 Slot::Manual { triggered_by } => (jobs::TRIGGER_MANUAL, None, triggered_by.clone()),
526 };
527 if let Some(fired) = self.paused_all_answer(job, scheduled_for).await {
528 return fired;
529 }
530 let admitted = match self.runs() {
531 Some(runs) => {
532 let (runs, owned, by) = (runs.clone(), job.clone(), by);
533 tokio::task::spawn_blocking(move || runs.admit_cron(&owned, trigger, scheduled_for, &by))
534 .await
535 .unwrap_or(Admission::Unrecorded)
536 }
537 None => Admission::Unrecorded,
538 };
539 let run_id = match admitted {
540 Admission::Run(run_id) => Some(run_id),
541 Admission::Unrecorded => None,
542 Admission::Taken => {
543 tracing::debug!(id, ?slot, "cron: another scheduler has this slot");
544 return Fired { run_id: None, outcome: None, waiting: None };
545 }
546 Admission::Skipped => return Fired { run_id: None, outcome: None, waiting: None },
547 Admission::Refused => {
548 let error = jobs::OVERLAP_REFUSAL.to_string();
549 return Fired { run_id: None, outcome: Some(FireOutcome::Failed { error }), waiting: None };
550 }
551 Admission::Capped(refusal) => {
552 let error = format!("Run now is refused: {}", refusal.words());
553 return Fired { run_id: None, outcome: Some(FireOutcome::Failed { error }), waiting: None };
554 }
555 Admission::Waiting(run_id, why) => {
556 self.publish_changed();
557 return Fired { run_id: Some(run_id), outcome: None, waiting: Some(why) };
558 }
559 };
560 let late_for = match slot {
561 Slot::CatchUp(ms) => Some(ms),
562 _ => None,
563 };
564 let scheduled = !matches!(slot, Slot::Manual { .. });
565 self.start_run(job, run_id, scheduled, late_for).await
566 }
567
568 async fn paused_all_answer(&self, job: &CronJob, scheduled_for: Option<i64>) -> Option<Fired> {
572 let runs = self.runs()?.clone();
573 let job = job.clone();
574 let answer = tokio::task::spawn_blocking(move || {
575 runs.paused_all()?;
576 Some(match scheduled_for {
577 Some(slot) => {
578 runs.record_skip_slot(&job, slot, crate::backend::storage::job_runs::reason::PAUSED_ALL);
579 Fired { run_id: None, outcome: None, waiting: None }
580 }
581 None => Fired {
582 run_id: None,
583 outcome: Some(FireOutcome::Failed { error: jobs::PAUSED_ALL_REFUSAL.to_string() }),
584 waiting: None,
585 },
586 })
587 });
588 answer.await.ok().flatten()
589 }
590
591 async fn deliver(&self, job: &CronJob, run_id: Option<&str>, late_for: Option<i64>) -> Option<FireOutcome> {
595 let id = job.id.as_str();
596 if job.created_by_uid.is_empty() {
597 crate::backend::agent_resolve::record_uid_fallback("m4c.cron_fire_unattributed");
598 }
599 let target_agent = fire_target(&job.target, &job.target_uid).to_string();
600 if target_agent.trim().is_empty() {
601 tracing::warn!(id, "cron: the job names no target");
602 return Some(FireOutcome::Missed { reason: MissReason::TargetMissing });
603 }
604 let message = fire_message(&job.prompt, run_id, late_for);
605 let request_id = run_id.map(str::to_string);
606 let body = match self.delivery.get() {
607 Some(deliver) => {
608 let req = InjectionRequest {
609 target_agent,
610 message,
611 source_agent: Some(SCHEDULER_SENDER.to_string()),
612 request_id,
613 scheduler_fire: scheduler_fire_of(job),
614 ..Default::default()
615 };
616 Some(deliver(req, job.created_by_uid.clone()).await)
617 }
618 None => {
619 if self.local_url.is_empty() || self.auth_key.is_empty() {
620 tracing::warn!(id, "cron: no local_url/auth_key — skipping fire");
621 return None;
622 }
623 crate::backend::agent_resolve::record_uid_fallback("m4c.cron_fire_http");
624 self.post_fire(id, target_agent, &message, request_id).await
625 }
626 };
627 let outcome = fire_outcome(body.as_ref());
628 if outcome.delivered() {
633 tracing::debug!(id, target = %job.target, "cron: fired");
634 } else {
635 tracing::warn!(id, target = %job.target, target_uid = %job.target_uid, ?outcome, "cron: fire was not delivered");
636 }
637 Some(outcome)
638 }
639
640 fn within_age_bound(&self, job: &CronJob, now_ms: i64) -> bool {
643 self.aged_out.lock().unwrap().contains(&job.id)
644 && job.max_age_secs.is_some_and(|age| now_ms < job.created_at.saturating_add(age).saturating_mul(1000))
645 }
646
647 #[cfg(test)]
649 pub(crate) fn disable_for_test(&self, job_id: &str, reason: &str) {
650 self.disable_job(job_id, reason);
651 }
652
653 fn persisted_fire_count(&self, id: &str) -> Option<i64> {
655 self.jobs_store.as_ref()?.cron_get(id).ok().flatten().map(|j| j.fire_count)
656 }
657
658 fn stop_at_max_fires(&self, id: &str) {
662 let at_max = self
663 .jobs_store
664 .as_ref()
665 .and_then(|s| s.cron_get(id).ok().flatten())
666 .is_some_and(|j| j.max_fires.is_some_and(|max| j.fire_count >= max));
667 if at_max {
668 tracing::info!(id, "cron: a pending fire reached max_fires; stopping the job");
669 self.cancel_job(id);
670 }
671 }
672
673 fn record_result(&self, id: &str, outcome: &FireOutcome) {
678 if let Some(store) = &self.jobs_store {
679 let now = Utc::now().timestamp();
680 let recorded = match outcome.miss_reason() {
681 None => store.cron_record_fire(id, now),
682 Some(reason) => store.cron_record_miss(id, now, &reason),
683 };
684 if let Err(e) = recorded {
685 tracing::warn!(id, error = %e, "cron: failed to record the fire in DB");
686 }
687 }
688 }
689
690 fn spawn_pending_delivery(self: &Arc<Self>) {
694 if self.runs().is_none() {
695 return;
696 }
697 let sched = self.clone();
698 tokio::spawn(async move {
699 loop {
700 sched.deliver_pending().await;
701 sched.run_policy_pass().await;
702 tokio::select! {
703 _ = jobs::pending_wake().notified() => {}
704 _ = tokio::time::sleep(PENDING_SWEEP_EVERY) => {}
705 }
706 }
707 });
708 }
709
710 pub(crate) async fn deliver_pending(&self) -> usize {
713 let Some(runs) = self.runs().cloned() else { return 0 };
714 let waiting = {
715 let runs = runs.clone();
716 tokio::task::spawn_blocking(move || runs.waiting_here()).await.unwrap_or_default()
717 };
718 let now = agentmux_common::time::now_ms();
719 let paused_all = {
720 let runs = runs.clone();
721 tokio::task::spawn_blocking(move || runs.paused_all().is_some()).await.unwrap_or(false)
722 };
723 let mut delivered = 0;
724 for run in waiting {
725 let job = self.jobs_store.as_ref().and_then(|s| s.cron_get(&run.job_id).ok().flatten());
726 let expired = match (&job, run.scheduled_for_ms) {
727 (Some(job), Some(slot)) => {
728 let stopped = !job.enabled && !self.within_age_bound(job, now);
731 let at_max = job.max_fires.is_some_and(|max| job.fire_count >= max);
732 stopped || at_max || jobs::next_slot_after(job, slot).is_none_or(|next| next <= now)
733 }
734 _ => true,
735 };
736 if expired {
737 runs.expire_pending(&run.id);
738 continue;
739 }
740 if paused_all {
742 continue;
743 }
744 let Some(job) = job else { continue };
745 let back = match (self.presence.get(), job.target_uid.is_empty()) {
746 (Some(present), false) => present(&job.target_uid),
747 _ => true,
749 };
750 if !back {
751 continue;
752 }
753 let may_start = {
756 let (runs, job) = (runs.clone(), job.clone());
757 let run_id = run.id.clone();
758 tokio::task::spawn_blocking(move || runs.pending_may_start(&job, &run_id)).await.unwrap_or(false)
759 };
760 if !may_start {
761 continue;
762 }
763 let delivery_started = agentmux_common::time::now_ms();
764 let Some(outcome) = self.deliver(&job, Some(&run.id), run.scheduled_for_ms).await else {
765 runs.pending_delivery_done(&run.id);
766 continue;
767 };
768 runs.record_pending_delivery(&run, &outcome, delivery_started);
769 runs.pending_delivery_done(&run.id);
770 if outcome.delivered() {
774 self.record_result(&job.id, &outcome);
775 self.stop_at_max_fires(&job.id);
776 delivered += 1;
777 self.publish_changed();
778 }
779 }
780 delivered
781 }
782
783 async fn post_fire(&self, id: &str, target_agent: String, prompt: &str, request_id: Option<String>) -> Option<serde_json::Value> {
787 let url = format!("{}/agentmux/reactive/inject", self.local_url.trim_end_matches('/'));
788 let req = InjectRequest {
789 target_agent,
790 message: prompt.to_string(),
791 source_agent: Some("cron".to_string()),
792 request_id,
793 ..Default::default()
794 };
795 match self.http_client.post(&url).header(AUTH_KEY_HEADER, &self.auth_key).json(&req).send().await {
796 Ok(r) if r.status().is_success() => Some(r.json().await.unwrap_or_default()),
797 Ok(r) => {
798 tracing::warn!(id, status = %r.status(), "cron: inject returned non-2xx");
799 None
800 }
801 Err(e) => {
802 tracing::warn!(id, error = %e, "cron: inject request failed");
803 None
804 }
805 }
806 }
807}
808
809fn scheduler_fire_of(job: &CronJob) -> Option<SchedulerFire> {
813 let proof = job.fire_proof()?;
814 let name = if job.name.trim().is_empty() { job.id.as_str() } else { job.name.as_str() };
815 Some(match proof {
816 FireProof::Operator => SchedulerFire { job_id: job.id.clone(), job: name.to_string(), proof_uid: String::new(), runs_for: WRITER_OPERATOR.to_string() },
817 FireProof::Agent(uid) => SchedulerFire { job_id: job.id.clone(), job: name.to_string(), proof_uid: uid, runs_for: String::new() },
818 })
819}
820
821fn should_catchup(job: &CronJob, now_dt: DateTime<Utc>) -> bool {
833 let last = catch_up_base_secs(job);
834 let last_dt = match DateTime::from_timestamp(last, 0) {
835 Some(dt) => dt,
836 None => return false,
837 };
838 let Ok(schedule) = schedule::JobSchedule::of(job) else {
839 return false;
840 };
841 match schedule.next_after(last_dt.timestamp_millis()) {
843 Some(next_after_last) => next_after_last < now_dt.timestamp_millis(),
844 None => false,
845 }
846}
847
848fn catch_up_base_secs(job: &CronJob) -> i64 {
851 job.last_fired.unwrap_or(job.created_at)
852}
853
854pub(crate) fn is_expired_by_age(created_at: i64, max_age_secs: Option<i64>, now: i64) -> bool {
860 match max_age_secs {
861 Some(max_age) => now - created_at >= max_age,
862 None => false,
863 }
864}
865
866#[cfg(test)]
867mod tests {
868 use super::*;
869
870 #[test]
871 fn is_expired_by_age_none_never_expires() {
872 assert!(!is_expired_by_age(1_000, None, 1_000_000_000));
873 }
874
875 #[test]
876 fn is_expired_by_age_before_bound_is_not_expired() {
877 assert!(!is_expired_by_age(1_000, Some(3_600), 1_000 + 3_599));
878 }
879
880 #[test]
881 fn is_expired_by_age_at_bound_is_expired() {
882 assert!(is_expired_by_age(1_000, Some(3_600), 1_000 + 3_600));
884 }
885
886 #[test]
887 fn is_expired_by_age_past_bound_is_expired() {
888 assert!(is_expired_by_age(1_000, Some(3_600), 1_000 + 10_000));
889 }
890
891 #[test]
901 fn is_expired_by_age_catches_a_next_fire_time_past_the_bound() {
902 let created_at = 1_000;
903 let max_age_secs = Some(3_600);
904 let next_fire_far_in_the_future = created_at + 86_400; assert!(is_expired_by_age(created_at, max_age_secs, next_fire_far_in_the_future));
906 }
907}
908
909#[cfg(any(test, feature = "test-support"))]
911pub fn test_job(id: &str, prompt: &str, target: &str, target_uid: &str, created_by_uid: &str) -> CronJob {
912 CronJob {
913 id: id.to_string(),
914 name: format!("{id} name"),
915 expression: "* * * * *".to_string(),
916 prompt: prompt.to_string(),
917 target: target.to_string(),
918 target_uid: target_uid.to_string(),
919 created_by: "creator".to_string(),
920 created_by_uid: created_by_uid.to_string(),
921 enabled: true,
922 last_fired: None,
923 fire_count: 0,
924 max_fires: None,
925 created_at: 0,
926 max_age_secs: None,
927 catch_up: jobs::CATCH_UP_SKIP.to_string(),
928 ..Default::default()
929 }
930}
931
932fn fire_target<'a>(target: &'a str, target_uid: &'a str) -> &'a str {
936 let uid = target_uid.trim();
937 if uid.is_empty() {
938 crate::backend::agent_resolve::record_uid_fallback("cron.fire_by_name");
939 target
940 } else {
941 uid
942 }
943}
944
945#[cfg(test)]
946mod identity_m3_tests {
947 use super::fire_target;
948
949 #[test]
950 fn fires_by_uid_when_captured_and_by_name_otherwise() {
951 assert_eq!(fire_target("AgentY", "4f3c-a91"), "4f3c-a91");
952 assert_eq!(fire_target("AgentY", ""), "AgentY");
953 assert_eq!(fire_target("AgentY", " "), "AgentY");
954 }
955}
956
957#[cfg(test)]
958mod identity_m4c3_tests {
959 use super::*;
960
961 #[tokio::test]
965 async fn a_fire_is_delivered_in_process_as_cron_with_the_creators_uid() {
966 let sched = CronScheduler::new(
967 None,
968 reqwest::Client::new(),
969 "http://127.0.0.1:1".to_string(),
971 "test".to_string(),
972 Arc::new(Broker::new()),
973 );
974 let seen: Arc<Mutex<Vec<(InjectionRequest, String)>>> = Arc::default();
975 let sink = seen.clone();
976 sched.install_delivery(Arc::new(move |req, creator_uid| {
977 sink.lock().unwrap().push((req, creator_uid));
978 Box::pin(async { serde_json::json!({"success": true}) })
979 }));
980
981 sched.fire(&test_job("job-1", "check in", "AgentY", "uid-target", "uid-creator"), Slot::Scheduled(0)).await;
982
983 let seen = seen.lock().unwrap();
984 assert_eq!(seen.len(), 1);
985 let (req, creator_uid) = &seen[0];
986 assert_eq!(req.target_agent, "uid-target");
987 assert_eq!(req.message, "check in", "no ledger installed: no run line");
988 assert_eq!(req.source_agent.as_deref(), Some("cron"), "the sender name stays cron");
989 let proof = req.scheduler_fire.as_ref().expect("a job whose creator was identified carries what proves its fire");
990 assert_eq!(proof.proof_uid, "uid-creator", "the creator, named later by srv from its own record");
991 assert_eq!(proof.runs_for, "", "the scheduler does not name it");
992 assert!(!proof.job.is_empty(), "the job's name rides with it");
993 assert_eq!(creator_uid, "uid-creator");
994 assert_eq!(req.audit_source_uid, "", "the delivery path sets it, on this instance only");
995 }
996}
997
998
999#[cfg(test)]
1000mod missed_fire_tests {
1001 use super::*;
1002 use serde_json::json;
1003
1004 fn sched_with(store: Option<Arc<Store>>, answer: serde_json::Value) -> Arc<CronScheduler> {
1005 let sched = CronScheduler::new(
1006 store,
1007 reqwest::Client::new(),
1008 "http://127.0.0.1:1".to_string(),
1009 "test".to_string(),
1010 Arc::new(Broker::new()),
1011 );
1012 sched.install_delivery(Arc::new(move |_, _| {
1013 let answer = answer.clone();
1014 Box::pin(async move { answer })
1015 }));
1016 sched
1017 }
1018
1019 fn store_with(job: &CronJob) -> Arc<Store> {
1020 let store = Arc::new(Store::open_in_memory().expect("store"));
1021 store.apply_identity_schema_for_tests().expect("the identity schema, which holds db_cron_jobs");
1022 store.cron_create(job).expect("create");
1023 store
1024 }
1025
1026 #[test]
1027 fn reads_the_inject_response() {
1028 assert_eq!(
1029 fire_outcome(Some(&json!({"success": true, "block_id": "b-1"}))),
1030 FireOutcome::Delivered { block_id: Some("b-1".into()) }
1031 );
1032 assert_eq!(
1033 fire_outcome(Some(&json!({"success": false, "error": "agent not found: uid-t"}))),
1034 FireOutcome::Missed { reason: MissReason::TargetStopped }
1035 );
1036 assert!(matches!(
1037 fire_outcome(Some(&json!({"success": false, "error": "ambiguous agent name: 'AgentY'"}))),
1038 FireOutcome::Failed { .. }
1039 ));
1040 assert!(matches!(fire_outcome(None), FireOutcome::Failed { .. }));
1041 }
1042
1043 #[test]
1044 fn a_miss_says_why_and_a_delivery_has_no_reason() {
1045 assert_eq!(FireOutcome::Delivered { block_id: None }.miss_reason(), None);
1046 assert_eq!(
1047 FireOutcome::Missed { reason: MissReason::TargetStopped }.miss_reason().as_deref(),
1048 Some("target_stopped")
1049 );
1050 assert_eq!(
1051 FireOutcome::Missed { reason: MissReason::TargetMissing }.miss_reason().as_deref(),
1052 Some("target_missing")
1053 );
1054 assert_eq!(FireOutcome::Failed { error: "x".into() }.miss_reason().as_deref(), Some("failed: x"));
1055 }
1056
1057 #[tokio::test]
1060 async fn an_undelivered_fire_is_a_miss_not_a_fire() {
1061 let job = test_job("job-m", "tick", "AgentZ", "uid-z", "uid-y");
1062 let store = store_with(&job);
1063 let sched = sched_with(Some(store.clone()), json!({"success": false, "error": "agent not found: uid-z"}));
1064
1065 let fired = sched.fire(&job, Slot::Scheduled(0)).await;
1066 assert_eq!(fired.outcome, Some(FireOutcome::Missed { reason: MissReason::TargetStopped }));
1067 let stored = store.cron_get("job-m").unwrap().unwrap();
1068 assert_eq!((stored.fire_count, stored.last_fired), (0, None));
1069 assert_eq!((stored.missed_count, stored.last_miss_reason.as_str()), (1, "target_stopped"));
1070 assert!(stored.last_missed_at.is_some());
1071 }
1072
1073 #[tokio::test]
1074 async fn a_delivered_fire_counts_and_leaves_the_miss_record() {
1075 let job = test_job("job-d", "tick", "AgentZ", "uid-z", "uid-y");
1076 let store = store_with(&job);
1077 let sched = sched_with(Some(store.clone()), json!({"success": true, "block_id": "b-1"}));
1078
1079 sched.fire(&job, Slot::Scheduled(0)).await;
1080 let stored = store.cron_get("job-d").unwrap().unwrap();
1081 assert_eq!((stored.fire_count, stored.missed_count), (1, 0));
1082 assert!(stored.last_fired.is_some());
1083 }
1084
1085 #[tokio::test]
1087 async fn a_job_with_no_target_is_a_miss() {
1088 let job = test_job("job-n", "tick", "", "", "uid-y");
1089 let store = store_with(&job);
1090 let sched = sched_with(Some(store.clone()), json!({"success": true}));
1091
1092 let fired = sched.fire(&job, Slot::Scheduled(0)).await;
1093 assert_eq!(fired.outcome, Some(FireOutcome::Missed { reason: MissReason::TargetMissing }));
1094 assert_eq!(store.cron_get("job-n").unwrap().unwrap().last_miss_reason, "target_missing");
1095 }
1096
1097 #[tokio::test]
1099 async fn run_now_counts_neither_way() {
1100 let job = test_job("job-r", "tick", "AgentZ", "uid-z", "uid-y");
1101 let store = store_with(&job);
1102 let sched = sched_with(Some(store.clone()), json!({"success": false, "error": "agent not found: uid-z"}));
1103
1104 sched.fire(&job, Slot::Manual { triggered_by: "user".into() }).await;
1105 let stored = store.cron_get("job-r").unwrap().unwrap();
1106 assert_eq!((stored.fire_count, stored.missed_count), (0, 0));
1107 }
1108}