1use std::sync::Arc;
19
20use super::Summarizer;
21
22#[derive(Clone, Default)]
37pub struct Config {
38 pub compaction_interval: i32,
41 pub overlap_size: i32,
44 pub token_threshold: i32,
48 pub event_retention_size: i32,
51 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
73#[error("{message}")]
74pub struct CompactionConfigError {
75 message: String,
76}
77
78impl CompactionConfigError {
79 pub fn new(message: impl Into<String>) -> Self {
81 Self {
82 message: message.into(),
83 }
84 }
85
86 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 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 assert_eq!(
234 cfg(-1, -2, -3, -4).validate().unwrap_err().message(),
235 "compaction_interval must not be negative, got -1"
236 );
237 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 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}