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
Expand Up @@ -147,6 +147,15 @@ boolean saveTaskEvent(TaskArtifactUpdateEvent event, boolean isReplicated, @Null
if (nonNullTaskId == null) {
throw new IllegalStateException("taskId should not be null after checkIdsAndUpdateIfNecessary");
}
// A task in a final state is immutable: refuse an artifact for it (for example from an agent that is
// still running after its task was canceled), as validateStateTransition refuses a status change.
TaskState currentState = task.status() != null ? task.status().state() : null;
if (currentState != null && currentState.isFinal()) {
throw new A2AServerException(
"Task " + nonNullTaskId + " is already in terminal state " + currentState
+ " and cannot accept an artifact update",
new InternalError("Task " + nonNullTaskId + " is already in terminal state " + currentState));
}
task = appendArtifactToTask(task, event, nonNullTaskId);
Task savedTask = saveTask(task, isReplicated);
if (taskSnapshot != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
package org.a2aproject.sdk.server.requesthandlers;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

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.spec.A2AError;
import org.a2aproject.sdk.spec.CancelTaskParams;
import org.a2aproject.sdk.spec.Message;
import org.a2aproject.sdk.spec.MessageSendConfiguration;
import org.a2aproject.sdk.spec.MessageSendParams;
import org.a2aproject.sdk.spec.StreamingEventKind;
import org.a2aproject.sdk.spec.Task;
import org.a2aproject.sdk.spec.TaskArtifactUpdateEvent;
import org.a2aproject.sdk.spec.TaskState;
import org.a2aproject.sdk.spec.TaskStatusUpdateEvent;
import org.a2aproject.sdk.spec.TextPart;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;

/**
* After {@code onCancelTask} has returned the CANCELED task, an agent that is still running (cancelling its future does
* not interrupt it) adds an artifact. The artifact must be neither stored on the CANCELED task nor handed to the push
* notification sender. The recording {@link PushNotificationSender} records each event where it is handed over (there
* is no push configuration, so no webhook is called).
*
* <p>The test asserts that no event other than CANCELED is pushed after the cancel returned. CANCELED itself is
* exempt: the push chain is asynchronous and the cancel does not wait for it, so the CANCELED status may be handed over
* after the return.
*/
public class CancelLateArtifactPushTest {

record Push(long nanos, StreamingEventKind event) {}

private final List<Push> pushes = new CopyOnWriteArrayList<>();
private final Executor internalExecutor = Executors.newCachedThreadPool();
private MainEventBusProcessor processor;
private DefaultRequestHandler handler;
private InMemoryTaskStore taskStore;
private CountDownLatch release;
private CountDownLatch agentDone;

@BeforeEach
void init() {
release = new CountDownLatch(1);
agentDone = new CountDownLatch(1);
AgentExecutor agent = new AgentExecutor() {
@Override
public void execute(RequestContext context, AgentEmitter emitter) throws A2AError {
try {
emitter.startWork();
// the agent keeps working until the test releases it
release.await(10, TimeUnit.SECONDS);
emitter.addArtifact(List.of(new TextPart("late")));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
agentDone.countDown();
}
}

@Override
public void cancel(RequestContext context, AgentEmitter emitter) throws A2AError {
emitter.cancel();
}
};
taskStore = new InMemoryTaskStore();
MainEventBus bus = new MainEventBus();
InMemoryQueueManager queueManager = new InMemoryQueueManager(taskStore, bus);
PushNotificationSender recorder = (event, snapshot) -> {
pushes.add(new Push(System.nanoTime(), event));
return true;
};
processor = new MainEventBusProcessor(bus, taskStore, recorder, queueManager);
EventQueueUtil.start(processor);
handler = DefaultRequestHandler.builder()
.agentExecutor(agent)
.taskStore(taskStore)
.queueManager(queueManager)
.pushConfigStore(new InMemoryPushNotificationConfigStore())
.pushNotificationsEnabled(true)
.mainEventBusProcessor(processor)
.executor(internalExecutor)
.eventConsumerExecutor(internalExecutor)
.authorizationRequired(false)
.build();
}

@AfterEach
void cleanup() {
EventQueueUtil.stop(processor);
}

@RepeatedTest(5)
void noTaskEventIsPushedAfterTheCancelReturned() throws Exception {
MessageSendParams params = MessageSendParams.builder()
.message(Message.builder().messageId("m-late-artifact").role(Message.Role.ROLE_USER)
.parts(new TextPart("work")).build())
.configuration(MessageSendConfiguration.builder().returnImmediately(true)
.acceptedOutputModes(List.of()).build())
.build();
Task started = (Task) handler.onMessageSend(params, (ServerCallContext) null);
String id = started.id();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (taskStore.get(id) == null || taskStore.get(id).status().state() != TaskState.TASK_STATE_WORKING) {
if (System.nanoTime() > deadline) {
throw new AssertionError("task never WORKING");
}
Thread.sleep(5);
}

Task canceled = handler.onCancelTask(new CancelTaskParams(id, null, Map.of()), (ServerCallContext) null);
long ack = System.nanoTime();
assertEquals(TaskState.TASK_STATE_CANCELED, canceled.status().state());

release.countDown(); // the agent goes on, as an agent that ignores its cancel callback does
agentDone.await(5, TimeUnit.SECONDS);
Thread.sleep(500); // let the processor and the push chain drain

long lateOther = pushes.stream().filter(p -> p.nanos() > ack && !isCanceled(p.event())).count();
long lateCanceled = pushes.stream().filter(p -> p.nanos() > ack && isCanceled(p.event())).count();
Task stored = taskStore.get(id);
System.out.printf("pushes=%d lateNonCanceled=%d lateCanceled=%d storedState=%s storedArtifacts=%d kinds=%s%n",
pushes.size(), lateOther, lateCanceled, stored.status().state(),
stored.artifacts() == null ? 0 : stored.artifacts().size(),
pushes.stream().map(p -> kind(p.event()) + (p.nanos() > ack ? "@late" : "")).toList());
assertEquals(0, lateOther, "a non-CANCELED event of the task was pushed after the cancel returned");
}

private static boolean isCanceled(StreamingEventKind e) {
return (e instanceof TaskStatusUpdateEvent s && s.status().state() == TaskState.TASK_STATE_CANCELED)
|| (e instanceof Task t && t.status().state() == TaskState.TASK_STATE_CANCELED);
}

private static String kind(StreamingEventKind e) {
if (e instanceof TaskStatusUpdateEvent s) {
return "Status(" + s.status().state() + ")";
}
if (e instanceof TaskArtifactUpdateEvent) {
return "Artifact";
}
if (e instanceof Task t) {
return "Task(" + t.status().state() + ")";
}
return e.getClass().getSimpleName();
}
}
Loading