Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -305,6 +307,14 @@ public class DefaultRequestHandler implements RequestHandler {
*/
private final ConcurrentMap<String, Object> 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<String, OffsetDateTime> answeredInputs = new ConcurrentHashMap<>();


private Executor executor;
private Executor eventConsumerExecutor;
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> 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<Object> 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<Object> 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);
}
}