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..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 @@ -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,43 @@ 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; + + /** + * 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[] 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; private TaskStore taskStore; @@ -237,6 +275,30 @@ synchronized void stop() { LOGGER.info("MainEventBusProcessor stopped"); } + /** + * 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 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(String taskId, Supplier action) { + synchronized (lockFor(taskId)) { + return action.get(); + } + } + @Override public void run() { LOGGER.info("MainEventBusProcessor processing loop started"); @@ -274,68 +336,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 (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" - 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 44a02bbdb..b50548282 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,38 @@ 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 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(); + + 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 the task's event processing paused. + */ + private SubscribeStart readAndTap(String taskId) throws A2AError { + Task task = taskStore.get(taskId); if (task == null) { throw new TaskNotFoundError(); } @@ -1369,9 +1400,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 +1409,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/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(); + } +} 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); + } + } +}