Skip to main content

a2a_protocol_server/store/retention/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Retention for the persistent task stores.
5//!
6//! # The settled policy
7//!
8//! **A persistent store deletes nothing unless the operator asks it to.**
9//!
10//! That is a decision, not an omission, and it is the opposite of what the
11//! in-memory store does. [`TaskStoreConfig`](super::TaskStoreConfig) defaults
12//! to a one-hour TTL and a 10,000-task cap, so the default in-process
13//! deployment forgets a task an hour after it finishes. `SqliteTaskStore` and
14//! `PostgresTaskStore` never read that config — they took a URL and nothing
15//! else — so the durable deployment kept every task forever. Two opposite
16//! behaviours, neither written down where an operator would look, and the
17//! divergence was the actual defect: not that the table grows, but that
18//! nothing said it would.
19//!
20//! Forgetting is right for a cache and wrong for a database. A library that
21//! quietly deleted rows from an operator's `PostgreSQL` would be a far worse
22//! surprise than one that grows, and "how long do we keep completed work" is a
23//! question with legal answers, not just engineering ones — retention
24//! schedules, audit obligations, and the customer's own contracts all have a
25//! say. So the default stays "keep everything", and this module is the
26//! mechanism for any other answer.
27//!
28//! # Using it
29//!
30//! `purge_expired` on each persistent store deletes terminal
31//! tasks older than [`RetentionPolicy::terminal_max_age`], in batches, and
32//! reports what it did. Call it from whatever already schedules work —
33//! a cron, a Kubernetes `CronJob`, a `tokio::spawn` loop. It is deliberately
34//! not wired to a timer inside the store: a sweep that fires on its own is a
35//! sweep that fires during your traffic peak, and the store does not know when
36//! that is.
37//!
38//! The example is gated on `sqlite` because the type it needs is: this crate
39//! has no default features, so a doctest naming `SqliteTaskStore`
40//! unconditionally fails to compile in every build that does not ask for a
41//! backend — which is most of the CI matrix.
42//!
43//! ```no_run
44//! # #[cfg(feature = "sqlite")]
45//! # mod example {
46//! use a2a_protocol_server::store::{RetentionPolicy, SqliteTaskStore};
47//! use a2a_protocol_types::error::A2aResult;
48//! use std::time::Duration;
49//!
50//! pub async fn sweep(store: &SqliteTaskStore) -> A2aResult<()> {
51//!     let policy = RetentionPolicy::new(Duration::from_secs(30 * 24 * 3600));
52//!     let report = store.purge_expired(&policy).await?;
53//!     println!("purged {} task(s)", report.tasks_deleted);
54//!     Ok(())
55//! }
56//! # }
57//! ```
58//!
59//! # What it will not delete
60//!
61//! Terminal tasks — `Completed`, `Failed`, `Canceled`, `Rejected` — and,
62//! only when the policy says so, parked ones.
63//!
64//! A task that is still `Working` is never eligible, however old it is. One
65//! parked in `InputRequired` or `AuthRequired` is a workflow waiting on
66//! someone, not a leak, and by default it is never eligible either: the
67//! in-memory store does evict non-terminal tasks as a last resort under
68//! capacity pressure, because RAM is a hard bound, but disk is not.
69//!
70//! An operator whose parked tasks are abandoned by the people they wait on can
71//! opt in with [`RetentionPolicy::with_parked_max_age`] (ADR 0056, which
72//! amends ADR 0011). A parked task whose last update is older than that is
73//! then **deleted**, with its event log, as a terminal one is: a store cannot
74//! write the cancellation a handler would (the event, the push notification,
75//! the audit record), so it does not pretend to. A client that answers it
76//! afterwards is told the task was not found; a stream open on it ends
77//! without a terminal state. A task that a turn is running on right now (a
78//! live claim) is skipped, whatever its age. The count is
79//! [`PurgeReport::parked_tasks_deleted`].
80
81// Gated as `effective_batch_size` is: its callers are the SQL sweeps, and
82// without a backend it is dead code under `-D warnings`.
83#[cfg(any(feature = "sqlite", feature = "postgres"))]
84pub(crate) mod compact;
85#[cfg(any(feature = "sqlite", feature = "postgres"))]
86#[cfg(test)]
87mod compact_tests;
88#[cfg(feature = "postgres")]
89pub(crate) mod postgres;
90#[cfg(feature = "sqlite")]
91pub(crate) mod sqlite;
92
93use std::time::Duration;
94
95use a2a_protocol_types::task::TaskState;
96
97/// The states a purge is allowed to delete.
98///
99/// Listed here rather than derived from `TaskState::ALL`, and that is a
100/// packaging constraint rather than a preference. `cargo package` verifies the
101/// server tarball against `a2a-protocol-types` **from crates.io** — the path
102/// dependency is stripped, and the published 0.9.0 has no `ALL` — so
103/// referencing it from library code fails the packaging gate on every PR until
104/// a version bump makes the local copy the only candidate.
105///
106/// The guard therefore lives in the test below, which *does* see the local
107/// crate: `cargo package` builds the library and not the tests, so a
108/// `#[cfg(test)]` reference to `TaskState::ALL` costs nothing at packaging
109/// time and still fails the moment this list stops agreeing with
110/// [`TaskState::is_terminal`] across every variant the protocol defines.
111const TERMINAL_STATES: [TaskState; 4] = [
112    TaskState::Completed,
113    TaskState::Failed,
114    TaskState::Canceled,
115    TaskState::Rejected,
116];
117
118/// The states a purge is allowed to delete.
119#[must_use]
120pub fn terminal_states() -> Vec<TaskState> {
121    TERMINAL_STATES.to_vec()
122}
123
124/// The states [`RetentionPolicy::parked_max_age`] may delete: a task waiting
125/// for input or authorization. Listed here for the reason
126/// [`TERMINAL_STATES`] is, and checked in the tests against
127/// [`TaskState::is_interrupted`] for every variant.
128#[cfg(any(feature = "sqlite", feature = "postgres"))]
129const PARKED_STATES: [TaskState; 2] = [TaskState::InputRequired, TaskState::AuthRequired];
130
131/// How long an idempotency key is kept when nothing else is asked for.
132///
133/// One day. The number has to exceed the longest window in which a client
134/// might still retry a send and expect a replay rather than a second
135/// execution, and clients retry in seconds — `RetryPolicy`'s own schedule is
136/// bounded in the low tens of seconds. A day is the figure the wider industry
137/// settled on for the same trade, and it is far enough above any retry budget
138/// this SDK ships that the choice is not delicate.
139///
140/// See [`RetentionPolicy::idempotency_key_max_age`] for what expiring a key
141/// costs.
142pub const DEFAULT_IDEMPOTENCY_KEY_MAX_AGE: Duration = Duration::from_hours(24);
143
144/// How long terminal tasks are kept, and how aggressively they are removed.
145///
146/// `#[non_exhaustive]`: build it with [`new`](Self::new) and the `with_*`
147/// setters, which cover every field. `STABILITY.md` §4 lists the
148/// configuration structs that carry this marking so a new option on any of
149/// them is additive; this one was missed by the 0.12.0 conversion that
150/// introduced the rule, and adding
151/// [`idempotency_key_max_age`](Self::idempotency_key_max_age) is what found
152/// it.
153#[derive(Debug, Clone)]
154#[non_exhaustive]
155pub struct RetentionPolicy {
156    /// Terminal tasks whose last update is older than this are eligible.
157    ///
158    /// Measured against `updated_at`, which the store maintains, and evaluated
159    /// by the database rather than the caller — an application clock that runs
160    /// fast would otherwise delete work that is younger than it looks.
161    pub terminal_max_age: Duration,
162
163    /// Parked tasks (`input-required`, `auth-required`) whose last update is
164    /// older than this are eligible too. `None`, the default, deletes none:
165    /// a parked task is a workflow waiting on someone, and every release
166    /// before this field kept it for ever (ADR 0011; ADR 0056 amends it).
167    ///
168    /// # What deleting one costs
169    ///
170    /// The task is deleted, with its event log, not cancelled: a store cannot
171    /// write what a `CancelTask` writes (the event a stream replays, the push
172    /// notification, the audit record), and a purge that made up a
173    /// cancellation without them would leave a task that says `canceled` and
174    /// a history that does not. So a client that answers the task afterwards
175    /// is told it was not found, and a stream open on it ends without a
176    /// terminal state. The age is measured from `updated_at`, by the
177    /// database's clock, as for terminal tasks.
178    ///
179    /// A task that a turn is running on now (an unexpired turn claim) is
180    /// skipped however old it is: a continuation in flight is not abandoned.
181    ///
182    /// # Idempotency keys
183    ///
184    /// A key must outlive the task it names, so
185    /// [`effective_idempotency_key_max_age`](Self::effective_idempotency_key_max_age)
186    /// is never below this either.
187    pub parked_max_age: Option<Duration>,
188
189    /// Rows per `DELETE`. Default 1,000.
190    ///
191    /// The point of batching is the lock, not the throughput. One statement
192    /// deleting a million rows holds locks and grows a transaction for as long
193    /// as it takes; a thousand statements deleting a thousand rows each let
194    /// every other query through in between.
195    pub batch_size: u32,
196
197    /// Idempotency keys older than this are deleted. `None` keeps them for
198    /// ever, which is what every release before this one did.
199    ///
200    /// # Why a key has to expire at all
201    ///
202    /// A key is released when the send it guards fails, and otherwise it
203    /// stays — deliberately, because it has to outlive the task it names or a
204    /// late retry would execute a second time. Nothing else ever removed one.
205    /// A busy deployment therefore accumulated a row per keyed send for the
206    /// life of the database, and the index that makes the claim atomic grew
207    /// with it.
208    ///
209    /// # What expiring one costs
210    ///
211    /// Exactly what the key was preventing: a retry arriving **after** the
212    /// key expires re-executes the send. That is the trade every idempotency
213    /// key has, and the reason the default is a full day rather than
214    /// something tidier — it has to exceed the longest window in which a
215    /// client might still retry, and clients retry in seconds.
216    ///
217    /// # It is never allowed below `terminal_max_age`
218    ///
219    /// A key expiring while the task it names is still retained is the bad
220    /// case: the retry does not replay, it creates a *second* task alongside
221    /// the first, and the caller ends up with two ids for one logical send.
222    /// So the sweep uses
223    /// [`effective_idempotency_key_max_age`](Self::effective_idempotency_key_max_age),
224    /// which never returns less than
225    /// [`terminal_max_age`](Self::terminal_max_age) — the invariant holds by
226    /// construction rather than by the operator having read this paragraph.
227    pub idempotency_key_max_age: Option<Duration>,
228
229    /// Stop after this many batches, leaving the rest for the next call.
230    /// `None` runs until nothing is left.
231    ///
232    /// Set it to bound how long one sweep can run when the first sweep after
233    /// switching retention on has years of backlog to work through.
234    pub max_batches: Option<u32>,
235
236    /// The most events a live (non-terminal) task's log keeps, or `None`, the
237    /// default: a live task's log then grows for as long as the task runs.
238    ///
239    /// With it, `purge_expired` also compacts the log of each live task
240    /// holding more than this many events to the newest this many, dropping
241    /// only events the stored task already reflects (audit H13, ADR 0047). A
242    /// subscriber that asks to resume from a dropped position is answered
243    /// with the task's snapshot, as a lagged one is, never with a replay
244    /// that silently skips. `0` is taken as `1`: the last event is kept, as
245    /// a continued task numbers its events on from it.
246    pub max_events_per_live_task: Option<u64>,
247}
248
249impl RetentionPolicy {
250    /// A policy keeping terminal tasks for `terminal_max_age`, with default
251    /// batching.
252    #[must_use]
253    pub const fn new(terminal_max_age: Duration) -> Self {
254        Self {
255            terminal_max_age,
256            batch_size: 1_000,
257            idempotency_key_max_age: Some(DEFAULT_IDEMPOTENCY_KEY_MAX_AGE),
258            parked_max_age: None,
259            max_batches: None,
260            max_events_per_live_task: None,
261        }
262    }
263
264    /// Compacts each live task's log to its newest `max` events; see
265    /// [`max_events_per_live_task`](Self::max_events_per_live_task). `None`
266    /// turns it off.
267    #[must_use]
268    pub const fn with_max_events_per_live_task(mut self, max: Option<u64>) -> Self {
269        self.max_events_per_live_task = max;
270        self
271    }
272
273    /// Deletes parked tasks (`input-required`, `auth-required`) that have sat
274    /// unanswered for `max_age`. Unset by default: nothing parked is deleted.
275    ///
276    /// See [`parked_max_age`](Self::parked_max_age) for what it deletes and
277    /// what that costs. Measured in whole seconds, as
278    /// [`terminal_max_age`](Self::terminal_max_age) is: a sub-second part is
279    /// dropped.
280    #[must_use]
281    pub const fn with_parked_max_age(mut self, max_age: Duration) -> Self {
282        self.parked_max_age = Some(max_age);
283        self
284    }
285
286    /// Sets the rows-per-`DELETE` batch size. Zero is treated as one.
287    #[must_use]
288    pub const fn with_batch_size(mut self, batch_size: u32) -> Self {
289        self.batch_size = batch_size;
290        self
291    }
292
293    /// Sets how long an idempotency key is kept; `None` keeps them for ever.
294    ///
295    /// See [`idempotency_key_max_age`](Self::idempotency_key_max_age) for what
296    /// expiring one costs and why the sweep will not honour a value below
297    /// [`terminal_max_age`](Self::terminal_max_age).
298    #[must_use]
299    pub const fn with_idempotency_key_max_age(mut self, max_age: Option<Duration>) -> Self {
300        self.idempotency_key_max_age = max_age;
301        self
302    }
303
304    /// The key age the sweep actually uses: never below
305    /// [`terminal_max_age`](Self::terminal_max_age), nor below
306    /// [`parked_max_age`](Self::parked_max_age) when one is set.
307    ///
308    /// A key must outlive the task it names. Deleting one while its task is
309    /// still retained turns the next retry into a second task rather than a
310    /// replay, so a policy that asks for that is clamped rather than obeyed —
311    /// the same shape as `effective_batch_size` — which is `pub(crate)` and
312    /// feature-gated, so it cannot be linked from a public doc comment —
313    /// where a nonsensical value is floored at the nearest sensible one
314    /// instead of being honoured into a defect.
315    #[must_use]
316    pub fn effective_idempotency_key_max_age(&self) -> Option<Duration> {
317        self.idempotency_key_max_age.map(|age| {
318            age.max(self.terminal_max_age)
319                .max(self.parked_max_age.unwrap_or_default())
320        })
321    }
322
323    /// Bounds how many batches a single sweep runs.
324    #[must_use]
325    pub const fn with_max_batches(mut self, max_batches: u32) -> Self {
326        self.max_batches = Some(max_batches);
327        self
328    }
329
330    /// The batch size actually used, never zero — a zero-size batch would
331    /// delete nothing forever while reporting progress.
332    // Feature-gated because its only callers are the two backends. Without
333    // either, `-D warnings` makes it dead code -- and RUSTFLAGS applies to
334    // this crate even when it is built as a dependency of something else,
335    // which is why a policy type with no backend compiled broke fifteen CI
336    // jobs that never mention retention.
337    #[cfg(any(feature = "sqlite", feature = "postgres"))]
338    #[must_use]
339    pub(crate) const fn effective_batch_size(&self) -> u32 {
340        if self.batch_size == 0 {
341            1
342        } else {
343            self.batch_size
344        }
345    }
346}
347
348/// What one call to `purge_expired` did.
349///
350/// `#[non_exhaustive]`: read its fields, do not construct or exhaustively
351/// destructure it. A sweep that learns to count something new should not be a
352/// breaking change — 0.13.0's breaking list already carries one renamed field
353/// of this struct.
354#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
355#[non_exhaustive]
356pub struct PurgeReport {
357    /// Terminal task rows deleted.
358    pub tasks_deleted: u64,
359    /// Parked task rows deleted for being older than
360    /// [`RetentionPolicy::parked_max_age`]. Zero without it, which is the
361    /// default.
362    ///
363    /// Counted apart from [`tasks_deleted`](Self::tasks_deleted), and not in
364    /// it: a terminal task is finished work being forgotten, a parked one is
365    /// a wait nobody answered, and an operator watching the second wants to
366    /// see it move on its own.
367    pub parked_tasks_deleted: u64,
368    /// Side-table rows this sweep had to reclaim itself: artifact-journal
369    /// rows and event-log rows whose task was deleted.
370    ///
371    /// Normally **zero**, and that is the healthy reading: both tables have
372    /// an `ON DELETE CASCADE`, so on a pool with `foreign_keys=ON` — which
373    /// `SqliteTaskStore::new` sets — the rows go with the task and the sweep
374    /// finds nothing left to do. A non-zero count means rows had outlived
375    /// their task, which happens when `from_pool` was handed a pool without
376    /// the pragma.
377    ///
378    /// # It is zero on `PostgreSQL` because nothing counts there
379    ///
380    /// Only the `SQLite` sweep runs anti-join deletes; the `PostgreSQL` one
381    /// has no orphan statement at all, so this field is *structurally* zero on
382    /// both Postgres stores rather than observed to be. That is a deliberate
383    /// omission and not an oversight: `PostgreSQL` has no per-session
384    /// equivalent of `foreign_keys=OFF`, so a declared `ON DELETE CASCADE`
385    /// always fires and there is nothing for a sweep to find.
386    ///
387    /// The residual case it does **not** cover is a caller who handed
388    /// `from_pool` a database in which `task_events` or `tenant_task_events`
389    /// already existed without the foreign key — `CREATE TABLE IF NOT EXISTS`
390    /// leaves such a table alone. Rows can then be stranded there and no
391    /// Postgres sweep will reclaim them. Declare the tables from this crate's
392    /// own DDL, or from its migration runner, and the case does not arise.
393    ///
394    /// Since 0.13 the `SQLite` sweep runs on every purge rather than only on
395    /// one that deleted a task: a purge that fails part way strands rows that
396    /// outlive it, and the sweep is what reclaims them.
397    pub orphan_rows_deleted: u64,
398    /// Idempotency keys deleted for being older than
399    /// [`RetentionPolicy::idempotency_key_max_age`].
400    ///
401    /// Zero when that is `None`, and zero on a sweep that finds none expired.
402    /// Unlike [`orphan_rows_deleted`](Self::orphan_rows_deleted) a non-zero
403    /// count here is the healthy reading, not a warning: it is the sweep doing
404    /// the job it was given.
405    pub idempotency_keys_deleted: u64,
406    /// Events dropped from live tasks' logs by
407    /// [`RetentionPolicy::max_events_per_live_task`]; zero without it.
408    pub events_compacted: u64,
409
410    /// Batches executed.
411    pub batches: u32,
412    /// `false` when [`RetentionPolicy::max_batches`] stopped the sweep with
413    /// work still to do, so a caller can tell "nothing left" from "ran out of
414    /// budget" instead of inferring it from a count.
415    pub complete: bool,
416}
417
418/// The `state` column values a purge matches.
419///
420/// Built from [`TaskState`]'s own `Display`, not from string literals: the
421/// column holds whatever `to_string()` produced at write time, and a purge
422/// filtering on a hand-copied spelling would match nothing while looking
423/// correct.
424#[cfg(any(feature = "sqlite", feature = "postgres"))]
425pub(crate) fn terminal_state_labels() -> Vec<String> {
426    terminal_states().iter().map(TaskState::to_string).collect()
427}
428
429/// The `state` column values the parked sweep matches; built as
430/// [`terminal_state_labels`] is.
431#[cfg(any(feature = "sqlite", feature = "postgres"))]
432pub(crate) fn parked_state_labels() -> Vec<String> {
433    PARKED_STATES.iter().map(TaskState::to_string).collect()
434}
435
436#[cfg(test)]
437mod tests;