Skip to main content

gadk_session/compaction/
config.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! [`Config`] and [`Config::validate`].
17
18use std::sync::Arc;
19
20use super::Summarizer;
21
22/// Configures context compaction for an application.
23///
24/// At least one strategy must be enabled; a `Config` that enables neither is rejected by
25/// [`Config::validate`]. Use `None` (`Option<Config>`) to disable compaction.
26///
27/// - Sliding window (`compaction_interval`, `overlap_size`) runs after an invocation completes and
28///   summarizes whole invocations at a time.
29/// - Tail retention (`token_threshold`, `event_retention_size`) runs inside an invocation before a
30///   model call and summarizes everything but the most recent events once the prompt grows past a
31///   token budget.
32///
33/// Both can be enabled at once and they compose, but the sliding window consumes the events tail
34/// retention would otherwise summarize: tail retention only fires when more events accumulate
35/// between windows than `event_retention_size` holds back.
36#[derive(Clone, Default)]
37pub struct Config {
38    /// Number of new user-initiated invocations that triggers a sliding-window compaction; also
39    /// the most invocations one compaction covers. Zero disables sliding-window compaction.
40    pub compaction_interval: i32,
41    /// How many already-compacted invocations to pull back into the next sliding window, for
42    /// continuity between summaries. Only meaningful alongside `compaction_interval`.
43    pub overlap_size: i32,
44    /// Prompt token count at which tail-retention compaction fires before a model call. Zero
45    /// disables tail-retention compaction. Summaries produced by this strategy do not pass
46    /// through the plugin pipeline.
47    pub token_threshold: i32,
48    /// How many of the most recent events are kept raw when tail retention fires. Required with
49    /// `token_threshold`.
50    pub event_retention_size: i32,
51    /// Produces the summary content. When `None`, the runner supplies an `LlmSummarizer` backed by
52    /// the root agent's model, which therefore has to be an LLM agent.
53    pub summarizer: Option<Arc<dyn Summarizer>>,
54}
55
56impl std::fmt::Debug for Config {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("Config")
59            .field("compaction_interval", &self.compaction_interval)
60            .field("overlap_size", &self.overlap_size)
61            .field("token_threshold", &self.token_threshold)
62            .field("event_retention_size", &self.event_retention_size)
63            .field(
64                "summarizer",
65                &self.summarizer.as_ref().map(|s| s.type_name()),
66            )
67            .finish()
68    }
69}
70
71/// An unusable compaction configuration; the message says which setting is wrong.
72#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
73#[error("{message}")]
74pub struct CompactionConfigError {
75    message: String,
76}
77
78impl CompactionConfigError {
79    /// An error carrying `message` verbatim.
80    pub fn new(message: impl Into<String>) -> Self {
81        Self {
82            message: message.into(),
83        }
84    }
85
86    /// The error text.
87    pub fn message(&self) -> &str {
88        &self.message
89    }
90}
91
92impl Config {
93    fn has_sliding_window(&self) -> bool {
94        self.compaction_interval > 0
95    }
96
97    fn has_tail_retention(&self) -> bool {
98        self.token_threshold > 0
99    }
100
101    /// Reports whether the configuration is usable: the checks run in a fixed order and each has
102    /// its own error text. A config with no strategy enabled is an error; `None` already
103    /// expresses "disabled".
104    pub fn validate(&self) -> Result<(), CompactionConfigError> {
105        let err = |m: String| Err(CompactionConfigError::new(m));
106        if self.compaction_interval < 0 {
107            return err(format!(
108                "compaction_interval must not be negative, got {}",
109                self.compaction_interval
110            ));
111        }
112        if self.overlap_size < 0 {
113            return err(format!(
114                "overlap_size must not be negative, got {}",
115                self.overlap_size
116            ));
117        }
118        if self.token_threshold < 0 {
119            return err(format!(
120                "token_threshold must not be negative, got {}",
121                self.token_threshold
122            ));
123        }
124        if self.event_retention_size < 0 {
125            return err(format!(
126                "event_retention_size must not be negative, got {}",
127                self.event_retention_size
128            ));
129        }
130        if self.overlap_size > 0 && self.compaction_interval == 0 {
131            return err(format!(
132                "overlap_size is set to {} but compaction_interval is 0, so sliding-window compaction never runs",
133                self.overlap_size
134            ));
135        }
136        if self.token_threshold > 0 && self.event_retention_size == 0 {
137            return err(format!(
138                "token_threshold is set to {} but event_retention_size is 0, so a compaction would summarize the whole conversation including the turn being answered",
139                self.token_threshold
140            ));
141        }
142        if self.event_retention_size > 0 && self.token_threshold == 0 {
143            return err(format!(
144                "event_retention_size is set to {} but token_threshold is 0, so tail-retention compaction never runs",
145                self.event_retention_size
146            ));
147        }
148        if !self.has_sliding_window() && !self.has_tail_retention() {
149            return err(
150                "no compaction strategy is enabled, set compaction_interval or token_threshold (or leave the compaction config as None to disable compaction)"
151                    .to_string(),
152            );
153        }
154        Ok(())
155    }
156}
157
158#[cfg(test)]
159#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
160mod tests {
161    use super::*;
162    use crate::Event;
163    use crate::compaction::SummarizeResult;
164
165    struct Decliner;
166
167    #[async_trait::async_trait]
168    impl Summarizer for Decliner {
169        async fn summarize_events(
170            &self,
171            _events: &[Event],
172        ) -> Result<SummarizeResult, Box<dyn std::error::Error + Send + Sync>> {
173            Ok(SummarizeResult::default())
174        }
175    }
176
177    fn cfg(interval: i32, overlap: i32, threshold: i32, retention: i32) -> Config {
178        Config {
179            compaction_interval: interval,
180            overlap_size: overlap,
181            token_threshold: threshold,
182            event_retention_size: retention,
183            summarizer: None,
184        }
185    }
186
187    #[test]
188    fn validate_messages_are_go_texts() {
189        let cases = [
190            (
191                cfg(-1, 0, 0, 0),
192                "compaction_interval must not be negative, got -1",
193            ),
194            (
195                cfg(2, -2, 0, 0),
196                "overlap_size must not be negative, got -2",
197            ),
198            (
199                cfg(2, 0, -3, 0),
200                "token_threshold must not be negative, got -3",
201            ),
202            (
203                cfg(2, 0, 0, -4),
204                "event_retention_size must not be negative, got -4",
205            ),
206            (
207                cfg(0, 1, 0, 0),
208                "overlap_size is set to 1 but compaction_interval is 0, so sliding-window compaction never runs",
209            ),
210            (
211                cfg(0, 0, 100, 0),
212                "token_threshold is set to 100 but event_retention_size is 0, so a compaction would summarize the whole conversation including the turn being answered",
213            ),
214            (
215                cfg(0, 0, 0, 5),
216                "event_retention_size is set to 5 but token_threshold is 0, so tail-retention compaction never runs",
217            ),
218            (
219                cfg(0, 0, 0, 0),
220                "no compaction strategy is enabled, set compaction_interval or token_threshold (or leave the compaction config as None to disable compaction)",
221            ),
222        ];
223        for (c, want) in cases {
224            let got = c.validate().unwrap_err();
225            assert_eq!(got.message(), want, "{c:?}");
226            assert_eq!(got.to_string(), want, "{c:?}");
227        }
228    }
229
230    #[test]
231    fn validate_checks_in_go_order() {
232        // Every check fails: the first one (CompactionInterval) is reported.
233        assert_eq!(
234            cfg(-1, -2, -3, -4).validate().unwrap_err().message(),
235            "compaction_interval must not be negative, got -1"
236        );
237        // Negative checks come before the pairing checks.
238        assert_eq!(
239            cfg(0, -2, 100, 0).validate().unwrap_err().message(),
240            "overlap_size must not be negative, got -2"
241        );
242        assert_eq!(
243            cfg(0, 1, -3, 0).validate().unwrap_err().message(),
244            "token_threshold must not be negative, got -3"
245        );
246        assert_eq!(
247            cfg(0, 1, 0, -4).validate().unwrap_err().message(),
248            "event_retention_size must not be negative, got -4"
249        );
250        // OverlapSize pairing before TokenThreshold pairing, before EventRetentionSize pairing.
251        assert_eq!(
252            cfg(0, 1, 100, 0).validate().unwrap_err().message(),
253            "overlap_size is set to 1 but compaction_interval is 0, so sliding-window compaction never runs"
254        );
255        assert_eq!(
256            cfg(2, 0, 100, 0).validate().unwrap_err().message(),
257            "token_threshold is set to 100 but event_retention_size is 0, so a compaction would summarize the whole conversation including the turn being answered"
258        );
259    }
260
261    #[test]
262    fn validate_accepts_each_strategy_and_both() {
263        assert_eq!(cfg(2, 1, 0, 0).validate(), Ok(()));
264        assert_eq!(cfg(3, 0, 0, 0).validate(), Ok(()));
265        assert_eq!(cfg(0, 0, 100, 5).validate(), Ok(()));
266        assert_eq!(cfg(2, 1, 100, 5).validate(), Ok(()));
267    }
268
269    #[test]
270    fn config_debug_names_the_summarizer() {
271        let mut c = cfg(2, 1, 0, 0);
272        assert_eq!(
273            format!("{c:?}"),
274            "Config { compaction_interval: 2, overlap_size: 1, token_threshold: 0, event_retention_size: 0, summarizer: None }"
275        );
276        c.summarizer = Some(Arc::new(Decliner));
277        assert_eq!(
278            format!("{c:?}"),
279            "Config { compaction_interval: 2, overlap_size: 1, token_threshold: 0, event_retention_size: 0, summarizer: Some(\"Decliner\") }"
280        );
281    }
282
283    #[test]
284    fn config_default_and_clone() {
285        let d = Config::default();
286        assert_eq!(
287            (
288                d.compaction_interval,
289                d.overlap_size,
290                d.token_threshold,
291                d.event_retention_size
292            ),
293            (0, 0, 0, 0)
294        );
295        assert!(d.summarizer.is_none());
296        let c = Config {
297            summarizer: Some(Arc::new(Decliner)),
298            ..cfg(2, 0, 0, 0)
299        };
300        let c2 = c.clone();
301        assert!(Arc::ptr_eq(
302            c.summarizer.as_ref().unwrap(),
303            c2.summarizer.as_ref().unwrap()
304        ));
305    }
306}