Skip to main content

a2a_protocol_server/conformance/halt/
handlers.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! The kill switch end to end: handlers built on the store under grade,
5//! standing for replicas.
6
7use std::future::Future;
8use std::sync::Arc;
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::time::Duration;
11
12use a2a_protocol_types::message::Message;
13use a2a_protocol_types::params::{MessageSendParams, TaskQueryParams};
14use a2a_protocol_types::responses::SendMessageResponse;
15use a2a_protocol_types::task::TaskState;
16
17use super::{BOUND, Shared};
18use crate::builder::RequestHandlerBuilder;
19use crate::conformance::{CheckResult, Report};
20use crate::error::ServerError;
21use crate::handler::HaltScope;
22use crate::store::{HaltStore, TenantAwareInMemoryTaskStore};
23use crate::{EventEmitter, RequestHandler, SendMessageResult, agent_executor};
24
25/// How often the harness's handlers read the store.
26const POLL: Duration = Duration::from_millis(50);
27
28/// Works until cancelled.
29struct Worker;
30agent_executor!(Worker, |ctx, queue| async {
31    EventEmitter::new(ctx, queue)
32        .status(TaskState::Working)
33        .await?;
34    ctx.cancellation_token.cancelled().await;
35    Ok(())
36});
37
38fn replica(store: Arc<dyn HaltStore>) -> Result<RequestHandler, String> {
39    RequestHandlerBuilder::new(Worker)
40        .without_agent_card()
41        .with_task_store(TenantAwareInMemoryTaskStore::new())
42        .with_halt_store(Shared(store))
43        .with_halt_poll_interval(POLL)
44        .build()
45        .map_err(|e| format!("a handler on the store did not build: {e}"))
46}
47
48/// A report of one failure, for a run that could not get started.
49fn stopped_at(name: &'static str, why: impl Into<String>) -> Report {
50    Report {
51        subject: "kill switch",
52        results: vec![CheckResult::fail(name, why)],
53    }
54}
55
56fn params(tenant: &str) -> MessageSendParams {
57    static NEXT: AtomicU64 = AtomicU64::new(0);
58    let id = format!("halt-conformance-{}", NEXT.fetch_add(1, Ordering::Relaxed));
59    let mut p = MessageSendParams::new(Message::user_text(id, "work"));
60    p.tenant = Some(tenant.to_owned());
61    p.configuration = serde_json::from_value(serde_json::json!({ "returnImmediately": true })).ok();
62    p
63}
64
65/// Starts a task in `tenant`; its id, or why it was not started.
66async fn start(h: &RequestHandler, tenant: &str) -> Result<String, String> {
67    match h.on_send_message(params(tenant), false, None).await {
68        Ok(SendMessageResult::Response(SendMessageResponse::Task(t))) => Ok(t.id.0),
69        Ok(_) => Err("the send answered without a task".to_owned()),
70        Err(e) => Err(e.to_string()),
71    }
72}
73
74/// Whether a send to `tenant` is refused as halted.
75async fn refused(h: &RequestHandler, tenant: &str) -> bool {
76    matches!(
77        h.on_send_message(params(tenant), false, None).await,
78        Err(ServerError::Halted(_))
79    )
80}
81
82async fn state(h: &RequestHandler, tenant: &str, id: &str) -> Option<TaskState> {
83    let q = TaskQueryParams::new(id.to_owned()).with_tenant(tenant.to_owned());
84    h.on_get_task(q, None).await.ok().map(|t| t.status.state)
85}
86
87/// Waits up to [`BOUND`] for `done` to hold.
88async fn within<F, Fut>(done: F) -> bool
89where
90    F: Fn() -> Fut + Send + Sync,
91    Fut: Future<Output = bool> + Send,
92{
93    tokio::time::timeout(BOUND, async {
94        while !done().await {
95            tokio::time::sleep(Duration::from_millis(10)).await;
96        }
97    })
98    .await
99    .is_ok()
100}
101
102async fn reaches(h: &RequestHandler, tenant: &str, id: &str, want: TaskState) -> bool {
103    within(|| async { state(h, tenant, id).await == Some(want) }).await
104}
105
106fn grade(name: &'static str, ok: bool, pass: &str, fail: impl Into<String>) -> CheckResult {
107    if ok {
108        CheckResult::pass(name, pass)
109    } else {
110        CheckResult::fail(name, fail)
111    }
112}
113
114/// Grades the kill switch on handlers built on the store `open` opens: each
115/// call must open the same backing store, starting empty, as
116/// [`check_store`](super::check_store) requires. The store is left empty.
117///
118/// The checks run in order, each on the state the last left: a halt that
119/// never reaches the other replica also fails the checks after it that need
120/// it to have.
121pub async fn check_handlers<F, Fut>(open: &F) -> Report
122where
123    F: Fn() -> Fut + Sync,
124    Fut: Future<Output = Arc<dyn HaltStore>> + Send,
125{
126    let (here, there) = match (replica(open().await), replica(open().await)) {
127        (Ok(here), Ok(there)) => (here, there),
128        (Err(e), _) | (_, Err(e)) => return stopped_at("replicas_build", e),
129    };
130    let (Ok(local), Ok(remote)) = (start(&here, "t1").await, start(&there, "t1").await) else {
131        return stopped_at(
132            "tasks_start_before_the_halt",
133            "the harness could not start a task on a fresh replica",
134        );
135    };
136    let mut results = halts(&here, &there, &local, &remote).await;
137    let restarted = match replica(open().await) {
138        Ok(h) => h,
139        Err(e) => {
140            results.push(CheckResult::fail(
141                "a_restarted_replica_comes_back_halted",
142                e,
143            ));
144            return Report {
145                subject: "kill switch",
146                results,
147            };
148        }
149    };
150    results.extend(restart_and_resume(&here, &there, &restarted).await);
151    results.push(tenant_scope(&here, &there).await);
152    Report {
153        subject: "kill switch",
154        results,
155    }
156}
157
158/// Halts everything on `here` while `local` runs there and `remote` on
159/// `there`, and grades what each replica does.
160async fn halts(
161    here: &RequestHandler,
162    there: &RequestHandler,
163    local: &str,
164    remote: &str,
165) -> Vec<CheckResult> {
166    let ran = reaches(here, "t1", local, TaskState::Working).await
167        && reaches(there, "t1", remote, TaskState::Working).await;
168    let mut results = vec![grade(
169        "tasks_start_before_the_halt",
170        ran,
171        "a task runs on each replica",
172        "a task never reached working",
173    )];
174    let report = here
175        .halt(HaltScope::All, "conformance", "kill switch")
176        .await;
177    results.push(grade(
178        "a_halt_is_written_to_the_store",
179        report.persisted == Some(true),
180        "the halt was stored",
181        format!("persisted = {:?}", report.persisted),
182    ));
183    results.push(grade(
184        "a_halt_stops_this_replicas_tasks",
185        report.stopped.iter().any(|t| t == local)
186            && reaches(here, "t1", local, TaskState::Canceled).await,
187        "the running task was stopped and ended canceled",
188        format!(
189            "stopped {:?}; the task did not end canceled",
190            report.stopped
191        ),
192    ));
193    results.push(grade(
194        "a_halt_refuses_new_work_here",
195        refused(here, "t1").await,
196        "a new send was refused as halted",
197        "a new send was admitted",
198    ));
199    results.push(grade(
200        "a_halt_stops_the_other_replicas_tasks",
201        reaches(there, "t1", remote, TaskState::Canceled).await,
202        "the other replica's task ended canceled",
203        "the other replica's task was still not canceled after 10 s",
204    ));
205    results.push(grade(
206        "a_halt_refuses_new_work_on_the_other_replica",
207        within(|| refused(there, "t1")).await,
208        "the other replica refused a new send",
209        "the other replica still admitted sends after 10 s",
210    ));
211    results
212}
213
214/// A replica built after the halt starts halted; a resume on another lifts
215/// it on every replica.
216async fn restart_and_resume(
217    here: &RequestHandler,
218    there: &RequestHandler,
219    restarted: &RequestHandler,
220) -> Vec<CheckResult> {
221    let came_back = grade(
222        "a_restarted_replica_comes_back_halted",
223        refused(restarted, "t1").await,
224        "the first send to a new replica was refused",
225        "a replica built after the halt admitted its first send",
226    );
227    let resumed = there.resume(HaltScope::All, "conformance").await;
228    let lifted = matches!(resumed, Ok(true))
229        && within(|| async { start(here, "t1").await.is_ok() }).await
230        && within(|| async { start(restarted, "t1").await.is_ok() }).await;
231    let resume = grade(
232        "a_resume_on_any_replica_lifts_the_halt_everywhere",
233        lifted,
234        "after a resume on one replica, the others admitted sends",
235        format!("resume answered {resumed:?}, or a replica still refused after 10 s"),
236    );
237    vec![came_back, resume]
238}
239
240/// A tenant's halt stops that tenant's work and only that.
241async fn tenant_scope(here: &RequestHandler, there: &RequestHandler) -> CheckResult {
242    const NAME: &str = "a_tenant_halt_spares_other_tenants";
243    let (Ok(acme), Ok(beta)) = (start(here, "acme").await, start(here, "beta").await) else {
244        return CheckResult::fail(NAME, "tasks could not be started after the resume");
245    };
246    let scope = HaltScope::Tenant("acme".into());
247    here.halt(scope.clone(), "conformance", "one tenant").await;
248    let stopped = reaches(here, "acme", &acme, TaskState::Canceled).await;
249    // Once the other replica refuses acme it has read the halt, so beta is
250    // judged against what the store holds, not against a replica that has
251    // not looked yet: a store that widened the halt to every tenant passed
252    // when beta was judged first.
253    let refused_there = within(|| refused(there, "acme")).await;
254    let spared = state(here, "beta", &beta).await == Some(TaskState::Working)
255        && start(there, "beta").await.is_ok();
256    let _ = here.resume(scope, "conformance").await;
257    grade(
258        NAME,
259        stopped && spared && refused_there,
260        "acme stopped and refused on both replicas; beta kept working and admitted sends",
261        format!(
262            "acme stopped: {stopped}; beta spared: {spared}; acme refused on the other replica: {refused_there}"
263        ),
264    )
265}
266
267#[cfg(test)]
268#[path = "handlers_tests.rs"]
269mod tests;