From 78d22347b63a5363851a93f787280fc3e527c708 Mon Sep 17 00:00:00 2001 From: Mohammad Hossein Khoshechin Jorshari Date: Fri, 4 Dec 2026 23:10:37 +0100 Subject: [PATCH] fix(server-common): admit one answer per pending input A message that continues a task is admitted in three steps: the task is read and checked in authorizeTaskAccess, the snapshot is saved with the message, and the agent is submitted. Nothing recorded that an input request had already been answered, so two messages answering the same INPUT_REQUIRED could both run the agent, and an answer that read the task before the other answer's turn was saved and run after that turn had completed the task, displacing the first answer from the history. Right after authorizeTaskAccess, a message to a task in INPUT_REQUIRED now reserves that input request, identified by its status timestamp, which updateWithMessage keeps. The reservation is an atomic compute on a per-task map that holds the latest request answered. A message whose request is not newer than that one is refused with InvalidRequestError before its snapshot is saved and before the agent is started. Messages to tasks in other non-final states and new tasks are not affected. The reservation lives in the handler instance and is not shared between handlers or persisted across a restart. Status timestamps are taken as increasing per task. A failure after the reservation leaves the request reserved. TwoAnswersOneInputTest holds one task-store read back after it happened and checks that of two answers to one input request exactly one runs the agent and the other is refused. Fixes: #1389 --- .../DefaultRequestHandler.java | 24 ++ .../TwoAnswersOneInputTest.java | 223 ++++++++++++++++++ 2 files changed, 247 insertions(+) create mode 100644 server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/TwoAnswersOneInputTest.java diff --git a/server-common/src/main/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandler.java b/server-common/src/main/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandler.java index f53ee5cdf..975e9ab0a 100644 --- a/server-common/src/main/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandler.java +++ b/server-common/src/main/java/org/a2aproject/sdk/server/requesthandlers/DefaultRequestHandler.java @@ -1,5 +1,6 @@ package org.a2aproject.sdk.server.requesthandlers; +import java.time.OffsetDateTime; import static java.util.concurrent.TimeUnit.SECONDS; import static org.a2aproject.sdk.server.util.async.AsyncUtils.convertingProcessor; import static org.a2aproject.sdk.server.util.async.AsyncUtils.createTubeConfig; @@ -63,6 +64,7 @@ import org.a2aproject.sdk.spec.GetTaskPushNotificationConfigParams; import org.a2aproject.sdk.spec.InternalError; import org.a2aproject.sdk.spec.InvalidParamsError; +import org.a2aproject.sdk.spec.InvalidRequestError; import org.a2aproject.sdk.spec.ListTaskPushNotificationConfigsParams; import org.a2aproject.sdk.spec.ListTaskPushNotificationConfigsResult; import org.a2aproject.sdk.spec.ListTasksParams; @@ -305,6 +307,14 @@ public class DefaultRequestHandler implements RequestHandler { */ private final ConcurrentMap cancelLocks = new ConcurrentHashMap<>(); + /** + * Per task, the latest INPUT_REQUIRED status (identified by its timestamp, which updateWithMessage keeps) + * that a message has been admitted to answer. Each input request is answered once: a message read against a + * request that is not newer than the last answered one is refused, even when it read the task before the + * other answer's turn. Messages to tasks in any other non-final state (refinements) are not affected. + */ + private final ConcurrentMap answeredInputs = new ConcurrentHashMap<>(); + private Executor executor; private Executor eventConsumerExecutor; @@ -1659,6 +1669,20 @@ private MessageSendSetup initMessageSend(MessageSendParams params, ServerCallCon throw new InvalidParamsError("Client message role must be ROLE_USER"); } Task task = authorizeTaskAccess(params, context); + if (task != null && task.status().state() == TaskState.TASK_STATE_INPUT_REQUIRED) { + OffsetDateTime asked = task.status().timestamp(); + boolean[] first = {false}; + answeredInputs.compute(task.id(), (id, answered) -> { + if (answered != null && !asked.isAfter(answered)) { + return answered; + } + first[0] = true; + return asked; + }); + if (!first[0]) { + throw new InvalidRequestError("The input requested by task " + task.id() + " has already been answered"); + } + } MessageSendParams requestParams = task == null ? params : normalizeRequestParamsForTask(params, task); RequestContext requestContext = requestContextBuilder.get() diff --git a/server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/TwoAnswersOneInputTest.java b/server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/TwoAnswersOneInputTest.java new file mode 100644 index 000000000..14fc2f6e1 --- /dev/null +++ b/server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/TwoAnswersOneInputTest.java @@ -0,0 +1,223 @@ +package org.a2aproject.sdk.server.requesthandlers; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.a2aproject.sdk.jsonrpc.common.wrappers.ListTasksResult; +import org.a2aproject.sdk.server.ServerCallContext; +import org.a2aproject.sdk.server.agentexecution.AgentExecutor; +import org.a2aproject.sdk.server.agentexecution.RequestContext; +import org.a2aproject.sdk.server.events.EventQueueUtil; +import org.a2aproject.sdk.server.events.InMemoryQueueManager; +import org.a2aproject.sdk.server.events.MainEventBus; +import org.a2aproject.sdk.server.events.MainEventBusProcessor; +import org.a2aproject.sdk.server.tasks.AgentEmitter; +import org.a2aproject.sdk.server.tasks.InMemoryPushNotificationConfigStore; +import org.a2aproject.sdk.server.tasks.InMemoryTaskStore; +import org.a2aproject.sdk.server.tasks.PushNotificationSender; +import org.a2aproject.sdk.server.tasks.TaskStore; +import org.a2aproject.sdk.spec.A2AError; +import org.a2aproject.sdk.spec.EventKind; +import org.a2aproject.sdk.spec.ListTasksParams; +import org.a2aproject.sdk.spec.Message; +import org.a2aproject.sdk.spec.MessageSendParams; +import org.a2aproject.sdk.spec.Task; +import org.a2aproject.sdk.spec.TaskState; +import org.a2aproject.sdk.spec.TextPart; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Two answers to one INPUT_REQUIRED (A2A v1.0.0 ยง3.4.3, docs/specification.md:634-635). The continuation + * path reads the task and checks that it is not final (DefaultRequestHandler.authorizeTaskAccess), saves + * that snapshot with the message (TaskManager.updateWithMessage), and starts the agent + * (registerAndExecuteAgentAsync) with no check of a running agent. An answer whose read happens before + * another answer's whole turn is executed after it, on a task that is COMPLETED by then. The store holds one + * read back after it happened (a slow store); nothing else is changed. A runs in its own thread and B is + * released when A is done, or after 2 s (a fix that serialises the two answers makes A wait for B). The test + * requires one executed answer and one refused answer. Handler wiring copied from + * BlockingSendMessageStaleStateTest. + */ +class TwoAnswersOneInputTest { + + private final ExecutorService internalExecutor = Executors.newCachedThreadPool(); + private MainEventBusProcessor mainEventBusProcessor; + + @AfterEach + void stopProcessor() { + if (mainEventBusProcessor != null) { + EventQueueUtil.stop(mainEventBusProcessor); + mainEventBusProcessor = null; + } + internalExecutor.shutdownNow(); + } + + private RequestHandler buildHandler(TaskStore taskStore, InMemoryTaskStore stateProvider, AgentExecutor agent) { + MainEventBus mainEventBus = new MainEventBus(); + InMemoryQueueManager queueManager = new InMemoryQueueManager(stateProvider, mainEventBus); + mainEventBusProcessor = + new MainEventBusProcessor(mainEventBus, taskStore, PushNotificationSender.NOOP, queueManager); + EventQueueUtil.start(mainEventBusProcessor); + return DefaultRequestHandler.builder() + .agentExecutor(agent) + .taskStore(taskStore) + .queueManager(queueManager) + .pushConfigStore(new InMemoryPushNotificationConfigStore()) + .mainEventBusProcessor(mainEventBusProcessor) + .executor(internalExecutor) + .eventConsumerExecutor(internalExecutor) + .authorizationRequired(false) + .build(); + } + + /** The in-memory store; {@code holdNextGet} makes the next get read, report, and wait for a release. */ + private static final class HoldingStore implements TaskStore { + final InMemoryTaskStore delegate; + volatile CountDownLatch read; + volatile CountDownLatch release; + + HoldingStore(InMemoryTaskStore delegate) { + this.delegate = delegate; + } + + synchronized void holdNextGet(CountDownLatch read, CountDownLatch release) { + this.read = read; + this.release = release; + } + + @Override + public void save(Task task, boolean isReplicated) { + delegate.save(task, isReplicated); + } + + @Override + public @Nullable Task get(String taskId) { + Task t = delegate.get(taskId); + CountDownLatch r; + CountDownLatch rel; + synchronized (this) { + r = read; + rel = release; + read = null; + release = null; + } + if (r != null) { + r.countDown(); + try { + rel.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + return t; + } + + @Override + public void delete(String taskId) { + delegate.delete(taskId); + } + + @Override + public ListTasksResult list(ListTasksParams params, @Nullable ServerCallContext context) { + return delegate.list(params, context); + } + } + + private static MessageSendParams send(String text, @Nullable String taskId) { + Message.Builder b = Message.builder().messageId("m-" + text).role(Message.Role.ROLE_USER).parts(new TextPart(text)); + if (taskId != null) { + b.taskId(taskId); + } + return MessageSendParams.builder().message(b.build()).build(); + } + + @Test + void twoAnswersToOneInputRequiredRunTheAgentOnce() throws Exception { + List calls = new CopyOnWriteArrayList<>(); + InMemoryTaskStore backing = new InMemoryTaskStore(); + HoldingStore store = new HoldingStore(backing); + RequestHandler handler = buildHandler(store, backing, new AgentExecutor() { + @Override + public void execute(RequestContext context, AgentEmitter emitter) throws A2AError { + String text = context.getUserInput(); + Task t = context.getTask(); + calls.add(text + "@" + (t == null ? null : t.status().state())); + if (text.equals("start")) { + emitter.requiresInput(); + } else { + emitter.complete(); + } + } + + @Override + public void cancel(RequestContext context, AgentEmitter emitter) throws A2AError { + } + }); + + EventKind first = handler.onMessageSend(send("start", null), null); + Task task = assertInstanceOf(Task.class, first); + assertEquals(TaskState.TASK_STATE_INPUT_REQUIRED, task.status().state()); + String id = task.id(); + + // answer B: its read of the task happens now, then it waits + CountDownLatch read = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + store.holdNextGet(read, release); + ExecutorService clients = Executors.newSingleThreadExecutor(); + Future b = clients.submit(() -> { + try { + return handler.onMessageSend(send("B", id), null); + } catch (A2AError e) { + return e; + } + }); + read.await(10, TimeUnit.SECONDS); + + // answer A: its whole turn, in its own thread; B goes on when A is done, or after 2 s if A waits for B + ExecutorService clientA = Executors.newSingleThreadExecutor(); + Future a = clientA.submit(() -> { + try { + return handler.onMessageSend(send("A", id), null); + } catch (A2AError e) { + return e; + } + }); + Object aResult; + try { + aResult = a.get(2, TimeUnit.SECONDS); + Thread.sleep(200); + } catch (java.util.concurrent.TimeoutException e) { + aResult = null; + } + + // B goes on + release.countDown(); + Object bResult = b.get(15, TimeUnit.SECONDS); + if (aResult == null) { + aResult = a.get(15, TimeUnit.SECONDS); + } + clients.shutdownNow(); + clientA.shutdownNow(); + Thread.sleep(200); + + Task stored = backing.get(id); + System.out.println("AB06 executor calls: " + calls); + System.out.println("AB06 answer A: " + aResult); + System.out.println("AB06 answer B: " + bResult); + System.out.println("AB06 stored state: " + stored.status().state() + ", history: " + + stored.history().stream().map(m -> m.parts().toString()).toList()); + long answered = calls.stream().filter(c -> !c.startsWith("start@")).count(); + assertEquals(1, answered, "two answers to one INPUT_REQUIRED were both executed: " + calls); + assertEquals(1, (aResult instanceof A2AError ? 1 : 0) + (bResult instanceof A2AError ? 1 : 0), + "exactly one of the two answers must be refused: A=" + aResult + ", B=" + bResult); + } +}