Skip to content

fix(core): threadsafe asyncio future cancellation in CancellationToken - #8359

Open
MOHAMMED WASIM KHAN (wasim-builds) wants to merge 1 commit into
microsoft:mainfrom
wasim-builds:fix/cancellation-token-threadsafe-future
Open

MOHAMMED WASIM KHAN (wasim-builds) wants to merge 1 commit into
microsoft:mainfrom
wasim-builds:fix/cancellation-token-threadsafe-future

Conversation

@wasim-builds

Copy link
Copy Markdown

Closes #8358

Summary

Fixes cross-thread cancellation in CancellationToken.link_future() when cancellation originates from a background thread or thread pool worker.

Problem

Previously, CancellationToken.cancel() executed callbacks synchronously in the invoking thread, calling future.cancel() directly outside the future's owning event loop. Under debug mode or cross-thread execution, this raised:
RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one

Solution

  • Introduced threadsafe future cancellation via loop.call_soon_threadsafe(future.cancel) when the future's owning event loop is running.
  • Falls back to direct cancellation when the loop is not running or shutdown.
  • Added unit test test_cancellation_token_threadsafe_link_future verifying safe future cancellation from worker threads.

Copilot AI balanced review requested due to automatic review settings October 16, 2026 10:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CancellationToken.link_future() cancels asyncio futures from the wrong thread

2 participants