1pub(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
31fn 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#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum Admission {
43 Run(String),
45 Waiting(String, &'static str),
47 Skipped,
49 Refused,
51 Capped(Refusal),
53 Taken,
55 Unrecorded,
57}
58
59pub type Started = (JobRun, CronJob);
62
63impl RunLedger {
64 pub fn install_jobs(&self, jobs: Arc<Store>) {
66 let _ = self.jobs.set(jobs);
67 }
68
69 #[cfg(any(test, feature = "test-support"))]
72 pub fn install_interrupt(&self, interrupt: super::BlockHook) {
73 let _ = self.interrupt.set(interrupt);
74 }
75
76 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 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 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 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 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 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 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 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 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 fn decide(&self, job: &CronJob, waiting: bool) -> Decision {
274 policy::decide(job, &self.occupancy(job), waiting)
275 }
276
277 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 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 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 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 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 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 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 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 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 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 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 pub(super) fn maybe_retry(&self, run_id: &str) {
409 match self.file_retry(run_id) {
410 Some(next) => self.carry_event_input(run_id, &next),
412 None => self.drop_event_input(run_id),
413 }
414 }
415
416 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 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 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 pub(crate) fn reap_worker(&self, run_id: &str) {
465 self.stop_worker(run_id, false);
466 }
467
468 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 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}