Skip to main content

agentmux_srv_core/backend/vault/
pace.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How much an agent may add or change in an hour (docs/specs/SPEC_VAULT_AGENT_ADDS_AND_EDITS_WITHOUT_ASKING_2026_11_25.md
5//! R6). Adding and editing ask nobody, so this is the bound on what one misled agent can do before the person looks: a pace,
6//! never a permission. A call over the budget is refused at once with the time the budget next has room, and changes nothing.
7//! The budget resets by itself as the hour slides.
8
9use std::collections::HashMap;
10use std::sync::{Mutex, OnceLock};
11
12/// The window the budget is counted over.
13pub const WINDOW_MS: i64 = 60 * 60 * 1000;
14/// Writes of any kind in the window.
15pub const WRITES: usize = 30;
16/// Replacements of an existing entry's value in the window.
17pub const REPLACES: usize = 6;
18/// Replacements of one entry in the window.
19pub const REPLACES_PER_ENTRY: usize = 5;
20/// New entries in the window.
21pub const NEW_ENTRIES: usize = 20;
22/// "Refused: pace" history lines one agent may have written for it in the window: a refusal is a record, and an agent that
23/// keeps asking over its pace must not be able to fill an entry's history with its own words.
24pub const REFUSAL_LINES: usize = 3;
25
26/// One thing an agent writes.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum Act {
29    /// A new entry.
30    New,
31    /// A new value for the entry with this id.
32    Replace(String),
33    /// A change to an entry's details (label, fields, tags, where its machine copy is).
34    Edit,
35}
36
37#[derive(Default)]
38pub struct Pace {
39    log: Mutex<HashMap<String, Vec<(i64, Act)>>>,
40    refusals: Mutex<HashMap<String, Vec<i64>>>,
41}
42
43/// The time `limit` leaves room again: when the `count - limit + needed`-th oldest of `times` leaves the window.
44fn room_at(mut times: Vec<i64>, limit: usize, needed: usize) -> i64 {
45    times.sort_unstable();
46    let leaves = (times.len() + needed).saturating_sub(limit).max(1);
47    times.get(leaves - 1).map_or(0, |t| t + WINDOW_MS)
48}
49
50fn when(now: i64, at: i64) -> String {
51    let minutes = ((at - now).max(0) + 59_999) / 60_000;
52    if minutes <= 1 {
53        "in about a minute".to_string()
54    } else {
55        format!("in about {minutes} minutes")
56    }
57}
58
59/// The refusal when one call asks for more than the pace ever allows in an hour: waiting would not help.
60fn too_large(what: &str, asked: usize, most: usize) -> String {
61    format!("this call changes {asked} {what} and the Vault's pace allows at most {most} in an hour, so it can never be taken as one: split it into smaller calls")
62}
63
64impl Pace {
65    /// Counts `acts` against `agent`'s budget at `now` (ms) and records them, or refuses all of them, saying when there is
66    /// room. A batch is `acts` with one per row.
67    pub fn admit(&self, agent: &str, acts: &[Act], now: i64) -> Result<(), String> {
68        let (new, replaces) = (acts.iter().filter(|a| **a == Act::New).count(), acts.iter().filter(|a| matches!(a, Act::Replace(_))).count());
69        for (what, asked, most) in [("things", acts.len(), WRITES), ("new entries", new, NEW_ENTRIES), ("values", replaces, REPLACES)] {
70            if asked > most {
71                return Err(too_large(what, asked, most));
72            }
73        }
74        let mut log = self.log.lock().unwrap();
75        let mine = log.entry(agent.to_string()).or_default();
76        mine.retain(|(at, _)| now - at < WINDOW_MS);
77        let times = |keep: &dyn Fn(&Act) -> bool| mine.iter().filter(|(_, a)| keep(a)).map(|(t, _)| *t).collect::<Vec<_>>();
78        let refuse = |what: String, at: i64| Err(format!("this agent has {what}; the Vault's pace gives it room again {}", when(now, at)));
79        if mine.len() + acts.len() > WRITES {
80            return refuse(format!("made {} changes to the Vault in the last hour (at most {WRITES})", mine.len()), room_at(times(&|_| true), WRITES, acts.len()));
81        }
82        if new > 0 && times(&|a| *a == Act::New).len() + new > NEW_ENTRIES {
83            return refuse(format!("added {} entries in the last hour (at most {NEW_ENTRIES})", times(&|a| *a == Act::New).len()), room_at(times(&|a| *a == Act::New), NEW_ENTRIES, new));
84        }
85        if replaces > 0 && times(&|a| matches!(a, Act::Replace(_))).len() + replaces > REPLACES {
86            return refuse(
87                format!("replaced the value of {} entries in the last hour (at most {REPLACES})", times(&|a| matches!(a, Act::Replace(_))).len()),
88                room_at(times(&|a| matches!(a, Act::Replace(_))), REPLACES, replaces),
89            );
90        }
91        for id in acts.iter().filter_map(|a| if let Act::Replace(id) = a { Some(id) } else { None }) {
92            let of_it = |a: &Act| matches!(a, Act::Replace(i) if i == id);
93            let asked = acts.iter().filter(|a| of_it(a)).count();
94            if asked > REPLACES_PER_ENTRY {
95                return Err(too_large("new values of one entry", asked, REPLACES_PER_ENTRY));
96            }
97            if times(&of_it).len() + asked > REPLACES_PER_ENTRY {
98                return refuse(format!("replaced the value of one entry {} times in the last hour (at most {REPLACES_PER_ENTRY})", times(&of_it).len()), room_at(times(&of_it), REPLACES_PER_ENTRY, asked));
99            }
100        }
101        mine.extend(acts.iter().map(|a| (now, a.clone())));
102        Ok(())
103    }
104
105    /// Gives back `acts` an agent was admitted for and did not make (the call failed before anything was stored): the latest
106    /// matching entry of each is dropped.
107    pub fn refund(&self, agent: &str, acts: &[Act]) {
108        let mut log = self.log.lock().unwrap();
109        let Some(mine) = log.get_mut(agent) else { return };
110        for act in acts {
111            if let Some(at) = mine.iter().rposition(|(_, a)| a == act) {
112                mine.remove(at);
113            }
114        }
115    }
116
117    /// Whether a "refused: pace" line may be written for `agent` now, and counts it when so.
118    pub fn may_note_refusal(&self, agent: &str, now: i64) -> bool {
119        let mut notes = self.refusals.lock().unwrap();
120        let mine = notes.entry(agent.to_string()).or_default();
121        mine.retain(|at| now - at < WINDOW_MS);
122        if mine.len() >= REFUSAL_LINES {
123            return false;
124        }
125        mine.push(now);
126        true
127    }
128}
129
130/// The one budget every handler counts against.
131pub fn pace() -> &'static Pace {
132    static PACE: OnceLock<Pace> = OnceLock::new();
133    PACE.get_or_init(Pace::default)
134}
135
136/// What an agent was admitted for and has not yet made. Dropped before it is settled (the call was denied, cancelled or
137/// failed on the way), it gives the pace back.
138#[derive(Default)]
139pub struct Reservation {
140    agent: String,
141    acts: Vec<Act>,
142}
143
144impl Reservation {
145    pub fn new(agent: &str, acts: Vec<Act>) -> Self {
146        Self { agent: agent.to_string(), acts }
147    }
148
149    /// The work it was for has begun: whatever becomes of it, its own steps give the pace back.
150    pub fn settle(&mut self) {
151        self.acts.clear();
152    }
153}
154
155impl Drop for Reservation {
156    fn drop(&mut self) {
157        if !self.acts.is_empty() {
158            refund(&self.agent, &self.acts);
159        }
160    }
161}
162
163/// [`Pace::refund`].
164pub fn refund(agent: &str, acts: &[Act]) {
165    pace().refund(agent, acts);
166}
167
168/// [`Pace::may_note_refusal`] now.
169pub fn may_note_refusal(agent: &str) -> bool {
170    pace().may_note_refusal(agent, agentmux_common::time::now_ms())
171}
172
173/// [`Pace::admit`] now.
174pub fn admit(agent: &str, acts: &[Act]) -> Result<(), String> {
175    pace().admit(agent, acts, agentmux_common::time::now_ms())
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    const T: i64 = 1_000_000_000;
183
184    fn replace(id: &str) -> Act {
185        Act::Replace(id.to_string())
186    }
187
188    #[test]
189    fn the_thirty_first_write_in_an_hour_is_refused_and_says_when_there_is_room() {
190        let p = Pace::default();
191        for i in 0..WRITES as i64 {
192            p.admit("a", &[Act::Edit], T + i * 1000).unwrap();
193        }
194        let why = p.admit("a", &[Act::Edit], T + 60_000).unwrap_err();
195        assert!(why.contains("30 changes") && why.contains("in about 59 minutes"), "{why}");
196        // Another agent has its own budget.
197        p.admit("b", &[Act::Edit], T + 60_000).unwrap();
198        // The window slides: the first write leaves it an hour on.
199        p.admit("a", &[Act::Edit], T + WINDOW_MS + 1).unwrap();
200    }
201
202    #[test]
203    fn the_twenty_first_new_entry_and_the_seventh_replacement_are_refused() {
204        let p = Pace::default();
205        for _ in 0..NEW_ENTRIES {
206            p.admit("a", &[Act::New], T).unwrap();
207        }
208        assert!(p.admit("a", &[Act::New], T + 1).unwrap_err().contains("added 20 entries"));
209        let q = Pace::default();
210        for i in 0..REPLACES {
211            q.admit("a", &[replace(&format!("e{i}"))], T).unwrap();
212        }
213        assert!(q.admit("a", &[replace("e9")], T + 1).unwrap_err().contains("replaced the value of 6 entries"));
214        // A new entry and an edit are not replacements.
215        q.admit("a", &[Act::New, Act::Edit], T + 2).unwrap();
216    }
217
218    #[test]
219    fn the_sixth_replacement_of_one_entry_is_refused_though_the_hour_has_room() {
220        let p = Pace::default();
221        for _ in 0..REPLACES_PER_ENTRY {
222            p.admit("a", &[replace("same")], T).unwrap();
223        }
224        assert!(p.admit("a", &[replace("same")], T + 1).unwrap_err().contains("one entry 5 times"));
225        p.admit("a", &[replace("other")], T + 1).unwrap();
226    }
227
228    #[test]
229    fn a_call_larger_than_the_pace_ever_allows_is_told_to_split_not_to_wait() {
230        let p = Pace::default();
231        let why = p.admit("a", &vec![Act::New; NEW_ENTRIES + 1], T).unwrap_err();
232        assert!(why.contains("split it") && !why.contains("room again"), "{why}");
233        assert!(p.admit("a", &vec![Act::Edit; WRITES + 1], T).unwrap_err().contains("split it"));
234        p.admit("a", &vec![Act::New; NEW_ENTRIES], T).unwrap();
235    }
236
237    #[test]
238    fn a_refund_gives_back_what_a_failed_call_took_and_refusal_lines_are_few() {
239        let p = Pace::default();
240        for _ in 0..WRITES {
241            p.admit("a", &[Act::Edit], T).unwrap();
242        }
243        assert!(p.admit("a", &[Act::Edit], T + 1).is_err());
244        p.refund("a", &[Act::Edit]);
245        p.admit("a", &[Act::Edit], T + 2).unwrap();
246        p.refund("a", &[Act::New]);
247        assert!(p.admit("a", &[Act::Edit], T + 3).is_err(), "nothing of that kind was held, so nothing came back");
248        for _ in 0..REFUSAL_LINES {
249            assert!(p.may_note_refusal("a", T));
250        }
251        assert!(!p.may_note_refusal("a", T + 1) && p.may_note_refusal("b", T + 1));
252        assert!(p.may_note_refusal("a", T + WINDOW_MS + 1));
253    }
254
255    #[test]
256    fn a_reservation_dropped_unsettled_gives_the_pace_back_and_a_settled_one_does_not() {
257        let who = "reservation-test-agent";
258        let held = || pace().admit(who, &[Act::Edit], agentmux_common::time::now_ms());
259        for _ in 0..WRITES - 1 {
260            held().unwrap();
261        }
262        drop(Reservation::new(who, vec![Act::Edit; WRITES - 1]));
263        for _ in 0..WRITES {
264            held().unwrap();
265        }
266        assert!(held().is_err());
267        let mut settled = Reservation::new(who, vec![Act::Edit]);
268        settled.settle();
269        drop(settled);
270        assert!(held().is_err(), "a settled reservation gives nothing back");
271    }
272
273    #[test]
274    fn a_batch_counts_a_write_a_row_and_is_taken_whole_or_not_at_all() {
275        let p = Pace::default();
276        p.admit("a", &vec![Act::Edit; 25], T).unwrap();
277        let rows: Vec<Act> = (0..6).map(|_| Act::New).collect();
278        assert!(p.admit("a", &rows, T + 1).is_err());
279        // Nothing of the refused batch was counted: five more still fit.
280        p.admit("a", &rows[..5], T + 2).unwrap();
281        assert!(p.admit("a", &[Act::Edit], T + 3).is_err());
282    }
283}