agentmux_srv_core/backend/jobs/policy.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! What a job's policy decides about a run before it starts, and what to do
5//! when it failed (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.1
6//! "Policy"). Pure: the ledger gathers who is running and acts on the answer
7//! (`admission.rs`).
8
9use crate::backend::jobs::definition::Overlap;
10use crate::backend::storage::cron::CronJob;
11use crate::backend::storage::job_runs::{infra, JobRun};
12
13/// Unattended agent runs at once, across all jobs (§5.1): the providers'
14/// rate limits.
15pub const GLOBAL_LIMIT: usize = 3;
16
17/// The built-in concurrency group infrastructure deploys run in, one at a
18/// time (§5.1, operator decision 6).
19pub const GROUP_DEPLOY: &str = "deploy";
20
21/// The wait before retry number 1, 2 and 3, in minutes (§5.1).
22pub const RETRY_BACKOFF_MIN: [i64; 3] = [1, 5, 15];
23
24/// The job's concurrency group: the one it names, or `deploy` when it
25/// declares a deploy output (`deploy`, `deploy:prod`…).
26pub fn group_of(job: &CronJob) -> Option<String> {
27 if let Some(group) = job.policy.group.as_deref().filter(|g| !g.is_empty()) {
28 return Some(group.to_string());
29 }
30 let deploys = job.outputs.iter().any(|o| o.split(':').next() == Some(GROUP_DEPLOY));
31 deploys.then(|| GROUP_DEPLOY.to_string())
32}
33
34/// Whether a run of the job is an agent working unattended: a message starts
35/// a turn, a spawn starts a worker, a drone can run Agent blocks. Filing a
36/// task starts nothing. A job for which this holds is under the spending
37/// caps and the limit on agents running at once.
38pub fn starts_an_agent(job: &CronJob) -> bool {
39 matches!(job.action_kind.as_str(), "" | "message" | "spawn" | "drone")
40}
41
42/// Who is running, as the ledger found it, for one job's next run.
43#[derive(Debug, Default, Clone, PartialEq, Eq)]
44pub struct Occupancy {
45 /// This job's runs that are running or being delivered.
46 pub job_running: usize,
47 /// Of those, the ones already running here (a `cancel_other` can stop them).
48 pub job_started: usize,
49 /// Of those, the ones running in another channel: stopped by asking that
50 /// channel, so a `cancel_other` run waits for them to end.
51 pub job_remote: usize,
52 /// This job's runs waiting on its own previous run (`overlap`).
53 pub job_buffered: usize,
54 /// This job's runs that wait for a place (`group_busy`, `global_limit`):
55 /// the job's next run is already queued, so another slot isn't.
56 pub job_blocked: usize,
57 /// Runs of the same concurrency group, in any job.
58 pub group_running: usize,
59 /// Unattended agent runs in all jobs.
60 pub agents_running: usize,
61}
62
63/// What to do with a run that wants to start.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum Decision {
66 Start,
67 /// Start after stopping the job's own running runs (`cancel_other`).
68 CancelThenStart,
69 /// Wait; the reason is what the row shows.
70 Wait(&'static str),
71 /// Don't run this slot: the previous run is still going.
72 SkipOverlap,
73}
74
75/// The policy's answer for a run of `job`. `waiting` is a run that already
76/// waits (it keeps its place; the buffer's one place isn't counted against
77/// it, and it is never skipped).
78pub fn decide(job: &CronJob, occ: &Occupancy, waiting: bool) -> Decision {
79 use crate::backend::storage::job_runs::reason;
80 let mut cancel = false;
81 if occ.job_running > 0 {
82 match job.policy.overlap {
83 Overlap::Skip if waiting => return Decision::Wait(reason::OVERLAP),
84 Overlap::Skip => return Decision::SkipOverlap,
85 Overlap::BufferOne if waiting => return Decision::Wait(reason::OVERLAP),
86 Overlap::BufferOne if occ.job_buffered > 0 => return Decision::SkipOverlap,
87 Overlap::BufferOne => return Decision::Wait(reason::OVERLAP),
88 // Only a started run can be stopped; one still being delivered
89 // is left to finish its start, so the new slot is skipped.
90 Overlap::CancelOther if occ.job_running > occ.job_started + occ.job_remote => return Decision::SkipOverlap,
91 // A run in another channel is stopped by its follower, which takes a
92 // moment: the new run waits for it, as one buffered run does.
93 Overlap::CancelOther if occ.job_remote > 0 && (waiting || occ.job_buffered == 0) => return Decision::Wait(reason::OVERLAP),
94 Overlap::CancelOther if occ.job_remote > 0 => return Decision::SkipOverlap,
95 Overlap::CancelOther => cancel = true,
96 }
97 }
98 // The runs a cancel_other stops don't hold the group or a place in the limit
99 // against the run that replaces them.
100 let mut occ = occ.clone();
101 if cancel {
102 occ.group_running = occ.group_running.saturating_sub(occ.job_started);
103 if starts_an_agent(job) {
104 occ.agents_running = occ.agents_running.saturating_sub(occ.job_started);
105 }
106 }
107 let occ = &occ;
108 // A run of this job already waits for a place: a further slot is the same
109 // overlap as one behind a running run, whatever the policy keeps.
110 if !waiting && occ.job_running == 0 && occ.job_blocked > 0 {
111 return Decision::SkipOverlap;
112 }
113 if group_of(job).is_some() && occ.group_running > 0 {
114 return Decision::Wait(reason::GROUP_BUSY);
115 }
116 if starts_an_agent(job) && occ.agents_running >= GLOBAL_LIMIT {
117 return Decision::Wait(reason::GLOBAL_LIMIT);
118 }
119 if cancel {
120 Decision::CancelThenStart
121 } else {
122 Decision::Start
123 }
124}
125
126/// Whether a run that ended should be tried again (§5.1 "Retries"): only an
127/// infrastructure failure: the agent never started, its process exited, or
128/// the provider answered with a transient error. A run whose agent concluded
129/// `failed`, one that hit its own timeout, and one that finished are never
130/// retried; they alert.
131pub fn infra_retryable(run: &JobRun) -> bool {
132 if run.outcome == "failed" {
133 return false;
134 }
135 match run.infra.as_str() {
136 infra::INTERRUPTED => true,
137 infra::ERROR => {
138 crate::backend::reactive::is_transient_delivery_error(&run.summary)
139 || crate::backend::reactive::is_unavailable_refusal(&run.summary)
140 || crate::agents::failure::classify(None, None, &run.summary, None).retryable
141 }
142 _ => false,
143 }
144}
145
146/// Attempt `attempt`'s retry delay in ms (attempt 1 failed: wait 1 minute).
147pub fn retry_delay_ms(attempt: i64) -> i64 {
148 let i = (attempt.max(1) as usize - 1).min(RETRY_BACKOFF_MIN.len() - 1);
149 RETRY_BACKOFF_MIN[i] * 60_000
150}
151
152#[cfg(test)]
153#[path = "policy_tests.rs"]
154mod tests;