Skip to main content

merry_runtime/context/
budget.rs

1use super::ContextError;
2use merry_core::ContextWindowSource;
3
4/// Share of the dynamic body budget that starts automatic compaction.
5///
6/// This is the same single percentage grok-build uses for `should_auto_compact`.
7pub const AUTO_COMPACT_THRESHOLD_PERCENT: u8 = 85;
8
9/// Derived context body budget and the one compaction trigger.
10///
11/// The budget subtracts cacheable stable-prefix tokens and output reserve from
12/// an effective model context window. Automatic compaction starts when the
13/// dynamic body reaches [`AUTO_COMPACT_THRESHOLD_PERCENT`] of that body budget.
14/// Whether a request can be sent is still the body budget itself. The budget
15/// does not perform token estimation or mutate runtime state.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct ContextBudget {
18    effective_window_tokens: u64,
19    stable_prefix_tokens: u64,
20    output_reserve_tokens: u64,
21    body_budget_tokens: u64,
22    compact_at_tokens: u64,
23}
24
25impl ContextBudget {
26    /// Calculates the dynamic-body budget and its compaction trigger using
27    /// [`AUTO_COMPACT_THRESHOLD_PERCENT`].
28    pub fn from_window(
29        resolved_context_window_tokens: u64,
30        effective_context_window_percent: u8,
31        stable_prefix_tokens: u64,
32        output_reserve_tokens: u64,
33    ) -> Result<Self, ContextError> {
34        Self::from_window_with_compaction_threshold(
35            resolved_context_window_tokens,
36            effective_context_window_percent,
37            stable_prefix_tokens,
38            output_reserve_tokens,
39            AUTO_COMPACT_THRESHOLD_PERCENT,
40        )
41    }
42
43    /// Calculates the dynamic-body budget and its compaction trigger with an
44    /// explicit automatic compaction threshold percentage (`1..=100`).
45    pub fn from_window_with_compaction_threshold(
46        resolved_context_window_tokens: u64,
47        effective_context_window_percent: u8,
48        stable_prefix_tokens: u64,
49        output_reserve_tokens: u64,
50        compaction_threshold_percent: u8,
51    ) -> Result<Self, ContextError> {
52        if !(1..=100).contains(&effective_context_window_percent) {
53            return Err(ContextError::InvalidBudget {
54                reason: "effective context window percent must be between 1 and 100",
55            });
56        }
57        if !(1..=100).contains(&compaction_threshold_percent) {
58            return Err(ContextError::InvalidBudget {
59                reason: "compaction threshold percent must be between 1 and 100",
60            });
61        }
62
63        let effective_window_tokens = resolved_context_window_tokens
64            .checked_mul(u64::from(effective_context_window_percent))
65            .and_then(|value| value.checked_div(100))
66            .ok_or(ContextError::InvalidBudget {
67                reason: "effective context window calculation overflowed",
68            })?;
69        let reserved_tokens = stable_prefix_tokens
70            .checked_add(output_reserve_tokens)
71            .ok_or(ContextError::InvalidBudget {
72                reason: "reserved context tokens overflowed",
73            })?;
74        let body_budget_tokens = effective_window_tokens.checked_sub(reserved_tokens).ok_or(
75            ContextError::InvalidBudget {
76                reason: "effective context window must exceed stable prefix and output reserve",
77            },
78        )?;
79        if body_budget_tokens == 0 {
80            return Err(ContextError::InvalidBudget {
81                reason: "body budget must be greater than zero",
82            });
83        }
84
85        let compact_at_tokens =
86            compaction_threshold_tokens(body_budget_tokens, compaction_threshold_percent)?;
87
88        Ok(Self {
89            effective_window_tokens,
90            stable_prefix_tokens,
91            output_reserve_tokens,
92            body_budget_tokens,
93            compact_at_tokens,
94        })
95    }
96
97    /// Context window after applying the effective window percentage.
98    #[must_use]
99    pub fn effective_window_tokens(&self) -> u64 {
100        self.effective_window_tokens
101    }
102
103    /// Tokens reserved for cacheable stable-prefix messages and tool profile.
104    #[must_use]
105    pub fn stable_prefix_tokens(&self) -> u64 {
106        self.stable_prefix_tokens
107    }
108
109    /// Tokens reserved for model output.
110    #[must_use]
111    pub fn output_reserve_tokens(&self) -> u64 {
112        self.output_reserve_tokens
113    }
114
115    /// Remaining token budget for dynamic body content.
116    #[must_use]
117    pub fn body_budget_tokens(&self) -> u64 {
118        self.body_budget_tokens
119    }
120
121    /// Dynamic-body size that starts automatic compaction.
122    #[must_use]
123    pub fn compact_at_tokens(&self) -> u64 {
124        self.compact_at_tokens
125    }
126}
127
128fn compaction_threshold_tokens(
129    body_budget_tokens: u64,
130    threshold_percent: u8,
131) -> Result<u64, ContextError> {
132    let scaled = body_budget_tokens
133        .checked_mul(u64::from(threshold_percent))
134        .ok_or(ContextError::InvalidBudget {
135            reason: "compaction threshold calculation overflowed",
136        })?;
137    Ok(scaled.div_ceil(100).clamp(1, body_budget_tokens))
138}
139
140/// Resolved model context window and the metadata source that supplied it.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub struct ResolvedContextWindow {
143    tokens: u64,
144    source: ContextWindowSource,
145}
146
147impl ResolvedContextWindow {
148    /// Resolved context window size in tokens.
149    #[must_use]
150    pub fn tokens(&self) -> u64 {
151        self.tokens
152    }
153
154    /// Source that supplied the resolved context window.
155    #[must_use]
156    pub fn source(&self) -> ContextWindowSource {
157        self.source
158    }
159}
160
161/// Resolves context window metadata without provider probing.
162pub fn resolve_context_window(
163    explicit_override: Option<u64>,
164    provider_capability: Option<u64>,
165    bundled_catalog_value: Option<u64>,
166    fallback: u64,
167) -> Result<ResolvedContextWindow, ContextError> {
168    let (tokens, source) = if let Some(tokens) = explicit_override {
169        (tokens, ContextWindowSource::ExplicitConfig)
170    } else if let Some(tokens) = provider_capability {
171        (tokens, ContextWindowSource::ProviderCapabilities)
172    } else if let Some(tokens) = bundled_catalog_value {
173        (tokens, ContextWindowSource::BundledCatalog)
174    } else {
175        (fallback, ContextWindowSource::Fallback)
176    };
177
178    if tokens == 0 {
179        return Err(ContextError::InvalidContextWindow {
180            reason: "resolved context window must be greater than zero",
181        });
182    }
183
184    Ok(ResolvedContextWindow { tokens, source })
185}
186
187pub use merry_llm::bundled_model_context_window;
188
189/// Whether the dynamic body has reached the compaction threshold.
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub enum CheckpointDecision {
192    /// Dynamic body remains below the compaction threshold.
193    Continue,
194    /// Dynamic body reached the compaction threshold.
195    Compact,
196}
197
198impl CheckpointDecision {
199    pub(crate) fn as_str(self) -> &'static str {
200        match self {
201            Self::Continue => "continue",
202            Self::Compact => "compact",
203        }
204    }
205}
206
207/// Decides whether dynamic body growth has reached the compaction threshold.
208#[must_use]
209pub fn decide_checkpoint(dynamic_body_tokens: u64, budget: ContextBudget) -> CheckpointDecision {
210    if dynamic_body_tokens >= budget.compact_at_tokens() {
211        CheckpointDecision::Compact
212    } else {
213        CheckpointDecision::Continue
214    }
215}