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.
27    pub fn from_window(
28        resolved_context_window_tokens: u64,
29        effective_context_window_percent: u8,
30        stable_prefix_tokens: u64,
31        output_reserve_tokens: u64,
32    ) -> Result<Self, ContextError> {
33        if !(1..=100).contains(&effective_context_window_percent) {
34            return Err(ContextError::InvalidBudget {
35                reason: "effective context window percent must be between 1 and 100",
36            });
37        }
38
39        let effective_window_tokens = resolved_context_window_tokens
40            .checked_mul(u64::from(effective_context_window_percent))
41            .and_then(|value| value.checked_div(100))
42            .ok_or(ContextError::InvalidBudget {
43                reason: "effective context window calculation overflowed",
44            })?;
45        let reserved_tokens = stable_prefix_tokens
46            .checked_add(output_reserve_tokens)
47            .ok_or(ContextError::InvalidBudget {
48                reason: "reserved context tokens overflowed",
49            })?;
50        let body_budget_tokens = effective_window_tokens.checked_sub(reserved_tokens).ok_or(
51            ContextError::InvalidBudget {
52                reason: "effective context window must exceed stable prefix and output reserve",
53            },
54        )?;
55        if body_budget_tokens == 0 {
56            return Err(ContextError::InvalidBudget {
57                reason: "body budget must be greater than zero",
58            });
59        }
60
61        let compact_at_tokens = compaction_threshold_tokens(body_budget_tokens)?;
62
63        Ok(Self {
64            effective_window_tokens,
65            stable_prefix_tokens,
66            output_reserve_tokens,
67            body_budget_tokens,
68            compact_at_tokens,
69        })
70    }
71
72    /// Context window after applying the effective window percentage.
73    #[must_use]
74    pub fn effective_window_tokens(&self) -> u64 {
75        self.effective_window_tokens
76    }
77
78    /// Tokens reserved for cacheable stable-prefix messages and tool profile.
79    #[must_use]
80    pub fn stable_prefix_tokens(&self) -> u64 {
81        self.stable_prefix_tokens
82    }
83
84    /// Tokens reserved for model output.
85    #[must_use]
86    pub fn output_reserve_tokens(&self) -> u64 {
87        self.output_reserve_tokens
88    }
89
90    /// Remaining token budget for dynamic body content.
91    #[must_use]
92    pub fn body_budget_tokens(&self) -> u64 {
93        self.body_budget_tokens
94    }
95
96    /// Dynamic-body size that starts automatic compaction.
97    #[must_use]
98    pub fn compact_at_tokens(&self) -> u64 {
99        self.compact_at_tokens
100    }
101}
102
103fn compaction_threshold_tokens(body_budget_tokens: u64) -> Result<u64, ContextError> {
104    let scaled = body_budget_tokens
105        .checked_mul(u64::from(AUTO_COMPACT_THRESHOLD_PERCENT))
106        .ok_or(ContextError::InvalidBudget {
107            reason: "compaction threshold calculation overflowed",
108        })?;
109    Ok(scaled.div_ceil(100).clamp(1, body_budget_tokens))
110}
111
112/// Resolved model context window and the metadata source that supplied it.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct ResolvedContextWindow {
115    tokens: u64,
116    source: ContextWindowSource,
117}
118
119impl ResolvedContextWindow {
120    /// Resolved context window size in tokens.
121    #[must_use]
122    pub fn tokens(&self) -> u64 {
123        self.tokens
124    }
125
126    /// Source that supplied the resolved context window.
127    #[must_use]
128    pub fn source(&self) -> ContextWindowSource {
129        self.source
130    }
131}
132
133/// Resolves context window metadata without provider probing.
134pub fn resolve_context_window(
135    explicit_override: Option<u64>,
136    provider_capability: Option<u64>,
137    bundled_catalog_value: Option<u64>,
138    fallback: u64,
139) -> Result<ResolvedContextWindow, ContextError> {
140    let (tokens, source) = if let Some(tokens) = explicit_override {
141        (tokens, ContextWindowSource::ExplicitConfig)
142    } else if let Some(tokens) = provider_capability {
143        (tokens, ContextWindowSource::ProviderCapabilities)
144    } else if let Some(tokens) = bundled_catalog_value {
145        (tokens, ContextWindowSource::BundledCatalog)
146    } else {
147        (fallback, ContextWindowSource::Fallback)
148    };
149
150    if tokens == 0 {
151        return Err(ContextError::InvalidContextWindow {
152            reason: "resolved context window must be greater than zero",
153        });
154    }
155
156    Ok(ResolvedContextWindow { tokens, source })
157}
158
159/// Whether the dynamic body has reached the compaction threshold.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum CheckpointDecision {
162    /// Dynamic body remains below the compaction threshold.
163    Continue,
164    /// Dynamic body reached the compaction threshold.
165    Compact,
166}
167
168impl CheckpointDecision {
169    pub(crate) fn as_str(self) -> &'static str {
170        match self {
171            Self::Continue => "continue",
172            Self::Compact => "compact",
173        }
174    }
175}
176
177/// Decides whether dynamic body growth has reached the compaction threshold.
178#[must_use]
179pub fn decide_checkpoint(dynamic_body_tokens: u64, budget: ContextBudget) -> CheckpointDecision {
180    if dynamic_body_tokens >= budget.compact_at_tokens() {
181        CheckpointDecision::Compact
182    } else {
183        CheckpointDecision::Continue
184    }
185}