Skip to main content

agentmux_srv/server/
compact_backstop.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! The srv backstop of an agent's compaction. For a route agent it is the model's budget
4//! (`docs/specs/SPEC_ROUTE_AGENT_BRAKES_2026_11_10.md` section 4.2): the launch environment moves the CLI's own auto-compact
5//! down to it; if the agent's context is still more than 1.5 times that budget (the variable was ignored, or the CLI's
6//! compaction is off or failing), srv sends the agent `/compact` the way `Agents compact` does: once per try, between
7//! turns, never mid-turn. For a container agent it is one size well under its window (`agent:compactbackstopat`, 600K
8//! unless set), for an agent that does not act on the note it is given at 400K: the same rule, with the compaction placed
9//! at the head of the container's queue. After two tries that left either over, the agent's pane gets a warning line
10//! (block meta `agent:context_warning`, its own key: the spend watcher's 80% warning is not touched) and its leader a
11//! note, once.
12//!
13//! A route agent is looked at off the spend watcher's per-response event, a container agent when a turn of it ends well:
14//! a map lookup each.
15
16use std::collections::HashMap;
17use std::sync::{LazyLock, Mutex};
18
19use serde_json::{json, Value};
20
21use crate::backend::context_reading::{self, ContextReading};
22use crate::backend::model_gateway::token::Grant;
23use crate::backend::model_gateway::{catalog, launch};
24use crate::backend::obj;
25use crate::backend::worker_notes;
26use crate::server::spend_watch;
27use crate::server::AppState;
28
29/// The pane's context warning: `{at, context}`. Taken off when the context is back under the limit.
30pub const CONTEXT_WARNING_META_KEY: &str = "agent:context_warning";
31
32/// Compactions sent for one stretch over the limit before the agent's pane and leader are told.
33const TRIES: u8 = 2;
34/// After the last try, how long the context may stay over the limit before that try counts as failed.
35const SETTLE_MS: u64 = context_reading::MIN_MS_BETWEEN;
36
37/// What srv has done about one pane's context since it passed the limit.
38#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
39struct Episode {
40    tries: u8,
41    /// When the last try was scheduled, and from the moment it was sent, when that was.
42    last_try_ms: u64,
43    /// The last try is scheduled and not yet known to have been sent or given up.
44    pending: bool,
45    told: bool,
46}
47
48impl Episode {
49    /// Settles a pending try against what the reading says happened to it: sent (counted from when it went) or given up
50    /// (not counted: the turn never ended, or the send failed).
51    fn settle(&mut self, reading: &ContextReading) {
52        if !self.pending || reading.compact_scheduled {
53            return;
54        }
55        self.pending = false;
56        match reading.last_self_compact_ms.filter(|sent| *sent >= self.last_try_ms) {
57            Some(sent) => self.last_try_ms = sent,
58            None => self.tries = self.tries.saturating_sub(1),
59        }
60    }
61}
62
63#[derive(Debug, PartialEq, Eq)]
64enum Step {
65    Nothing,
66    Compact,
67    Tell,
68    Recovered,
69}
70
71/// What to do for a pane whose context is `tokens` against `limit`, the size it may not stay over.
72fn decide(tokens: u64, limit: u64, ep: Option<Episode>, reading: &ContextReading, now_ms: u64) -> Step {
73    if tokens <= limit {
74        return if ep.is_some() { Step::Recovered } else { Step::Nothing };
75    }
76    if reading.compacting || reading.compact_scheduled {
77        return Step::Nothing;
78    }
79    let ep = ep.unwrap_or_default();
80    if ep.tries < TRIES {
81        return Step::Compact;
82    }
83    if !ep.told && now_ms.saturating_sub(ep.last_try_ms) >= SETTLE_MS {
84        return Step::Tell;
85    }
86    Step::Nothing
87}
88
89fn episodes() -> &'static Mutex<HashMap<String, Episode>> {
90    static EPISODES: LazyLock<Mutex<HashMap<String, Episode>>> = LazyLock::new(Default::default);
91    &EPISODES
92}
93
94/// Whose context is looked at, for the log and the note to its leader.
95struct Subject<'a> {
96    def_id: &'a str,
97    agent: &'a str,
98    /// What the context is over, in words: "over 1.5 times its compaction budget on <route>".
99    over: String,
100    /// The size, in tokens, the context may not stay over.
101    limit: u64,
102    /// What the leader can tell the agent to do: a container agent can't start a fresh session.
103    remedy: &'static str,
104}
105
106/// A response of `grant`'s agent has been counted: look at how full each of its panes' contexts is.
107pub(crate) fn after_settled(state: &AppState, grant: &Grant) {
108    let Some(route) = catalog::route(&grant.route) else { return };
109    let Some(budget) = launch::model_on_route(&state.mstore, &grant.def_id, route).and_then(|m| m.compact_budget()) else { return };
110    // A pane that was closed leaves no reading: its episode goes with it.
111    episodes().lock().unwrap().retain(|block_id, _| context_reading::get(block_id).is_some());
112    let place = route.label.to_string();
113    let subject = Subject { def_id: &grant.def_id, agent: &grant.agent, over: format!("over 1.5 times its compaction budget on {place}"), limit: u64::from(budget).saturating_mul(3) / 2, remedy: "compact or restart it (Agents compact, Agents fresh)" };
114    for block_id in worker_notes::live_panes_of(&state.mstore, &grant.def_id) {
115        look(state, &subject, &block_id);
116    }
117}
118
119/// A container agent's turn has ended well: look at how full its context is, against `agent:compactbackstopat`. An agent
120/// on a model route has the budget's backstop already, so it is left to that one.
121pub(crate) fn after_container_turn(state: &AppState, block_id: &str) {
122    let Some(limit) = context_reading::backstop_at() else { return };
123    let Some(block) = state.mstore.get::<obj::Block>(block_id).ok().flatten() else { return };
124    let def_id = obj::meta_get_string(&block.meta, "agentId", "");
125    if def_id.is_empty() || launch::choice_of(&state.mstore, &def_id).is_some() {
126        return;
127    }
128    let Some(def) = state.mstore.agent_def_get(&def_id).ok().flatten() else { return };
129    let subject = Subject { def_id: &def_id, agent: &def.slug, over: format!("over {}K tokens, where AgentMux compacts a container agent", limit / 1000), limit, remedy: "have it compact (Agents compact)" };
130    look(state, &subject, block_id);
131}
132
133/// One pane: settle the last try, decide what is next and do it.
134fn look(state: &AppState, subject: &Subject, block_id: &str) {
135    let Some(reading) = context_reading::get(block_id) else { return };
136    let Some(tokens) = reading.tokens else { return };
137    let now = agentmux_common::time::now_ms_u64();
138    let ep = episodes().lock().unwrap().get_mut(block_id).map(|ep| {
139        ep.settle(&reading);
140        *ep
141    });
142    match decide(tokens, subject.limit, ep, &reading, now) {
143        Step::Nothing => {}
144        Step::Recovered => recovered(state, subject, block_id, ep.is_some_and(|e| e.told)),
145        Step::Compact => compact(state, subject, block_id, tokens, now),
146        Step::Tell => tell(state, subject, block_id, tokens),
147    }
148}
149
150fn compact(state: &AppState, subject: &Subject, block_id: &str, tokens: u64, now: u64) {
151    match crate::server::app_api::agent_context::compact_for_backstop(state, block_id) {
152        Ok(()) => {
153            let mut map = episodes().lock().unwrap();
154            let ep = map.entry(block_id.to_string()).or_default();
155            ep.tries += 1;
156            ep.last_try_ms = now;
157            ep.pending = true;
158            tracing::info!(block_id, tokens, limit = subject.limit, try_no = ep.tries, over = %subject.over, "compaction backstop: the context is over its limit, /compact sent when the turn ends");
159        }
160        // Too soon after the last compaction, or one already scheduled: the next look is another try.
161        Err(why) => tracing::debug!(block_id, tokens, why, "compaction backstop: not sent"),
162    }
163}
164
165fn tell(state: &AppState, subject: &Subject, block_id: &str, tokens: u64) {
166    if let Some(ep) = episodes().lock().unwrap().get_mut(block_id) {
167        ep.told = true;
168    }
169    let card = json!({ "at": agentmux_common::time::now_ms(), "context": tokens });
170    spend_watch::set_meta(state, block_id, CONTEXT_WARNING_META_KEY, card);
171    let name = state.mstore.agent_def_get(subject.def_id).ok().flatten().map_or_else(|| subject.def_id.to_string(), |d| d.name);
172    let note = format!(
173        "{name}'s context is {}K tokens, {}, and two /compact attempts did not bring it down. It re-reads that context on every turn: {}.",
174        tokens / 1000,
175        subject.over,
176        subject.remedy
177    );
178    tracing::warn!(agent = %subject.agent, tokens, "compaction backstop: compaction did not run, the agent's leader is told");
179    worker_notes::tell_leader(&state.mstore, subject.def_id, &note);
180}
181
182/// The context is back under the limit: forget the episode, and take our warning off the pane.
183fn recovered(state: &AppState, subject: &Subject, block_id: &str, told: bool) {
184    episodes().lock().unwrap().remove(block_id);
185    if !told {
186        return;
187    }
188    spend_watch::set_meta(state, block_id, CONTEXT_WARNING_META_KEY, Value::Null);
189    tracing::info!(agent = %subject.agent, "compaction backstop: the context is back under the limit");
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    fn reading() -> ContextReading {
197        ContextReading::default()
198    }
199
200    #[test]
201    fn a_context_within_its_limit_is_left_alone() {
202        assert_eq!(decide(450_000, 450_000, None, &reading(), 0), Step::Nothing);
203        assert_eq!(decide(450_001, 450_000, None, &reading(), 0), Step::Compact);
204    }
205
206    #[test]
207    fn it_tries_twice_then_tells_once_after_the_last_try_had_time() {
208        let at = |tries, last_try_ms, told| Some(Episode { tries, last_try_ms, pending: false, told });
209        assert_eq!(decide(480_000, 450_000, at(1, 0, false), &reading(), 1), Step::Compact);
210        assert_eq!(decide(480_000, 450_000, at(2, 1_000, false), &reading(), 1_000 + SETTLE_MS - 1), Step::Nothing, "the second try still has time");
211        assert_eq!(decide(480_000, 450_000, at(2, 1_000, false), &reading(), 1_000 + SETTLE_MS), Step::Tell);
212        assert_eq!(decide(480_000, 450_000, at(2, 1_000, true), &reading(), 1_000 + 10 * SETTLE_MS), Step::Nothing, "told once");
213    }
214
215    #[test]
216    fn nothing_is_sent_while_a_compaction_runs_or_waits_for_the_turn() {
217        let (mut compacting, mut scheduled) = (reading(), reading());
218        compacting.compacting = true;
219        scheduled.compact_scheduled = true;
220        for r in [compacting, scheduled] {
221            assert_eq!(decide(900_000, 450_000, None, &r, 0), Step::Nothing);
222        }
223    }
224
225    /// A container agent over `agent:compactbackstopat` goes through the route agents' decision with that size as the
226    /// limit: two tries, the second only when the first did not bring the context down, then one warning, never a third.
227    #[test]
228    fn a_container_agent_gets_two_tries_at_the_default_size_then_one_warning() {
229        let limit = context_reading::DEFAULT_BACKSTOP_AT;
230        assert_eq!(limit, 600_000, "well under a 1M window, above the 400K hint");
231        let mut ep = Episode::default();
232        assert_eq!(decide(limit, limit, None, &reading(), 0), Step::Nothing, "at the size is not over it");
233        assert_eq!(decide(limit + 1, limit, None, &reading(), 0), Step::Compact, "the first try");
234        for (tries, expected) in [(1, Step::Compact), (2, Step::Nothing)] {
235            ep.tries = tries;
236            ep.last_try_ms = 1_000;
237            assert_eq!(decide(limit + 1, limit, Some(ep), &reading(), 1_001), expected, "after {tries} tries");
238        }
239        assert_eq!(decide(limit + 1, limit, Some(ep), &reading(), 1_000 + SETTLE_MS), Step::Tell, "the warning, once the second try had time");
240        ep.told = true;
241        assert_eq!(decide(limit + 1, limit, Some(ep), &reading(), 1_000 + 50 * SETTLE_MS), Step::Nothing, "no third try, no second warning");
242        assert_eq!(decide(limit - 1, limit, Some(ep), &reading(), 1_000 + 50 * SETTLE_MS), Step::Recovered);
243    }
244
245    #[test]
246    fn a_context_that_came_back_under_ends_the_episode() {
247        let ep = Some(Episode { tries: 2, last_try_ms: 1, pending: false, told: true });
248        assert_eq!(decide(200_000, 450_000, ep, &reading(), 5), Step::Recovered);
249        assert_eq!(decide(200_000, 450_000, None, &reading(), 5), Step::Nothing);
250    }
251
252    #[test]
253    fn a_try_counts_from_when_it_was_sent_and_not_at_all_when_it_never_was() {
254        let scheduled = Episode { tries: 1, last_try_ms: 1_000, pending: true, told: false };
255        let mut waiting = scheduled;
256        let mut queued = reading();
257        queued.compact_scheduled = true;
258        waiting.settle(&queued);
259        assert_eq!(waiting, scheduled, "still waiting for the turn to end");
260
261        let mut sent = scheduled;
262        let mut r = reading();
263        r.last_self_compact_ms = Some(5_000);
264        sent.settle(&r);
265        assert_eq!((sent.tries, sent.last_try_ms, sent.pending), (1, 5_000, false), "counted from the send");
266
267        let mut given_up = scheduled;
268        given_up.settle(&reading());
269        assert_eq!((given_up.tries, given_up.pending), (0, false), "the turn never ended: no try was made");
270    }
271}