1use 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("compaction trigger_threshold_percent {percent} must be between 1 and 100")]
17 InvalidTriggerThresholdPercent { percent: u8 },
18
19 #[error("compaction prompt {field} must not be blank")]
20 EmptyPromptField { field: &'static str },
21
22 #[error("summary budget {summary_tokens} exceeds compactor output limit {model_limit_tokens}")]
23 OutputBudgetExceedsModelLimit {
24 summary_tokens: u64,
26 model_limit_tokens: u64,
28 },
29
30 #[error("compaction budget arithmetic overflowed")]
31 BudgetOverflow,
32
33 #[error("cannot compact while pending tool calls exist")]
34 PendingToolCalls,
35
36 #[error("no compressible history exists before retained model turns")]
37 NoCompressibleWindow,
38
39 #[error("no compaction window fits the compaction request budget")]
40 NoWindowFitsCompactionRequest,
41
42 #[error(
43 "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"
44 )]
45 ConvergenceExhausted {
46 passes: usize,
47 estimated_tokens: u64,
48 body_budget_tokens: u64,
49 },
50
51 #[error("compaction payload serialization failed: {message}")]
52 PayloadSerialization { message: String },
53
54 #[error("compaction window is stale")]
55 StaleWindow,
56
57 #[error(
58 "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"
59 )]
60 UncompressibleCurrentInput {
61 estimated_tokens: u64,
62 limit_tokens: u64,
63 },
64
65 #[error(
66 "the newest completed turn cannot fit under the {limit_tokens} token context limit. Compaction cannot keep a smaller raw turn. Raise the context window"
67 )]
68 MinimumRawTurnCannotFit { limit_tokens: u64 },
69
70 #[error("compaction model response shape is invalid: {reason}")]
71 InvalidModelResponseShape { reason: &'static str },
72}
73
74#[path = "compaction/summary.rs"]
75mod summary;
76#[path = "compaction/window.rs"]
77mod window;
78
79#[path = "compaction/runner.rs"]
80mod runner;
81
82pub(crate) use runner::{
83 compaction_model_window, compaction_request_required_tokens,
84 generate_validated_compaction_candidate, validate_compaction_model_window,
85};
86pub use summary::{CompactionPrompt, citation_compaction_tail_directive};
87
88mod budget;
89mod policy;
90mod request;
91pub(crate) use budget::{
92 CompactionReasoningReserve, compaction_window_safety_tokens, tightened_covered_budget,
93};
94pub(crate) use policy::CitationCompactionInputPolicy;
95pub use policy::{CitationCompactionPolicy, ResolvedCitationCompactionBudget};
96pub(crate) use request::{
97 CompactionRequestMode, CompactionRequestProjection, CompactionRequestSource,
98 compile_citation_compaction_model_request,
99};
100pub(crate) use summary::{
101 citation_compaction_tail_directive_with_prompt, format_compact_summary, format_continuation,
102 is_degenerate_summary,
103};
104
105pub(crate) use window::{
106 ArchiveOnlyCompactionInput, CitationCompactionModelTurn, CitationCompactionToolResult,
107 CitationCompactionTurnItem, CompactionCoverageBudget, CompactionShape, CompactionWindowBudget,
108 CompactionWindowFingerprint, CompactionWindowPlan, RetainedFit, retained_turn_fallbacks,
109};
110
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct CompactionOutcome {
113 checkpoint_id: CheckpointId,
114 covered_model_turn_count: usize,
115 covered_history_item_count: usize,
116 retained_history_item_count: usize,
117}
118
119impl CompactionOutcome {
120 pub(crate) fn followed_by(self, next: Self) -> Result<Self, CompactionError> {
122 Ok(Self {
123 covered_model_turn_count: self
124 .covered_model_turn_count
125 .checked_add(next.covered_model_turn_count)
126 .ok_or(CompactionError::BudgetOverflow)?,
127 covered_history_item_count: self
128 .covered_history_item_count
129 .checked_add(next.covered_history_item_count)
130 .ok_or(CompactionError::BudgetOverflow)?,
131 ..next
132 })
133 }
134
135 pub(crate) fn new(
136 checkpoint_id: CheckpointId,
137 covered_model_turn_count: usize,
138 covered_history_item_count: usize,
139 retained_history_item_count: usize,
140 ) -> Self {
141 Self {
142 checkpoint_id,
143 covered_model_turn_count,
144 covered_history_item_count,
145 retained_history_item_count,
146 }
147 }
148
149 #[must_use]
150 pub fn checkpoint_id(&self) -> &CheckpointId {
151 &self.checkpoint_id
152 }
153
154 #[must_use]
156 pub fn covered_model_turn_count(&self) -> usize {
157 self.covered_model_turn_count
158 }
159
160 #[must_use]
161 pub fn covered_history_item_count(&self) -> usize {
162 self.covered_history_item_count
163 }
164
165 #[must_use]
166 pub fn retained_history_item_count(&self) -> usize {
167 self.retained_history_item_count
168 }
169}
170
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct CitationCompactionInput {
173 window: Vec<CitationCompactionModelTurn>,
174 manifest: CheckpointRefManifest,
175 covered_history_ids: BTreeSet<u64>,
176 task_anchor_snapshot: Option<TaskAnchor>,
177 window_plan: CompactionWindowPlan,
178 archived_refs: Vec<CheckpointRef>,
179 resolved_budget: ResolvedCitationCompactionBudget,
180}
181
182pub(crate) struct CitationCompactionInputParts {
183 pub(crate) input_policy: CitationCompactionInputPolicy,
184 pub(crate) task_anchor_snapshot: Option<TaskAnchor>,
185 pub(crate) manifest: CheckpointRefManifest,
186}
187
188pub(crate) struct CitationCompactionWindowBundle {
189 pub(crate) covered_history_ids: BTreeSet<u64>,
190 pub(crate) window: Vec<CitationCompactionModelTurn>,
191 pub(crate) window_plan: CompactionWindowPlan,
192 pub(crate) archived_refs: Vec<CheckpointRef>,
193}
194
195impl CitationCompactionInput {
196 pub(crate) fn new(
197 parts: CitationCompactionInputParts,
198 window_bundle: CitationCompactionWindowBundle,
199 ) -> Self {
200 let CitationCompactionInputParts {
201 input_policy,
202 task_anchor_snapshot,
203 manifest,
204 } = parts;
205 let CitationCompactionWindowBundle {
206 covered_history_ids,
207 window,
208 window_plan,
209 archived_refs,
210 } = window_bundle;
211 let CitationCompactionInputPolicy { resolved_budget } = input_policy;
212
213 Self {
214 window,
215 manifest,
216 covered_history_ids,
217 task_anchor_snapshot,
218 window_plan,
219 archived_refs,
220 resolved_budget,
221 }
222 }
223
224 pub(crate) fn payload_tool_exchange_count(&self) -> usize {
226 self.window
227 .iter()
228 .map(CitationCompactionModelTurn::tool_exchange_count)
229 .sum()
230 }
231
232 pub(crate) fn covered_payload_token_estimate(&self) -> Result<u64, CompactionError> {
238 Ok(estimate_text_tokens(&self.render_covered_segment()))
239 }
240
241 #[must_use]
242 pub fn manifest(&self) -> &CheckpointRefManifest {
243 &self.manifest
244 }
245
246 #[cfg(test)]
248 #[must_use]
249 pub(crate) fn covered_window(&self) -> &[CitationCompactionModelTurn] {
250 &self.window
251 }
252
253 #[must_use]
255 pub fn render_covered_segment(&self) -> String {
256 self.window
257 .iter()
258 .map(CitationCompactionModelTurn::render_markdown)
259 .collect::<Vec<_>>()
260 .join("\n\n")
261 }
262
263 #[must_use]
264 pub fn covered_history_ids(&self) -> &BTreeSet<u64> {
265 &self.covered_history_ids
266 }
267
268 #[must_use]
269 pub fn task_anchor_snapshot(&self) -> Option<&TaskAnchor> {
270 self.task_anchor_snapshot.as_ref()
271 }
272
273 #[must_use]
274 pub fn resolved_budget(&self) -> ResolvedCitationCompactionBudget {
275 self.resolved_budget
276 }
277
278 pub(crate) fn window_plan(&self) -> &CompactionWindowPlan {
279 &self.window_plan
280 }
281
282 pub(crate) fn archived_refs(&self) -> &[CheckpointRef] {
283 &self.archived_refs
284 }
285}
286
287#[derive(Debug, Clone, PartialEq, Eq)]
288pub(crate) enum CompactionPreparation {
289 ReplaceCheckpoint(Box<CitationCompactionInput>),
290 ArchiveToolResults(ArchiveOnlyCompactionInput),
291}
292
293pub(crate) fn bounded_excerpt(text: &str, max_bytes: usize) -> String {
294 if text.len() <= max_bytes {
295 return text.to_owned();
296 }
297
298 let mut end = max_bytes;
299 while !text.is_char_boundary(end) {
300 end -= 1;
301 }
302 format!("{}...[truncated]", &text[..end])
303}
304
305#[cfg(test)]
306#[path = "compaction/budget_tests.rs"]
307mod budget_tests;
308
309#[cfg(test)]
310mod tests;