From 65c6e4332af6b2e845bcb9a67c0f1704f14da6a4 Mon Sep 17 00:00:00 2001 From: Mohammad Hossein Khoshechin Jorshari Date: Mon, 30 Nov 2026 15:13:16 +0100 Subject: [PATCH 1/3] fix(server-common): read and tap a subscribed task under the event bus lock onSubscribeToTask read the task from the store and tapped its queue in two unordered steps, while the bus thread persisted and distributed each event. An event persisted after the read and distributed before the tap reached neither the snapshot nor the stream: an artifact was lost, or a terminal status was lost and the stream never closed (A2A spec 3.1.6). MainEventBusProcessor.processEvent now holds a private monitor from persisting an event to distributing it to the child queues, and onSubscribeToTask runs its read, checks, tap and createOrTap fallback under the same monitor (withEventProcessingPaused). Adds SubscribeWindowTest. Fixes #1370 --- .../server/events/MainEventBusProcessor.java | 142 ++++--- .../DefaultRequestHandler.java | 49 ++- .../requesthandlers/SubscribeWindowTest.java | 382 ++++++++++++++++++ 3 files changed, 500 insertions(+), 73 deletions(-) create mode 100644 server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/SubscribeWindowTest.java diff --git a/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java b/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java index d4f3e4470..749db56cd 100644 --- a/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java +++ b/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java @@ -5,6 +5,7 @@ import java.util.concurrent.Executor; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import jakarta.annotation.Nullable; import jakarta.annotation.PostConstruct; @@ -104,6 +105,14 @@ private record UpdateResult(boolean isFinal, @Nullable Task taskSnapshot) {} */ private final ConcurrentHashMap initialTasks = new ConcurrentHashMap<>(); + /** + * Held by {@link #processEvent} from persisting an event until it has been distributed to the + * ChildQueues, and by {@link #withEventProcessingPaused} callers. A caller that reads a task from + * the TaskStore and then taps its queue under this lock therefore sees every event either in the + * stored task or on its new ChildQueue, never in neither. + */ + private final Object persistAndDistributeLock = new Object(); + private MainEventBus eventBus; private TaskStore taskStore; @@ -237,6 +246,24 @@ synchronized void stop() { LOGGER.info("MainEventBusProcessor stopped"); } + /** + * Runs {@code action} while no event is between being persisted and being distributed. + *

+ * Used by subscribe: reading the task from the TaskStore and tapping its queue inside one + * call means every event is either already in the task read or still to be distributed to the + * new ChildQueue. The action must not wait for this processor. + *

