Skip to main content

agentmux_srv_core/backend/jobs/admission/
events.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Letting a run start for an event (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md §3.2, §3.7): the same
5//! overlap, group, global-limit and spending-cap decisions a timer's slot gets, but a fire with no slot. What differs:
6//!
7//! - **At least once, deduplicated.** The job's `(job_id, event_id)` is recorded first (`db_job_trigger_events`); an event it
8//!   already heard of starts nothing, here or in another instance sharing the ledger.
9//! - **A fire that policy or a cap refuses is a `skipped` row**, folded into the job's newest skip of the same reason
10//!   like a timer's, not a refusal: nobody pressed Run now, so there is nobody to tell.
11//! - **Pause all** skips it the same way (`paused_all`).
12//!
13//! - **A trigger's `delay`** makes the run a `scheduled` row (`delay_wait`) due at event time + delay, picked up by the
14//!   same wake that starts waiting runs; policy and the caps are asked when it is due, not when the event came.
15//!
16//! The event's data is not in the ledger row. It is kept beside it (`db_job_event_inputs`) for the run that starts: the
17//! Drone run reads it as its input, a retry of the run takes it over, and a restart in between does not lose it.
18
19use agentmux_common::time::now_ms;
20use serde_json::Value;
21
22use super::Admission;
23use crate::backend::jobs::definition::{DEFAULT_EVENT_RATE_PER_HOUR, MAX_EVENT_DELAY_MINUTES, MAX_EVENT_RATE_PER_HOUR};
24use crate::backend::jobs::caps::Refusal;
25use crate::backend::jobs::policy::Decision;
26use crate::backend::jobs::{Begin, RunLedger, BY_EVENT, SOURCE_CRON, TRIGGER_EVENT};
27use crate::backend::storage::cron::CronJob;
28use crate::backend::storage::job_events::{INPUT_KEEP_MS, KEEP_MS};
29use crate::backend::storage::job_runs::{reason, state, JobRun};
30
31impl RunLedger {
32    /// The input kept for run `run_id` (what the graph reads as `{{trigger.*}}`). It stays while the run lives, so a
33    /// run that waited through a delay, its turn or a restart, and a retry of it, read the same event.
34    pub fn event_input(&self, run_id: &str) -> Option<Value> {
35        self.store.job_event_input_get(run_id).unwrap_or_else(|e| {
36            tracing::warn!(run_id, error = %e, "jobs: couldn't read an event's input");
37            None
38        })
39    }
40
41    /// The run is over for good (it was not retried): its input is no longer needed.
42    pub(in crate::backend::jobs) fn drop_event_input(&self, run_id: &str) {
43        if let Err(e) = self.store.job_event_input_drop(run_id) {
44            tracing::warn!(run_id, error = %e, "jobs: couldn't let go of an event's input");
45        }
46    }
47
48    /// A retry `to` takes over what `from` held, so the next attempt reads the same event.
49    pub(in crate::backend::jobs) fn carry_event_input(&self, from: &str, to: &str) {
50        if let Err(e) = self.store.job_event_input_carry(from, to) {
51            tracing::warn!(run_id = from, error = %e, "jobs: couldn't hand an event's input to its retry");
52        }
53    }
54
55    /// Record the event `event_id` for `job` and decide whether its run starts. `Taken` is an event the job already
56    /// heard of; `Skipped` is a fire that Pause all, the rate limit, overlap policy or a cap refused (it has its row).
57    /// An event that starts no run stays heard but does not count toward the rate limit.
58    pub fn admit_event(&self, job: &CronJob, event_id: &str, source: &str, input: &Value) -> Admission {
59        let _one_at_a_time = self.admission.lock().unwrap_or_else(|e| e.into_inner());
60        let now = now_ms();
61        let id = uuid::Uuid::new_v4().to_string();
62        match self.store.job_event_claim(&job.id, event_id, &id, now) {
63            Ok(true) => {
64                if let Err(e) = self.store.job_events_forget_before(now - KEEP_MS).and(self.store.job_event_inputs_forget_before(now - INPUT_KEEP_MS)) {
65                    tracing::warn!(error = %e, "jobs: couldn't forget old event ids");
66                }
67            }
68            Ok(false) => return Admission::Taken,
69            Err(e) => {
70                tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record an event; firing it unrecorded");
71                return Admission::Unrecorded;
72            }
73        }
74        let admission = self.admit_claimed(job, id, source, input, now);
75        if matches!(admission, Admission::Skipped | Admission::Capped(_) | Admission::Refused) {
76            if let Err(e) = self.store.job_event_unadmit(&job.id, event_id) {
77                tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't mark an event as not started");
78            }
79        }
80        admission
81    }
82
83    /// What becomes of an event the job has just recorded under run id `id`.
84    fn admit_claimed(&self, job: &CronJob, id: String, source: &str, input: &Value, now: i64) -> Admission {
85        if self.paused_all().is_some() {
86            return self.skip_event(job, id, source, reason::PAUSED_ALL);
87        }
88        // The count includes this event: it is the (limit + 1)th that is refused.
89        let heard = self.store.job_events_since(&job.id, now - HOUR_MS).unwrap_or(0);
90        if heard > event_rate_limit(job) {
91            let first = self.first_cap_skip_today(job);
92            let skipped = self.skip_event(job, id, source, reason::RATE);
93            if first {
94                self.alert_cap(job, Refusal::Rate);
95            }
96            return skipped;
97        }
98        let delay_ms = event_delay_ms(job);
99        if delay_ms > 0 {
100            return self.hold_for_delay(job, id, source, input, now, delay_ms);
101        }
102        let decision = self.decide(job, false);
103        if decision == Decision::SkipOverlap {
104            return self.skip_event(job, id, source, reason::OVERLAP);
105        }
106        let mut account = String::new();
107        if matches!(decision, Decision::Start | Decision::CancelThenStart) {
108            let gate = self.cap_gate(job);
109            if let Some(refusal) = gate.refusal {
110                if let Begin::Run(run_id) = self.begin_event(job, &id, source, now) {
111                    self.skip_run_for_cap(&run_id, job, refusal);
112                }
113                return Admission::Skipped;
114            }
115            account = gate.account;
116        }
117        let run_id = match self.begin_event(job, &id, source, now) {
118            Begin::Run(run_id) => run_id,
119            Begin::SlotTaken => return Admission::Taken,
120            Begin::Unrecorded => return Admission::Unrecorded,
121        };
122        self.note_account(&run_id, &account);
123        self.keep_event_input(&run_id, &job.id, input, now);
124        match decision {
125            Decision::Wait(why) => {
126                if let Err(e) = self.store.job_run_set_wait(&run_id, why) {
127                    tracing::warn!(run_id = %run_id, error = %e, "jobs: couldn't make an event's run wait");
128                }
129                self.changed(&job.id);
130                self.ask_remote_stops(job, decision);
131                Admission::Waiting(run_id, why)
132            }
133            Decision::CancelThenStart => {
134                self.cancel_started(job);
135                Admission::Run(run_id)
136            }
137            Decision::Start | Decision::SkipOverlap => Admission::Run(run_id),
138        }
139    }
140
141    /// The row of an event's run, `scheduled`, under the id the event was recorded with.
142    fn event_row(&self, job: &CronJob, run_id: &str, source: &str, now: i64) -> JobRun {
143        let mut run = JobRun::new(run_id, &job.id, SOURCE_CRON, &job.name, TRIGGER_EVENT, state::SCHEDULED, now);
144        run.recorded_by = self.recorded_by.clone();
145        run.triggered_by = format!("{BY_EVENT}:{source}");
146        run.target_agent_uid = job.target_uid.clone();
147        run
148    }
149
150    /// The `scheduled` row of an event's run, with the id it was recorded under.
151    fn begin_event(&self, job: &CronJob, run_id: &str, source: &str, now: i64) -> Begin {
152        let run = self.event_row(job, run_id, source, now);
153        match self.store.job_run_insert(&run) {
154            Ok(true) => Begin::Run(run.id),
155            Ok(false) => Begin::SlotTaken,
156            Err(e) => {
157                tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record an event's run");
158                Begin::Unrecorded
159            }
160        }
161    }
162
163    /// An event whose trigger has a `delay`: its run waits as a `scheduled` row until `now + delay_ms`.
164    fn hold_for_delay(&self, job: &CronJob, run_id: String, source: &str, input: &Value, now: i64, delay_ms: i64) -> Admission {
165        let mut run = self.event_row(job, &run_id, source, now);
166        run.reason = reason::DELAY_WAIT.to_string();
167        run.links = serde_json::json!({ "due_at_ms": now + delay_ms });
168        match self.store.job_run_insert(&run) {
169            Ok(true) => {}
170            Ok(false) => return Admission::Taken,
171            Err(e) => {
172                tracing::warn!(job_id = %job.id, error = %e, "jobs: couldn't record a delayed event's run");
173                return Admission::Unrecorded;
174            }
175        }
176        self.keep_event_input(&run_id, &job.id, input, now);
177        self.changed(&job.id);
178        Admission::Waiting(run_id, reason::DELAY_WAIT)
179    }
180
181    /// Keep the event's data for its run. A run that finds none when it starts fails saying so.
182    fn keep_event_input(&self, run_id: &str, job_id: &str, input: &Value, now: i64) {
183        if let Err(e) = self.store.job_event_input_put(run_id, job_id, input, now) {
184            tracing::warn!(run_id, error = %e, "jobs: couldn't keep an event's input");
185        }
186    }
187
188    /// An event that is skipped for `why`: a `skipped` row, folded into the job's newest skip of the same reason.
189    fn skip_event(&self, job: &CronJob, run_id: String, source: &str, why: &str) -> Admission {
190        if let Begin::Run(id) = self.begin_event(job, &run_id, source, now_ms()) {
191            if let Err(e) = self.store.job_run_skip(&id, why, 1, now_ms()) {
192                tracing::warn!(run_id = %id, error = %e, "jobs: couldn't skip an event's run");
193            }
194        }
195        self.changed(&job.id);
196        Admission::Skipped
197    }
198}
199
200/// The trigger's `delay` in ms: 0 for none.
201fn event_delay_ms(job: &CronJob) -> i64 {
202    let minutes = job.trigger_event.get("delay").and_then(Value::as_u64).unwrap_or(0);
203    i64::try_from(minutes.min(u64::from(MAX_EVENT_DELAY_MINUTES))).unwrap_or(0) * 60_000
204}
205
206const HOUR_MS: i64 = 3_600_000;
207
208/// How many runs the trigger starts in an hour: its `max_per_hour`, or the default.
209fn event_rate_limit(job: &CronJob) -> i64 {
210    let n = job.trigger_event.get("max_per_hour").and_then(Value::as_u64).unwrap_or(u64::from(DEFAULT_EVENT_RATE_PER_HOUR));
211    i64::try_from(n.clamp(1, u64::from(MAX_EVENT_RATE_PER_HOUR))).unwrap_or(1)
212}