From d56e9926b7095abbcfd426711aa61a6a482c385f Mon Sep 17 00:00:00 2001
From: gulldan <5641375+gulldan@users.noreply.github.com>
Date: Sat, 31 Oct 2026 13:20:16 +0300
Subject: [PATCH 1/5] fix(client): report the HTTP status of a non-JSON-RPC
error response
The JSON-RPC transport never looked at the status of a response. An
error that something in front of the agent answers itself (an
authenticating proxy's 401, a gateway's 429 or 502) carries no
JSON-RPC envelope, so the caller got "failed to parse JSON-RPC
response" and could not tell a credential or rate-limit problem from
a broken server. A streaming call answered that way without a content
type was handed to the SSE parser and came back as an empty stream.
A body that is not a JSON-RPC envelope is now reported with its
status, as the REST transport already does ("HTTP 429 Too Many
Requests:
"); a JSON-RPC envelope is still decoded whatever the
status, and a non-success status is never treated as a stream.
Fixes: #404
Co-Authored-By: Claude Opus 5.5
Signed-off-by: gulldan <5641375+gulldan@users.noreply.github.com>
---
a2a-client/src/jsonrpc.rs | 107 +++++++++++++++++++++++++++++++++-----
1 file changed, 93 insertions(+), 14 deletions(-)
diff --git a/a2a-client/src/jsonrpc.rs b/a2a-client/src/jsonrpc.rs
index 79887b9e..6d3cf3ae 100644
--- a/a2a-client/src/jsonrpc.rs
+++ b/a2a-client/src/jsonrpc.rs
@@ -35,6 +35,22 @@ fn parse_jsonrpc_error(err: JsonRpcError) -> A2AError {
crate::a2a_error_from_details(err.code, err.message, details)
}
+/// Parses a JSON-RPC envelope. A body that is not one, sent with a non-success
+/// status (an authenticating proxy's 401, a gateway's 429 or 502), is reported
+/// with that status, as the REST transport reports it.
+fn parse_jsonrpc_response(
+ status: reqwest::StatusCode,
+ body: &str,
+) -> Result {
+ serde_json::from_str(body).map_err(|e| {
+ if status.is_success() {
+ A2AError::internal(format!("failed to parse JSON-RPC response: {e}"))
+ } else {
+ A2AError::internal(format!("HTTP {status}: {body}"))
+ }
+ })
+}
+
/// JSON-RPC transport implementation.
///
/// Sends all requests as JSON-RPC 2.0 POSTs to a single endpoint.
@@ -67,6 +83,7 @@ impl JsonRpcTransport {
}
let response = wire::send(&self.client, builder.json(&rpc_request)).await?;
+ let status = response.status();
// Read the body as text first so the raw bytes can be logged before
// they become a typed value; one error message still covers both a
@@ -74,8 +91,7 @@ impl JsonRpcTransport {
let body = wire::response_text(response)
.await
.map_err(|e| A2AError::internal(format!("failed to parse JSON-RPC response: {e}")))?;
- let rpc_response: JsonRpcResponse = serde_json::from_str(&body)
- .map_err(|e| A2AError::internal(format!("failed to parse JSON-RPC response: {e}")))?;
+ let rpc_response = parse_jsonrpc_response(status, &body)?;
if let Some(err) = rpc_response.error {
return Err(parse_jsonrpc_error(err));
@@ -150,14 +166,16 @@ impl JsonRpcTransport {
// in the envelope rather than via status code. Detect that case by
// content type before handing the body to the SSE parser, which
// would otherwise find no `data:` frames and yield an empty stream.
- // A response with no content type is still treated as a stream:
+ // A success with no content type is still treated as a stream:
// reading it to inspect it would hang on a stream that has not sent
- // anything yet.
- let is_event_stream = response
- .headers()
- .get(reqwest::header::CONTENT_TYPE)
- .map(|v| v.as_bytes().starts_with(b"text/event-stream"))
- .unwrap_or(true);
+ // anything yet. A non-success status is never a stream.
+ let status = response.status();
+ let is_event_stream = status.is_success()
+ && response
+ .headers()
+ .get(reqwest::header::CONTENT_TYPE)
+ .map(|v| v.as_bytes().starts_with(b"text/event-stream"))
+ .unwrap_or(true);
if is_event_stream {
let stream = response.bytes_stream();
@@ -166,9 +184,7 @@ impl JsonRpcTransport {
let body = wire::response_text(response).await.map_err(|e| {
A2AError::internal(format!("failed to parse JSON-RPC response: {e}"))
})?;
- let rpc_response: JsonRpcResponse = serde_json::from_str(&body).map_err(|e| {
- A2AError::internal(format!("failed to parse JSON-RPC response: {e}"))
- })?;
+ let rpc_response = parse_jsonrpc_response(status, &body)?;
match rpc_response.error {
Some(err) => Err(parse_jsonrpc_error(err)),
@@ -525,12 +541,12 @@ impl Transport for JsonRpcTransport {
}
let response = wire::send(&self.client, builder.json(&rpc_request)).await?;
+ let status = response.status();
let body = wire::response_text(response)
.await
.map_err(|e| A2AError::internal(format!("failed to parse JSON-RPC response: {e}")))?;
- let rpc_response: JsonRpcResponse = serde_json::from_str(&body)
- .map_err(|e| A2AError::internal(format!("failed to parse JSON-RPC response: {e}")))?;
+ let rpc_response = parse_jsonrpc_response(status, &body)?;
if let Some(err) = rpc_response.error {
return Err(parse_jsonrpc_error(err));
@@ -657,6 +673,25 @@ mod tests {
format!("http://{addr}")
}
+ /// Answers one request with `status` and a body that is not JSON-RPC, as an
+ /// authenticating proxy or a gateway in front of the agent does.
+ async fn spawn_http_error_server(status: &'static str, body: &'static str) -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+
+ tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let _request = read_http_request(&mut socket).await;
+ let response = format!(
+ "HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len(),
+ );
+ socket.write_all(response.as_bytes()).await.unwrap();
+ });
+
+ format!("http://{addr}")
+ }
+
async fn read_http_request(socket: &mut TcpStream) -> String {
let mut buffer = Vec::new();
let mut chunk = [0_u8; 1024];
@@ -1502,6 +1537,50 @@ mod tests {
assert!(error.message.contains("failed to parse JSON-RPC response"));
}
+ #[tokio::test]
+ async fn test_http_error_without_jsonrpc_body_reports_the_status() {
+ let endpoint = spawn_http_error_server("429 Too Many Requests", "budget exceeded").await;
+ let transport =
+ JsonRpcTransport::new(crate::default_reqwest_client(None).unwrap(), endpoint);
+
+ let error = transport
+ .get_task(
+ &ServiceParams::new(),
+ &GetTaskRequest {
+ id: "task-1".into(),
+ history_length: None,
+ tenant: None,
+ },
+ )
+ .await
+ .unwrap_err();
+
+ assert_eq!(error.code, error_code::INTERNAL_ERROR);
+ assert_eq!(error.message, "HTTP 429 Too Many Requests: budget exceeded");
+ }
+
+ #[tokio::test]
+ async fn test_streaming_http_error_reports_the_status_not_an_empty_stream() {
+ // No content type, so the status is the only thing marking it as no stream.
+ let endpoint = spawn_http_error_server("401 Unauthorized", "").await;
+ let transport =
+ JsonRpcTransport::new(crate::default_reqwest_client(None).unwrap(), endpoint);
+
+ let req = SubscribeToTaskRequest {
+ id: "task-1".into(),
+ tenant: None,
+ };
+ let error = match transport
+ .subscribe_to_task(&ServiceParams::new(), &req)
+ .await
+ {
+ Err(e) => e,
+ Ok(_) => panic!("expected error, got a stream"),
+ };
+
+ assert_eq!(error.message, "HTTP 401 Unauthorized: ");
+ }
+
#[tokio::test]
async fn test_create_push_config_rejects_missing_result() {
let response = json!({
From 70f0f45658eefc229e52011417c6b067e0fb420a Mon Sep 17 00:00:00 2001
From: gulldan <5641375+gulldan@users.noreply.github.com>
Date: Sat, 31 Oct 2026 18:20:02 +0300
Subject: [PATCH 2/5] test(client): take the subscribe error without an
unreachable arm
The streaming test matched on the result and panicked in an `Ok` arm that a
passing run never reaches, so that line stayed uncovered. Taking the error
with `.err().expect()` keeps the assertion and needs no `Debug` on the stream.
Co-Authored-By: Claude Opus 5.5
Signed-off-by: gulldan <5641375+gulldan@users.noreply.github.com>
---
a2a-client/src/jsonrpc.rs | 8 +++-----
1 file changed, 3 insertions(+), 5 deletions(-)
diff --git a/a2a-client/src/jsonrpc.rs b/a2a-client/src/jsonrpc.rs
index 6d3cf3ae..87ea8b0c 100644
--- a/a2a-client/src/jsonrpc.rs
+++ b/a2a-client/src/jsonrpc.rs
@@ -1570,13 +1570,11 @@ mod tests {
id: "task-1".into(),
tenant: None,
};
- let error = match transport
+ let error = transport
.subscribe_to_task(&ServiceParams::new(), &req)
.await
- {
- Err(e) => e,
- Ok(_) => panic!("expected error, got a stream"),
- };
+ .err()
+ .expect("expected error, got a stream");
assert_eq!(error.message, "HTTP 401 Unauthorized: ");
}
From 9e749f4c2c1c45607a753eeabce27dae8ac5e76d Mon Sep 17 00:00:00 2001
From: gulldan <5641375+gulldan@users.noreply.github.com>
Date: Sat, 31 Oct 2026 13:20:13 +0300
Subject: [PATCH 3/5] fix(a2a-pb): decode integral Value numbers as integers
google.protobuf.Value carries every number as a double, and
proto_value_to_json_value turned each one back into a JSON float, so
an integer in a data part or in metadata reached the executor, and a
client's decoded response, as 3600.0. serde then refuses it for an
integer type ("invalid type: floating point `3600.0`, expected u32").
A whole number within +-2^53, where a double is exact, is now given
back as an integer; other numbers stay floats. The round-trip tests
that used floats to work around this now use integers, and a new
protojson test decodes a JSON-RPC SendMessage whose data part holds an
integer and deserializes it into u32.
Fixes: #399
Co-Authored-By: Claude Opus 5.5
Signed-off-by: gulldan <5641375+gulldan@users.noreply.github.com>
---
a2a-pb/src/pbconv.rs | 26 +++++++++++++++++---------
a2a-pb/tests/protojson.rs | 23 +++++++++++++++++++++++
2 files changed, 40 insertions(+), 9 deletions(-)
diff --git a/a2a-pb/src/pbconv.rs b/a2a-pb/src/pbconv.rs
index 64e561ad..ef8840eb 100644
--- a/a2a-pb/src/pbconv.rs
+++ b/a2a-pb/src/pbconv.rs
@@ -64,9 +64,7 @@ pub fn proto_value_to_json_value(v: &prost_types::Value) -> Value {
match &v.kind {
Some(Kind::NullValue(_)) => Value::Null,
Some(Kind::BoolValue(b)) => Value::Bool(*b),
- Some(Kind::NumberValue(n)) => serde_json::Number::from_f64(*n)
- .map(Value::Number)
- .unwrap_or(Value::Null),
+ Some(Kind::NumberValue(n)) => json_number(*n).map(Value::Number).unwrap_or(Value::Null),
Some(Kind::StringValue(s)) => Value::String(s.clone()),
Some(Kind::ListValue(list)) => {
Value::Array(list.values.iter().map(proto_value_to_json_value).collect())
@@ -83,6 +81,18 @@ pub fn proto_value_to_json_value(v: &prost_types::Value) -> Value {
}
}
+/// `google.protobuf.Value` holds every number as a double, so an integer such
+/// as `3600` arrives as `3600.0`. A whole number within ±2^53, where a double
+/// is exact, is given back as an integer so it still deserializes into one.
+fn json_number(n: f64) -> Option {
+ const MAX_EXACT_INTEGER: f64 = 9_007_199_254_740_992.0;
+ if n.fract() == 0.0 && n.abs() <= MAX_EXACT_INTEGER {
+ Some((n as i64).into())
+ } else {
+ serde_json::Number::from_f64(n)
+ }
+}
+
/// Lowest `seconds` a `google.protobuf.Timestamp` may carry: `0001-01-01T00:00:00Z`.
const PROTO_TIMESTAMP_MIN_SECONDS: i64 = -62_135_596_800;
/// Highest `seconds` a `google.protobuf.Timestamp` may carry: `9999-12-31T23:59:59Z`.
@@ -1495,10 +1505,9 @@ mod tests {
fn test_struct_roundtrip() {
let mut map = HashMap::new();
map.insert("str".to_string(), Value::String("hello".to_string()));
- map.insert(
- "num".to_string(),
- Value::Number(serde_json::Number::from_f64(42.0).unwrap()),
- );
+ map.insert("num".to_string(), serde_json::json!(42));
+ map.insert("negative".to_string(), serde_json::json!(-7));
+ map.insert("fraction".to_string(), serde_json::json!(4.5));
map.insert("bool".to_string(), Value::Bool(true));
map.insert("null".to_string(), Value::Null);
let proto_s = to_proto_struct(&map);
@@ -2166,8 +2175,7 @@ mod tests {
#[test]
fn test_part_data_roundtrip() {
- // Use f64 numbers since proto Value stores all numbers as f64
- let data = serde_json::json!({"nested": [1.0, 2.0, 3.0]});
+ let data = serde_json::json!({"nested": [1, 2, 3], "ratio": 0.5});
let part = Part {
content: PartContent::Data(data),
filename: None,
diff --git a/a2a-pb/tests/protojson.rs b/a2a-pb/tests/protojson.rs
index 160809e9..b91a901a 100644
--- a/a2a-pb/tests/protojson.rs
+++ b/a2a-pb/tests/protojson.rs
@@ -313,3 +313,26 @@ fn stream_response_protojson_roundtrip_serializes_oneof_payloads() {
let roundtrip: StreamResponse = serde_json::from_value(json).unwrap();
assert_eq!(response, roundtrip);
}
+
+/// `google.protobuf.Value` carries every number as a double, so an integer in
+/// a data part has to come back out as an integer, not as `3600.0`.
+#[test]
+fn integers_in_data_parts_stay_integers() {
+ let request: a2a::SendMessageRequest = a2a_pb::protojson_conv::from_value(json!({
+ "message": {
+ "messageId": "msg-1",
+ "role": "ROLE_USER",
+ "parts": [{"data": {"sinceSeconds": 3600, "ratio": 0.5}}]
+ }
+ }))
+ .unwrap();
+
+ let a2a::PartContent::Data(data) = &request.message.parts[0].content else {
+ panic!("expected a data part");
+ };
+ assert_eq!(
+ serde_json::from_value::(data["sinceSeconds"].clone()).unwrap(),
+ 3600
+ );
+ assert_eq!(data["ratio"], json!(0.5));
+}
From 1997ab7d5d3e17d8d01bfbf1241576d5a4d0c2ec Mon Sep 17 00:00:00 2001
From: gulldan <5641375+gulldan@users.noreply.github.com>
Date: Sat, 31 Oct 2026 13:22:30 +0300
Subject: [PATCH 4/5] feat(server): bound the finished tasks InMemoryTaskStore
keeps
InMemoryTaskStore never removed a task, and TaskStore has no delete,
so a long-running agent kept every task it ever served: 20,000 tasks
with a 4 KiB artifact each held 192 MiB.
InMemoryTaskStore::with_terminal_task_limit(n) keeps at most n tasks
in a terminal state and purges the one that reached its terminal state
earliest. Tasks that are not terminal are never purged, and a purged
task reads as TaskNotFoundError, which A2A 3.3.2 allows for a task
that was completed and purged. new() keeps every task, as before. With
a limit of 1,000 the same run stays at about 20 MiB.
Fixes: #401
Co-Authored-By: Claude Opus 5.5
Signed-off-by: gulldan <5641375+gulldan@users.noreply.github.com>
---
a2a-server/src/task_store/inmemory.rs | 124 ++++++++++++++++++++++++--
1 file changed, 116 insertions(+), 8 deletions(-)
diff --git a/a2a-server/src/task_store/inmemory.rs b/a2a-server/src/task_store/inmemory.rs
index 93878f4e..e8b7e270 100644
--- a/a2a-server/src/task_store/inmemory.rs
+++ b/a2a-server/src/task_store/inmemory.rs
@@ -3,7 +3,7 @@
// SPDX-License-Identifier: Apache-2.0
use a2a::*;
use async_trait::async_trait;
-use std::collections::HashMap;
+use std::collections::{HashMap, VecDeque};
use tokio::sync::RwLock;
use super::apply_history_length;
@@ -15,17 +15,54 @@ struct StoredEntry {
version: TaskVersion,
}
+#[derive(Default)]
+struct Tasks {
+ entries: HashMap,
+ /// Terminal task ids, oldest first; tracked only under a limit.
+ terminal: VecDeque,
+}
+
+impl Tasks {
+ /// Records that `id` reached a terminal state, then purges the tasks that
+ /// reached one earliest until at most `limit` remain.
+ fn retire(&mut self, id: &str, limit: Option) {
+ let Some(limit) = limit else {
+ return;
+ };
+ self.terminal.push_back(id.to_string());
+ while self.terminal.len() > limit {
+ if let Some(oldest) = self.terminal.pop_front() {
+ self.entries.remove(&oldest);
+ }
+ }
+ }
+}
+
/// In-memory task store. Contents do not survive restarts.
+///
+/// Keeps every task for the life of the process unless
+/// [`Self::with_terminal_task_limit`] bounds how many finished ones it holds.
pub struct InMemoryTaskStore {
- tasks: RwLock>,
+ tasks: RwLock,
+ terminal_task_limit: Option,
}
impl InMemoryTaskStore {
pub fn new() -> Self {
InMemoryTaskStore {
- tasks: RwLock::new(HashMap::new()),
+ tasks: RwLock::new(Tasks::default()),
+ terminal_task_limit: None,
}
}
+
+ /// Keep at most `limit` tasks in a terminal state, purging the one that
+ /// reached its terminal state earliest first. A purged task is reported
+ /// as `TaskNotFoundError`, which §3.3.2 allows for a completed and purged
+ /// task. Tasks that are not terminal are never purged.
+ pub fn with_terminal_task_limit(mut self, limit: usize) -> Self {
+ self.terminal_task_limit = Some(limit);
+ self
+ }
}
impl Default for InMemoryTaskStore {
@@ -38,17 +75,24 @@ impl Default for InMemoryTaskStore {
impl TaskStore for InMemoryTaskStore {
async fn create(&self, task: Task) -> Result {
let mut store = self.tasks.write().await;
- if store.contains_key(&task.id) {
+ if store.entries.contains_key(&task.id) {
return Err(crate::sanitized_internal_error("task already exists"));
}
let id = task.id.clone();
- store.insert(id, StoredEntry { task, version: 1 });
+ let terminal = task.status.state.is_terminal();
+ store
+ .entries
+ .insert(id.clone(), StoredEntry { task, version: 1 });
+ if terminal {
+ store.retire(&id, self.terminal_task_limit);
+ }
Ok(1)
}
async fn update(&self, task: Task) -> Result {
let mut store = self.tasks.write().await;
let entry = store
+ .entries
.get_mut(&task.id)
.ok_or_else(|| A2AError::task_not_found(&task.id))?;
// A terminal task's state is immutable. Re-applying the same
@@ -61,9 +105,15 @@ impl TaskStore for InMemoryTaskStore {
task.id, entry.task.status.state, task.status.state
)));
}
+ let retired = !entry.task.status.state.is_terminal() && task.status.state.is_terminal();
entry.version += 1;
entry.task = task;
- Ok(entry.version)
+ let version = entry.version;
+ if retired {
+ let id = entry.task.id.clone();
+ store.retire(&id, self.terminal_task_limit);
+ }
+ Ok(version)
}
async fn begin_cancel(&self, task_id: &str) -> Result {
@@ -72,6 +122,7 @@ impl TaskStore for InMemoryTaskStore {
// window.
let mut store = self.tasks.write().await;
let entry = store
+ .entries
.get_mut(task_id)
.ok_or_else(|| A2AError::task_not_found(task_id))?;
if entry.task.status.state.is_terminal() {
@@ -80,17 +131,20 @@ impl TaskStore for InMemoryTaskStore {
entry.version += 1;
entry.task.status.state = TaskState::Canceled;
entry.task.status.timestamp = Some(chrono::Utc::now());
- Ok(entry.task.clone())
+ let task = entry.task.clone();
+ store.retire(task_id, self.terminal_task_limit);
+ Ok(task)
}
async fn get(&self, task_id: &str) -> Result