Skip to content

Commit 4b19e4b

Browse files
Copilotedburns
andauthored
Fix race condition in sendAndWait: use whenCompleteAsync to prevent test-thread wakeup mid-dispatch
Agent-Logs-Url: https://github.com/github/copilot-sdk-java/sessions/e7c09bc7-4fc9-4619-a0d9-d1bed96104b9 Co-authored-by: edburns <75821+edburns@users.noreply.github.com>
1 parent ed3307f commit 4b19e4b

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/main/java/com/github/copilot/sdk/CopilotSession.java

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -542,9 +542,17 @@ public CompletableFuture<AssistantMessageEvent> sendAndWait(MessageOptions optio
542542
}
543543
}
544544

545-
// When inner future completes, run cleanup and propagate to result
545+
// When inner future completes, run cleanup and propagate to result.
546+
// Use whenCompleteAsync so that result.complete(r) is not called
547+
// synchronously on the event-dispatch thread while dispatchEvent() is
548+
// still iterating over handlers. Without async dispatch, a caller that
549+
// registered its own session.on() listener before calling sendAndWait()
550+
// could see its listener invoked *after* result.get() returned, because
551+
// sendAndWait's internal handler would complete the future mid-loop. By
552+
// submitting the completion to timeoutScheduler we allow the current
553+
// dispatch loop to finish calling all other handlers first.
546554
final ScheduledFuture<?> taskToCancel = timeoutTask;
547-
future.whenComplete((r, ex) -> {
555+
future.whenCompleteAsync((r, ex) -> {
548556
try {
549557
subscription.close();
550558
} catch (IOException e) {
@@ -560,7 +568,7 @@ public CompletableFuture<AssistantMessageEvent> sendAndWait(MessageOptions optio
560568
result.complete(r);
561569
}
562570
}
563-
});
571+
}, timeoutScheduler);
564572

565573
// When result is cancelled externally, cancel inner future to trigger cleanup
566574
result.whenComplete((v, ex) -> {

0 commit comments

Comments
 (0)