Skip to main content

a2a_protocol_server/tool_loop/
limits.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! How many bytes a run may hold (adversarial review N09, 2026-11-13).
5//!
6//! The loop bounded turns and calls per turn, and the model adapter bounded a
7//! provider's response, but nothing bounded what a tool returned, what the
8//! conversation grew to, or the checkpoint a journal wrote of it. One tool
9//! returning a large report was kept whole in the conversation (and, for a
10//! tool that is not read-only, in the record of answered calls), sent again on
11//! every later model turn, and written again in every checkpoint.
12//!
13//! * **A tool's result** past [`DEFAULT_RESULT_LIMIT`]
14//!   ([`ToolLoop::with_result_limit`](super::ToolLoop::with_result_limit)) is
15//!   cut, at a character boundary, and says so in words the model reads: how
16//!   many bytes there were and how many it is shown. The call's receipt is
17//!   unaffected (it holds a digest of the arguments, never the result).
18//! * **A model request** (preamble, conversation, tool catalogue) past
19//!   [`DEFAULT_REQUEST_LIMIT`]
20//!   ([`with_request_limit`](super::ToolLoop::with_request_limit)) is not
21//!   sent: the run ends with [`LoopError::TooLarge`](super::LoopError::TooLarge).
22//! * **A checkpoint** past [`DEFAULT_CHECKPOINT_LIMIT`]
23//!   ([`with_checkpoint_limit`](super::ToolLoop::with_checkpoint_limit)) is not
24//!   written: the run stops before the step it would have recorded, as for any
25//!   checkpoint the journal cannot write.
26
27use std::fmt::Write as _;
28
29/// The bytes of one tool result the model is shown: 1 MiB.
30pub const DEFAULT_RESULT_LIMIT: usize = 1024 * 1024;
31
32/// The bytes one model request may hold: 8 MiB, the size the bundled adapter
33/// accepts back from a provider
34/// ([`DEFAULT_MAX_RESPONSE_BYTES`](super::DEFAULT_MAX_RESPONSE_BYTES)).
35pub const DEFAULT_REQUEST_LIMIT: usize = 8 * 1024 * 1024;
36
37/// The bytes of one checkpoint body: 32 MiB.
38pub const DEFAULT_CHECKPOINT_LIMIT: usize = 32 * 1024 * 1024;
39
40/// A loop's byte limits.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub(super) struct ByteLimits {
43    pub(super) result: usize,
44    pub(super) request: usize,
45}
46
47impl Default for ByteLimits {
48    fn default() -> Self {
49        Self {
50            result: DEFAULT_RESULT_LIMIT,
51            request: DEFAULT_REQUEST_LIMIT,
52        }
53    }
54}
55
56/// `content`, cut to `limit` bytes at a character boundary with a note of
57/// what was cut, when it is longer.
58pub(super) fn bound_result(content: String, limit: usize) -> String {
59    if content.len() <= limit {
60        return content;
61    }
62    let mut end = limit;
63    while !content.is_char_boundary(end) {
64        end -= 1;
65    }
66    let total = content.len();
67    let mut out = content;
68    out.truncate(end);
69    let _ = write!(
70        out,
71        "\n[the tool's result was {total} bytes; only the first {end} are shown here]"
72    );
73    out
74}
75
76/// The bytes a model request holds: the preamble, the conversation and the
77/// tool catalogue, as JSON.
78pub(super) fn request_bytes(
79    preamble: &str,
80    messages: &[super::model::ChatMessage],
81    specs: &[super::model::ToolSpec],
82) -> usize {
83    let conversation = serde_json::to_vec(messages).map_or(usize::MAX, |b| b.len());
84    let catalogue: usize = specs
85        .iter()
86        .map(|s| s.name.len() + s.description.len() + s.parameters.to_string().len())
87        .sum();
88    preamble
89        .len()
90        .saturating_add(conversation)
91        .saturating_add(catalogue)
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    /// A request's size is the preamble's, the conversation's as JSON and
99    /// each tool's name, description and schema, added.
100    #[test]
101    fn a_request_counts_each_part_once() {
102        let spec = super::super::model::ToolSpec::new("ab", "cde", serde_json::json!({}));
103        // "p" (1) + "[]" (2) + "ab" (2) + "cde" (3) + "{}" (2).
104        assert_eq!(request_bytes("p", &[], &[spec]), 10);
105    }
106
107    #[test]
108    fn a_result_within_the_limit_is_unchanged() {
109        assert_eq!(bound_result("abc".to_owned(), 3), "abc");
110    }
111
112    #[test]
113    fn a_result_past_the_limit_is_cut_and_says_so() {
114        let out = bound_result("abcdef".to_owned(), 4);
115        assert_eq!(
116            out,
117            "abcd\n[the tool's result was 6 bytes; only the first 4 are shown here]"
118        );
119    }
120
121    #[test]
122    fn a_result_is_cut_at_a_character_boundary() {
123        // "é" is two bytes: a cut at 2 would split it.
124        let out = bound_result("aé…".to_owned(), 2);
125        assert!(out.starts_with("a\n"), "{out}");
126        assert!(out.contains("was 6 bytes; only the first 1"), "{out}");
127    }
128}