Skip to content

Commit faa3482

Browse files
MiloszSobczykcopybara-github
authored andcommitted
fix(a2a): fail the A2A stream in the handler, not via the transport
`StreamHandler.handleEvent` called `ResponseConverter.clientEventToEvent` with no guard, so a conversion failure escaped into the transport's read loop and whether the caller saw anything at all depended on what that loop did with it. On the default JSON-RPC/SSE transport it does terminate today, but only by accident of an implementation detail: the throw escapes the body subscriber in `JdkA2AHttpClient` and the JDK's own line-subscriber adapter catches it, cancels the subscription and re-signals it as `onError`. Nothing in the A2A client guarantees that - `Client` catches only `A2AClientError` and the SSE listener only `JsonProcessingException` - and a gRPC `StreamObserver` or a custom `A2AHttpClient` need not behave the same way. The error also arrives mislabelled as `Failed to communicate with the remote agent` when the connection was fine and the payload was not. Fail the flow in the handler with a message that names the real cause, then rethrow so the transport still tears the connection down as it does today. The rethrow is skipped in exactly one case: synchronous dispatch, where `Client.sendMessage` invokes the consumer inline and `Flowable.create` has already failed the flow, so throwing into it would only add an undeliverable through `RxJavaPlugins`. That case is identified by both being inside the `sendMessage` call and running on the subscribe thread. Each condition alone misses a different transport, and both misses silently leak the connection: thread identity alone misses a transport that delivers on the subscribe thread after `sendMessage` returns, and the `sendMessage` window alone misses a transport thread that delivers while the call is still on the stack. `handleError` is idempotent, so a transport that re-signals cannot double-report to the subscriber. Behaviour change for non-streaming callers: a conversion failure previously reached the subscriber as the raw `IllegalArgumentException`, because `Flowable.create` passed the throw straight through. It is now wrapped in `A2AClientError` with the original as the cause, which is what makes the two paths consistent. PiperOrigin-RevId: 962031390
1 parent e5aba3a commit faa3482

2 files changed

Lines changed: 204 additions & 9 deletions

File tree

‎a2a/src/main/java/com/google/adk/a2a/agent/RemoteA2AAgent.java‎

Lines changed: 67 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -228,14 +228,25 @@ protected Flowable<Event> runAsyncImpl(InvocationContext invocationContext) {
228228
emitter -> {
229229
StreamHandler handler =
230230
new StreamHandler(
231-
emitter.serialize(), invocationContext, requestJson, streaming, name());
231+
emitter.serialize(),
232+
invocationContext,
233+
requestJson,
234+
name(),
235+
/* subscribeThread= */ Thread.currentThread());
232236
ImmutableList<BiConsumer<ClientEvent, AgentCard>> consumers =
233237
ImmutableList.of(handler::handleEvent);
234-
a2aClient.sendMessage(originalMessage, consumers, handler::handleError, null);
238+
handler.dispatchSynchronously(
239+
() -> a2aClient.sendMessage(originalMessage, consumers, handler::handleError, null));
235240
},
236241
BackpressureStrategy.BUFFER);
237242
}
238243

