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 @@ -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;
Expand Down Expand Up @@ -104,6 +105,43 @@ private record UpdateResult(boolean isFinal, @Nullable Task taskSnapshot) {}
*/
private final ConcurrentHashMap<String, Task> 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;
Expand Down Expand Up @@ -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.
* <p>
* 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.
* </p>
*
* @param taskId the task whose event processing is paused
* @param action the action to run
* @param <T> the action's result type
* @return the action's result
*/
public <T> T withEventProcessingPaused(String taskId, Supplier<T> action) {
synchronized (lockFor(taskId)) {
return action.get();
}
}

@Override
public void run() {
LOGGER.info("MainEventBusProcessor processing loop started");
Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1353,7 +1353,38 @@ public Flow.Publisher<StreamingEventKind> 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<EventQueueItem> 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();
}
Expand All @@ -1369,9 +1400,6 @@ public Flow.Publisher<StreamingEventKind> 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");

Expand All @@ -1381,19 +1409,7 @@ public Flow.Publisher<StreamingEventKind> 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<EventQueueItem> 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
Expand Down
Loading
Loading