Skip to main content

agentmux_srv_core/backend/jobs/
reservation.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Spending caps at work (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md
5//! §5.3): the reservation before a run starts, the stop when a run reaches
6//! its own cap, and the skips a cap makes. The rules are `caps.rs`; this
7//! reads the spend from the ledger and writes the rows.
8//!
9//! **The reservation.** A run starts only if its job's spend today plus its
10//! per-run cap fits the job's daily cap, and the same for its account. The
11//! spend counts the runs that ended, and, for each run still going, its
12//! whole per-run cap: so the day's total can't pass a daily cap even if every
13//! run spends all of its own.
14//!
15//! **The stop.** The turn ledger's cost is the sum of the `result` frames of
16//! the passes that ended (`blockcontroller::health`), so the follower sees a
17//! run's spend between passes, not inside one: a turn of several passes is
18//! stopped at the first pass that brings it to its cap, and a single pass
19//! costs what it costs. The reservation is what bounds the day.
20//!
21//! **No cost reported.** A run on a provider whose turns carry no cost counts
22//! $0 toward the dollar caps (`caps::reports_cost`) and is bounded by its
23//! timeout.
24
25use std::sync::Arc;
26
27use agentmux_common::time::now_ms;
28
29use super::caps::{self, Limits, Refusal, Spend};
30use super::{policy, RunLedger};
31use crate::backend::storage::cron::CronJob;
32use crate::backend::storage::job_runs::{reason, RunCost};
33
34/// The caps Settings → Jobs holds, read at each decision so a change takes
35/// effect at once.
36pub type LimitsSource = Arc<dyn Fn() -> Limits + Send + Sync>;
37
38/// Where a job's next run would go: the server knows (a message's target
39/// pane, the account a spawn picks).
40pub type TargetOf = Arc<dyn Fn(&CronJob) -> Target + Send + Sync>;
41
42/// The account and provider a run would use. Empty when not known.
43#[derive(Debug, Clone, Default, PartialEq, Eq)]
44pub struct Target {
45    pub account: String,
46    pub provider: String,
47}
48
49pub struct CapSources {
50    limits: LimitsSource,
51    target: TargetOf,
52}
53
54/// What the caps say about starting a run now.
55pub(super) struct Gate {
56    pub refusal: Option<Refusal>,
57    /// The account the run would use, to note on its row.
58    pub account: String,
59}
60
61impl RunLedger {
62    /// Weigh runs against Settings' caps from now on, finding each run's
63    /// account and provider with `target`. Once. Without it the defaults
64    /// apply and only a job's own spend is weighed.
65    pub fn install_caps(&self, limits: LimitsSource, target: TargetOf) {
66        let _ = self.caps.set(CapSources { limits, target });
67    }
68
69    /// Tests: a day that starts as `f` says, from now on (a test moves it to
70    /// cross midnight).
71    #[cfg(test)]
72    pub fn set_day_start(&self, f: Arc<dyn Fn(i64) -> i64 + Send + Sync>) {
73        *self.day_start.lock().unwrap() = Some(f);
74    }
75
76    /// Tests: the cap alerts raised so far, `(job id, reason)`.
77    #[cfg(any(test, feature = "test-support"))]
78    pub fn cap_alerts(&self) -> Vec<(String, String)> {
79        self.cap_alerts.lock().unwrap().clone()
80    }
81
82    pub fn limits(&self) -> Limits {
83        self.caps.get().map(|c| (c.limits)()).unwrap_or_default()
84    }
85
86    fn target(&self, job: &CronJob) -> Target {
87        self.caps.get().map(|c| (c.target)(job)).unwrap_or_default()
88    }
89
90    /// The start of the operator's local day containing `now`.
91    pub(super) fn day_start(&self, now: i64) -> i64 {
92        #[cfg(any(test, feature = "test-support"))]
93        if let Some(f) = self.day_start.lock().unwrap().clone() {
94            return f(now);
95        }
96        caps::local_day_start_ms(now)
97    }
98
99    /// The most one run of `job` may spend.
100    pub fn run_cap_usd(&self, job: &CronJob) -> f64 {
101        caps::effective(job.policy.caps.as_ref(), &self.limits()).run_usd
102    }
103
104    /// The spend at which run `run_id` is stopped, when its provider reports
105    /// what a turn costs. `None` for a run that can't be weighed.
106    pub(super) fn stop_at_usd(&self, run_id: &str, provider: &str) -> Option<f64> {
107        if !caps::reports_cost(provider) {
108            return None;
109        }
110        let run = self.store.job_run_get(run_id).ok().flatten()?;
111        let job = self.job(&run.job_id)?;
112        policy::starts_an_agent(&job).then(|| self.run_cap_usd(&job))
113    }
114
115    /// What `job` has spent since `day_start`, and what its runs still going
116    /// may yet spend, for the job and for `account`.
117    fn spend(&self, job: &CronJob, account: &str, day_start: i64) -> Spend {
118        let limits = self.limits();
119        let (mut job_usd, _) = self.store.job_runs_cost_since(&job.id, day_start).unwrap_or_default();
120        let mut account_usd = (!account.is_empty()).then(|| self.store.account_runs_cost_since(account, day_start).unwrap_or(0.0));
121        // A pending fire being delivered holds its place before its row says so.
122        let occupying = self.store.job_runs_occupying().unwrap_or_default();
123        let claimed: Vec<String> = {
124            let claims = self.pending_claims.lock().unwrap_or_else(|e| e.into_inner());
125            claims.keys().filter(|id| !occupying.iter().any(|r| &r.id == *id)).cloned().collect()
126        };
127        let claimed_rows: Vec<_> = claimed.iter().filter_map(|id| self.store.job_run_get(id).ok().flatten()).collect();
128        let claimed_here = claimed_rows.iter().filter(|r| r.job_id == job.id).count();
129        for r in occupying.into_iter().chain(claimed_rows) {
130            let Some(other) = self.job(&r.job_id).filter(policy::starts_an_agent) else { continue };
131            if !caps::reports_cost(&r.provider) {
132                continue;
133            }
134            let held = caps::effective(other.policy.caps.as_ref(), &limits).run_usd;
135            if r.job_id == job.id {
136                job_usd += held;
137            }
138            if let Some(a) = account_usd.as_mut().filter(|_| r.account_id == account) {
139                *a += held;
140            }
141        }
142        let messages = if caps::sends_to_another(job) {
143            // A pending fire being delivered is a message the day already owes.
144            self.store.job_runs_delivered_since(&job.id, day_start).unwrap_or(0) + claimed_here as i64
145        } else {
146            0
147        };
148        Spend { job_usd, account_usd, messages }
149    }
150
151    /// May `job`'s next run start? Filing a task spends nothing, so it always may.
152    pub(super) fn cap_gate(&self, job: &CronJob) -> Gate {
153        if !policy::starts_an_agent(job) {
154            return Gate { refusal: None, account: String::new() };
155        }
156        let target = self.target(job);
157        let limits = self.limits();
158        let mut eff = caps::effective(job.policy.caps.as_ref(), &limits);
159        if !caps::reports_cost(&target.provider) {
160            eff.run_usd = 0.0;
161        }
162        let spend = self.spend(job, &target.account, self.day_start(now_ms()));
163        Gate { refusal: caps::check(&eff, &limits, &spend, caps::sends_to_another(job)), account: target.account }
164    }
165
166    /// The cap `job` is over today, for the Jobs tab ("over cap today"): its
167    /// own daily cap or messages a day as of now, or an account cap that
168    /// skipped one of its runs today.
169    pub fn over_cap_today(&self, job: &CronJob) -> Option<&'static str> {
170        if !policy::starts_an_agent(job) {
171            return None;
172        }
173        let limits = self.limits();
174        let mut eff = caps::effective(job.policy.caps.as_ref(), &limits);
175        if !caps::reports_cost(&self.target(job).provider) {
176            eff.run_usd = 0.0;
177        }
178        let day_start = self.day_start(now_ms());
179        let spend = self.spend(job, "", day_start);
180        if let Some(over) = caps::check(&eff, &limits, &spend, caps::sends_to_another(job)) {
181            return Some(over.reason());
182        }
183        let skipped = self.store.job_cap_skips_since(&job.id, day_start).unwrap_or_default();
184        skipped.iter().any(|r| r == reason::ACCOUNT_CAP).then_some(reason::ACCOUNT_CAP)
185    }
186
187    /// Whether `job` has no cap skip yet today: the next one raises the alert.
188    pub(super) fn first_cap_skip_today(&self, job: &CronJob) -> bool {
189        self.store.job_cap_skips_since(&job.id, self.day_start(now_ms())).map(|v| v.is_empty()).unwrap_or(false)
190    }
191
192    /// A scheduled slot of `job` that a cap skips: a collapsed `skipped` row,
193    /// and, for the job's first cap skip of the day, the alert.
194    pub(super) fn skip_slot_for_cap(&self, job: &CronJob, slot_ms: i64, refusal: Refusal) {
195        let first = self.first_cap_skip_today(job);
196        self.record_skip_slot(job, slot_ms, refusal.reason());
197        if first {
198            self.alert_cap(job, refusal);
199        }
200    }
201
202    /// A run that already has its row (it waited, or was pending) and that a
203    /// cap skips.
204    pub(super) fn skip_run_for_cap(&self, run_id: &str, job: &CronJob, refusal: Refusal) {
205        let first = self.first_cap_skip_today(job);
206        if let Err(e) = self.store.job_run_skip(run_id, refusal.reason(), 1, now_ms()) {
207            tracing::warn!(run_id, error = %e, "jobs: couldn't skip a run for a cap");
208        }
209        self.changed(&job.id);
210        if first {
211            self.alert_cap(job, refusal);
212        }
213    }
214
215    /// The follower saw run `run_id` reach `cap` dollars: end it `over_budget`,
216    /// interrupt its turn, and stop a worker it started (§5.3).
217    pub(crate) fn over_budget(&self, run_id: &str, cost: RunCost, cap: f64) {
218        let Some(run) = self.store.job_run_get(run_id).ok().flatten() else { return };
219        let summary = format!("stopped: the run reached its spending cap (${cap:.2}; spent ${:.2})", cost.cost_usd);
220        match self.store.job_run_over_budget(run_id, cost, &summary, now_ms()) {
221            Ok(true) => {
222                tracing::info!(run_id, job_id = %run.job_id, spent = cost.cost_usd, cap, "jobs: a run reached its spending cap and was stopped");
223                self.interrupt_block(&run.block_id);
224                self.stop_worker(run_id, true);
225                self.run_changed(run_id);
226                super::pending_wake().notify_one();
227            }
228            Ok(false) => {}
229            Err(e) => tracing::warn!(run_id, error = %e, "jobs: couldn't stop an over-budget run"),
230        }
231    }
232}