Skip to main content

a2a_protocol_server/conformance/halt/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Kill-switch conformance: grading a [`HaltStore`], and the halt it
5//! carries between replicas (ADR 0019, ADR 0024).
6//!
7//! A halt is the operator's last control over agents that misbehave, so a
8//! store that loses one, or keeps one it was told to remove, fails at the
9//! worst moment. Adopters write their own stores; this grades one the way
10//! [`check`](super::check) grades an executor.
11//!
12//! ```rust
13//! # use std::sync::Arc;
14//! # use a2a_protocol_server::conformance::halt::{check_handlers, check_store};
15//! # use a2a_protocol_server::store::{HaltStore, InMemoryHaltStore};
16//! # // rustdoc drops a `#[test]` fn without type-checking it, so make `#[tokio::test]` build it.
17//! # mod tokio { pub use ::tokio::*; pub use ::tokio::main as test; }
18//! # const URL: &str = "postgres://localhost/halts";
19//! # struct MyHaltStore;
20//! # impl MyHaltStore {
21//! #     async fn connect(_url: &str) -> InMemoryHaltStore { InMemoryHaltStore::new() }
22//! # }
23//!
24//! #[tokio::test]
25//! async fn my_halt_store_conforms() {
26//!     // Each call opens the same backing store, as a second replica would,
27//!     // or this one after a restart. Start from an empty one.
28//!     let open = || async { Arc::new(MyHaltStore::connect(URL).await) as Arc<dyn HaltStore> };
29//!     check_store(&open).await.assert_pass();
30//!     check_handlers(&open).await.assert_pass();
31//! }
32//! ```
33//!
34//! - [`check_store`] grades the [`HaltStore`] contract: a write replaces the
35//!   halt of its scope, a removal removes exactly its scope, scopes do not
36//!   collide (two job halts, [`HaltScope::Root`], whose tenant and root read
37//!   alike joined by a `:` included), another handle (a replica, a restarted
38//!   process) reads what was written, and a store that pushes delivers each write and each
39//!   cancel to the other handle.
40//! - [`check_handlers`] builds handlers on the store, as replicas, and grades
41//!   the kill switch end to end: a halt stops the tasks running on this
42//!   replica and on another, refuses new work on both, survives a restart,
43//!   is lifted everywhere by a resume on any replica, and a tenant's halt
44//!   spares the other tenants.
45//!
46//! # What it cannot tell you
47//!
48//! It cannot make the store fail, so the rule that a store which cannot be
49//! read answers with an error and not with no halts is not graded. It uses
50//! its own poll interval (50 ms) and its own executor, which honours
51//! cancellation, so it grades the store and the handler's wiring, not your
52//! interval or whether your executor stops when told; the executor harness
53//! ([`check`](super::check)) grades that. It runs each check once, so it
54//! cannot find a race. A pushed signal is graded by its arrival after a
55//! write: a store whose listener announces itself with a spurious signal,
56//! late, could pass a push check it would fail; the harness waits half a
57//! second for such signals first.
58
59use std::future::Future;
60use std::pin::Pin;
61use std::sync::Arc;
62use std::time::Duration;
63
64use a2a_protocol_types::error::A2aResult;
65
66use super::{CheckResult, Report};
67use crate::handler::HaltScope;
68use crate::store::{HaltSignal, HaltStore, StoredHalt};
69
70mod handlers;
71#[cfg(test)]
72mod tests;
73
74pub use handlers::check_handlers;
75
76/// How long a check waits for something to happen before it fails.
77const BOUND: Duration = Duration::from_secs(10);
78
79/// An adopter's store behind an `Arc`, as a [`HaltStore`] the builder takes.
80pub(super) struct Shared(pub(super) Arc<dyn HaltStore>);
81
82impl HaltStore for Shared {
83    fn load(&self) -> Pin<Box<dyn Future<Output = A2aResult<Vec<StoredHalt>>> + Send + '_>> {
84        self.0.load()
85    }
86    fn put<'a>(
87        &'a self,
88        halt: &'a StoredHalt,
89    ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
90        self.0.put(halt)
91    }
92    fn remove<'a>(
93        &'a self,
94        scope: &'a HaltScope,
95    ) -> Pin<Box<dyn Future<Output = A2aResult<bool>> + Send + 'a>> {
96        self.0.remove(scope)
97    }
98    fn signals(&self) -> Option<tokio::sync::broadcast::Receiver<HaltSignal>> {
99        self.0.signals()
100    }
101    fn publish_cancel<'a>(
102        &'a self,
103        tenant: &'a str,
104        task: &'a str,
105    ) -> Pin<Box<dyn Future<Output = A2aResult<()>> + Send + 'a>> {
106        self.0.publish_cancel(tenant, task)
107    }
108}
109
110/// The halts `store` holds, sorted, or the error as text.
111async fn loaded(store: &dyn HaltStore) -> Result<Vec<StoredHalt>, String> {
112    let mut halts = store
113        .load()
114        .await
115        .map_err(|e| format!("load failed: {e}"))?;
116    halts.sort_by_key(|h| format!("{:?}", h.scope));
117    Ok(halts)
118}
119
120fn sorted(mut halts: Vec<StoredHalt>) -> Vec<StoredHalt> {
121    halts.sort_by_key(|h| format!("{:?}", h.scope));
122    halts
123}
124
125/// Grades the [`HaltStore`] that `open` opens. Each call to `open` must open
126/// the same backing store, starting empty, as another replica would, or
127/// this process after a restart. The store is left empty.
128pub async fn check_store<F, Fut>(open: &F) -> Report
129where
130    F: Fn() -> Fut + Sync,
131    Fut: Future<Output = Arc<dyn HaltStore>> + Send,
132{
133    let store = open().await;
134    let halts = Halts::new();
135    let mut results = vec![fresh(&*store).await];
136    let (written, expected) = writes(&*store, &halts).await;
137    results.extend(written);
138    let reopened = open().await;
139    results.push(reads_elsewhere(&*reopened, &expected).await);
140    results.extend(removals(&*store, &*reopened, &halts).await);
141    results.push(jobs(&*store, &*reopened).await);
142    results.extend(pushes(&*store, &*reopened).await);
143    Report {
144        subject: "halt store",
145        results,
146    }
147}
148
149/// The halts the store checks write.
150struct Halts {
151    all: StoredHalt,
152    acme: StoredHalt,
153    /// A tenant named like the other scope: a store that keys scopes by a
154    /// bare string makes the two one halt.
155    named_all: StoredHalt,
156    replaced: StoredHalt,
157}
158
159impl Halts {
160    fn new() -> Self {
161        Self {
162            all: StoredHalt::new(HaltScope::All, "incident", "oncall"),
163            acme: StoredHalt::new(HaltScope::Tenant("acme".into()), "spend", "alice"),
164            named_all: StoredHalt::new(HaltScope::Tenant("all".into()), "odd name", "bob"),
165            replaced: StoredHalt::new(HaltScope::Tenant("acme".into()), "spend, again", "carol"),
166        }
167    }
168}
169
170async fn fresh(store: &dyn HaltStore) -> CheckResult {
171    const NAME: &str = "a_fresh_store_is_empty";
172    match loaded(store).await {
173        Ok(h) if h.is_empty() => CheckResult::pass(NAME, "no halts"),
174        Ok(h) => CheckResult::fail(
175            NAME,
176            format!("{} halt(s) already stored; grade an empty store", h.len()),
177        ),
178        Err(e) => CheckResult::fail(NAME, e),
179    }
180}
181
182/// Writes four halts, the last replacing the second, and grades what is
183/// loaded; returns the results and the halts the store should now hold.
184async fn writes(store: &dyn HaltStore, h: &Halts) -> (Vec<CheckResult>, Vec<StoredHalt>) {
185    const REPLACES: &str = "a_put_replaces_the_halt_of_its_scope";
186    const COLLIDE: &str = "scopes_do_not_collide";
187    let mut wrote = Ok(());
188    for halt in [&h.all, &h.acme, &h.named_all, &h.replaced] {
189        if let Err(e) = store.put(halt).await {
190            wrote = Err(format!("put failed: {e}"));
191        }
192    }
193    let expected = sorted(vec![h.all.clone(), h.replaced.clone(), h.named_all.clone()]);
194    let after = match wrote {
195        Ok(()) => loaded(store).await,
196        Err(e) => Err(e),
197    };
198    let replaces = match &after {
199        Ok(got) if *got == expected => {
200            CheckResult::pass(REPLACES, "the second halt of a tenant replaced the first")
201        }
202        Ok(got) => CheckResult::fail(REPLACES, format!("expected {expected:?}, loaded {got:?}")),
203        Err(e) => CheckResult::fail(REPLACES, e.clone()),
204    };
205    let collide = match &after {
206        Ok(got)
207            if got.iter().any(|x| x.scope == HaltScope::All)
208                && got
209                    .iter()
210                    .any(|x| x.scope == HaltScope::Tenant("all".into())) =>
211        {
212            CheckResult::pass(
213                COLLIDE,
214                "the halt of everything and the halt of a tenant named `all` are two halts",
215            )
216        }
217        Ok(got) => CheckResult::fail(
218            COLLIDE,
219            format!("the halt of everything and of tenant `all` were merged: {got:?}"),
220        ),
221        Err(e) => CheckResult::fail(COLLIDE, e.clone()),
222    };
223    (vec![replaces, collide], expected)
224}
225
226async fn reads_elsewhere(reopened: &dyn HaltStore, expected: &[StoredHalt]) -> CheckResult {
227    const NAME: &str = "another_handle_reads_what_was_written";
228    match loaded(reopened).await {
229        Ok(h) if h == expected => {
230            CheckResult::pass(NAME, "a second handle on the store loaded the same halts")
231        }
232        Ok(h) => CheckResult::fail(
233            NAME,
234            format!("written {expected:?}, another handle loaded {h:?}"),
235        ),
236        Err(e) => CheckResult::fail(NAME, e),
237    }
238}
239
240/// Removes a tenant's halt twice, then the rest, and grades what each
241/// handle loads after.
242async fn removals(store: &dyn HaltStore, reopened: &dyn HaltStore, h: &Halts) -> Vec<CheckResult> {
243    const EXACT: &str = "a_remove_removes_exactly_its_scope";
244    const SEEN: &str = "a_removal_is_seen_by_another_handle";
245    let tenant = HaltScope::Tenant("acme".into());
246    let removal = async {
247        let first = store.remove(&tenant).await.map_err(|e| e.to_string())?;
248        let second = store.remove(&tenant).await.map_err(|e| e.to_string())?;
249        let left = loaded(store).await?;
250        Ok::<_, String>((first, second, left))
251    }
252    .await;
253    let rest = sorted(vec![h.all.clone(), h.named_all.clone()]);
254    let exact = match removal {
255        Ok((true, false, left)) if left == rest => {
256            CheckResult::pass(EXACT, "true, then false, and the other halts stayed")
257        }
258        Ok((first, second, left)) => CheckResult::fail(
259            EXACT,
260            format!(
261                "remove answered {first} then {second} (want true then false); left {left:?}, want {rest:?}"
262            ),
263        ),
264        Err(e) => CheckResult::fail(EXACT, e),
265    };
266    let emptied = async {
267        for scope in [HaltScope::All, HaltScope::Tenant("all".into())] {
268            store.remove(&scope).await.map_err(|e| e.to_string())?;
269        }
270        loaded(reopened).await
271    }
272    .await;
273    let seen = match emptied {
274        Ok(left) if left.is_empty() => {
275            CheckResult::pass(SEEN, "the other handle loads no halts once all are removed")
276        }
277        Ok(left) => CheckResult::fail(
278            SEEN,
279            format!("all removed, another handle still loads {left:?}"),
280        ),
281        Err(e) => CheckResult::fail(SEEN, e),
282    };
283    vec![exact, seen]
284}
285
286/// Two job halts ([`HaltScope::Root`], ADR 0034) whose tenant and root read
287/// alike joined by a `:` are two halts, and removing one leaves the other.
288async fn jobs(store: &dyn HaltStore, reopened: &dyn HaltStore) -> CheckResult {
289    const NAME: &str = "job_halts_are_kept_apart";
290    let a = StoredHalt::new(HaltScope::root("a:b", "c"), "job a", "dave");
291    let b = StoredHalt::new(HaltScope::root("a", "b:c"), "job b", "erin");
292    let run = async {
293        for halt in [&a, &b] {
294            store
295                .put(halt)
296                .await
297                .map_err(|e| format!("put failed: {e}"))?;
298        }
299        let both = loaded(reopened).await?;
300        let removed = store.remove(&a.scope).await.map_err(|e| e.to_string())?;
301        let left = loaded(reopened).await?;
302        store.remove(&b.scope).await.map_err(|e| e.to_string())?;
303        Ok::<_, String>((both, removed, left))
304    }
305    .await;
306    let want_both = sorted(vec![a, b.clone()]);
307    match run {
308        Ok((both, true, left)) if both == want_both && left == [b.clone()] => CheckResult::pass(
309            NAME,
310            "the jobs (\"a:b\", \"c\") and (\"a\", \"b:c\") are two halts, removed one at a time",
311        ),
312        Ok((both, removed, left)) => CheckResult::fail(
313            NAME,
314            format!(
315                "loaded {both:?} (want {want_both:?}); remove answered {removed}; then left {left:?} (want only {b:?})"
316            ),
317        ),
318        Err(e) => CheckResult::fail(NAME, e),
319    }
320}
321
322/// The push checks: what `writer` writes, `reader`'s subscription is told.
323async fn pushes(writer: &dyn HaltStore, reader: &dyn HaltStore) -> Vec<CheckResult> {
324    let Some(mut rx) = reader.signals() else {
325        let why = "the store does not push: handlers sharing it learn of a halt by polling";
326        return vec![
327            CheckResult::skip("a_write_is_pushed_to_another_handle", why),
328            CheckResult::skip("a_cancel_is_pushed_to_another_handle", why),
329        ];
330    };
331    // Settle: a listener may announce itself with a signal of its own.
332    let _ = tokio::time::timeout(Duration::from_millis(500), async {
333        while rx.recv().await.is_ok() {}
334    })
335    .await;
336    while rx.try_recv().is_ok() {}
337
338    let scope = HaltScope::Tenant("conformance-push".into());
339    let mut out = Vec::new();
340    let write = async {
341        writer
342            .put(&StoredHalt::new(scope.clone(), "push", "conformance"))
343            .await
344            .map_err(|e| format!("put failed: {e}"))?;
345        next(&mut rx, |s| *s == HaltSignal::Changed)
346            .await
347            .ok_or("no signal within 10 s of a put")?;
348        writer
349            .remove(&scope)
350            .await
351            .map_err(|e| format!("remove failed: {e}"))?;
352        next(&mut rx, |s| *s == HaltSignal::Changed)
353            .await
354            .ok_or("no signal within 10 s of a remove")?;
355        Ok::<_, String>(())
356    }
357    .await;
358    out.push(match write {
359        Ok(()) => CheckResult::pass(
360            "a_write_is_pushed_to_another_handle",
361            "a put and a remove each signalled the other handle",
362        ),
363        Err(e) => CheckResult::fail("a_write_is_pushed_to_another_handle", e),
364    });
365
366    out.push(pushed_cancel(writer, &mut rx).await);
367    out
368}
369
370/// A cancel published on `writer` reaches `rx`, another handle's
371/// subscription.
372async fn pushed_cancel(
373    writer: &dyn HaltStore,
374    rx: &mut tokio::sync::broadcast::Receiver<HaltSignal>,
375) -> CheckResult {
376    let want = HaltSignal::Cancel {
377        tenant: "conformance".to_owned(),
378        task: "task-1".to_owned(),
379    };
380    let cancel = async {
381        writer
382            .publish_cancel("conformance", "task-1")
383            .await
384            .map_err(|e| format!("publish_cancel failed: {e}"))?;
385        next(rx, |s| *s == want)
386            .await
387            .ok_or_else(|| "the cancel did not reach the other handle within 10 s".to_owned())
388    }
389    .await;
390    match cancel {
391        Ok(_) => CheckResult::pass(
392            "a_cancel_is_pushed_to_another_handle",
393            "the other handle was told which task to stop",
394        ),
395        Err(e) => CheckResult::fail("a_cancel_is_pushed_to_another_handle", e),
396    }
397}
398
399/// The first signal matching `want` within [`BOUND`], skipping others.
400async fn next(
401    rx: &mut tokio::sync::broadcast::Receiver<HaltSignal>,
402    want: impl Fn(&HaltSignal) -> bool + Send + Sync,
403) -> Option<HaltSignal> {
404    tokio::time::timeout(BOUND, async {
405        loop {
406            match rx.recv().await {
407                Ok(s) if want(&s) => return Some(s),
408                Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
409                Err(tokio::sync::broadcast::error::RecvError::Closed) => return None,
410            }
411        }
412    })
413    .await
414    .ok()
415    .flatten()
416}