Skip to main content

merry_runtime/compaction/
policy.rs

1use super::CompactionError;
2
3/// Summary acceptance limits and preferred raw-history retention.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub struct CitationCompactionPolicy {
6    target_output_tokens: Option<u64>,
7    max_accepted_output_bytes: Option<usize>,
8    retained_model_turns: usize,
9    one_shot_retained_tool_exchanges: usize,
10}
11
12/// Prompt guidance as a share of the destination window. This is not an
13/// acceptance limit: the model may exceed it up to the hard ceiling.
14const GUIDANCE_WINDOW_PERCENT: u64 = 5;
15const MIN_GUIDANCE_TOKENS: u64 = 512;
16const MAX_GUIDANCE_TOKENS: u64 = 8_192;
17/// Hard acceptance is generous enough that a typical overshoot does not spend
18/// another model call, without starving the compaction request on a small
19/// window. Below 32k the share stays at 10%; at 32k and above it is 15% or
20/// 2.5× guidance, whichever is larger, then clamped to 20480. A 128k window
21/// therefore accepts an 8569-token summary; a 12k window still has room to
22/// host the request; a 2M window saturates at 20480 rather than 15% of 2M.
23const ACCEPTANCE_OVERSHOOT_NUMERATOR: u64 = 5;
24const ACCEPTANCE_OVERSHOOT_DENOMINATOR: u64 = 2;
25const SMALL_WINDOW_TOKENS: u64 = 32_000;
26const SMALL_WINDOW_ACCEPTANCE_PERCENT: u64 = 10;
27const ACCEPTANCE_WINDOW_PERCENT: u64 = 15;
28const MIN_ACCEPTANCE_TOKENS: u64 = 1_024;
29const MAX_ACCEPTANCE_TOKENS: u64 = 20_480;
30const RETAINED_HISTORY_WINDOW_PERCENT: u64 = 10;
31const MAX_RETAINED_HISTORY_TOKENS: u64 = 32_768;
32/// Bytes per token used to convert an accepted-checkpoint byte cap into tokens.
33///
34/// This is a size ceiling with slack, not the runtime's estimation ratio
35/// ([`crate::token_estimate`]): the cap is deliberately looser than the estimate
36/// so a checkpoint that fits the token budget is never rejected on byte count.
37const DEFAULT_ACCEPTED_OUTPUT_BYTES_PER_TOKEN: u64 = 8;
38const DEFAULT_RETAINED_MODEL_TURNS: usize = 5;
39/// Newest covered exchanges retained on the first cache-breaking attempt.
40const DEFAULT_ONE_SHOT_RETAINED_TOOL_EXCHANGES: usize = 5;
41
42impl CitationCompactionPolicy {
43    /// Validates explicit summary limits and a nonzero retained-turn preference.
44    pub fn new(
45        target_output_tokens: Option<u64>,
46        max_accepted_output_bytes: Option<usize>,
47        retained_model_turns: usize,
48    ) -> Result<Self, CompactionError> {
49        if target_output_tokens == Some(0) {
50            return Err(CompactionError::InvalidPolicy {
51                field: "target_output_tokens",
52            });
53        }
54        if max_accepted_output_bytes == Some(0) {
55            return Err(CompactionError::InvalidPolicy {
56                field: "max_accepted_output_bytes",
57            });
58        }
59        if retained_model_turns == 0 {
60            return Err(CompactionError::InvalidPolicy {
61                field: "retained_model_turns",
62            });
63        }
64
65        Ok(Self {
66            target_output_tokens,
67            max_accepted_output_bytes,
68            retained_model_turns,
69            one_shot_retained_tool_exchanges: DEFAULT_ONE_SHOT_RETAINED_TOOL_EXCHANGES,
70        })
71    }
72
73    #[must_use]
74    /// Optional override of the hard rendered-summary ceiling, not provider output.
75    pub fn target_output_tokens(self) -> Option<u64> {
76        self.target_output_tokens
77    }
78
79    #[must_use]
80    /// Optional upper bound on candidate JSON bytes accepted from the model.
81    pub fn max_accepted_output_bytes(self) -> Option<usize> {
82        self.max_accepted_output_bytes
83    }
84
85    #[must_use]
86    /// Preferred completed turns to retain; fitting may choose a shorter tail.
87    pub fn retained_model_turns(self) -> usize {
88        self.retained_model_turns
89    }
90
91    #[must_use]
92    /// Recent covered exchanges initially kept after prefix reuse cannot fit.
93    pub fn one_shot_retained_tool_exchanges(self) -> usize {
94        self.one_shot_retained_tool_exchanges
95    }
96
97    /// Sets how many recent covered tool exchanges a rebuilt request first keeps.
98    #[must_use]
99    pub fn with_one_shot_retained_tool_exchanges(self, retained_tool_exchanges: usize) -> Self {
100        Self {
101            one_shot_retained_tool_exchanges: retained_tool_exchanges,
102            ..self
103        }
104    }
105
106    /// Changes retention without resetting other limits; rejects zero.
107    pub fn with_retained_model_turns(
108        self,
109        retained_model_turns: usize,
110    ) -> Result<Self, CompactionError> {
111        if retained_model_turns == 0 {
112            return Err(CompactionError::InvalidPolicy {
113                field: "retained_model_turns",
114            });
115        }
116        Ok(Self {
117            retained_model_turns,
118            ..self
119        })
120    }
121
122    /// Resolves prompt guidance, hard acceptance, and the preferred raw tail.
123    ///
124    /// These three numbers stay independent: the prompt aims at the soft target,
125    /// validation accepts anything up to the hard ceiling, and installation
126    /// reserves that ceiling plus the retained-history target. Rejects a zero
127    /// window and arithmetic overflow.
128    pub fn resolve(
129        self,
130        primary_window_tokens: u64,
131    ) -> Result<ResolvedCitationCompactionBudget, CompactionError> {
132        if primary_window_tokens == 0 {
133            return Err(CompactionError::InvalidPolicy {
134                field: "primary_window_tokens",
135            });
136        }
137        let (target_output_tokens, automatic_acceptance) =
138            window_summary_limits(primary_window_tokens)?;
139        let retained_history_token_target =
140            window_share(primary_window_tokens, RETAINED_HISTORY_WINDOW_PERCENT)?
141                .clamp(1, MAX_RETAINED_HISTORY_TOKENS);
142        let output_token_limit = self.target_output_tokens.unwrap_or(automatic_acceptance);
143        let derived_bytes = output_token_limit
144            .checked_mul(DEFAULT_ACCEPTED_OUTPUT_BYTES_PER_TOKEN)
145            .and_then(|value| usize::try_from(value).ok())
146            .ok_or(CompactionError::BudgetOverflow)?;
147
148        Ok(ResolvedCitationCompactionBudget {
149            target_output_tokens: target_output_tokens.min(output_token_limit),
150            retained_history_token_target,
151            output_token_limit,
152            max_accepted_output_bytes: self.max_accepted_output_bytes.unwrap_or(derived_bytes),
153        })
154    }
155}
156
157fn window_share(window_tokens: u64, percent: u64) -> Result<u64, CompactionError> {
158    window_tokens
159        .checked_mul(percent)
160        .and_then(|value| value.checked_div(100))
161        .ok_or(CompactionError::BudgetOverflow)
162}
163
164/// Returns `(guidance, acceptance)` for one destination window.
165fn window_summary_limits(window_tokens: u64) -> Result<(u64, u64), CompactionError> {
166    let guidance = window_share(window_tokens, GUIDANCE_WINDOW_PERCENT)?
167        .clamp(MIN_GUIDANCE_TOKENS, MAX_GUIDANCE_TOKENS);
168    let scaled = guidance
169        .checked_mul(ACCEPTANCE_OVERSHOOT_NUMERATOR)
170        .and_then(|value| value.checked_div(ACCEPTANCE_OVERSHOOT_DENOMINATOR))
171        .ok_or(CompactionError::BudgetOverflow)?;
172    let share_percent = if window_tokens < SMALL_WINDOW_TOKENS {
173        SMALL_WINDOW_ACCEPTANCE_PERCENT
174    } else {
175        ACCEPTANCE_WINDOW_PERCENT
176    };
177    let window_share_tokens = window_share(window_tokens, share_percent)?.max(1);
178    let unclamped = if window_tokens < SMALL_WINDOW_TOKENS {
179        window_share_tokens
180    } else {
181        scaled.max(window_share_tokens)
182    };
183    let mut acceptance = unclamped.clamp(MIN_ACCEPTANCE_TOKENS, MAX_ACCEPTANCE_TOKENS);
184    if window_tokens < SMALL_WINDOW_TOKENS {
185        acceptance = acceptance.min((window_tokens / 8).max(1));
186    }
187    let acceptance = acceptance.min(window_tokens.saturating_sub(1).max(1));
188    Ok((guidance.min(acceptance), acceptance))
189}
190
191impl Default for CitationCompactionPolicy {
192    fn default() -> Self {
193        Self {
194            target_output_tokens: None,
195            max_accepted_output_bytes: None,
196            retained_model_turns: DEFAULT_RETAINED_MODEL_TURNS,
197            one_shot_retained_tool_exchanges: DEFAULT_ONE_SHOT_RETAINED_TOOL_EXCHANGES,
198        }
199    }
200}
201
202/// Soft guidance, hard acceptance, and the preferred raw-history budget.
203///
204/// The install-time body target is not stored here. The runtime builds it from
205/// this hard ceiling plus the retained-history target and the fixed request body,
206/// rather than from half the body budget.
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub struct ResolvedCitationCompactionBudget {
209    target_output_tokens: u64,
210    retained_history_token_target: u64,
211    output_token_limit: u64,
212    max_accepted_output_bytes: usize,
213}
214
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub(crate) struct CitationCompactionInputPolicy {
217    pub(super) resolved_budget: ResolvedCitationCompactionBudget,
218}
219
220impl CitationCompactionInputPolicy {
221    pub(crate) const fn new(
222        _policy: CitationCompactionPolicy,
223        resolved_budget: ResolvedCitationCompactionBudget,
224    ) -> Self {
225        Self { resolved_budget }
226    }
227}
228
229impl ResolvedCitationCompactionBudget {
230    /// Preferred retained-history size, independent of summary and reasoning limits.
231    pub(crate) const fn retained_history_token_target(self) -> u64 {
232        self.retained_history_token_target
233    }
234
235    /// Prompt guidance written into the compaction instruction.
236    /// Exceeding it is allowed within [`Self::output_token_limit`].
237    #[must_use]
238    pub fn target_output_tokens(self) -> u64 {
239        self.target_output_tokens
240    }
241
242    #[must_use]
243    /// Hard rendered-summary ceiling, including restored keep entries and framing.
244    /// Crossing it repairs; staying under it installs without another model call.
245    pub fn output_token_limit(self) -> u64 {
246        self.output_token_limit
247    }
248
249    #[must_use]
250    /// Maximum accepted candidate JSON size in bytes.
251    pub fn max_accepted_output_bytes(self) -> usize {
252        self.max_accepted_output_bytes
253    }
254}