Skip to main content

agentmux_srv_core/backend/jobs/
admission.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Letting a run start under its job's policy
5//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.1 "Policy"): overlap,
6//! concurrency groups and the global limit when it wants to start, the
7//! timeout while it runs, and the retry of an infrastructure failure when it
8//! ends. The decisions are `policy.rs`; this reads who is running from the
9//! ledger and writes the rows.
10//!
11//! One lock covers deciding and writing a run's row, so two fires in this
12//! process can't both take the last place. Two instances sharing the ledger
13//! can still both see room for one more for an instant; the limits are for
14//! the providers' rate limits and for tidiness, not safety.
15
16pub(super) mod events;
17
18use std::sync::Arc;
19
20use agentmux_common::time::now_ms;
21use serde_json::json;
22
23use super::caps::Refusal;
24use super::definition::Overlap;
25use super::policy::{self, Decision, Occupancy};
26use super::{Begin, RunLedger, BY_SCHEDULER, SOURCE_CRON, TRIGGER_EVENT, TRIGGER_RETRY};
27use crate::backend::storage::cron::CronJob;
28use crate::backend::storage::job_runs::{infra, reason, state, JobRun};
29use crate::backend::storage::store::Store;
30
31/// Whether a disabled job is done rather than paused: a one-time job after its
32/// time, or one that reached its fire count or age. Its last run may still be
33/// waiting for a place, and must get one.
34fn schedule_finished(job: &CronJob, now_ms: i64) -> bool {
35    job.trigger_kind == "once"
36        || job.max_fires.is_some_and(|max| job.fire_count >= max)
37        || crate::backend::cron::is_expired_by_age(job.created_at, job.max_age_secs, now_ms / 1000)
38}
39
40/// What admitting a fire did.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum Admission {
43    /// Start it: this is its run id.
44    Run(String),
45    /// Its row waits, for the reason.
46    Waiting(String, &'static str),
47    /// The slot is skipped (`overlap`) and has its row.
48    Skipped,
49    /// Run now, refused: the previous run is still going (policy `overlap`).
50    Refused,
51    /// Run now, refused: a spending cap leaves no room (§5.3).
52    Capped(Refusal),
53    /// Another scheduler has the slot.
54    Taken,
55    /// The row couldn't be written; fire anyway, unrecorded.
56    Unrecorded,
57}
58
59/// A run another instance's scheduler might also be starting is only
60/// started by whoever clears its waiting reason.
61pub type Started = (JobRun, CronJob);
62
63impl RunLedger {
64    /// Where jobs are, for the policy of other jobs' runs.
65    pub fn install_jobs(&self, jobs: Arc<Store>) {
66        let _ = self.jobs.set(jobs);
67    }
68
69    /// Tests: how to interrupt the turn in a pane (a timeout, `cancel_other`).
70    /// Otherwise the pane's controller is asked, as the Stop button does.
71    #[cfg(any(test, feature = "test-support"))]
72    pub fn install_interrupt(&self, interrupt: super::BlockHook) {
73        let _ = self.interrupt.set(interrupt);
74    }
75
76    /// How to stop a worker a `spawn` job started, once its run ended.
77    pub fn install_worker_stop(&self, stop: super::BlockHook) {
78        let _ = self.worker_stop.set(stop);
79    }
80
81    pub(super) fn job(&self, id: &str) -> Option<CronJob> {
82        self.jobs.get()?.cron_get(id).ok().flatten()
83    }
84
85    pub(super) fn interrupt_block(&self, block_id: &str) {
86        if block_id.is_empty() {
87            return;
88        }
89        match self.interrupt.get() {
90            Some(f) => f(block_id),
91            None => {
92                let sigint = crate::backend::blockcontroller::BlockInputUnion::signal("SIGINT");
93                if let Some(ctrl) = crate::backend::blockcontroller::get_controller(block_id) {
94                    if let Err(e) = ctrl.send_input(sigint, None) {
95                        tracing::warn!(block_id, error = %e, "jobs: couldn't interrupt a run's turn");
96                    }
97                }
98            }
99        }
100    }
101
102    /// Who is running, for the next run of `job`.
103    fn occupancy(&self, job: &CronJob) -> Occupancy {
104        let mut occ = Occupancy::default();
105        let group = policy::group_of(job);
106        let mut known: std::collections::HashMap<String, Option<CronJob>> = std::collections::HashMap::new();
107        for r in self.store.job_runs_occupying().unwrap_or_default() {
108            let other = known.entry(r.job_id.clone()).or_insert_with(|| self.job(&r.job_id)).clone();
109            if r.job_id == job.id {
110                occ.job_running += 1;
111                let elsewhere = r.state == state::RUNNING && self.run_followed_elsewhere(&r);
112                occ.job_started += usize::from(r.state == state::RUNNING && !elsewhere);
113                occ.job_remote += usize::from(elsewhere);
114            }
115            if group.is_some() && other.as_ref().and_then(policy::group_of) == group {
116                occ.group_running += 1;
117            }
118            if other.as_ref().is_none_or(policy::starts_an_agent) {
119                occ.agents_running += 1;
120            }
121        }
122        // A pending fire being delivered holds its place until the delivery's
123        // row says so.
124        let occupying: std::collections::HashSet<String> =
125            self.store.job_runs_occupying().unwrap_or_default().into_iter().map(|r| r.id).collect();
126        for (run_id, job_id) in self.pending_claims.lock().unwrap_or_else(|e| e.into_inner()).iter() {
127            if occupying.contains(run_id) {
128                continue;
129            }
130            let other = known.entry(job_id.clone()).or_insert_with(|| self.job(job_id)).clone();
131            if *job_id == job.id {
132                occ.job_running += 1;
133            }
134            if group.is_some() && other.as_ref().and_then(policy::group_of) == group {
135                occ.group_running += 1;
136            }
137            if other.as_ref().is_none_or(policy::starts_an_agent) {
138                occ.agents_running += 1;
139            }
140        }
141        let waiting = self.store.job_runs_waiting().unwrap_or_default();
142        let own = || waiting.iter().filter(|r| r.job_id == job.id);
143        occ.job_buffered = own().filter(|r| r.reason == reason::OVERLAP).count();
144        occ.job_blocked = own().filter(|r| r.reason == reason::GROUP_BUSY || r.reason == reason::GLOBAL_LIMIT).count();
145        occ
146    }
147
148    /// Insert the row of a cron fire and decide whether it starts (see the
149    /// module doc). A scheduled slot that policy skips is a collapsed
150    /// `skipped (overlap)` row; Run now is refused.
151    pub fn admit_cron(&self, job: &CronJob, trigger: &str, scheduled_for_ms: Option<i64>, triggered_by: &str) -> Admission {
152        let _one_at_a_time = self.admission.lock().unwrap_or_else(|e| e.into_inner());
153        let decision = self.decide(job, false);
154        if decision == Decision::SkipOverlap {
155            return match scheduled_for_ms {
156                Some(slot) => {
157                    self.record_skip_slot(job, slot, reason::OVERLAP);
158                    Admission::Skipped
159                }
160                None => Admission::Refused,
161            };
162        }
163        // A run that would start now weighs on the caps first (§5.3): a slot
164        // they refuse is a collapsed skip, Run now is refused.
165        let mut account = String::new();
166        if matches!(decision, Decision::Start | Decision::CancelThenStart) {
167            let gate = self.cap_gate(job);
168            if let Some(refusal) = gate.refusal {
169                return match scheduled_for_ms {
170                    Some(slot) => {
171                        self.skip_slot_for_cap(job, slot, refusal);
172                        Admission::Skipped
173                    }
174                    None => Admission::Capped(refusal),
175                };
176            }
177            account = gate.account;
178        }
179        let id = match self.begin_cron(job, trigger, scheduled_for_ms, triggered_by) {
180            Begin::Run(id) => id,
181            Begin::SlotTaken => return Admission::Taken,
182            Begin::Unrecorded => return Admission::Unrecorded,
183        };
184        self.note_account(&id, &account);
185        match decision {
186            Decision::Wait(why) => {
187                if let Err(e) = self.store.job_run_set_wait(&id, why) {
188                    tracing::warn!(run_id = %id, error = %e, "jobs: couldn't make a run wait");
189                }
190                self.changed(&job.id);
191                self.ask_remote_stops(job, decision);
192                Admission::Waiting(id, why)
193            }
194            Decision::CancelThenStart => {
195                self.cancel_started(job);
196                Admission::Run(id)
197            }
198            Decision::Start | Decision::SkipOverlap => Admission::Run(id),
199        }
200    }
201
202    /// `cancel_other`: stop the job's own running runs, interrupting their
203    /// turns.
204    fn cancel_started(&self, job: &CronJob) {
205        for r in self.store.job_runs_occupying().unwrap_or_default() {
206            if r.job_id == job.id && r.state == state::RUNNING {
207                self.stop_run(&r, infra::INTERRUPTED, reason::OVERLAP, "stopped: the job's next run started (overlap: cancel_other)");
208            }
209        }
210    }
211
212    /// Close a running run that was stopped on purpose, and interrupt its
213    /// turn. `false` when it had ended already. A run another channel's
214    /// instance follows isn't closed here: that instance is asked to stop it
215    /// (`remote.rs`), so the row closes only once its agent's turn is
216    /// interrupted. `false` for it too.
217    pub fn stop_run(&self, run: &JobRun, infra_status: &str, why: &str, summary: &str) -> bool {
218        if self.run_followed_elsewhere(run) {
219            self.request_remote_stop(run, infra_status, why, summary);
220            return false;
221        }
222        match self.store.job_run_stop(&run.id, infra_status, why, summary, now_ms()) {
223            Ok(true) => {
224                self.interrupt_block(&run.block_id);
225                if let Some(drone_run) = run.links["drone_run_id"].as_str() {
226                    crate::backend::drone_cancel::cancel_run(drone_run, summary);
227                }
228                self.reap_worker(&run.id);
229                self.run_changed(&run.id);
230                super::pending_wake().notify_one();
231                true
232            }
233            Ok(false) => false,
234            Err(e) => {
235                tracing::warn!(run_id = %run.id, error = %e, "jobs: couldn't stop a run");
236                false
237            }
238        }
239    }
240
241    /// Stop this channel's runs that ran past their job's `timeout_minutes`
242    /// (infra `timeout`). Returns how many.
243    pub fn enforce_timeouts(&self) -> usize {
244        let now = now_ms();
245        let mut stopped = 0;
246        for r in self.store.job_runs_occupying().unwrap_or_default() {
247            if r.state != state::RUNNING || !self.recorded_here(&r) {
248                continue;
249            }
250            let Some(minutes) = self.job(&r.job_id).and_then(|j| j.policy.timeout_minutes) else { continue };
251            if now - r.started_at_ms >= i64::from(minutes) * 60_000
252                && self.stop_run(&r, infra::TIMEOUT, reason::TIMEOUT, &format!("stopped after {minutes} minutes (timeout_minutes)"))
253            {
254                stopped += 1;
255            }
256        }
257        stopped
258    }
259
260    /// A Drone run a restart left open, that a job started and whose job's
261    /// `timeout_minutes` ran out while AgentMux was down: close it as timed out
262    /// (the way the timeout pass does) and say so, so it is not taken up again
263    /// and able to act before the first pass. `false` for a run with no such
264    /// timeout, or one that has time left.
265    pub fn close_if_past_timeout(&self, drone_run_id: &str) -> bool {
266        let Some(run) = self.open_run_of_drone(drone_run_id).and_then(|id| self.store.job_run_get(&id).ok().flatten()) else { return false };
267        let Some(minutes) = self.job(&run.job_id).and_then(|j| j.policy.timeout_minutes) else { return false };
268        now_ms() - run.started_at_ms >= i64::from(minutes) * 60_000
269            && self.stop_run(&run, infra::TIMEOUT, reason::TIMEOUT, &format!("stopped after {minutes} minutes (timeout_minutes)"))
270    }
271
272    /// [`policy::decide`] for `job` now.
273    fn decide(&self, job: &CronJob, waiting: bool) -> Decision {
274        policy::decide(job, &self.occupancy(job), waiting)
275    }
276
277    /// A `cancel_other` job whose previous run is in another channel waits
278    /// for that run (`overlap`): ask the follower to stop it. Called once the
279    /// waiting run has its row (a slot another scheduler fired must not cost
280    /// the run already going), and again while it waits; the replacement does
281    /// not start before the stop has landed, or the interrupt could hit the
282    /// new run's turn.
283    fn ask_remote_stops(&self, job: &CronJob, decision: Decision) {
284        if decision != Decision::Wait(reason::OVERLAP) || job.policy.overlap != Overlap::CancelOther {
285            return;
286        }
287        // A replacement a cap would refuse isn't worth the run going now, as a
288        // local `cancel_other` leaves the old run alone when the caps refuse the new one.
289        if self.cap_gate(job).refusal.is_some() {
290            return;
291        }
292        for r in self.store.job_runs_occupying().unwrap_or_default() {
293            if r.job_id == job.id && r.state == state::RUNNING && self.run_followed_elsewhere(&r) {
294                self.request_remote_stop(&r, infra::INTERRUPTED, reason::OVERLAP, "stopped: the job's next run started (overlap: cancel_other)");
295            }
296        }
297    }
298
299    /// Whether another channel's instance follows `run`: its agent is there,
300    /// so this process can't interrupt it. Closing the row from here would free
301    /// its place while the agent goes on working, so its follower is asked to
302    /// stop it ([`Self::stop_run`]) and the row stays open until it has.
303    fn run_followed_elsewhere(&self, run: &JobRun) -> bool {
304        super::remote::followed_by(run).is_some_and(|f| f.channel != self.channel)
305    }
306
307    fn recorded_here(&self, run: &JobRun) -> bool {
308        run.recorded_by == self.recorded_by || run.recorded_by.starts_with(&format!("{}@", self.channel))
309    }
310
311    /// Start the waiting runs that policy now lets start, oldest first, each
312    /// against what is running after the ones before it. Runs of a job that
313    /// is gone or paused end; a retry waits out its backoff first. The
314    /// caller starts the returned runs.
315    pub fn start_waiting(&self) -> Vec<Started> {
316        let _one_at_a_time = self.admission.lock().unwrap_or_else(|e| e.into_inner());
317        if self.paused_all().is_some() {
318            return Vec::new();
319        }
320        let now = now_ms();
321        let mut out = Vec::new();
322        for run in self.store.job_runs_waiting().unwrap_or_default() {
323            // The ledger is shared by every instance, the jobs store is not: a
324            // run another instance recorded is its to start or end.
325            if !self.recorded_here(&run) {
326                continue;
327            }
328            let Some(job) = self.job(&run.job_id) else {
329                let _ = self.store.job_run_skip(&run.id, reason::TARGET_MISSING, 1, now);
330                self.run_changed(&run.id);
331                continue;
332            };
333            // A paused job's scheduled runs end; a Run now, asked for by a person, and
334            // the last run of a job whose schedule is done still get their place.
335            if !job.enabled && run.trigger != super::TRIGGER_MANUAL && !schedule_finished(&job, now) {
336                let _ = self.store.job_run_skip(&run.id, reason::PAUSED, 1, now);
337                self.changed(&job.id);
338                continue;
339            }
340            if run.reason == reason::RETRY_WAIT && run.links["retry_at_ms"].as_i64().unwrap_or(0) > now {
341                continue;
342            }
343            // An event's run held back by the trigger's `delay` is not due yet.
344            if run.reason == reason::DELAY_WAIT && run.links["due_at_ms"].as_i64().unwrap_or(0) > now {
345                continue;
346            }
347            let decision = self.decide(&job, true);
348            self.ask_remote_stops(&job, decision);
349            match decision {
350                Decision::Start | Decision::CancelThenStart => {
351                    let gate = self.cap_gate(&job);
352                    if let Some(refusal) = gate.refusal {
353                        self.skip_run_for_cap(&run.id, &job, refusal);
354                    } else if self.store.job_run_admit(&run.id, &run.reason, now).unwrap_or(false) {
355                        self.note_account(&run.id, &gate.account);
356                        self.cancel_started(&job);
357                        out.push((run, job));
358                    }
359                }
360                Decision::Wait(why) if why != run.reason => {
361                    let _ = self.store.job_run_set_wait(&run.id, why);
362                }
363                Decision::Wait(_) | Decision::SkipOverlap => {}
364            }
365        }
366        out
367    }
368
369    /// Whether a pending catch-up delivery of `job` may start now: the same
370    /// answer a waiting run gets (overlap, group, the global limit). A job that
371    /// would cancel its own running run does so here, as a new slot would.
372    pub fn pending_may_start(&self, job: &CronJob, run_id: &str) -> bool {
373        let _one_at_a_time = self.admission.lock().unwrap_or_else(|e| e.into_inner());
374        let decision = self.decide(job, true);
375        self.ask_remote_stops(job, decision);
376        let start = match decision {
377            Decision::Start | Decision::CancelThenStart => {
378                // Caps weigh the runs still going, so they are asked once policy
379                // says it may start, as for a waiting run (§5.3).
380                let gate = self.cap_gate(job);
381                if let Some(refusal) = gate.refusal {
382                    self.skip_run_for_cap(run_id, job, refusal);
383                    return false;
384                }
385                self.note_account(run_id, &gate.account);
386                self.cancel_started(job);
387                true
388            }
389            Decision::Wait(_) | Decision::SkipOverlap => false,
390        };
391        if start {
392            // Hold its place while the delivery runs: the row is still pending.
393            self.pending_claims.lock().unwrap_or_else(|e| e.into_inner()).insert(run_id.to_string(), job.id.clone());
394        }
395        start
396    }
397
398    /// The delivery of a pending fire ended (it started, or stays pending to
399    /// be retried): its place is the ledger's again.
400    pub fn pending_delivery_done(&self, run_id: &str) {
401        self.pending_claims.lock().unwrap_or_else(|e| e.into_inner()).remove(run_id);
402    }
403
404    /// A run ended: if it failed in the infrastructure and its job has
405    /// retries left, file the next attempt, waiting out the backoff (1, 5,
406    /// then 15 minutes). The failed run is marked `retried_by`, so it isn't
407    /// an incident of its own; the last attempt decides.
408    pub(super) fn maybe_retry(&self, run_id: &str) {
409        match self.file_retry(run_id) {
410            // The next attempt reads the same event the first one did; a run that is over for good has no more use for it.
411            Some(next) => self.carry_event_input(run_id, &next),
412            None => self.drop_event_input(run_id),
413        }
414    }
415
416    /// The retry of `run_id`, filed if it has one coming: its id.
417    fn file_retry(&self, run_id: &str) -> Option<String> {
418        let run = self.store.job_run_get(run_id).ok().flatten()?;
419        if run.job_source != SOURCE_CRON || !policy::infra_retryable(&run) || !run.links["retried_by"].is_null() {
420            return None;
421        }
422        let job = self.job(&run.job_id)?;
423        if run.attempt > i64::from(job.policy.retries) {
424            return None;
425        }
426        let now = now_ms();
427        let mut next = self.row(&job.id, SOURCE_CRON, &job.name, TRIGGER_RETRY, now);
428        next.attempt = run.attempt + 1;
429        next.state = state::SCHEDULED.to_string();
430        next.reason = reason::RETRY_WAIT.to_string();
431        next.triggered_by = BY_SCHEDULER.to_string();
432        next.target_agent_uid = run.target_agent_uid.clone();
433        next.links = json!({ "retry_of": run.id, "retry_at_ms": now + policy::retry_delay_ms(run.attempt) });
434        // A retry of an event's run reads the event too, and must not start without it.
435        if run.trigger == TRIGGER_EVENT || run.links["from_event"] == json!(true) {
436            next.links["from_event"] = json!(true);
437        }
438        match self.store.job_run_insert(&next) {
439            Ok(true) => {
440                let _ = self.store.job_run_add_links(&run.id, &json!({ "retried_by": next.id }));
441                tracing::info!(job_id = %job.id, attempt = next.attempt, "jobs: an infrastructure failure will be retried");
442                Some(next.id)
443            }
444            Ok(false) => None,
445            Err(e) => {
446                tracing::warn!(run_id, error = %e, "jobs: couldn't file a retry");
447                None
448            }
449        }
450    }
451
452    /// A `task` run filed its task: the run is done, outcome `ok`, linked to
453    /// the task (`links.kanban_task`, with its queue id).
454    pub fn task_filed(&self, run_id: &str, job_name: &str, work_id: &str, num: i64) {
455        let _ = self.store.job_run_add_links(run_id, &json!({ "kanban_task": num, "work_id": work_id }));
456        let summary = format!("filed task #{num} for \"{job_name}\"");
457        if let Err(e) = self.store.job_run_conclude(run_id, "ok", &summary, now_ms()) {
458            tracing::warn!(run_id, error = %e, "jobs: couldn't close a task run");
459        }
460        self.run_changed(run_id);
461    }
462
463    /// A `spawn` run ended: stop its worker, unless the job keeps it.
464    pub(crate) fn reap_worker(&self, run_id: &str) {
465        self.stop_worker(run_id, false);
466    }
467
468    /// Note the account a run will use, before it is delivered.
469    fn note_account(&self, run_id: &str, account: &str) {
470        if !account.is_empty() {
471            if let Err(e) = self.store.job_run_set_account(run_id, account) {
472                tracing::warn!(run_id, error = %e, "jobs: couldn't note a run's account");
473            }
474        }
475    }
476
477    /// Stop the worker a `spawn` run started. A job that keeps its worker
478    /// keeps it, unless `force` (the run was stopped at its spending cap).
479    pub(super) fn stop_worker(&self, run_id: &str, force: bool) {
480        let Some(run) = self.store.job_run_get(run_id).ok().flatten() else { return };
481        let worker = &run.links["worker"];
482        let block_id = worker["block_id"].as_str().unwrap_or("");
483        if block_id.is_empty() || (worker["keep"].as_bool().unwrap_or(false) && !force) {
484            return;
485        }
486        if let Some(stop) = self.worker_stop.get() {
487            stop(block_id);
488        }
489    }
490}