+ * + * @param action the action to run + * @param the action's result type + * @return the action's result + */ + public T withEventProcessingPaused(Supplier action) { + synchronized (persistAndDistributeLock) { + return action.get(); + } + } + @Override public void run() { LOGGER.info("MainEventBusProcessor processing loop started"); @@ -274,68 +301,71 @@ private void processEvent(MainEventBusContext context) { UpdateResult updateResult = null; boolean persisted = false; boolean isReplicated = context.eventQueueItem().isReplicated(); + int childCount; try { - // Step 1: Update TaskStore FIRST (persistence before clients see it) - // If this throws, we distribute an error to ensure "persist before client visibility" + synchronized (persistAndDistributeLock) { + // Step 1: Update TaskStore FIRST (persistence before clients see it) + // If this throws, we distribute an error to ensure "persist before client visibility" - try { - Message initialMessage = initialMessages.get(taskId); - Task initialTask = initialTasks.get(taskId); - updateResult = updateTaskStore(taskId, event, isReplicated, initialMessage, initialTask); - if (event instanceof Task || event instanceof TaskStatusUpdateEvent - || event instanceof TaskArtifactUpdateEvent || event instanceof A2AError) { - initialMessages.remove(taskId); - initialTasks.remove(taskId); - } - boolean isFinal = updateResult.isFinal(); - - eventToDistribute = event instanceof Task && updateResult.taskSnapshot() != null - ? updateResult.taskSnapshot() : event; - - // Trigger replication AFTER successful persistence - // SKIP replication if task is final - ReplicatedQueueManager handles this via TaskFinalizedEvent - // to ensure final Task is sent before poison pill (QueueClosedEvent) - if (!isFinal) { - EventEnqueueHook hook = mainQueue.getEnqueueHook(); - if (hook != null) { - LOGGER.debug("Triggering replication hook for task {} after successful persistence", taskId); - hook.onEnqueue(eventToDistribute == event ? context.eventQueueItem() - : new LocalEventQueueItem(eventToDistribute)); + try { + Message initialMessage = initialMessages.get(taskId); + Task initialTask = initialTasks.get(taskId); + updateResult = updateTaskStore(taskId, event, isReplicated, initialMessage, initialTask); + if (event instanceof Task || event instanceof TaskStatusUpdateEvent + || event instanceof TaskArtifactUpdateEvent || event instanceof A2AError) { + initialMessages.remove(taskId); + initialTasks.remove(taskId); } - } else { - LOGGER.debug("Task {} is final - skipping replication hook (handled by ReplicatedQueueManager)", taskId); + boolean isFinal = updateResult.isFinal(); + + eventToDistribute = event instanceof Task && updateResult.taskSnapshot() != null + ? updateResult.taskSnapshot() : event; + + // Trigger replication AFTER successful persistence + // SKIP replication if task is final - ReplicatedQueueManager handles this via TaskFinalizedEvent + // to ensure final Task is sent before poison pill (QueueClosedEvent) + if (!isFinal) { + EventEnqueueHook hook = mainQueue.getEnqueueHook(); + if (hook != null) { + LOGGER.debug("Triggering replication hook for task {} after successful persistence", taskId); + hook.onEnqueue(eventToDistribute == event ? context.eventQueueItem() + : new LocalEventQueueItem(eventToDistribute)); + } + } else { + LOGGER.debug("Task {} is final - skipping replication hook (handled by ReplicatedQueueManager)", taskId); + } + persisted = true; + } catch (InternalError e) { + // Persistence failed - create error event to distribute instead + LOGGER.error("Failed to persist event for task {}, distributing error to clients", taskId, e); + String errorMessage = "Failed to persist event: " + e.getMessage(); + eventToDistribute = e; + } catch (Exception e) { + LOGGER.error("Failed to persist event for task {}, distributing error to clients", taskId, e); + String errorMessage = "Failed to persist event: " + e.getMessage(); + eventToDistribute = new InternalError(errorMessage); } - persisted = true; - } catch (InternalError e) { - // Persistence failed - create error event to distribute instead - LOGGER.error("Failed to persist event for task {}, distributing error to clients", taskId, e); - String errorMessage = "Failed to persist event: " + e.getMessage(); - eventToDistribute = e; - } catch (Exception e) { - LOGGER.error("Failed to persist event for task {}, distributing error to clients", taskId, e); - String errorMessage = "Failed to persist event: " + e.getMessage(); - eventToDistribute = new InternalError(errorMessage); - } - // Step 2: Send push notification AFTER successful persistence (only from active node) - // Skip push notifications for replicated events to avoid duplicate notifications in multi-instance deployments - // Push notifications are sent for all StreamingEventKind events (Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent) - // per A2A spec section 4.3.3 - if (!isReplicated && persisted && eventToDistribute instanceof StreamingEventKind streamingEvent - && (!(eventToDistribute instanceof Message message) || message.taskId() != null)) { - // Send the streaming event directly - it will be wrapped in StreamResponse format by PushNotificationSender - sendPushNotification(taskId, streamingEvent, updateResult != null ? updateResult.taskSnapshot() : null); - } + // Step 2: Send push notification AFTER successful persistence (only from active node) + // Skip push notifications for replicated events to avoid duplicate notifications in multi-instance deployments + // Push notifications are sent for all StreamingEventKind events (Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent) + // per A2A spec section 4.3.3 + if (!isReplicated && persisted && eventToDistribute instanceof StreamingEventKind streamingEvent + && (!(eventToDistribute instanceof Message message) || message.taskId() != null)) { + // Send the streaming event directly - it will be wrapped in StreamResponse format by PushNotificationSender + sendPushNotification(taskId, streamingEvent, updateResult != null ? updateResult.taskSnapshot() : null); + } - // Step 3: Then distribute to ChildQueues (clients see either event or error AFTER persistence attempt) - int childCount = mainQueue.getChildCount(); - LOGGER.debug("MainEventBusProcessor: Distributing {} to {} children for task {}", - eventToDistribute.getClass().getSimpleName(), childCount, taskId); - // Create new EventQueueItem with the event to distribute (original or error) - EventQueueItem itemToDistribute = new LocalEventQueueItem(eventToDistribute); - mainQueue.distributeToChildren(itemToDistribute); - LOGGER.debug("MainEventBusProcessor: Distributed {} to {} children for task {}", - eventToDistribute.getClass().getSimpleName(), childCount, taskId); + // Step 3: Then distribute to ChildQueues (clients see either event or error AFTER persistence attempt) + childCount = mainQueue.getChildCount(); + LOGGER.debug("MainEventBusProcessor: Distributing {} to {} children for task {}", + eventToDistribute.getClass().getSimpleName(), childCount, taskId); + // Create new EventQueueItem with the event to distribute (original or error) + EventQueueItem itemToDistribute = new LocalEventQueueItem(eventToDistribute); + mainQueue.distributeToChildren(itemToDistribute); + LOGGER.debug("MainEventBusProcessor: Distributed {} to {} children for task {}", + eventToDistribute.getClass().getSimpleName(), childCount, taskId); + } // Step 3b: Notify stream lifecycle hook after distribution (only if there were active subscribers) TaskStreamLifecycleHook streamHook = mainQueue.getTaskStreamLifecycleHook(); 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..041535f4d 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 @@ -1353,7 +1353,37 @@ public Flow.Publisher onSubscribeToTask(TaskIdParams params, validateRequiredId(context, "id", params.id()); LOGGER.debug("onSubscribeToTask - taskId: {}", params.id()); enforceRead(context, params.id(), TaskOperation.SUBSCRIBE_TO_TASK); - Task task = taskStore.get(params.id()); + // Read the task and tap its queue with event processing paused: every event is then either + // in the snapshot read here or still to be distributed to the tapped queue. + SubscribeStart start = mainEventBusProcessor.withEventProcessingPaused(() -> readAndTap(params.id())); + Task task = start.task(); + EventQueue queue = start.queue(); + + TaskManager taskManager = new TaskManager(task.id(), task.contextId(), taskStore, null); + ResultAggregator resultAggregator = new ResultAggregator(taskManager, null, executor, eventConsumerExecutor, + SECONDS.toNanos(reconciliationTimeoutSeconds)); + + // Per A2A Protocol Spec 3.1.6 (Subscribe to Task): + // "The operation MUST return a Task object as the first event in the stream, + // representing the current state of the task at the time of subscription." + // Instead of enqueuing and hoping EventConsumer polls it in time, we prepend it + // directly to the Publisher stream, ensuring synchronous delivery to subscriber + EventConsumer consumer = new EventConsumer(queue, eventConsumerExecutor); + Flow.Publisher results = resultAggregator.consumeAndEmit(consumer); + LOGGER.debug("onSubscribeToTask - prepending initial task snapshot to stream, taskId: {}", params.id()); + return insertingProcessor( + convertingProcessor(results, item -> (StreamingEventKind) item.getEvent()), + task + ); + } + + private record SubscribeStart(Task task, EventQueue queue) {} + + /** + * The task read and the queue tap of {@link #onSubscribeToTask}, run with event processing paused. + */ + private SubscribeStart readAndTap(String taskId) throws A2AError { + Task task = taskStore.get(taskId); if (task == null) { throw new TaskNotFoundError(); } @@ -1369,9 +1399,6 @@ public Flow.Publisher onSubscribeToTask(TaskIdParams params, null); } - TaskManager taskManager = new TaskManager(task.id(), task.contextId(), taskStore, null); - ResultAggregator resultAggregator = new ResultAggregator(taskManager, null, executor, eventConsumerExecutor, - SECONDS.toNanos(reconciliationTimeoutSeconds)); EventQueue queue = queueManager.tap(task.id()); LOGGER.debug("onSubscribeToTask - tapped queue: {}", queue != null ? System.identityHashCode(queue) : "null"); @@ -1381,19 +1408,7 @@ public Flow.Publisher onSubscribeToTask(TaskIdParams params, LOGGER.debug("Queue not found for active task {}, creating new queue for future events", task.id()); queue = queueManager.createOrTap(task.id()); } - - // Per A2A Protocol Spec 3.1.6 (Subscribe to Task): - // "The operation MUST return a Task object as the first event in the stream, - // representing the current state of the task at the time of subscription." - // Instead of enqueuing and hoping EventConsumer polls it in time, we prepend it - // directly to the Publisher stream, ensuring synchronous delivery to subscriber - EventConsumer consumer = new EventConsumer(queue, eventConsumerExecutor); - Flow.Publisher results = resultAggregator.consumeAndEmit(consumer); - LOGGER.debug("onSubscribeToTask - prepending initial task snapshot to stream, taskId: {}", params.id()); - return insertingProcessor( - convertingProcessor(results, item -> (StreamingEventKind) item.getEvent()), - task - ); + return new SubscribeStart(task, queue); } @Override diff --git a/server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/SubscribeWindowTest.java b/server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/SubscribeWindowTest.java new file mode 100644 index 000000000..771b45137 --- /dev/null +++ b/server-common/src/test/java/org/a2aproject/sdk/server/requesthandlers/SubscribeWindowTest.java @@ -0,0 +1,382 @@ +package org.a2aproject.sdk.server.requesthandlers; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +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.Flow; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +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.EventQueue; +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.events.MainEventBusProcessorCallback; +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.Event; +import org.a2aproject.sdk.spec.EventKind; +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.TaskIdParams; +import org.a2aproject.sdk.spec.TaskState; +import org.a2aproject.sdk.spec.TaskStatusUpdateEvent; +import org.a2aproject.sdk.spec.TextPart; +import org.a2aproject.sdk.spec.UnsupportedOperationError; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * SubscribeToTask reads the task from the store, checks that it is not terminal, and only then taps the task's event + * queue. These tests stop the subscribe when it calls {@code QueueManager.tap}, let the agent publish, and give the + * event bus up to {@link #WINDOW_MILLIS} to persist and distribute the event before the tap goes ahead. Where the read + * and the tap are not serialised with the bus (the defect), the bus finishes inside the window. Where they are (a + * fix that reads and taps under the bus's lock), the bus cannot run until the subscribe is done, the wait times out, + * and the event follows the tap. A fix that taps before it reads meets the hook before its read. Every run must show + * that the window was exercised ({@link #assertWindowExercised}): either the bus finished inside it, or, when the + * wait ended, the agent had published and the bus thread ({@code MainEventBusProcessor}) was blocked on a lock held + * by the subscribing thread, and the bus finished only after the tap returned. A late agent or a bus that is merely + * slow fails the run instead of passing it. The assertions accept + * every correct outcome: the event in the snapshot or on the stream; for a terminal state, a closed stream showing + * the completion in the snapshot or on the stream, or a refusal of a subscribe that found the task terminal. + */ +public class SubscribeWindowTest { + + /** How long the held tap waits for the bus to finish the event published in the window. */ + static final long WINDOW_MILLIS = 3_000; + + private static final ServerCallContext NULL_CONTEXT = null; + + private static final MessageSendConfiguration RETURN_IMMEDIATELY = MessageSendConfiguration.builder() + .returnImmediately(true) + .acceptedOutputModes(List.of()) + .build(); + + /** + * At the next {@code tap}: counts {@link #reached} down, then waits up to {@link #WINDOW_MILLIS} for {@link + * #processed} (counted down by the bus callback), recording whether the bus finished inside the window, whether + * the agent had published by the end of the wait ({@link #published}), and when the tap returned. + */ + static final class WindowQueueManager extends InMemoryQueueManager { + volatile boolean armed; + final CountDownLatch reached = new CountDownLatch(1); + final CountDownLatch published = new CountDownLatch(1); + final CountDownLatch processed = new CountDownLatch(1); + volatile boolean processedInWindow; + volatile boolean publishedInWindow; + volatile boolean busBlockedOnSubscriber; + volatile String busStateAtTimeout = "-"; + volatile long tapReturnedNanos; + volatile long processedNanos; + + WindowQueueManager(InMemoryTaskStore store, MainEventBus bus) { + super(store, bus); + } + + /** Whether the bus thread is blocked on a lock (monitor or synchronizer) owned by the calling thread. */ + private void inspectBus() { + long me = Thread.currentThread().getId(); + for (ThreadInfo t : ManagementFactory.getThreadMXBean().dumpAllThreads(true, true)) { + if ("MainEventBusProcessor".equals(t.getThreadName())) { + busStateAtTimeout = t.getThreadState() + " on " + t.getLockName() + " owned by " + t.getLockOwnerId(); + busBlockedOnSubscriber = t.getLockOwnerId() == me; + } + } + } + + @Override + public EventQueue tap(String taskId) { + if (armed) { + armed = false; + reached.countDown(); + try { + processedInWindow = processed.await(WINDOW_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted in the window", e); + } + publishedInWindow = published.getCount() == 0; + if (!processedInWindow) { + inspectBus(); + } + EventQueue q = super.tap(taskId); + tapReturnedNanos = System.nanoTime(); + return q; + } + return super.tap(taskId); + } + } + + interface AgentBody { + void run(RequestContext context, AgentEmitter emitter) throws A2AError; + } + + private volatile AgentBody agentBody; + private InMemoryTaskStore taskStore; + private WindowQueueManager queueManager; + private MainEventBusProcessor processor; + private DefaultRequestHandler handler; + private final ExecutorService pool = Executors.newCachedThreadPool(); + + @BeforeEach + void init() { + AgentExecutor executor = new AgentExecutor() { + @Override + public void execute(RequestContext context, AgentEmitter emitter) throws A2AError { + agentBody.run(context, emitter); + } + + @Override + public void cancel(RequestContext context, AgentEmitter emitter) throws A2AError { + } + }; + taskStore = new InMemoryTaskStore(); + MainEventBus bus = new MainEventBus(); + queueManager = new WindowQueueManager(taskStore, bus); + processor = new MainEventBusProcessor(bus, taskStore, PushNotificationSender.NOOP, queueManager); + EventQueueUtil.start(processor); + handler = DefaultRequestHandler.builder() + .agentExecutor(executor) + .taskStore(taskStore) + .queueManager(queueManager) + .pushConfigStore(new InMemoryPushNotificationConfigStore()) + .pushNotificationsEnabled(false) + .mainEventBusProcessor(processor) + .executor(pool) + .eventConsumerExecutor(pool) + .authorizationRequired(false) + .build(); + } + + @AfterEach + void cleanup() { + queueManager.processed.countDown(); + EventQueueUtil.stop(processor); + pool.shutdownNow(); + } + + /** Collects a subscribe stream. */ + static final class Collector implements Flow.Subscriber { + final List items = new CopyOnWriteArrayList<>(); + final CountDownLatch done = new CountDownLatch(1); + final AtomicReference error = new AtomicReference<>(); + + @Override + public void onSubscribe(Flow.Subscription s) { + s.request(Long.MAX_VALUE); + } + + @Override + public void onNext(StreamingEventKind item) { + items.add(item); + } + + @Override + public void onError(Throwable t) { + error.set(t); + done.countDown(); + } + + @Override + public void onComplete() { + done.countDown(); + } + } + + private Task startWorkingTask(CountDownLatch working) throws Exception { + Message message = Message.builder() + .messageId("m-" + System.nanoTime()) + .role(Message.Role.ROLE_USER) + .parts(new TextPart("go")) + .build(); + EventKind kind = handler.onMessageSend( + MessageSendParams.builder().message(message).configuration(RETURN_IMMEDIATELY).build(), NULL_CONTEXT); + assertInstanceOf(Task.class, kind); + Task task = (Task) kind; + assertTrue(working.await(5, TimeUnit.SECONDS), "the agent did not start"); + long deadline = System.currentTimeMillis() + 5_000; + while (System.currentTimeMillis() < deadline) { + Task stored = taskStore.get(task.id()); + if (stored != null && stored.status().state() == TaskState.TASK_STATE_WORKING) { + return stored; + } + Thread.sleep(10); + } + throw new AssertionError("the task was not stored as WORKING"); + } + + /** + * Subscribes on another thread, arms the hook, and lets the agent publish once the subscribe has reached {@code + * tap}. Returns the subscribe's future: its publisher, or the refusal it threw. + */ + private Future> subscribeAndPublishInTheWindow(Task task, CountDownLatch publish) + throws Exception { + queueManager.armed = true; + Future> f = pool.submit( + () -> handler.onSubscribeToTask(new TaskIdParams(task.id(), null), NULL_CONTEXT)); + awaitOrFail(queueManager.reached, "the subscribe did not reach tap"); + publish.countDown(); + return f; + } + + /** Counts {@code processed} down when the bus has finished an event of {@code type}, or the task's final event. */ + private MainEventBusProcessorCallback countDownOn(Class type, boolean onFinal) { + return new MainEventBusProcessorCallback() { + @Override + public void onEventProcessed(String taskId, Event event) { + if (type != null && type.isInstance(event)) { + processed(); + } + } + + @Override + public void onTaskFinalized(String taskId) { + if (onFinal) { + processed(); + } + } + + private void processed() { + if (queueManager.processed.getCount() > 0) { + queueManager.processedNanos = System.nanoTime(); + } + queueManager.processed.countDown(); + } + }; + } + + /** + * Fails unless the window was exercised: the bus finished the event inside it (no serialisation); or, when the + * wait ended, the agent had published and the bus thread was blocked on a lock the subscribing thread held, and the + * bus finished only after the tap returned (verified serialisation). Called after the event is known to have been + * processed or its stream to have ended. + */ + private void assertWindowExercised() { + WindowQueueManager w = queueManager; + if (w.processedInWindow) { + return; + } + awaitOrFail(w.processed, "the bus did not finish the window's event after the tap"); + assertTrue(w.publishedInWindow, "window not exercised: the agent had not published when the " + + WINDOW_MILLIS + " ms wait ended"); + assertTrue(w.busBlockedOnSubscriber, "window not exercised: the bus had not finished the event within " + + WINDOW_MILLIS + " ms but was not blocked on a lock of the subscribing thread (" + w.busStateAtTimeout + ")"); + assertTrue(w.processedNanos - w.tapReturnedNanos > 0, + "window not exercised: the bus finished the event before the tap returned, outside the wait"); + } + + /** + * (a) An event published after the subscribe read the task and before it tapped the queue must reach the + * subscriber, in the Task snapshot or on the stream (S:288's rationale, "This prevents a potential loss of + * information"). + */ + @Test + void eventPublishedBetweenReadAndTap_reachesSnapshotOrStream() throws Exception { + CountDownLatch working = new CountDownLatch(1); + CountDownLatch publishArtifact = new CountDownLatch(1); + CountDownLatch finish = new CountDownLatch(1); + agentBody = (context, emitter) -> { + emitter.startWork(); + working.countDown(); + awaitOrFail(publishArtifact, "the agent was not told to publish"); + emitter.addArtifact(List.of(new TextPart("in the window"))); + queueManager.published.countDown(); + awaitOrFail(finish, "the agent was not told to finish"); + emitter.complete(); + }; + processor.setCallback(countDownOn(TaskArtifactUpdateEvent.class, false)); + Task task = startWorkingTask(working); + Future> f = subscribeAndPublishInTheWindow(task, publishArtifact); + + Collector c = new Collector(); + f.get(WINDOW_MILLIS + 5_000, TimeUnit.MILLISECONDS).subscribe(c); + finish.countDown(); + assertTrue(c.done.await(5, TimeUnit.SECONDS), "the stream did not close after completion: " + c.items); + assertNull(c.error.get()); + assertWindowExercised(); + + Task snapshot = (Task) c.items.get(0); + boolean inSnapshot = snapshot.artifacts() != null && !snapshot.artifacts().isEmpty(); + boolean onStream = c.items.stream().anyMatch(i -> i instanceof TaskArtifactUpdateEvent); + assertTrue(inSnapshot || onStream, "the artifact published in the window (bus done inside the window: " + + queueManager.processedInWindow + ") reached neither the snapshot nor the stream: " + c.items); + } + + /** + * (b) A task that reaches a terminal state after the subscribe read it (non-terminal) and before it tapped the + * queue must still end the subscriber's stream (S:286, "The stream MUST terminate when the task reaches a terminal + * state"). Correct outcomes: the stream closes and shows the completion in its snapshot or as an update; or the + * subscribe is refused because it found the task terminal (S:282). + */ + @Test + void terminalStateBetweenReadAndTap_closesTheStream() throws Exception { + CountDownLatch working = new CountDownLatch(1); + CountDownLatch finish = new CountDownLatch(1); + agentBody = (context, emitter) -> { + emitter.startWork(); + working.countDown(); + awaitOrFail(finish, "the agent was not told to finish"); + emitter.complete(); + queueManager.published.countDown(); + }; + processor.setCallback(countDownOn(null, true)); + Task task = startWorkingTask(working); + Future> f = subscribeAndPublishInTheWindow(task, finish); + + Flow.Publisher publisher; + try { + publisher = f.get(WINDOW_MILLIS + 5_000, TimeUnit.MILLISECONDS); + } catch (ExecutionException e) { + assertInstanceOf(UnsupportedOperationError.class, e.getCause(), + "a refused subscribe must be refused as terminal: " + e.getCause()); + assertWindowExercised(); + return; + } + Collector c = new Collector(); + publisher.subscribe(c); + assertTrue(c.done.await(5, TimeUnit.SECONDS), "the subscriber's stream never closed after the task completed in" + + " the window (bus done inside the window: " + queueManager.processedInWindow + "): " + c.items); + assertNull(c.error.get()); + assertWindowExercised(); + boolean completedSnapshot = c.items.get(0) instanceof Task t + && t.status().state() == TaskState.TASK_STATE_COMPLETED; + boolean completedUpdate = c.items.stream().anyMatch(i -> i instanceof TaskStatusUpdateEvent u + && u.status().state() == TaskState.TASK_STATE_COMPLETED); + assertTrue(completedSnapshot || completedUpdate, "the completion is in neither the snapshot nor the stream: " + + c.items); + } + + private static void awaitOrFail(CountDownLatch l, String what) { + try { + if (!l.await(10, TimeUnit.SECONDS)) { + fail(what + " within 10 s"); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + fail("interrupted: " + what); + } + } +} From 9003d7217f0349937c626db8e3baf39aca3e64c9 Mon Sep 17 00:00:00 2001 From: Mohammad Hossein Khoshechin Jorshari Date: Wed, 2 Dec 2026 20:03:17 +0100 Subject: [PATCH 2/3] fix(server-common): lock per task, not per processor, around subscribe's read and tap The subscribe fix held one processor-wide monitor while a subscriber read the task and tapped its queue, and while the bus persisted and distributed any event. The ordering it protects is per task, so a subscribe on one task held up every other task's events, with a database read on that path when the TaskStore is JDBC-backed. The monitor becomes 64 lock stripes indexed by a hash of the task ID: processEvent holds the stripe of the event's task, and withEventProcessingPaused(taskId, action) holds the same stripe for the read and the tap. A fixed stripe set keeps memory bounded and needs no cleanup when a task ends; tasks that share a stripe only share contention. The Javadoc states the remaining limit (the processor is single-threaded, so an event of the held task makes later events wait) and forbids nesting the stripes of two tasks. Adds MainEventBusProcessorTaskLockTest: while a subscriber holds task A's stripe, a task-B event is persisted and distributed and a task-A event waits; a second subscriber to A blocks, one to B does not. --- .../server/events/MainEventBusProcessor.java | 57 +++++- .../DefaultRequestHandler.java | 9 +- .../MainEventBusProcessorTaskLockTest.java | 188 ++++++++++++++++++ 3 files changed, 239 insertions(+), 15 deletions(-) create mode 100644 server-common/src/test/java/org/a2aproject/sdk/server/events/MainEventBusProcessorTaskLockTest.java diff --git a/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java b/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java index 749db56cd..936975e56 100644 --- a/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java +++ b/server-common/src/main/java/org/a2aproject/sdk/server/events/MainEventBusProcessor.java @@ -105,13 +105,42 @@ private record UpdateResult(boolean isFinal, @Nullable Task taskSnapshot) {} */ private final ConcurrentHashMap initialTasks = new ConcurrentHashMap<>(); + /** The number of lock stripes; a power of two. */ + static final int LOCK_STRIPES = 64; + /** - * Held by {@link #processEvent} from persisting an event until it has been distributed to the - * ChildQueues, and by {@link #withEventProcessingPaused} callers. A caller that reads a task from - * the TaskStore and then taps its queue under this lock therefore sees every event either in the - * stored task or on its new ChildQueue, never in neither. + * Per-task locks, striped by task ID. A task's stripe is held by {@link #processEvent} from + * persisting an event of that task until it has been distributed to the ChildQueues, and by + * {@link #withEventProcessingPaused} callers for that task. A caller that reads a task from the + * TaskStore and then taps its queue under the task's stripe therefore sees every event of the task + * either in the stored task or on its new ChildQueue, never in neither. The invariant concerns one + * task only, so a subscriber holding one task's stripe does not hold up the events of other tasks + * on other stripes. The processor is single-threaded, though: once it takes an event of the held + * task, it waits for the stripe, and the events queued after that one wait with it. A fixed set of + * stripes keeps memory bounded and needs no cleanup when a task ends. */ - private final Object persistAndDistributeLock = new Object(); + private final Object[] persistAndDistributeLocks = newLocks(); + + private static Object[] newLocks() { + Object[] locks = new Object[LOCK_STRIPES]; + for (int i = 0; i < LOCK_STRIPES; i++) { + locks[i] = new Object(); + } + return locks; + } + + /** The stripe index of a task ID (a null ID uses stripe 0). */ + static int stripe(@Nullable String taskId) { + if (taskId == null) { + return 0; + } + int h = taskId.hashCode(); + return (h ^ (h >>> 16)) & (LOCK_STRIPES - 1); + } + + private Object lockFor(@Nullable String taskId) { + return persistAndDistributeLocks[stripe(taskId)]; + } private MainEventBus eventBus; @@ -247,19 +276,25 @@ synchronized void stop() { } /** - * Runs {@code action} while no event is between being persisted and being distributed. + * Runs {@code action} while no event of the task is between being persisted and being distributed. *

* Used by subscribe: reading the task from the TaskStore and tapping its queue inside one - * call means every event is either already in the task read or still to be distributed to the - * new ChildQueue. The action must not wait for this processor. + * call means every event of the task is either already in the task read or still to be + * distributed to the new ChildQueue. Events of other tasks whose IDs map to other stripes are not + * held up while the processor is not itself waiting for this task's stripe (see + * {@code persistAndDistributeLocks}). The action + * must not wait for this processor, and must not call this method for another task, directly or + * through a callback it runs (for example a {@code TaskStreamLifecycleHook}): two subscribers + * nesting the stripes of two tasks in opposite orders would deadlock. *

* + * @param taskId the task whose event processing is paused * @param action the action to run * @param the action's result type * @return the action's result */ - public T withEventProcessingPaused(Supplier action) { - synchronized (persistAndDistributeLock) { + public T withEventProcessingPaused(String taskId, Supplier action) { + synchronized (lockFor(taskId)) { return action.get(); } } @@ -303,7 +338,7 @@ private void processEvent(MainEventBusContext context) { boolean isReplicated = context.eventQueueItem().isReplicated(); int childCount; try { - synchronized (persistAndDistributeLock) { + synchronized (lockFor(taskId)) { // Step 1: Update TaskStore FIRST (persistence before clients see it) // If this throws, we distribute an error to ensure "persist before client visibility" 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 041535f4d..2f3ce670e 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 @@ -1353,9 +1353,10 @@ public Flow.Publisher onSubscribeToTask(TaskIdParams params, validateRequiredId(context, "id", params.id()); LOGGER.debug("onSubscribeToTask - taskId: {}", params.id()); enforceRead(context, params.id(), TaskOperation.SUBSCRIBE_TO_TASK); - // Read the task and tap its queue with event processing paused: every event is then either - // in the snapshot read here or still to be distributed to the tapped queue. - SubscribeStart start = mainEventBusProcessor.withEventProcessingPaused(() -> readAndTap(params.id())); + // Read the task and tap its queue with the task's event processing paused: every event of the task is + // then either in the snapshot read here or still to be distributed to the tapped queue. + SubscribeStart start = mainEventBusProcessor.withEventProcessingPaused(params.id(), + () -> readAndTap(params.id())); Task task = start.task(); EventQueue queue = start.queue(); @@ -1380,7 +1381,7 @@ public Flow.Publisher onSubscribeToTask(TaskIdParams params, private record SubscribeStart(Task task, EventQueue queue) {} /** - * The task read and the queue tap of {@link #onSubscribeToTask}, run with event processing paused. + * The task read and the queue tap of {@link #onSubscribeToTask}, run with the task's event processing paused. */ private SubscribeStart readAndTap(String taskId) throws A2AError { Task task = taskStore.get(taskId); diff --git a/server-common/src/test/java/org/a2aproject/sdk/server/events/MainEventBusProcessorTaskLockTest.java b/server-common/src/test/java/org/a2aproject/sdk/server/events/MainEventBusProcessorTaskLockTest.java new file mode 100644 index 000000000..7b2801d72 --- /dev/null +++ b/server-common/src/test/java/org/a2aproject/sdk/server/events/MainEventBusProcessorTaskLockTest.java @@ -0,0 +1,188 @@ +package org.a2aproject.sdk.server.events; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; + +import org.a2aproject.sdk.server.tasks.PushNotificationSender; +import org.a2aproject.sdk.server.tasks.TaskStore; +import org.a2aproject.sdk.spec.Event; +import org.a2aproject.sdk.spec.Task; +import org.a2aproject.sdk.spec.TaskState; +import org.a2aproject.sdk.spec.TaskStatus; +import org.junit.jupiter.api.Test; + +/** + * The subscribe lock of {@link MainEventBusProcessor} is per task (striped by task ID). While a subscriber to one + * task holds it (its TaskStore read and queue tap), a subscriber to, and the events of, a task on another stripe are + * not held up; a second subscriber to the same task, and that task's events, wait. + */ +class MainEventBusProcessorTaskLockTest { + + /** A task ID whose stripe differs from {@code taskA}'s; fails if none of the first 10,000 candidates has one. */ + private static String otherStripe(String taskA) { + for (int i = 0; i < 10_000; i++) { + String id = "task-" + i; + if (MainEventBusProcessor.stripe(id) != MainEventBusProcessor.stripe(taskA)) { + return id; + } + } + throw new AssertionError("no task ID on another stripe than " + taskA + "'s"); + } + + /** Waits until {@code condition} holds, at most 10 s. */ + private static boolean await(BooleanSupplier condition) throws InterruptedException { + long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < end) { + if (condition.getAsBoolean()) { + return true; + } + Thread.sleep(10); + } + return false; + } + + /** Whether {@code thread} is blocked on a monitor inside the given method of MainEventBusProcessor. */ + private static boolean blockedIn(Thread thread, String method) { + if (thread.getState() != Thread.State.BLOCKED) { + return false; + } + for (StackTraceElement f : thread.getStackTrace()) { + if (f.getClassName().equals(MainEventBusProcessor.class.getName()) + && f.getMethodName().equals(method)) { + return true; + } + } + return false; + } + + /** Holds task A's stripe on another thread until {@code release} counts down; returns once it is held. */ + private static CompletableFuture holdStripe(MainEventBusProcessor processor, String taskId, + CountDownLatch release) throws InterruptedException { + CountDownLatch entered = new CountDownLatch(1); + CompletableFuture holder = CompletableFuture.supplyAsync(() -> + processor.withEventProcessingPaused(taskId, () -> { + entered.countDown(); + try { + release.await(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return taskId; + })); + assertTrue(entered.await(10, TimeUnit.SECONDS), "the holder never entered"); + return holder; + } + + @Test + void subscribeOnOneTask_doesNotBlockAnotherTasksSubscribe_butBlocksTheSameTask() throws Exception { + MainEventBusProcessor processor = new MainEventBusProcessor(); + String taskA = "task-A"; + String taskB = otherStripe(taskA); + assertNotEquals(MainEventBusProcessor.stripe(taskA), MainEventBusProcessor.stripe(taskB)); + CountDownLatch release = new CountDownLatch(1); + try { + CompletableFuture holderA = holdStripe(processor, taskA, release); + + // Another task: proceeds while task A's lock is held. + assertEquals("B", CompletableFuture.supplyAsync(() -> + processor.withEventProcessingPaused(taskB, () -> "B")).get(10, TimeUnit.SECONDS)); + + // The same task: blocks on the monitor until the holder is done. + CompletableFuture secondA = new CompletableFuture<>(); + Thread second = new Thread(() -> secondA.complete(processor.withEventProcessingPaused(taskA, () -> "A2"))); + second.start(); + assertTrue(await(() -> second.getState() == Thread.State.BLOCKED), "the second subscriber never blocked"); + assertFalse(secondA.isDone()); + + release.countDown(); + assertEquals(taskA, holderA.get(10, TimeUnit.SECONDS)); + assertEquals("A2", secondA.get(10, TimeUnit.SECONDS)); + } finally { + release.countDown(); + } + } + + @Test + void eventsOfAnotherTask_areProcessed_whileATasksSubscribeHoldsItsLock() throws Exception { + MainEventBus bus = new MainEventBus(); + InMemoryQueueManager queueManager = new InMemoryQueueManager(null, bus); + MainEventBusProcessor processor = new MainEventBusProcessor(bus, mock(TaskStore.class), + PushNotificationSender.NOOP, queueManager); + String taskA = "task-A"; + String taskB = otherStripe(taskA); + Map processed = new ConcurrentHashMap<>(); + processed.put(taskA, new CountDownLatch(1)); + processed.put(taskB, new CountDownLatch(1)); + AtomicBoolean released = new AtomicBoolean(); + AtomicReference processorThread = new AtomicReference<>(); + AtomicBoolean aBeforeRelease = new AtomicBoolean(); + processor.setCallback(new MainEventBusProcessorCallback() { + @Override + public void onEventProcessed(String taskId, Event event) { + // The callback runs on this processor's thread. + processorThread.compareAndSet(null, Thread.currentThread()); + if (taskId.equals(taskA) && !released.get()) { + aBeforeRelease.set(true); + } + processed.get(taskId).countDown(); + } + + @Override + public void onTaskFinalized(String taskId) { + } + }); + EventQueueUtil.start(processor); + EventQueue queueA = EventQueueUtil.getEventQueueBuilder(bus).taskId(taskA).mainEventBus(bus).build().tap(); + EventQueue queueB = EventQueueUtil.getEventQueueBuilder(bus).taskId(taskB).mainEventBus(bus).build().tap(); + CountDownLatch release = new CountDownLatch(1); + try { + CompletableFuture holderA = holdStripe(processor, taskA, release); + + // Task B's event is processed while task A's lock is held. + queueB.enqueueEvent(task(taskB)); + assertTrue(processed.get(taskB).await(10, TimeUnit.SECONDS), "task B's event was held up"); + Thread busThread = processorThread.get(); + + // Task A's event waits: this processor's thread blocks in processEvent on A's stripe until the holder is + // done. + queueA.enqueueEvent(task(taskA)); + assertTrue(await(() -> blockedIn(busThread, "processEvent")), + "the processor never blocked on task A's lock"); + released.set(true); + release.countDown(); + assertTrue(processed.get(taskA).await(10, TimeUnit.SECONDS), "task A's event was never processed"); + assertFalse(aBeforeRelease.get(), "task A's event was processed while its lock was held"); + assertEquals(taskA, holderA.get(10, TimeUnit.SECONDS)); + } finally { + release.countDown(); + processor.setCallback(null); + EventQueueUtil.stop(processor); + } + } + + @Test + void stripe_isWithinBounds_andStableForATask() { + for (String id : new String[] {"", "t", "task-A", "a-much-longer-task-identifier-0123456789"}) { + int s = MainEventBusProcessor.stripe(id); + assertTrue(s >= 0 && s < MainEventBusProcessor.LOCK_STRIPES, id + " -> " + s); + assertEquals(s, MainEventBusProcessor.stripe(new String(id.toCharArray()))); + } + assertEquals(0, MainEventBusProcessor.stripe(null)); + } + + private static Task task(String id) { + return Task.builder().id(id).contextId("ctx").status(new TaskStatus(TaskState.TASK_STATE_SUBMITTED)).build(); + } +} From 74464c447c9699673cbd17b3ae6efaafbccab576 Mon Sep 17 00:00:00 2001 From: Mohammad Hossein Khoshechin Jorshari Date: Thu, 3 Dec 2026 16:01:53 +0100 Subject: [PATCH 3/3] test(replicated): wait for the first stream event before sending COMPLETED testKafkaEventReceivedByA2AServer starts subscribeToTask, which returns before the server has handled the subscribe request, and then sends the COMPLETED event to Kafka at once. When the server processes the COMPLETED event before the subscribe reads the task, the subscribe correctly rejects the task as terminal, and the test fails with "Cannot subscribe to task ... task is in terminal state". In local runs the subscribe reached the server only a few milliseconds before the COMPLETED event. Wait until the subscription delivers its first event (the initial task snapshot) before sending COMPLETED, as #864 did for testQueueClosedEventTerminatesRemoteSubscribers. The assertions are unchanged. --- .../tests/KafkaReplicationIntegrationTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/extras/queue-manager-replicated/tests-single-instance/src/test/java/org/a2aproject/sdk/extras/queuemanager/replicated/tests/KafkaReplicationIntegrationTest.java b/extras/queue-manager-replicated/tests-single-instance/src/test/java/org/a2aproject/sdk/extras/queuemanager/replicated/tests/KafkaReplicationIntegrationTest.java index c5b74c0b6..2d0f0caf2 100644 --- a/extras/queue-manager-replicated/tests-single-instance/src/test/java/org/a2aproject/sdk/extras/queuemanager/replicated/tests/KafkaReplicationIntegrationTest.java +++ b/extras/queue-manager-replicated/tests-single-instance/src/test/java/org/a2aproject/sdk/extras/queuemanager/replicated/tests/KafkaReplicationIntegrationTest.java @@ -220,6 +220,7 @@ public void testKafkaEventReceivedByA2AServer() throws Exception { // Set up resubscription to listen for task updates using streaming client CountDownLatch subscribeLatch = new CountDownLatch(1); + CountDownLatch firstEventLatch = new CountDownLatch(1); AtomicReference receivedCompletedEvent = new AtomicReference<>(); AtomicBoolean wasUnexpectedEvent = new AtomicBoolean(false); AtomicReference errorRef = new AtomicReference<>(); @@ -231,6 +232,7 @@ public void testKafkaEventReceivedByA2AServer() throws Exception { if (!receivedInitialTask.get()) { if (event instanceof TaskEvent) { receivedInitialTask.set(true); + firstEventLatch.countDown(); return; } else { throw new AssertionError("First event on subscribe MUST be TaskEvent, but was: " + event.getClass().getSimpleName()); @@ -259,12 +261,19 @@ public void testKafkaEventReceivedByA2AServer() throws Exception { if (!isStreamClosedError(error)) { errorRef.set(error); } + firstEventLatch.countDown(); subscribeLatch.countDown(); }; // Subscribe to the task to listen for updates streamingClient.subscribeToTask(new TaskIdParams(taskId), List.of(consumer), errorHandler); + // Wait until the subscription delivers its first event (the initial task snapshot) before sending + // COMPLETED. subscribeToTask returns before the server has handled the request, so without this + // wait the COMPLETED event can be processed first and the subscribe then finds a terminal task. + assertTrue(firstEventLatch.await(15, TimeUnit.SECONDS), + "Should receive initial task snapshot from subscription"); + // Now manually send a TaskStatusUpdateEvent to Kafka using reactive messaging TaskStatusUpdateEvent statusEvent = TaskStatusUpdateEvent.builder() .taskId(taskId)