a2a_protocol_server/audit/outcomes.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Records a required log must not lose: spooling, draining and reconciling
5//! (adversarial review A3, 2026-11-12).
6//!
7//! [`AuditLog::require_record`] used to gate admission on the `call.started`
8//! record and nothing after it. When the store refused the `call` record that
9//! says how the call ended, or a `task.event`, the failure was counted and the
10//! record was gone: a chain proves the records it holds are intact and cannot
11//! show that one was never written.
12//!
13//! In a required log a record the store refuses is **spooled** and written
14//! when the store answers again. Three things keep the promise honest:
15//!
16//! * the spool is bounded; a record that does not fit is counted in
17//! [`AuditLog::outcomes_lost`], never dropped silently;
18//! * a start with no end, which a crash leaves behind and a full spool
19//! can, is found by [`AuditLog::unresolved_calls`] and closed with a
20//! `call.unresolved` record by [`AuditLog::reconcile_unresolved`];
21//! * the spool is memory. A process that dies with records in it loses them,
22//! which is what reconciliation is for, and what the docs say.
23
24use std::collections::{HashSet, VecDeque};
25use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
26use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
27use std::time::Duration;
28
29use a2a_protocol_types::audit::{AuditRecord, kind};
30use a2a_protocol_types::error::{A2aError, A2aResult};
31
32use super::log::AuditLog;
33use super::store::record_millis;
34
35/// Records a log holds for a store that is refusing them. A record past it is
36/// counted as lost.
37pub(super) const MAX_PENDING: usize = 1_024;
38
39/// Tries a spooled record makes before the store is asked whether it is the
40/// record that is refused, or the store.
41const POISON_AFTER: u32 = 8;
42
43/// The wait before a retry, doubled up to [`RETRY_CEILING`].
44const RETRY_FLOOR: Duration = Duration::from_millis(100);
45const RETRY_CEILING: Duration = Duration::from_secs(5);
46
47/// A spooled record and how many times the store has refused it.
48#[derive(Debug)]
49struct Spooled {
50 record: AuditRecord,
51 refused: u32,
52}
53
54/// The state a required log keeps for records the store has refused.
55#[derive(Debug, Default)]
56pub(super) struct Outcomes {
57 /// Ids of calls admitted and not yet ended in this process.
58 in_flight: Mutex<HashSet<String>>,
59 pending: Mutex<VecDeque<Spooled>>,
60 /// Held by whoever is writing the spool; drains are one at a time, so
61 /// the front of the queue is the same record before and after a write.
62 draining: tokio::sync::Mutex<()>,
63 /// A retry task exists.
64 retrying: AtomicBool,
65 lost: AtomicU64,
66}
67
68fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
69 m.lock().unwrap_or_else(PoisonError::into_inner)
70}
71
72/// A call that was admitted and has no record of how it ended.
73#[derive(Debug, Clone, PartialEq, Eq)]
74#[non_exhaustive]
75pub struct UnresolvedCall {
76 /// The chain the call belongs to.
77 pub chain: String,
78 /// The position of its `call.started` record.
79 pub started_seq: u64,
80 /// The call's id ([`CallContext::call_id`](crate::CallContext::call_id)).
81 pub call_id: String,
82 /// The method it called.
83 pub method: Option<String>,
84}
85
86fn call_id_of(record: &AuditRecord) -> Option<&str> {
87 record.detail.get("callId").and_then(|v| v.as_str())
88}
89
90impl AuditLog {
91 /// Records waiting for the store to take them; see
92 /// [`require_record`](Self::require_record).
93 #[must_use]
94 pub fn pending_outcomes(&self) -> usize {
95 lock(&self.outcomes.pending).len()
96 }
97
98 /// Records a required log could not keep: the spool was full, or the
99 /// record was the one the store kept refusing. Each is a call, event or
100 /// decision whose record does not exist and which no later write will
101 /// supply; [`reconcile_unresolved`](Self::reconcile_unresolved) closes
102 /// the calls among them. Zero in a healthy deployment.
103 #[must_use]
104 pub fn outcomes_lost(&self) -> u64 {
105 self.outcomes.lost.load(Ordering::Relaxed)
106 }
107
108 pub(super) fn admit(&self, call_id: &str) {
109 lock(&self.outcomes.in_flight).insert(call_id.to_owned());
110 }
111
112 pub(super) fn end_call(&self, call_id: &str) {
113 lock(&self.outcomes.in_flight).remove(call_id);
114 }
115
116 /// Appends `record`, and spools it if the store refuses.
117 ///
118 /// The write runs in a task of its own, so a caller that is dropped while
119 /// it waits (a client that hung up, a deadline) does not abandon a record
120 /// the store may already hold, nor one that was about to be spooled.
121 ///
122 /// # Errors
123 ///
124 /// The store's refusal; the record is then in the spool.
125 pub(crate) async fn append_required(
126 self: &Arc<Self>,
127 record: AuditRecord,
128 ) -> A2aResult<AuditRecord> {
129 let log = Arc::clone(self);
130 tokio::spawn(async move {
131 match log.append(record.clone()).await {
132 Ok(sealed) => Ok(sealed),
133 Err(e) => {
134 log.spool(record);
135 Err(e)
136 }
137 }
138 })
139 .await
140 .unwrap_or_else(|e| Err(A2aError::internal(format!("an audit write failed: {e}"))))
141 }
142
143 fn spool(self: &Arc<Self>, record: AuditRecord) {
144 {
145 let mut pending = lock(&self.outcomes.pending);
146 if pending.len() >= MAX_PENDING {
147 drop(pending);
148 self.outcomes.lost.fetch_add(1, Ordering::Relaxed);
149 trace_error!(kind = %record.kind, "audit: the spool is full, a record is lost");
150 return;
151 }
152 pending.push_back(Spooled { record, refused: 1 });
153 }
154 self.ensure_retrying();
155 }
156
157 /// Writes the spool, oldest first, until the store refuses one or none is
158 /// left; returns how many remain. A drain already running counts as the
159 /// records it has not yet written.
160 ///
161 /// Runs in a task of its own, so dropping the caller does not stop it
162 /// between the store taking a record and the spool forgetting it.
163 pub async fn flush_pending(self: &Arc<Self>) -> usize {
164 if self.pending_outcomes() == 0 {
165 return 0;
166 }
167 let log = Arc::clone(self);
168 tokio::spawn(async move { log.drain().await })
169 .await
170 .unwrap_or_else(|_| self.pending_outcomes())
171 }
172
173 async fn drain(&self) -> usize {
174 let Ok(_one) = self.outcomes.draining.try_lock() else {
175 return self.pending_outcomes();
176 };
177 loop {
178 let Some(record) = lock(&self.outcomes.pending)
179 .front()
180 .map(|s| s.record.clone())
181 else {
182 return 0;
183 };
184 if self.append(record).await.is_ok() {
185 lock(&self.outcomes.pending).pop_front();
186 continue;
187 }
188 if self.give_up_on_head().await {
189 continue;
190 }
191 return self.pending_outcomes();
192 }
193 }
194
195 /// Whether the record at the front has been refused enough times, by a
196 /// store that answers reads, that it is the record at fault: it is
197 /// counted lost and removed, so it does not hold back the ones behind it.
198 /// A store that does not answer is not at fault in that sense; its
199 /// records wait.
200 async fn give_up_on_head(&self) -> bool {
201 let Some(chain) = self.count_refusal_of_head() else {
202 return false;
203 };
204 if self.store().head(&chain).await.is_err() {
205 return false;
206 }
207 let _gone = lock(&self.outcomes.pending).pop_front();
208 self.outcomes.lost.fetch_add(1, Ordering::Relaxed);
209 trace_error!(
210 kind = _gone.as_ref().map_or("", |s| s.record.kind.as_str()),
211 "audit: the store refuses this record and answers reads; it is lost"
212 );
213 true
214 }
215
216 /// Counts one more refusal of the record at the front; its chain once it
217 /// has been refused [`POISON_AFTER`] times.
218 fn count_refusal_of_head(&self) -> Option<String> {
219 let mut pending = lock(&self.outcomes.pending);
220 let head = pending.front_mut()?;
221 head.refused += 1;
222 let chain = (head.refused >= POISON_AFTER).then(|| head.record.chain.clone());
223 drop(pending);
224 chain
225 }
226
227 /// Whether the task that retries the spool is running, for the tests that
228 /// say it ends once the spool is empty.
229 #[cfg(test)]
230 pub(super) fn retry_task_running(&self) -> bool {
231 self.outcomes.retrying.load(Ordering::SeqCst)
232 }
233
234 /// Starts the task that retries the spool, unless one is running.
235 fn ensure_retrying(self: &Arc<Self>) {
236 if self.outcomes.retrying.swap(true, Ordering::SeqCst) {
237 return;
238 }
239 let log = Arc::clone(self);
240 drop(tokio::spawn(async move {
241 let mut wait = RETRY_FLOOR;
242 loop {
243 tokio::time::sleep(wait).await;
244 if log.drain().await > 0 {
245 wait = (wait * 2).min(RETRY_CEILING);
246 continue;
247 }
248 log.outcomes.retrying.store(false, Ordering::SeqCst);
249 // A record spooled after the drain found none, whose own call
250 // saw this task still running and started no other.
251 if log.pending_outcomes() == 0 || log.outcomes.retrying.swap(true, Ordering::SeqCst)
252 {
253 return;
254 }
255 wait = RETRY_FLOOR;
256 }
257 }));
258 }
259
260 /// The calls of `chain` after position `after` that were admitted at least
261 /// `older_than` ago and have no record of how they ended.
262 ///
263 /// A call is unresolved when its `call.started` record names a call id
264 /// that no `call` or `call.unresolved` record names, and the call is not
265 /// still running in this process or waiting in its spool. A `call.started`
266 /// written before call ids existed names none and is not reported.
267 ///
268 /// **`older_than` must exceed your longest request.** Another replica
269 /// sharing the store may be serving a call this log cannot see, and its
270 /// start looks the same as a dead one's until its outcome arrives.
271 ///
272 /// # Errors
273 ///
274 /// When the store cannot be read.
275 pub async fn unresolved_calls(
276 &self,
277 chain: &str,
278 after: u64,
279 older_than: Duration,
280 ) -> A2aResult<Vec<UnresolvedCall>> {
281 // Snapshotted before the read: a call that ends meanwhile is in the
282 // chain, and one that has not ended is excluded by this.
283 let live = self.live_call_ids();
284 let now = std::time::SystemTime::now()
285 .duration_since(std::time::UNIX_EPOCH)
286 .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX));
287 let cutoff = i64::try_from(older_than.as_millis()).unwrap_or(i64::MAX);
288 let mut started = Vec::new();
289 let mut ended = HashSet::new();
290 let mut cursor = after;
291 loop {
292 let page = self.store().read(chain, cursor, 1_000).await?;
293 let Some(last) = page.last().map(|r| r.seq) else {
294 break;
295 };
296 cursor = last;
297 for r in page {
298 match (r.kind.as_str(), call_id_of(&r)) {
299 (kind::CALL | kind::CALL_UNRESOLVED, Some(id)) => {
300 ended.insert(id.to_owned());
301 }
302 (kind::CALL_STARTED, Some(id)) => {
303 started.push((r.seq, id.to_owned(), r.method.clone(), record_millis(&r)));
304 }
305 _ => {}
306 }
307 }
308 }
309 Ok(started
310 .into_iter()
311 .filter(|(_, id, _, at)| {
312 !ended.contains(id) && !live.contains(id) && now.saturating_sub(*at) >= cutoff
313 })
314 .map(|(started_seq, call_id, method, _)| UnresolvedCall {
315 chain: chain.to_owned(),
316 started_seq,
317 call_id,
318 method,
319 })
320 .collect())
321 }
322
323 pub(super) fn live_call_ids(&self) -> HashSet<String> {
324 let mut ids = lock(&self.outcomes.in_flight).clone();
325 ids.extend(
326 lock(&self.outcomes.pending)
327 .iter()
328 .filter_map(|s| call_id_of(&s.record).map(str::to_owned)),
329 );
330 ids
331 }
332
333 /// Closes every call [`unresolved_calls`](Self::unresolved_calls) finds
334 /// with a `call.unresolved` record, and returns the records it wrote.
335 ///
336 /// Run it at start-up, before serving, and on a schedule: it is how a
337 /// crash that took records with it, or a spool that overflowed, becomes
338 /// visible in the chain, so that an auditor reading it sees "the outcome
339 /// of this call is not known" instead of nothing. It is safe to run twice
340 /// and from several replicas: a call already closed is not closed again,
341 /// and one closed twice at once reads as closed. It does not claim the
342 /// call failed.
343 ///
344 /// # Errors
345 ///
346 /// When the store cannot be read or a record cannot be appended; the ones
347 /// written before that stay written.
348 pub async fn reconcile_unresolved(
349 &self,
350 chain: &str,
351 after: u64,
352 older_than: Duration,
353 ) -> A2aResult<Vec<AuditRecord>> {
354 let mut written = Vec::new();
355 for call in self.unresolved_calls(chain, after, older_than).await? {
356 let mut r = AuditRecord::new(chain, kind::CALL_UNRESOLVED);
357 r.method = call.method;
358 r.detail
359 .insert("callId".to_owned(), call.call_id.clone().into());
360 r.detail
361 .insert("startedSeq".to_owned(), call.started_seq.into());
362 written.push(self.append(r).await?);
363 }
364 Ok(written)
365 }
366}