From e7b743981424c7dcf3649f708965e2a81fe16ad9 Mon Sep 17 00:00:00 2001 From: Google Team Member Date: Wed, 2 Dec 2026 05:06:05 -0800 Subject: [PATCH] fix(a2a): keep an update's error code when none of its parts convert PiperOrigin-RevId: 1034362891 --- .../google/adk/a2a/agent/RemoteA2AAgent.java | 70 ++++--- .../adk/a2a/converters/ResponseConverter.java | 45 ++-- .../adk/a2a/agent/RemoteA2AAgentTest.java | 198 ++++++++++++++++++ .../a2a/converters/ResponseConverterTest.java | 120 +++++++++++ 4 files changed, 393 insertions(+), 40 deletions(-) diff --git a/a2a/src/main/java/com/google/adk/a2a/agent/RemoteA2AAgent.java b/a2a/src/main/java/com/google/adk/a2a/agent/RemoteA2AAgent.java index 3f49dfd24..2520781f0 100644 --- a/a2a/src/main/java/com/google/adk/a2a/agent/RemoteA2AAgent.java +++ b/a2a/src/main/java/com/google/adk/a2a/agent/RemoteA2AAgent.java @@ -568,35 +568,34 @@ synchronized void handleEvent(ClientEvent clientEvent, AgentCard unused) { * surrounding aggregation bookkeeping is ADK's own; none of it throws on peer input today. */ private void emit(ClientEvent clientEvent, Optional eventOpt) { - eventOpt.ifPresent( - event -> { - addMetadata(event, clientEvent); - - if (isCompleted(clientEvent)) { - // Terminal event, check if we can merge. - boolean mergeResult = mergeAggregatedContentIntoEvent(event); - if (!mergeResult) { - emitAggregatedEventAndClearBuffer(null); - } - } else { - boolean isPartial = event.partial().orElse(false); - if (isPartial) { - if (shouldResetBuffer(clientEvent)) { - clearBuffer(); - } - boolean addedToBuffer = bufferContent(event, clientEvent); - if (!addedToBuffer) { - // Partial event with no content to buffer (e.g. tool call). - // Flush buffer before emitting this event. - emitAggregatedEventAndClearBuffer(null); - } - } else { - // Intermediate non-partial. - emitAggregatedEventAndClearBuffer(null); - } + eventOpt.ifPresent(event -> { + addMetadata(event, clientEvent); + + if (isCompleted(clientEvent)) { + // Terminal event, check if we can merge. + boolean mergeResult = mergeAggregatedContentIntoEvent(event); + if (!mergeResult) { + emitAggregatedEventAndClearBuffer(null); + } + } else if (!isMidStreamEmptyUpdate(clientEvent, event)) { + boolean isPartial = event.partial().orElse(false); + if (isPartial) { + if (shouldResetBuffer(clientEvent)) { + clearBuffer(); + } + boolean addedToBuffer = bufferContent(event, clientEvent); + if (!addedToBuffer) { + // Partial event with no content to buffer (e.g. tool call). + // Flush buffer before emitting this event. + emitAggregatedEventAndClearBuffer(null); } - emitter.onNext(event); - }); + } else { + // Intermediate non-partial. + emitAggregatedEventAndClearBuffer(null); + } + } + emitter.onNext(event); + }); // Wait until the client receives a status payload marking the completion of the task // regardless of the underlying streaming or non-streaming protocol configuration. @@ -791,6 +790,21 @@ private Event createAggregatedEvent(Content content, @Nullable ClientEvent trigg } } + /** + * Returns whether {@code event}, converted from {@code clientEvent}, is a task update without + * content that neither ends the turn nor is an artifact's last chunk, such as an error code alone + * in the middle of a stream. It leaves the streamed text alone, as in ADK Kotlin. + */ + private static boolean isMidStreamEmptyUpdate(ClientEvent clientEvent, Event event) { + if (!(clientEvent instanceof TaskUpdateEvent updateEvent) + || event.content().isPresent() + || event.turnComplete().orElse(false)) { + return false; + } + return !(updateEvent.getUpdateEvent() instanceof TaskArtifactUpdateEvent artifactEvent + && Objects.equals(artifactEvent.isLastChunk(), true)); + } + private static boolean isCompleted(ClientEvent event) { TaskState state; if (event instanceof TaskEvent taskEvent) { diff --git a/a2a/src/main/java/com/google/adk/a2a/converters/ResponseConverter.java b/a2a/src/main/java/com/google/adk/a2a/converters/ResponseConverter.java index 65f683d4a..7024ec6fe 100644 --- a/a2a/src/main/java/com/google/adk/a2a/converters/ResponseConverter.java +++ b/a2a/src/main/java/com/google/adk/a2a/converters/ResponseConverter.java @@ -90,9 +90,11 @@ private ResponseConverter() {} /** * Converts a A2A {@link ClientEvent} to an ADK {@link Event}, based on the event type. Returns an - * empty optional if the event should be ignored: a TaskArtifactUpdateEvent that is not a final - * update, a TaskStatusUpdateEvent with an empty message or none of whose parts convert and that - * does not end the turn, or a message none of whose parts convert and that reports no error code. + * empty optional if the event should be ignored: a last artifact chunk marked partial, an + * artifact update none of whose parts convert, a status update with no message or none of whose + * parts convert that does not end the turn, or a message none of whose parts convert. An artifact + * or status message with an error code is kept with no content, and a message with one with empty + * content. * * @throws IllegalArgumentException if the event type is not supported. */ @@ -133,10 +135,10 @@ private static boolean isLongRunning(@Nullable Map metadata) { } /** - * Converts a A2A {@link TaskUpdateEvent} to an ADK {@link Event}, if applicable. Returns empty if - * the event is not a final update for TaskArtifactUpdateEvent, if the message is empty for - * TaskStatusUpdateEvent, or if no part could be converted from the message of a status update - * that does not end the turn. + * Converts a A2A {@link TaskUpdateEvent} to an ADK {@link Event}, if applicable. Returns empty + * for a last artifact chunk marked partial, and for an artifact update none of whose parts + * convert, or a status update with no message or none of whose parts convert that does not end + * the turn, unless the artifact or status message has an error code. * * @throws IllegalArgumentException if the task update type is not supported. */ @@ -153,14 +155,20 @@ private static Optional handleTaskUpdate( } Event eventPart = artifactToEvent(artifactEvent.getArtifact(), context, converter); - if (!hasParts(eventPart)) { - return Optional.empty(); + boolean hasContent = hasParts(eventPart); + if (!hasContent) { + // With no convertible part, still emit the artifact's error code, as ADK Python does. + if (errorCode(artifactEvent.getArtifact().metadata()) == null) { + return Optional.empty(); + } + eventPart.setContent(null); } - eventPart.setPartial(isAppend || !isLastChunk); + eventPart.setPartial((hasContent && isAppend) || !isLastChunk); // append=true, lastChunk=false: emit as partial, update aggregation // append=false, lastChunk=false: emit as partial, reset aggregation // append=true, lastChunk=true: emit as partial, update aggregation and emit as non-partial // append=false, lastChunk=true: emit as non-partial, drop aggregation + // no content, lastChunk=true: emit as non-partial return Optional.of( updateEventMetadata( eventPart, @@ -183,7 +191,17 @@ private static Optional handleTaskUpdate( return messageToEvent( value, context, PENDING_STATES.contains(taskState), converter); }) - .filter(converted -> taskState == TaskState.FAILED || hasParts(converted)); + // With no convertible part, still emit the message's error code, as ADK Python does. + .filter(converted -> + taskState == TaskState.FAILED + || hasParts(converted) + || errorCode(statusMessage.getMetadata()) != null) + .map(converted -> { + if (!hasParts(converted)) { + converted.setContent(null); + } + return converted; + }); if (statusEvent.isFinal() || taskState == TaskState.INPUT_REQUIRED @@ -551,7 +569,10 @@ private static Event updateEventMetadata( * JSON string is decoded first, and other text, such as a number Go sends, is the error code * itself. */ - private static @Nullable FinishReason errorCode(Map clientMetadata) { + private static @Nullable FinishReason errorCode(@Nullable Map clientMetadata) { + if (clientMetadata == null) { + return null; + } if (!(clientMetadata.get(A2AMetadataKey.ERROR_CODE.getType()) instanceof String value)) { return parseMetadata(clientMetadata, A2AMetadataKey.ERROR_CODE, FinishReason.class); } diff --git a/a2a/src/test/java/com/google/adk/a2a/agent/RemoteA2AAgentTest.java b/a2a/src/test/java/com/google/adk/a2a/agent/RemoteA2AAgentTest.java index 6d87ec6c7..d8ef8a8e0 100644 --- a/a2a/src/test/java/com/google/adk/a2a/agent/RemoteA2AAgentTest.java +++ b/a2a/src/test/java/com/google/adk/a2a/agent/RemoteA2AAgentTest.java @@ -1853,6 +1853,204 @@ public void runAsync_streamedStatusWithErrorCodeOnMessage_emitsAndStoresIt() { assertErrorCodeEmittedAndStored(createAgent()); } + @Test + public void runAsync_streamedErrorOnlyUpdates_keepStreamedTextInOneEvent() { + TaskStatus completed = new TaskStatus(TaskState.COMPLETED); + mockStreamResponse(consumer -> { + consumer.accept(createPartialEvent("Hello ", true, false), agentCard); + consumer.accept( + createErrorOnlyChunk("SAFETY", /* append= */ true, /* lastChunk= */ false), agentCard); + consumer.accept( + createErrorOnlyChunk("SPII", /* append= */ false, /* lastChunk= */ false), agentCard); + consumer.accept(createErrorOnlyStatusUpdate("RECITATION"), agentCard); + consumer.accept(createPartialEvent("world", true, false), agentCard); + consumer.accept( + createErrorOnlyChunk("BLOCKLIST", /* append= */ true, /* lastChunk= */ true), agentCard); + consumer.accept( + new TaskUpdateEvent( + new Task.Builder().id("task-1").contextId("context-1").status(completed).build(), + new TaskStatusUpdateEvent("task-1", completed, "context-1", true, null)), + agentCard); + }); + InMemoryRunner runner = new InMemoryRunner(createAgent()); + Session session = runner.sessionService().createSession(runner.appName(), "user").blockingGet(); + + List events = + runner + .runAsync("user", session.id(), Content.fromParts(Part.fromText("Hi"))) + .toList() + .blockingGet(); + + assertThat(errorCodes(events)) + .containsExactly( + new FinishReason("SAFETY"), + new FinishReason("SPII"), + new FinishReason("RECITATION"), + new FinishReason("BLOCKLIST")) + .inOrder(); + ImmutableList stored = + runner + .sessionService() + .getSession(runner.appName(), "user", session.id(), Optional.empty()) + .blockingGet() + .immutableEvents() + .stream() + .filter(event -> event.author().equals("remote-agent")) + .collect(ImmutableList.toImmutableList()); + // The mid-stream chunks are partial, and partial events are not stored. The streamed text is + // stored as one event before the last chunk's error. + assertThat(storedSummary(stored)) + .containsExactly("error=RECITATION", "text=Hello world", "error=BLOCKLIST") + .inOrder(); + } + + @Test + public void runAsync_errorOnlyLastChunkThenNewArtifact_keepsBothTextsInOrder() { + mockStreamResponse(consumer -> { + consumer.accept(createPartialEvent("Hello ", true, false), agentCard); + consumer.accept( + createErrorOnlyChunk("SAFETY", /* append= */ true, /* lastChunk= */ true), agentCard); + consumer.accept(createPartialEvent("Bye", false, false), agentCard); + consumer.accept(completedStatusUpdate(), agentCard); + }); + + assertThat(storedSummary(runStoringEvents())) + .containsExactly("text=Hello ", "error=SAFETY", "text=Bye") + .inOrder(); + } + + @Test + public void runAsync_errorOnlyLastChunkThenCompleted_storesTextBeforeError() { + mockStreamResponse(consumer -> { + consumer.accept(createPartialEvent("Hello ", true, false), agentCard); + consumer.accept( + createErrorOnlyChunk("SAFETY", /* append= */ true, /* lastChunk= */ true), agentCard); + consumer.accept(completedStatusUpdate(), agentCard); + }); + + assertThat(storedSummary(runStoringEvents())) + .containsExactly("text=Hello ", "error=SAFETY") + .inOrder(); + } + + @Test + @SuppressWarnings("unchecked") // cast for Mockito + public void runAsync_finalUpdateOnWorkingTask_storesTextBeforeIt() { + TaskStatus working = new TaskStatus(TaskState.WORKING); + doAnswer( + invocation -> { + List> consumers = invocation.getArgument(1); + Consumer errorConsumer = invocation.getArgument(2); + consumers.get(0).accept(createPartialEvent("Hello ", true, false), agentCard); + consumers + .get(0) + .accept( + new TaskUpdateEvent( + new Task.Builder() + .id("task-1") + .contextId("context-1") + .status(working) + .build(), + new TaskStatusUpdateEvent("task-1", working, "context-1", true, null)), + agentCard); + // The a2a client signals the end of the stream with a null error. + errorConsumer.accept(null); + return null; + }) + .when(mockClient) + .sendMessage(any(Message.class), any(List.class), any(Consumer.class), any()); + + ImmutableList stored = runStoringEvents(); + + // The update that ends the turn comes after the streamed text. + assertThat(stored.get(0).stringifyContent()).isEqualTo("Hello "); + assertThat(stored.get(1).turnComplete()).hasValue(true); + } + + private static ClientEvent completedStatusUpdate() { + TaskStatus completed = new TaskStatus(TaskState.COMPLETED); + return new TaskUpdateEvent( + new Task.Builder().id("task-1").contextId("context-1").status(completed).build(), + new TaskStatusUpdateEvent("task-1", completed, "context-1", true, null)); + } + + /** Runs the agent once through an {@link InMemoryRunner}; returns the events it stored. */ + private ImmutableList runStoringEvents() { + InMemoryRunner runner = new InMemoryRunner(createAgent()); + Session session = runner.sessionService().createSession(runner.appName(), "user").blockingGet(); + var unused = + runner + .runAsync("user", session.id(), Content.fromParts(Part.fromText("Hi"))) + .toList() + .blockingGet(); + return runner + .sessionService() + .getSession(runner.appName(), "user", session.id(), Optional.empty()) + .blockingGet() + .immutableEvents() + .stream() + .filter(event -> event.author().equals("remote-agent")) + .collect(ImmutableList.toImmutableList()); + } + + /** Returns each stored event's text and error code, in order. */ + private static ImmutableList storedSummary(List stored) { + ImmutableList.Builder summary = ImmutableList.builder(); + for (Event event : stored) { + String text = event.stringifyContent(); + if (!text.isEmpty()) { + summary.add("text=" + text); + } + event.errorCode().ifPresent(code -> summary.add("error=" + code.toString())); + } + return summary.build(); + } + + /** An artifact chunk whose only part does not convert, carrying {@code errorCode}. */ + private static ClientEvent createErrorOnlyChunk( + String errorCode, boolean append, boolean lastChunk) { + Artifact artifact = + new Artifact.Builder() + .artifactId("artifact-1") + .parts( + ImmutableList.of(new FilePart(new FileWithBytes("text/plain", "bad.txt", "!!!")))) + .metadata(ImmutableMap.of("adk_error_code", errorCode)) + .build(); + Task task = + new Task.Builder() + .id("task-1") + .contextId("context-1") + .status(new TaskStatus(TaskState.WORKING)) + .build(); + TaskArtifactUpdateEvent update = + new TaskArtifactUpdateEvent.Builder() + .append(append) + .lastChunk(lastChunk) + .contextId("context-1") + .artifact(artifact) + .taskId("task-1") + .build(); + return new TaskUpdateEvent(task, update); + } + + /** A working task's status update whose message's only part does not convert. */ + private static ClientEvent createErrorOnlyStatusUpdate(String errorCode) { + TaskStatus working = + new TaskStatus( + TaskState.WORKING, + new Message.Builder() + .role(Message.Role.AGENT) + .parts( + ImmutableList.of( + new FilePart(new FileWithBytes("text/plain", "bad.txt", "!!!")))) + .metadata(ImmutableMap.of("adk_error_code", errorCode)) + .build(), + null); + return new TaskUpdateEvent( + new Task.Builder().id("task-1").contextId("context-1").status(working).build(), + new TaskStatusUpdateEvent("task-1", working, "context-1", false, null)); + } + /** Runs {@code agent} once and checks that its event and the stored event carry SAFETY. */ private void assertErrorCodeEmittedAndStored(RemoteA2AAgent agent) { InMemoryRunner runner = new InMemoryRunner(agent); diff --git a/a2a/src/test/java/com/google/adk/a2a/converters/ResponseConverterTest.java b/a2a/src/test/java/com/google/adk/a2a/converters/ResponseConverterTest.java index 7edc40a7c..3da837438 100644 --- a/a2a/src/test/java/com/google/adk/a2a/converters/ResponseConverterTest.java +++ b/a2a/src/test/java/com/google/adk/a2a/converters/ResponseConverterTest.java @@ -63,6 +63,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import org.jspecify.annotations.Nullable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -1528,6 +1529,94 @@ public void taskToEvent_withCustomMetadataMapFromAdkPython_readsOtherFields() { .containsExactly("a2a:task_id", "a2a:context_id"); } + @Test + public void clientEventToEvent_withOnlyUnconvertibleArtifactPartAndErrorCode_keepsEvent() { + Event result = + ResponseConverter.clientEventToEvent( + unconvertibleArtifactUpdate( + /* append= */ false, /* lastChunk= */ true, "SAFETY", null), + invocationContext) + .orElseThrow(); + + assertThat(result.errorCode()).hasValue(new FinishReason(FinishReason.Known.SAFETY)); + assertThat(result.content()).isEmpty(); + assertThat(result.partial().orElse(false)).isFalse(); + } + + @Test + public void clientEventToEvent_withOnlyUnconvertibleAppendedLastChunkAndErrorCode_isFinal() { + Event result = + ResponseConverter.clientEventToEvent( + unconvertibleArtifactUpdate( + /* append= */ true, /* lastChunk= */ true, "SAFETY", null), + invocationContext) + .orElseThrow(); + + assertThat(result.partial().orElse(false)).isFalse(); + } + + @Test + public void clientEventToEvent_withOnlyUnconvertibleMidStreamChunkAndErrorCode_isPartial() { + Event result = + ResponseConverter.clientEventToEvent( + unconvertibleArtifactUpdate( + /* append= */ true, /* lastChunk= */ false, "SAFETY", null), + invocationContext) + .orElseThrow(); + + assertThat(result.partial()).hasValue(true); + } + + @Test + public void + clientEventToEvent_withOnlyUnconvertibleArtifactPartAndErrorCodeOnUpdate_returnsEmpty() { + // As in ADK Python, only the artifact's own error code keeps an event with no content. + assertThat( + ResponseConverter.clientEventToEvent( + unconvertibleArtifactUpdate( + /* append= */ false, /* lastChunk= */ true, null, "SAFETY"), + invocationContext)) + .isEmpty(); + } + + @Test + public void + clientEventToEvent_withOnlyUnconvertiblePartsAndErrorCodeInWorkingStatus_keepsEvent() { + Message statusMessage = + agentMessage() + .parts(ImmutableList.of(invalidBase64Part())) + .metadata(ImmutableMap.of(A2AMetadataKey.ERROR_CODE.getType(), "SAFETY")) + .build(); + TaskStatus status = new TaskStatus(TaskState.WORKING, statusMessage, null); + TaskStatusUpdateEvent updateEvent = + new TaskStatusUpdateEvent("task-1", status, "context-1", false, null); + TaskUpdateEvent event = new TaskUpdateEvent(testTask().status(status).build(), updateEvent); + + Event result = ResponseConverter.clientEventToEvent(event, invocationContext).orElseThrow(); + + assertThat(result.errorCode()).hasValue(new FinishReason(FinishReason.Known.SAFETY)); + assertThat(result.content()).isEmpty(); + assertThat(result.turnComplete().orElse(false)).isFalse(); + } + + @Test + public void + clientEventToEvent_withOnlyUnconvertiblePartsAndErrorCodeOnWorkingUpdate_returnsEmpty() { + // As in ADK Python, only the status message's own error code keeps an event with no content. + Message statusMessage = agentMessage().parts(ImmutableList.of(invalidBase64Part())).build(); + TaskStatus status = new TaskStatus(TaskState.WORKING, statusMessage, null); + TaskStatusUpdateEvent updateEvent = + new TaskStatusUpdateEvent( + "task-1", + status, + "context-1", + false, + ImmutableMap.of(A2AMetadataKey.ERROR_CODE.getType(), "SAFETY")); + TaskUpdateEvent event = new TaskUpdateEvent(testTask().status(status).build(), updateEvent); + + assertThat(ResponseConverter.clientEventToEvent(event, invocationContext)).isEmpty(); + } + @Test public void clientEventToEvent_withMetadataOnUpdateAndStatusMessage_fillsInMissingKeys() { Message statusMessage = @@ -1726,6 +1815,37 @@ public void clientEventToEvent_withTaskArtifactUpdateEventAndPartialTrue_returns assertThat(optionalEvent).isEmpty(); } + /** An artifact update for task-1 whose only part does not convert. */ + private TaskUpdateEvent unconvertibleArtifactUpdate( + boolean append, + boolean lastChunk, + @Nullable String artifactErrorCode, + @Nullable String updateErrorCode) { + Artifact artifact = + new Artifact.Builder() + .artifactId("artifact-1") + .parts(ImmutableList.of(invalidBase64Part())) + .metadata( + artifactErrorCode == null + ? ImmutableMap.of() + : ImmutableMap.of(A2AMetadataKey.ERROR_CODE.getType(), artifactErrorCode)) + .build(); + TaskArtifactUpdateEvent update = + new TaskArtifactUpdateEvent.Builder() + .append(append) + .lastChunk(lastChunk) + .contextId("context-1") + .artifact(artifact) + .taskId("task-1") + .metadata( + updateErrorCode == null + ? ImmutableMap.of() + : ImmutableMap.of(A2AMetadataKey.ERROR_CODE.getType(), updateErrorCode)) + .build(); + return new TaskUpdateEvent( + testTask().status(new TaskStatus(TaskState.WORKING)).build(), update); + } + /** An artifact with one text part and {@code metadata}. */ private static Artifact artifact(String id, Map metadata) { return new Artifact.Builder()