a2a_protocol_client/delegation/policy.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! How a delegation gets a lost stream back (audit H4, ADR 0030): the policy
5//! that bounds it. The loop that follows it is in [`resume`](super::resume).
6
7use std::time::Duration;
8
9/// How a [`Delegation`](super::Delegation) tries to get its stream back before it gives up on
10/// the child. The default is five attempts, 200 ms apart at first and
11/// doubling to 5 s, inside 30 s in all.
12///
13/// An attempt that gets a stream and then loses it without the position
14/// moving counts as spent: a server that accepts a subscription and drops it
15/// at once exhausts the policy rather than being asked for ever. A stream
16/// that delivered events (the position advanced) starts the count again.
17///
18/// Positions come from the agent's event ids. An agent that sends none (gRPC
19/// and WebSocket streams carry none) shows no progress that way, so a stream
20/// also counts as having worked when it delivered at least one event and
21/// stayed open for [`healthy_after`](Self::healthy_after): a long, quiet
22/// child cut again and again by an idle timeout is not given up on, while a
23/// server that accepts a subscription, sends its snapshot and drops it at
24/// once still exhausts the policy.
25///
26/// The waits between attempts are spread by up to half
27/// ([`with_jitter`](Self::with_jitter)), so that a fleet whose streams a
28/// proxy rollout cut in the same instant does not come back in the same
29/// instant.
30///
31/// [`ResumePolicy::none`] restores the behaviour before 2026-10-31: the first
32/// loss cancels the child.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct ResumePolicy {
36 /// How many times in a row to reopen the stream. Zero never resumes.
37 pub attempts: u32,
38 /// The wait before the second attempt; each later wait doubles.
39 pub backoff: Duration,
40 /// The longest a wait between attempts grows to.
41 pub max_backoff: Duration,
42 /// The longest one loss is worked on, from the loss to giving up.
43 pub deadline: Duration,
44 /// How long a reopened stream must stay open, having delivered an event,
45 /// to count as one that worked and start the attempt count again.
46 pub healthy_after: Duration,
47 /// Whether each wait between attempts is shortened by a random fraction
48 /// of up to half.
49 pub jitter: bool,
50}
51
52impl Default for ResumePolicy {
53 fn default() -> Self {
54 Self {
55 attempts: 5,
56 backoff: Duration::from_millis(200),
57 max_backoff: Duration::from_secs(5),
58 deadline: Duration::from_secs(30),
59 healthy_after: Duration::from_secs(5),
60 jitter: true,
61 }
62 }
63}
64
65impl ResumePolicy {
66 /// Never resumes: the first lost stream cancels the child.
67 #[must_use]
68 pub const fn none() -> Self {
69 Self {
70 attempts: 0,
71 backoff: Duration::ZERO,
72 max_backoff: Duration::ZERO,
73 deadline: Duration::ZERO,
74 healthy_after: Duration::ZERO,
75 jitter: false,
76 }
77 }
78
79 /// Sets how many times in a row the stream is reopened.
80 #[must_use]
81 pub const fn with_attempts(mut self, attempts: u32) -> Self {
82 self.attempts = attempts;
83 self
84 }
85
86 /// Sets the first wait between attempts and the longest one.
87 #[must_use]
88 pub const fn with_backoff(mut self, first: Duration, longest: Duration) -> Self {
89 self.backoff = first;
90 self.max_backoff = longest;
91 self
92 }
93
94 /// Sets how long one loss is worked on.
95 #[must_use]
96 pub const fn with_deadline(mut self, deadline: Duration) -> Self {
97 self.deadline = deadline;
98 self
99 }
100
101 /// The wait before attempt `streak + 1`: [`wait_before`](Self::wait_before),
102 /// shortened by `spread` when the policy asks for jitter. The shortening
103 /// is passed in so that a test can pin it; the delegation passes the
104 /// client's own jitter.
105 pub(crate) fn attempt_wait(
106 &self,
107 streak: u32,
108 spread: impl FnOnce(Duration) -> Duration,
109 ) -> Duration {
110 let wait = self.wait_before(streak);
111 if self.jitter { spread(wait) } else { wait }
112 }
113
114 /// Sets how long a reopened stream must stay open, having delivered an
115 /// event, to count as one that worked.
116 #[must_use]
117 pub const fn with_healthy_after(mut self, healthy_after: Duration) -> Self {
118 self.healthy_after = healthy_after;
119 self
120 }
121
122 /// Sets whether each wait between attempts is shortened by a random
123 /// fraction of up to half. On by default; a test that pins the waits
124 /// turns it off.
125 #[must_use]
126 pub const fn with_jitter(mut self, jitter: bool) -> Self {
127 self.jitter = jitter;
128 self
129 }
130
131 /// How long to wait before reopening attempt number `streak + 1`: nothing
132 /// before the first, then [`backoff`](Self::backoff), doubling each time,
133 /// never more than [`max_backoff`](Self::max_backoff). Pure, so that its
134 /// arithmetic is pinned exactly by the tests and not by how long a loop
135 /// happened to take.
136 pub(crate) fn wait_before(&self, streak: u32) -> Duration {
137 let Some(doublings) = streak.checked_sub(1) else {
138 return Duration::ZERO;
139 };
140 // The clamp keeps the shift in range for a long streak; the cap below
141 // is what bounds the wait.
142 self.backoff
143 .saturating_mul(1_u32 << doublings.min(16))
144 .min(self.max_backoff)
145 }
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151
152 fn ms(n: u64) -> Duration {
153 Duration::from_millis(n)
154 }
155
156 #[test]
157 fn there_is_no_wait_before_the_first_attempt_and_it_doubles_after() {
158 let p = ResumePolicy::default(); // 200 ms, doubling, capped at 5 s
159 let waits: Vec<_> = (0..=7).map(|streak| p.wait_before(streak)).collect();
160 assert_eq!(
161 waits,
162 [
163 Duration::ZERO,
164 ms(200),
165 ms(400),
166 ms(800),
167 ms(1_600),
168 ms(3_200),
169 ms(5_000), // 6,400 capped
170 ms(5_000),
171 ]
172 );
173 }
174
175 #[test]
176 fn the_cap_holds_for_any_streak_and_the_shift_cannot_overflow() {
177 let p = ResumePolicy::default().with_backoff(ms(7), Duration::from_secs(3_600));
178 assert_eq!(p.wait_before(1), ms(7));
179 assert_eq!(p.wait_before(2), ms(14));
180 assert_eq!(p.wait_before(3), ms(28));
181 // Far past the clamp: the cap, not a panic and not a wrapped shift.
182 assert_eq!(p.wait_before(17), ms(7 * 65_536));
183 assert_eq!(p.wait_before(18), ms(7 * 65_536));
184 assert_eq!(p.wait_before(u32::MAX), ms(7 * 65_536));
185 let capped = p.with_backoff(ms(300), ms(100));
186 assert_eq!(
187 capped.wait_before(1),
188 ms(100),
189 "the cap wins over the first wait"
190 );
191 }
192
193 fn halved(wait: Duration) -> Duration {
194 wait / 2
195 }
196
197 #[test]
198 fn jitter_shortens_the_wait_only_when_the_policy_asks_for_it() {
199 let on = ResumePolicy::default();
200 let off = ResumePolicy::default().with_jitter(false);
201 assert!(on.jitter && !off.jitter);
202 assert_eq!(on.attempt_wait(2, halved), ms(200), "400 ms, halved");
203 assert_eq!(off.attempt_wait(2, halved), ms(400), "left as it was");
204 assert_eq!(
205 on.attempt_wait(0, halved),
206 Duration::ZERO,
207 "no wait stays none"
208 );
209 assert!(!ResumePolicy::none().jitter, "none() waits for nothing");
210 }
211
212 #[test]
213 fn the_defaults_and_setters_of_the_new_fields() {
214 assert_eq!(
215 ResumePolicy::default().healthy_after,
216 Duration::from_secs(5)
217 );
218 assert_eq!(ResumePolicy::none().healthy_after, Duration::ZERO);
219 assert_eq!(
220 ResumePolicy::default()
221 .with_healthy_after(ms(7))
222 .healthy_after,
223 ms(7)
224 );
225 }
226
227 #[test]
228 fn a_zero_backoff_never_waits() {
229 let p = ResumePolicy::none();
230 assert!((0..40).all(|s| p.wait_before(s).is_zero()));
231 let p = ResumePolicy::default().with_backoff(Duration::ZERO, Duration::from_secs(5));
232 assert!((0..40).all(|s| p.wait_before(s).is_zero()));
233 }
234}