a2a_protocol_server/store/task_store/
history.rs1use a2a_protocol_types::message::Message;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct HistoryLimit {
31 pub max_messages: usize,
33 pub max_bytes: usize,
36}
37
38impl HistoryLimit {
39 #[must_use]
41 pub const fn new(max_messages: usize, max_bytes: usize) -> Self {
42 Self {
43 max_messages,
44 max_bytes,
45 }
46 }
47
48 pub fn trim(self, history: &mut Vec<Message>) {
66 let _dropped = self.trim_returning(history);
67 }
68
69 pub(crate) fn trim_returning(self, history: &mut Vec<Message>) -> Vec<Message> {
73 let excess = history.len().saturating_sub(self.max_messages);
75 let mut dropped: Vec<Message> = history.drain(..excess).collect();
76 let bound = history
77 .iter()
78 .map(upper_bound_len)
79 .fold(0usize, usize::saturating_add);
80 if bound <= self.max_bytes {
81 return dropped;
82 }
83 let mut total = 0usize;
84 let mut keep_from = history.len();
85 for (i, message) in history.iter().enumerate().rev() {
86 let size = serialized_len(message);
87 let newest = i + 1 == history.len();
88 if !newest && total.saturating_add(size) > self.max_bytes {
89 break;
90 }
91 total = total.saturating_add(size);
92 keep_from = i;
93 }
94 dropped.extend(history.drain(..keep_from));
95 dropped
96 }
97}
98
99const MESSAGE_OVERHEAD: usize = 256;
104
105const PART_OVERHEAD: usize = 96;
109
110fn upper_bound_len(message: &Message) -> usize {
116 let mut n = MESSAGE_OVERHEAD
117 .saturating_add(str_bound(&message.id.0))
118 .saturating_add(message.context_id.as_ref().map_or(0, |c| str_bound(&c.0)))
119 .saturating_add(message.task_id.as_ref().map_or(0, |t| str_bound(&t.0)))
120 .saturating_add(message.metadata.as_ref().map_or(0, value_bound));
121 for uri in message.extensions.iter().flatten() {
122 n = n.saturating_add(str_bound(uri)).saturating_add(1);
123 }
124 for id in message.reference_task_ids.iter().flatten() {
125 n = n.saturating_add(str_bound(&id.0)).saturating_add(1);
126 }
127 for part in &message.parts {
128 n = n.saturating_add(part_bound(part)).saturating_add(1);
129 }
130 n
131}
132
133fn part_bound(part: &a2a_protocol_types::message::Part) -> usize {
134 use a2a_protocol_types::message::PartContent;
135 let content = match &part.content {
136 PartContent::Text(s) | PartContent::Raw(s) | PartContent::Url(s) => str_bound(s),
137 PartContent::Data(v) => value_bound(v),
138 other => serde_json::to_vec(other).map_or(usize::MAX, |v| v.len()),
140 };
141 PART_OVERHEAD
142 .saturating_add(content)
143 .saturating_add(part.metadata.as_ref().map_or(0, value_bound))
144 .saturating_add(part.filename.as_deref().map_or(0, str_bound))
145 .saturating_add(part.media_type.as_deref().map_or(0, str_bound))
146}
147
148const fn str_bound(s: &str) -> usize {
149 s.len().saturating_mul(6).saturating_add(2)
150}
151
152fn value_bound(value: &serde_json::Value) -> usize {
153 use serde_json::Value;
154 match value {
155 Value::Null | Value::Bool(_) => 5,
156 Value::Number(n) => n.to_string().len(),
157 Value::String(s) => str_bound(s),
158 Value::Array(items) => items
159 .iter()
160 .map(|v| value_bound(v).saturating_add(1))
161 .fold(2, usize::saturating_add),
162 Value::Object(map) => map
163 .iter()
164 .map(|(k, v)| {
165 str_bound(k)
166 .saturating_add(value_bound(v))
167 .saturating_add(2)
168 })
169 .fold(2, usize::saturating_add),
170 }
171}
172
173fn serialized_len(message: &Message) -> usize {
177 struct Count(usize);
178 impl std::io::Write for Count {
179 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
180 self.0 += buf.len();
181 Ok(buf.len())
182 }
183 fn flush(&mut self) -> std::io::Result<()> {
184 Ok(())
185 }
186 }
187 let mut count = Count(0);
188 match serde_json::to_writer(&mut count, message) {
189 Ok(()) => count.0,
190 Err(_) => usize::MAX,
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 fn message(id: &str, text_len: usize) -> Message {
199 Message::user_text(id, "x".repeat(text_len))
200 }
201
202 fn ids(history: &[Message]) -> Vec<&str> {
203 history.iter().map(|m| m.id.0.as_str()).collect()
204 }
205
206 #[test]
207 fn the_count_drops_the_oldest() {
208 let mut h: Vec<_> = (0..5).map(|i| message(&format!("m{i}"), 1)).collect();
209 HistoryLimit::new(3, usize::MAX).trim(&mut h);
210 assert_eq!(ids(&h), ["m2", "m3", "m4"]);
211 }
212
213 #[test]
216 fn the_bytes_drop_the_oldest_at_the_exact_bound() {
217 let h: Vec<_> = (0..3).map(|i| message(&format!("m{i}"), 100)).collect();
218 let each = serialized_len(&h[0]);
219 assert!(h.iter().all(|m| serialized_len(m) == each));
220
221 let mut at = h.clone();
222 HistoryLimit::new(10, 3 * each).trim(&mut at);
223 assert_eq!(ids(&at), ["m0", "m1", "m2"]);
224
225 let mut under = h;
226 HistoryLimit::new(10, 3 * each - 1).trim(&mut under);
227 assert_eq!(ids(&under), ["m1", "m2"]);
228 }
229
230 #[test]
232 fn the_newest_message_is_kept_whatever_its_size() {
233 let mut h = vec![message("old", 10), message("huge", 10_000)];
234 HistoryLimit::new(10, 100).trim(&mut h);
235 assert_eq!(ids(&h), ["huge"]);
236 }
237
238 #[test]
241 fn no_gap_is_left_behind_a_message_that_did_not_fit() {
242 let mut h = vec![
243 message("small-old", 1),
244 message("big", 500),
245 message("new", 1),
246 ];
247 let budget = serialized_len(&h[2]) + serialized_len(&h[0]) + 10;
248 HistoryLimit::new(10, budget).trim(&mut h);
249 assert_eq!(ids(&h), ["new"]);
250 }
251
252 #[test]
255 fn trim_returning_hands_back_exactly_what_it_dropped() {
256 let original: Vec<_> = (0..6).map(|i| message(&format!("m{i}"), 50)).collect();
257 let each = serialized_len(&original[0]);
258 let mut kept = original.clone();
259 let dropped = HistoryLimit::new(5, 2 * each).trim_returning(&mut kept);
260 assert_eq!(ids(&kept), ["m4", "m5"]);
261 assert_eq!(ids(&dropped), ["m0", "m1", "m2", "m3"]);
262 let mut restored = dropped;
263 restored.extend(kept);
264 assert_eq!(restored, original);
265 }
266
267 #[test]
268 fn an_empty_history_stays_empty() {
269 let mut h = Vec::new();
270 HistoryLimit::new(1, 1).trim(&mut h);
271 assert_eq!(h, Vec::<Message>::new());
272 }
273
274 struct Gen(u64);
277
278 impl Gen {
279 fn next(&mut self) -> u64 {
280 self.0 ^= self.0 << 13;
281 self.0 ^= self.0 >> 7;
282 self.0 ^= self.0 << 17;
283 self.0
284 }
285
286 fn below(&mut self, n: u64) -> usize {
287 usize::try_from(self.next() % n).expect("small")
288 }
289
290 fn coin(&mut self) -> bool {
291 self.next().is_multiple_of(2)
292 }
293
294 fn string(&mut self) -> String {
297 let alphabet: Vec<char> = "a\"\\\u{1}\u{1f}\n\t/é😀\u{7f}<>&'".chars().collect();
298 (0..self.below(24))
299 .map(|_| alphabet[self.below(alphabet.len() as u64)])
300 .collect()
301 }
302
303 fn value(&mut self, depth: u32) -> serde_json::Value {
304 use serde_json::{Value, json};
305 match self.below(if depth > 2 { 6 } else { 8 }) {
306 0 => Value::Null,
307 1 => Value::Bool(self.coin()),
308 2 => json!(self.next().cast_signed()),
309 3 => json!(f64::from_bits(self.next() >> 2).clamp(-1e300, 1e300)),
310 4 => json!(self.next()),
311 5 => Value::String(self.string()),
312 6 => Value::Array((0..self.below(4)).map(|_| self.value(depth + 1)).collect()),
313 _ => Value::Object(
314 (0..self.below(4))
315 .map(|_| (self.string(), self.value(depth + 1)))
316 .collect(),
317 ),
318 }
319 }
320
321 fn part(&mut self) -> a2a_protocol_types::message::Part {
322 use a2a_protocol_types::message::{Part, PartContent};
323 let mut part = Part::text("");
324 part.content = match self.below(4) {
325 0 => PartContent::Text(self.string()),
326 1 => PartContent::Raw(self.string()),
327 2 => PartContent::Url(self.string()),
328 _ => PartContent::Data(self.value(0)),
329 };
330 part.metadata = self.coin().then(|| self.value(0));
331 part.filename = self.coin().then(|| self.string());
332 part.media_type = self.coin().then(|| self.string());
333 part
334 }
335
336 fn message(&mut self) -> Message {
337 use a2a_protocol_types::message::{MessageId, MessageRole};
338 use a2a_protocol_types::task::{ContextId, TaskId};
339 {
340 let mut built = Message::new(
341 MessageId::new(self.string()),
342 if self.coin() {
343 MessageRole::User
344 } else {
345 MessageRole::Agent
346 },
347 (0..=self.below(3)).map(|_| self.part()).collect(),
348 );
349 built.context_id = self.coin().then(|| ContextId::new(self.string()));
350 built.task_id = self.coin().then(|| TaskId::new(self.string()));
351 built.reference_task_ids = self.coin().then(|| {
352 (0..self.below(3))
353 .map(|_| TaskId::new(self.string()))
354 .collect()
355 });
356 built.extensions = self
357 .coin()
358 .then(|| (0..self.below(3)).map(|_| self.string()).collect());
359 built.metadata = self.coin().then(|| self.value(0));
360 built
361 }
362 }
363 }
364
365 #[test]
371 fn the_upper_bound_is_never_below_the_exact_length() {
372 let mut generate = Gen(0x9E37_79B9_7F4A_7C15);
373 for _ in 0..5_000 {
374 let message = generate.message();
375 let exact = serde_json::to_vec(&message).unwrap().len();
376 assert_eq!(serialized_len(&message), exact);
377 assert!(
378 upper_bound_len(&message) >= exact,
379 "bound {} below exact {exact} for {message:?}",
380 upper_bound_len(&message)
381 );
382 }
383 }
384
385 #[test]
390 fn the_upper_bound_holds_for_worst_case_escapes() {
391 use a2a_protocol_types::message::{MessageId, MessageRole, Part, PartContent};
392 use a2a_protocol_types::task::{ContextId, TaskId};
393 let worst = "\u{1}".repeat(4_000);
394 let mut data_part = Part::text("");
395 data_part.content = PartContent::Data(serde_json::json!({ &worst: [&worst] }));
396 data_part.metadata = Some(serde_json::json!(worst));
397 data_part.filename = Some(worst.clone());
398 data_part.media_type = Some(worst.clone());
399 let cases = [
400 Message::user_text(worst.clone(), worst.clone()),
401 Message::new(MessageId::new("m"), MessageRole::Agent, vec![data_part])
402 .with_context_id(ContextId::new(worst.clone()))
403 .with_task_id(TaskId::new(worst.clone()))
404 .with_reference_task_ids(vec![TaskId::new(worst.clone())])
405 .with_extensions(vec![worst.clone()])
406 .with_metadata(serde_json::json!({ "k": worst })),
407 ];
408 for message in &cases {
409 let exact = serde_json::to_vec(message).unwrap().len();
410 assert!(
411 upper_bound_len(message) >= exact,
412 "{} < {exact}",
413 upper_bound_len(message)
414 );
415 }
416 }
417
418 #[test]
422 fn a_history_within_budget_only_exactly_is_kept_whole() {
423 let h: Vec<_> = (0..4).map(|i| message(&format!("m{i}"), 100)).collect();
424 let exact: usize = h.iter().map(serialized_len).sum();
425 let bound: usize = h.iter().map(upper_bound_len).sum();
426 assert!(bound > exact);
427 let mut kept = h.clone();
428 HistoryLimit::new(10, exact).trim(&mut kept);
429 assert_eq!(kept, h);
430 }
431
432 #[test]
433 fn serialized_len_is_the_json_length() {
434 let m = message("m", 7);
435 assert_eq!(serialized_len(&m), serde_json::to_vec(&m).unwrap().len());
436 }
437}