Skip to main content

merry_runtime/
compaction.rs

1//! Citation-backed checkpoint compaction input construction.
2
3use crate::{
4    checkpoint::{CheckpointId, CheckpointRef, CheckpointRefManifest},
5    context::TaskAnchor,
6    token_estimate::estimate_text_tokens,
7};
8use std::collections::BTreeSet;
9use thiserror::Error;
10
11#[derive(Debug, Error, Clone, PartialEq, Eq)]
12pub enum CompactionError {
13    #[error("compaction policy field {field} must be greater than zero")]
14    InvalidPolicy { field: &'static str },
15
16    #[error("summary budget {summary_tokens} exceeds compactor output limit {model_limit_tokens}")]
17    OutputBudgetExceedsModelLimit {
18        /// Rendered summary ceiling the runtime asked for.
19        summary_tokens: u64,
20        /// Maximum output tokens the compaction model declared.
21        model_limit_tokens: u64,
22    },
23
24    #[error("compaction budget arithmetic overflowed")]
25    BudgetOverflow,
26
27    #[error("cannot compact while pending tool calls exist")]
28    PendingToolCalls,
29
30    #[error("no compressible history exists before retained model turns")]
31    NoCompressibleWindow,
32
33    #[error("no compaction window fits the compaction request budget")]
34    NoWindowFitsCompactionRequest,
35
36    #[error(
37        "compaction ran {passes} times and the request is still about {estimated_tokens} tokens, above the {body_budget_tokens} token body budget. Raise the context window, or shorten the fixed prompt and the current request"
38    )]
39    ConvergenceExhausted {
40        passes: usize,
41        estimated_tokens: u64,
42        body_budget_tokens: u64,
43    },
44
45    #[error("compaction payload serialization failed: {message}")]
46    PayloadSerialization { message: String },
47
48    #[error("compaction window is stale")]
49    StaleWindow,
50
51    #[error(
52        "this turn cannot fit in the context window: it is about {estimated_tokens} tokens and the limit is {limit_tokens}. Compaction cannot shrink the fixed prompt or this turn. Raise the context window, or send a shorter request"
53    )]
54    UncompressibleCurrentInput {
55        estimated_tokens: u64,
56        limit_tokens: u64,
57    },
58
59    #[error(
60        "the newest completed turn cannot fit under the {limit_tokens} token context limit. Compaction cannot keep a smaller raw turn. Raise the context window"
61    )]
62    MinimumRawTurnCannotFit { limit_tokens: u64 },
63
64    #[error("compaction model response shape is invalid: {reason}")]
65    InvalidModelResponseShape { reason: &'static str },
66}
67
68#[path = "compaction/summary.rs"]
69mod summary;
70#[path = "compaction/window.rs"]
71mod window;
72
73#[path = "compaction/runner.rs"]
74mod runner;
75
76pub(crate) use runner::{
77    compaction_model_window, compaction_request_required_tokens,
78    generate_validated_compaction_candidate, validate_compaction_model_window,
79};
80pub use summary::citation_compaction_tail_directive;
81
82mod budget;
83mod policy;
84mod request;
85pub(crate) use budget::{
86    CompactionReasoningReserve, compaction_window_safety_tokens, tightened_covered_budget,
87};
88pub(crate) use policy::CitationCompactionInputPolicy;
89pub use policy::{CitationCompactionPolicy, ResolvedCitationCompactionBudget};
90pub(crate) use request::{
91    CompactionRequestMode, CompactionRequestProjection, CompactionRequestSource,
92    compile_citation_compaction_model_request,
93};
94pub(crate) use summary::{format_compact_summary, format_continuation, is_degenerate_summary};
95
96pub(crate) use window::{
97    ArchiveOnlyCompactionInput, CitationCompactionModelTurn, CitationCompactionToolResult,
98    CitationCompactionTurnItem, CompactionCoverageBudget, CompactionShape, CompactionWindowBudget,
99    CompactionWindowFingerprint, CompactionWindowPlan, RetainedFit, retained_turn_fallbacks,
100};
101
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct CompactionOutcome {
104    checkpoint_id: CheckpointId,
105    covered_model_turn_count: usize,
106    covered_history_item_count: usize,
107    retained_history_item_count: usize,
108}
109
110impl CompactionOutcome {
111    /// Aggregates rolling coverage while keeping the final checkpoint and retained tail.
112    pub(crate) fn followed_by(self, next: Self) -> Result<Self, CompactionError> {
113        Ok(Self {
114            covered_model_turn_count: self
115                .covered_model_turn_count
116                .checked_add(next.covered_model_turn_count)
117                .ok_or(CompactionError::BudgetOverflow)?,
118            covered_history_item_count: self
119                .covered_history_item_count
120                .checked_add(next.covered_history_item_count)
121                .ok_or(CompactionError::BudgetOverflow)?,
122            ..next
123        })
124    }
125
126    pub(crate) fn new(
127        checkpoint_id: CheckpointId,
128        covered_model_turn_count: usize,
129        covered_history_item_count: usize,
130        retained_history_item_count: usize,
131    ) -> Self {
132        Self {
133            checkpoint_id,
134            covered_model_turn_count,
135            covered_history_item_count,
136            retained_history_item_count,
137        }
138    }
139
140    #[must_use]
141    pub fn checkpoint_id(&self) -> &CheckpointId {
142        &self.checkpoint_id
143    }
144
145    /// Number of model turns newly covered by this compaction.
146    #[must_use]
147    pub fn covered_model_turn_count(&self) -> usize {
148        self.covered_model_turn_count
149    }
150
151    #[must_use]
152    pub fn covered_history_item_count(&self) -> usize {
153        self.covered_history_item_count
154    }
155
156    #[must_use]
157    pub fn retained_history_item_count(&self) -> usize {
158        self.retained_history_item_count
159    }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct CitationCompactionInput {
164    window: Vec<CitationCompactionModelTurn>,
165    manifest: CheckpointRefManifest,
166    covered_history_ids: BTreeSet<u64>,
167    task_anchor_snapshot: Option<TaskAnchor>,
168    window_plan: CompactionWindowPlan,
169    archived_refs: Vec<CheckpointRef>,
170    resolved_budget: ResolvedCitationCompactionBudget,
171}
172
173pub(crate) struct CitationCompactionInputParts {
174    pub(crate) input_policy: CitationCompactionInputPolicy,
175    pub(crate) task_anchor_snapshot: Option<TaskAnchor>,
176    pub(crate) manifest: CheckpointRefManifest,
177}
178
179pub(crate) struct CitationCompactionWindowBundle {
180    pub(crate) covered_history_ids: BTreeSet<u64>,
181    pub(crate) window: Vec<CitationCompactionModelTurn>,
182    pub(crate) window_plan: CompactionWindowPlan,
183    pub(crate) archived_refs: Vec<CheckpointRef>,
184}
185
186impl CitationCompactionInput {
187    pub(crate) fn new(
188        parts: CitationCompactionInputParts,
189        window_bundle: CitationCompactionWindowBundle,
190    ) -> Self {
191        let CitationCompactionInputParts {
192            input_policy,
193            task_anchor_snapshot,
194            manifest,
195        } = parts;
196        let CitationCompactionWindowBundle {
197            covered_history_ids,
198            window,
199            window_plan,
200            archived_refs,
201        } = window_bundle;
202        let CitationCompactionInputPolicy { resolved_budget } = input_policy;
203
204        Self {
205            window,
206            manifest,
207            covered_history_ids,
208            task_anchor_snapshot,
209            window_plan,
210            archived_refs,
211            resolved_budget,
212        }
213    }
214
215    /// Bounds retention fitting by exchanges present, not an arbitrarily large configuration.
216    pub(crate) fn payload_tool_exchange_count(&self) -> usize {
217        self.window
218            .iter()
219            .map(CitationCompactionModelTurn::tool_exchange_count)
220            .sum()
221    }
222
223    /// Estimated tokens of the covered history the fallback request would send.
224    ///
225    /// The runtime uses this to decide how much covered history to give up when a
226    /// compaction request does not fit the compaction model window. It measures
227    /// the same markdown the payload-mode request shows the model.
228    pub(crate) fn covered_payload_token_estimate(&self) -> Result<u64, CompactionError> {
229        Ok(estimate_text_tokens(&self.render_covered_segment()))
230    }
231
232    #[must_use]
233    pub fn manifest(&self) -> &CheckpointRefManifest {
234        &self.manifest
235    }
236
237    /// Covered turns the summary request describes.
238    #[cfg(test)]
239    #[must_use]
240    pub(crate) fn covered_window(&self) -> &[CitationCompactionModelTurn] {
241        &self.window
242    }
243
244    /// Markdown of the covered turns used for payload-mode compaction requests and token estimation.
245    #[must_use]
246    pub fn render_covered_segment(&self) -> String {
247        self.window
248            .iter()
249            .map(CitationCompactionModelTurn::render_markdown)
250            .collect::<Vec<_>>()
251            .join("\n\n")
252    }
253
254    #[must_use]
255    pub fn covered_history_ids(&self) -> &BTreeSet<u64> {
256        &self.covered_history_ids
257    }
258
259    #[must_use]
260    pub fn task_anchor_snapshot(&self) -> Option<&TaskAnchor> {
261        self.task_anchor_snapshot.as_ref()
262    }
263
264    #[must_use]
265    pub fn resolved_budget(&self) -> ResolvedCitationCompactionBudget {
266        self.resolved_budget
267    }
268
269    pub(crate) fn window_plan(&self) -> &CompactionWindowPlan {
270        &self.window_plan
271    }
272
273    pub(crate) fn archived_refs(&self) -> &[CheckpointRef] {
274        &self.archived_refs
275    }
276}
277
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub(crate) enum CompactionPreparation {
280    ReplaceCheckpoint(Box<CitationCompactionInput>),
281    ArchiveToolResults(ArchiveOnlyCompactionInput),
282}
283
284pub(crate) fn bounded_excerpt(text: &str, max_bytes: usize) -> String {
285    if text.len() <= max_bytes {
286        return text.to_owned();
287    }
288
289    let mut end = max_bytes;
290    while !text.is_char_boundary(end) {
291        end -= 1;
292    }
293    format!("{}...[truncated]", &text[..end])
294}
295
296#[cfg(test)]
297#[path = "compaction/budget_tests.rs"]
298mod budget_tests;
299
300#[cfg(test)]
301mod tests;