244+
/** A {@link Runnable} that may throw, so the a2a client's checked exception can propagate. */
245+
@FunctionalInterface
246+
private interface ThrowingRunnable {
247+
void run() throws Exception;
248+
}
249+
239250
private @Nullable String serializeMessageToJson(Message message) {
240251
try {
241252
return objectMapper.writeValueAsString(message);
@@ -249,8 +260,26 @@ private static class StreamHandler {
249260
private final FlowableEmitter<Event> emitter;
250261
private final InvocationContext invocationContext;
251262
private final String requestJson;
252-
private final boolean streaming;
253263
private final String agentName;
264+
private final Thread subscribeThread;
265+
266+
/** True while {@code sendMessage} is running on {@link #subscribeThread}. */
267+
private volatile boolean dispatchingSynchronously = false;
268+
269+
/**
270+
* Runs the a2a client call that this handler is the consumer for, recording that any event
271+
* delivered on {@link #subscribeThread} while it is on the stack came from synchronous
272+
* dispatch. Owned here so the window cannot be left open by an edit at the call site.
273+
*/
274+
void dispatchSynchronously(ThrowingRunnable dispatch) throws Exception {
275+
dispatchingSynchronously = true;
276+
try {
277+
dispatch.run();
278+
} finally {
279+
dispatchingSynchronously = false;
280+
}
281+
}
282+
254283
private boolean done = false;
255284
private final StringBuilder textBuffer = new StringBuilder();
256285
private final StringBuilder thoughtsBuffer = new StringBuilder();
@@ -259,16 +288,20 @@ private static class StreamHandler {
259288
FlowableEmitter<Event> emitter,
260289
InvocationContext invocationContext,
261290
String requestJson,
262-
boolean streaming,
263-
String agentName) {
291+
String agentName,
292+
Thread subscribeThread) {
264293
this.emitter = emitter;
265294
this.invocationContext = invocationContext;
266295
this.requestJson = requestJson;
267-
this.streaming = streaming;
268296
this.agentName = agentName;
297+
this.subscribeThread = subscribeThread;
269298
}
270299

271300
synchronized void handleError(Throwable e) {
301+
handleError("Failed to communicate with the remote agent", e);
302+
}
303+
304+
synchronized void handleError(String message, Throwable e) {
272305
// Mark the flow as done if it is already cancelled.
273306
if (!done) {
274307
done = emitter.isCancelled();
@@ -280,7 +313,7 @@ synchronized void handleError(Throwable e) {
280313
}
281314
// If the error is raised, complete the flow with an error.
282315
done = true;
283-
emitter.tryOnError(new A2AClientError("Failed to communicate with the remote agent", e));
316+
emitter.tryOnError(new A2AClientError(message, e));
284317
}
285318

286319
// TODO: b/483038527 - The synchronized block might block the thread, we should optimize for
@@ -296,8 +329,33 @@ synchronized void handleEvent(ClientEvent clientEvent, AgentCard unused) {
296329
return;
297330
}
298331

299-
Optional<Event> eventOpt =
300-
ResponseConverter.clientEventToEvent(clientEvent, invocationContext);
332+
Optional<Event> eventOpt;
333+
try {
334+
eventOpt = ResponseConverter.clientEventToEvent(clientEvent, invocationContext);
335+
} catch (Throwable t) {
336+
logger.warn("Failed to convert A2A event", t);
337+
handleError("Failed to convert the remote agent's response", t);
338+
if (!dispatchingSynchronously || Thread.currentThread() != subscribeThread) {
339+
// Delivered by the transport rather than from inside sendMessage: rethrow so the
340+
// transport tears the connection down. Synchronous dispatch is the one case where
341+
// Flowable.create has already failed the flow, and rethrowing into it would only add
342+
// an undeliverable via RxJavaPlugins.
343+
throw t;
344+
}
345+
return;
346+
}
347+
emit(clientEvent, eventOpt);
348+
}
349+
350+
/**
351+
* Emits a converted event.
352+
*
353+
* <p>Outside the conversion guard above only because of the {@code emitter} calls: RxJava's
354+
* contract is that a downstream {@code onNext} does not throw, so such a throw is the
355+
* subscriber's bug and must not be fed back to that same subscriber as {@code onError}. The
356+
* surrounding aggregation bookkeeping is ADK's own; none of it throws on peer input today.
357+
*/
358+
private void emit(ClientEvent clientEvent, Optional<Event> eventOpt) {
301359
eventOpt.ifPresent(
302360
event -> {
303361
addMetadata(event, clientEvent);

‎a2a/src/test/java/com/google/adk/a2a/agent/RemoteA2AAgentTest.java‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,15 @@
1818

1919
import static com.google.common.truth.Truth.assertThat;
2020
import static java.util.concurrent.TimeUnit.SECONDS;
21+
import static org.junit.Assert.assertThrows;
2122
import static org.mockito.ArgumentMatchers.any;
2223
import static org.mockito.Mockito.doAnswer;
2324
import static org.mockito.Mockito.mock;
2425
import static org.mockito.Mockito.verify;
2526
import static org.mockito.Mockito.verifyNoInteractions;
2627
import static org.mockito.Mockito.when;
2728

29+
import com.google.adk.a2a.common.A2AClientError;
2830
import com.google.adk.a2a.common.A2AMetadata;
2931
import com.google.adk.agents.BaseAgent;
3032
import com.google.adk.agents.CallbackContext;
@@ -51,6 +53,7 @@
5153
import io.a2a.spec.Artifact;
5254
import io.a2a.spec.DataPart;
5355
import io.a2a.spec.FilePart;
56+
import io.a2a.spec.FileWithBytes;
5457
import io.a2a.spec.FileWithUri;
5558
import io.a2a.spec.Message;
5659
import io.a2a.spec.Task;
@@ -61,11 +64,17 @@
6164
import io.a2a.spec.TextPart;
6265
import io.reactivex.rxjava3.core.Flowable;
6366
import io.reactivex.rxjava3.core.Maybe;
67+
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
68+
import io.reactivex.rxjava3.subscribers.TestSubscriber;
69+
import java.util.ArrayList;
70+
import java.util.Collections;
6471
import java.util.HashMap;
6572
import java.util.List;
6673
import java.util.Map;
6774
import java.util.Objects;
75+
import java.util.concurrent.CountDownLatch;
6876
import java.util.concurrent.atomic.AtomicBoolean;
77+
import java.util.concurrent.atomic.AtomicReference;
6978
import java.util.function.BiConsumer;
7079
import java.util.function.Consumer;
7180
import org.junit.Before;
@@ -300,6 +309,125 @@ public void runAsync_handlesTasksWithMultipartArtifact() {
300309
assertResponseMetadata(events.get(0));
301310
}
302311

312+
@Test
313+
public void runAsync_whenConversionThrowsOnCallingThread_reportsError() {
314+
RemoteA2AAgent agent = createAgent();
315+
mockStreamResponse(consumer -> consumer.accept(unconvertibleEvent(), agentCard));
316+
317+
agent
318+
.runAsync(invocationContext)
319+
.test()
320+
.awaitDone(5, SECONDS)
321+
.assertError(A2AClientError.class)
322+
.assertError(e -> e.getCause() instanceof IllegalArgumentException);
323+
}
324+
325+
@Test
326+
public void runAsync_whenConversionThrowsOnCallingThread_doesNotSignalTwice() {
327+
List<Throwable> undeliverable = Collections.synchronizedList(new ArrayList<>());
328+
io.reactivex.rxjava3.functions.Consumer<? super Throwable> previousHandler =
329+
RxJavaPlugins.getErrorHandler();
330+
RxJavaPlugins.setErrorHandler(undeliverable::add);
331+
try {
332+
RemoteA2AAgent agent = createAgent();
333+
mockStreamResponse(consumer -> consumer.accept(unconvertibleEvent(), agentCard));
334+
335+
agent
336+
.runAsync(invocationContext)
337+
.test()
338+
.awaitDone(5, SECONDS)
339+
.assertError(A2AClientError.class);
340+
} finally {
341+
// Process-global; reset before asserting so a failure cannot leak it into the rest of the
342+
// suite.
343+
RxJavaPlugins.setErrorHandler(previousHandler);
344+
}
345+
// Rethrowing on the subscribe thread would land here via FlowableCreate.
346+
assertThat(undeliverable).isEmpty();
347+
}
348+
349+
@Test
350+
public void runAsync_whenConversionThrowsOnSubscribeThreadAfterSendMessage_rethrows() {
351+
RemoteA2AAgent agent = createAgent();
352+
AtomicReference<BiConsumer<ClientEvent, AgentCard>> captured = new AtomicReference<>();
353+
mockStreamResponse(captured::set); // capture, do not invoke
354+
355+
TestSubscriber<Event> subscriber = agent.runAsync(invocationContext).test();
356+
357+
// Subscribe thread, but sendMessage has already returned: the transport still needs the throw.
358+
assertThrows(
359+
IllegalArgumentException.class,
360+
() -> captured.get().accept(unconvertibleEvent(), agentCard));
361+
subscriber.assertError(A2AClientError.class);
362+
}
363+
364+
@Test
365+
public void runAsync_whenConversionThrowsOnTransportThreadDuringSendMessage_rethrows() {
366+
RemoteA2AAgent agent = createAgent();
367+
AtomicReference<Throwable> escaped = new AtomicReference<>();
368+
mockStreamResponse(
369+
consumer -> {
370+
Thread thread = new Thread(() -> consumer.accept(unconvertibleEvent(), agentCard));
371+
thread.setName("a2a-fake-transport");
372+
thread.setUncaughtExceptionHandler((t, e) -> escaped.set(e));
373+
thread.start();
374+
try {
375+
thread.join(); // deliver while sendMessage is still on the stack
376+
} catch (InterruptedException e) {
377+
Thread.currentThread().interrupt();
378+
}
379+
});
380+
381+
agent
382+
.runAsync(invocationContext)
383+
.test()
384+
.awaitDone(5, SECONDS)
385+
.assertError(A2AClientError.class);
386+
assertThat(escaped.get()).isInstanceOf(IllegalArgumentException.class);
387+
}
388+
389+
@Test
390+
public void runAsync_whenConversionThrowsOnTransportThread_failsStream()
391+
throws InterruptedException {
392+
RemoteA2AAgent agent = createAgent();
393+
CountDownLatch delivered = new CountDownLatch(1);
394+
// Released once subscribe has returned, so delivery is deterministically *after* sendMessage.
395+
CountDownLatch release = new CountDownLatch(1);
396+
AtomicReference<Thread> deliveryThread = new AtomicReference<>();
397+
AtomicReference<Throwable> escaped = new AtomicReference<>();
398+
mockStreamResponse(
399+
consumer -> {
400+
Thread thread =
401+
new Thread(
402+
() -> {
403+
try {
404+
release.await();
405+
consumer.accept(unconvertibleEvent(), agentCard);
406+
} catch (InterruptedException e) {
407+
Thread.currentThread().interrupt();
408+
} finally {
409+
delivered.countDown();
410+
}
411+
});
412+
thread.setName("a2a-fake-transport");
413+
thread.setUncaughtExceptionHandler((t, e) -> escaped.set(e));
414+
thread.start();
415+
deliveryThread.set(thread);
416+
});
417+
418+
TestSubscriber<Event> subscriber = agent.runAsync(invocationContext).test();
419+
release.countDown();
420+
assertThat(delivered.await(5, SECONDS)).isTrue();
421+
422+
subscriber
423+
.awaitDone(5, SECONDS)
424+
.assertError(A2AClientError.class)
425+
.assertError(e -> e.getCause() instanceof IllegalArgumentException);
426+
deliveryThread.get().join();
427+
// The failure must also leave the handler, so the transport can tear the connection down.
428+
assertThat(escaped.get()).isInstanceOf(IllegalArgumentException.class);
429+
}
430+
303431
@Test
304432
public void runAsync_handlesNonFinalStatusUpdatesAsThoughts() {
305433
RemoteA2AAgent agent = createAgent();
@@ -796,6 +924,15 @@ private RemoteA2AAgent createAgent() {
796924
return getAgentBuilder().streaming(true).build();
797925
}
798926

927+
/** An event whose file part carries invalid base64, so {@code PartConverter} cannot decode it. */
928+
private ClientEvent unconvertibleEvent() {
929+
return createTestEvent(
930+
new FilePart(new FileWithBytes("text/plain", "bad.txt", "!!!")),
931+
TaskState.WORKING,
932+
true,
933+
false);
934+
}
935+
799936
@SuppressWarnings("unchecked") // cast for Mockito
800937
private void mockStreamResponse(Consumer<BiConsumer<ClientEvent, AgentCard>> responseProducer) {
801938
doAnswer(

0 commit comments

Comments
 (0)