@@ -453,9 +453,37 @@ protected void doClose(boolean immediate) {
453453 return ;
454454 }
455455 LOGGER .debug ("Closing {} (immediate={})" , this , immediate );
456+ // onClose is invoked while the lock is still held so that subclasses can update
457+ // their own state (e.g. immediateClose + queue.clear()) atomically with closed=true.
458+ onClose (immediate );
456459 closed = true ;
457460 }
458- // Subclasses handle immediate close logic (e.g., ChildQueue clears its local queue)
461+ }
462+
463+ /**
464+ * Called from within the {@code synchronized(this)} block of {@link #doClose(boolean)},
465+ * before {@code closed} is set to {@code true}. Subclasses may override to perform
466+ * state updates that must be atomic with the close. The default implementation is a no-op.
467+ *
468+ * @param immediate whether this is an immediate (non-draining) close
469+ */
470+ protected void onClose (boolean immediate ) {
471+ // no-op — subclasses override
472+ }
473+
474+ /**
475+ * Returns whether an event represents a final task state.
476+ */
477+ static boolean isFinalEvent (Event event ) {
478+ if (event instanceof Task task ) {
479+ return task .status () != null && task .status ().state () != null
480+ && task .status ().state ().isFinal ();
481+ } else if (event instanceof TaskStatusUpdateEvent statusUpdate ) {
482+ return statusUpdate .isFinal ();
483+ } else if (event instanceof A2AError ) {
484+ return true ;
485+ }
486+ return false ;
459487 }
460488
461489 static class MainQueue extends EventQueue {
@@ -676,21 +704,6 @@ private void validateEventIds(Event event) {
676704 }
677705 }
678706
679- /**
680- * Checks if an event represents a final task state.
681- */
682- private boolean isFinalEvent (Event event ) {
683- if (event instanceof Task task ) {
684- return task .status () != null && task .status ().state () != null
685- && task .status ().state ().isFinal ();
686- } else if (event instanceof TaskStatusUpdateEvent statusUpdate ) {
687- return statusUpdate .isFinal ();
688- } else if (event instanceof A2AError ) {
689- return true ;
690- }
691- return false ;
692- }
693-
694707 @ Override
695708 public void awaitQueuePollerStart () throws InterruptedException {
696709 LOGGER .debug ("Waiting for queue poller to start on {}" , this );
@@ -756,6 +769,18 @@ void distributeToChildren(EventQueueItem item) {
756769 taskId , item .getEvent ().getClass ().getSimpleName (), childCount );
757770 }
758771 children .forEach (child -> {
772+ // Skip children that have already been closed. CopyOnWriteArrayList gives
773+ // snapshot semantics, so a child removed by closeIfNotAwaitingFinalEvent()
774+ // may still appear in this iteration. Checking isClosed() here narrows the
775+ // TOCTOU window to the time between the check and internalEnqueueItem();
776+ // a narrow residual race remains for graceful close but is harmless for
777+ // non-final events (they'd land in the draining queue) and impossible for
778+ // final events (submittedFinalEvents prevents close while one is in flight).
779+ if (child .isClosed ()) {
780+ LOGGER .debug ("MainQueue[{}]: Skipping closed child queue for event {}" ,
781+ taskId , item .getEvent ().getClass ().getSimpleName ());
782+ return ;
783+ }
759784 LOGGER .debug ("MainQueue[{}]: Enqueueing event {} to child queue" ,
760785 taskId , item .getEvent ().getClass ().getSimpleName ());
761786 child .internalEnqueueItem (item );
@@ -911,33 +936,18 @@ private void internalEnqueueItem(EventQueueItem item) {
911936 } else {
912937 LOGGER .debug ("Enqueued event {} {}" , event instanceof Throwable ? event .toString () : event , this );
913938
914- // If we were awaiting a final event and this is it, clear the flag
939+ // If we were awaiting a final event and this is it, decrement the counter
915940 if (isFinalEvent (event )) {
916941 synchronized (this ) {
917942 if (submittedFinalEvents > 0 ) {
918- submittedFinalEvents = 0 ;
943+ submittedFinalEvents -- ;
919944 LOGGER .debug ("ChildQueue {} received awaited final event" , System .identityHashCode (this ));
920945 }
921946 }
922947 }
923948 }
924949 }
925950
926- /**
927- * Checks if an event represents a final task state.
928- */
929- private boolean isFinalEvent (Event event ) {
930- if (event instanceof Task task ) {
931- return task .status () != null && task .status ().state () != null
932- && task .status ().state ().isFinal ();
933- } else if (event instanceof TaskStatusUpdateEvent statusUpdate ) {
934- return statusUpdate .isFinal ();
935- } else if (event instanceof A2AError ) {
936- return true ;
937- }
938- return false ;
939- }
940-
941951 @ Override
942952 public void enqueueLocalOnly (EventQueueItem item ) {
943953 internalEnqueueItem (item );
@@ -1012,21 +1022,18 @@ public void signalQueuePollerStarted() {
10121022 }
10131023
10141024 @ Override
1015- protected void doClose (boolean immediate ) {
1016- super .doClose (immediate ); // Sets closed flag
1025+ protected void onClose (boolean immediate ) {
1026+ // Invoked by EventQueue.doClose() while synchronized(this) is held, so closed,
1027+ // immediateClose, and the queue clear all become visible atomically.
10171028 if (immediate ) {
1018- // Immediate close: clear pending events from local queue
1019- int clearedCount ;
1020- synchronized (this ) {
1021- this .immediateClose = true ;
1022- pendingFinalEvents = 0 ;
1023- submittedFinalEvents = 0 ;
1024- clearedCount = queue .size ();
1025- queue .clear ();
1026- }
1029+ this .immediateClose = true ;
1030+ pendingFinalEvents = 0 ;
1031+ submittedFinalEvents = 0 ;
1032+ int clearedCount = queue .size ();
1033+ queue .clear ();
10271034 LOGGER .debug ("Cleared {} events from ChildQueue for immediate close: {}" , clearedCount , this );
10281035 }
1029- // For graceful close, let the queue drain naturally through normal consumption
1036+ // For graceful close the queue drains naturally; nothing to do here.
10301037 }
10311038
10321039 /**
@@ -1070,6 +1077,7 @@ synchronized void cancelSubmittedFinalEvent() {
10701077 */
10711078 @ Override
10721079 public synchronized void clearAwaitingFinalEvent () {
1080+ pendingFinalEvents = 0 ;
10731081 submittedFinalEvents = 0 ;
10741082 LOGGER .debug ("ChildQueue {} cleared awaitingFinalEvent flag (timeout)" , System .identityHashCode (this ));
10751083 }
0 commit comments