Skip to main content

a2a_protocol_server/store/task_store/
history.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! How much of a conversation a task keeps: [`HistoryLimit`].
5//!
6//! One type and one [`trim`](HistoryLimit::trim), used by every place a
7//! history grows — a send's turn appended by the store, and an agent's
8//! messages appended by the event processors. There were four copies of a
9//! count-only trim, and none bounded bytes (release audit F2).
10
11use a2a_protocol_types::message::Message;
12
13/// The most a task's `history` keeps: a number of messages and a number of
14/// bytes, whichever is reached first. The oldest messages go first.
15///
16/// # Why bytes as well as messages
17///
18/// A count alone bounds nothing in bytes: at the default 4 MiB request body,
19/// 1,024 messages is 4 GiB of one task's history, all of it from remote
20/// input. Bytes are each message's serialized JSON length, the form it is
21/// sent and stored in.
22///
23/// # The newest message is always kept
24///
25/// A turn is never stored without the message that made it, so a message
26/// larger than `max_bytes` on its own is kept and everything older goes. The
27/// request body limit bounds that message.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct HistoryLimit {
31    /// At most this many messages.
32    pub max_messages: usize,
33    /// At most this many bytes of serialized messages; the newest message is
34    /// kept even when it alone is larger.
35    pub max_bytes: usize,
36}
37
38impl HistoryLimit {
39    /// A limit of `max_messages` messages and `max_bytes` bytes.
40    #[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    /// Drops the oldest messages of `history` until it is within this limit,
49    /// keeping the newest message whatever its size.
50    ///
51    /// A cheap upper bound on the history's size is taken first, from string
52    /// lengths and structure without serializing anything; when it is within
53    /// `max_bytes` nothing can need trimming and nothing is measured. Only
54    /// otherwise are sizes measured exactly, from the newest message
55    /// backwards, stopping at the first that does not fit, so that cost is
56    /// bounded by `max_bytes` (plus one message) however long the history
57    /// was.
58    ///
59    /// Measured 2026-10-18 (release build, 4-vCPU Xeon at 2.8 GHz, 60 runs
60    /// each, a timing harness not kept in the tree): 1,024 messages of 100
61    /// bytes, median 10.2 µs (p90 16.6) with the bound against 108 µs (p90
62    /// 149) for the exact walk alone, which every turn of a long conversation
63    /// would otherwise pay; a history of sixteen 1 MiB messages, which the
64    /// bound cannot clear, median 11.0 ms either way.
65    pub fn trim(self, history: &mut Vec<Message>) {
66        let _dropped = self.trim_returning(history);
67    }
68
69    /// [`trim`](Self::trim), returning the messages it dropped, oldest
70    /// first, so a caller whose write then fails can put the history back
71    /// exactly as it was. Allocates only when something is dropped.
72    pub(crate) fn trim_returning(self, history: &mut Vec<Message>) -> Vec<Message> {
73        // `drain(..0)` skips its memmove, so this is O(1) under the count.
74        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
99/// Room for a message's member names and punctuation: `{"messageId":`,
100/// `"contextId":`, `"taskId":`, `"role":"ROLE_UNSPECIFIED"`, `"parts":[]`,
101/// `"metadata":`, `"extensions":[]` and `"referenceTaskIds":[]` come to 131
102/// bytes; this leaves room to spare.
103const MESSAGE_OVERHEAD: usize = 256;
104
105/// Room for a part's member names and punctuation: `{"text":` (or `raw`,
106/// `url`, `data`), `"metadata":`, `"filename":`, `"mediaType":` and the
107/// separators come to 47 bytes.
108const PART_OVERHEAD: usize = 96;
109
110/// An upper bound on `message`'s serialized JSON length, from its structure
111/// and string lengths alone. Never below the exact length, which is what
112/// lets [`HistoryLimit::trim`] skip measuring: a JSON string is at most six
113/// bytes per byte of content (`\u001f`) plus its quotes; numbers are
114/// measured exactly; everything else is a fixed allowance per member.
115fn 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        // A variant added later is measured exactly rather than guessed at.
139        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
173/// `message`'s serialized JSON length, counted without allocating it. A
174/// message that cannot be serialized counts as too large to keep, so it is
175/// dropped rather than silently costing nothing.
176fn 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    /// Exactly at the byte bound everything stays; one byte under, the
214    /// oldest goes.
215    #[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    /// A newest message larger than the whole bound is kept, alone.
231    #[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    /// A message that does not fit stops the walk: an older, smaller one is
239    /// not kept around a gap.
240    #[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    /// What `trim_returning` hands back, put in front of what it kept, is
253    /// the history it was given.
254    #[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    /// A seeded xorshift generator: the cases are random in shape and the
275    /// same on every run.
276    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        /// Up to 24 characters from an alphabet of JSON's costliest escapes
295        /// (control characters, quotes, backslashes) and multi-byte text.
296        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    /// The fast path is sound only if the bound never falls below the
366    /// exact length. Checked over 5,000 generated messages that include the
367    /// worst escapes JSON has (control characters, quotes, backslashes),
368    /// multi-byte text, nested data, numbers of every kind and every
369    /// optional member, from a fixed seed.
370    #[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    /// Long runs of the costliest escape in every string a message carries,
386    /// where the per-byte factor rather than the fixed allowances decides:
387    /// `\u{1}` serializes as six bytes, so a bound of fewer than six per
388    /// byte falls below the exact length here.
389    #[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    /// The fast path skips nothing it should not: a history whose bound is
419    /// over budget but whose exact size is within it is kept whole, so the
420    /// exact walk still decides.
421    #[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}