Skip to content

gh-92001: Count cancelled futures as done in wait() and as_completed() - #163141

Open
exllamav2 wants to merge 1 commit into
python:mainfrom
exllamav2:gh-92001-wait-cancelled-futures
Open

exllamav2 wants to merge 1 commit into
python:mainfrom
exllamav2:gh-92001-wait-cancelled-futures

Conversation

@exllamav2

@exllamav2 exllamav2 commented Dec 4, 2026 •

Copy link
Copy Markdown

wait() and as_completed() never count a future that was cancelled while still pending as done. The documentation says wait returns the futures that "finished or were cancelled", and Future.done() already reports such a future as done, so the two helpers contradict both the docs and the rest of the API:

import concurrent.futures, time

pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
for _ in range(50):
    future = pool.submit(time.sleep, 30)
future.cancel()  # True: it never started running

# never returns, even though future.done() is True
concurrent.futures.wait([future])

The root cause is that the only place waiters are notified of a cancellation is set_running_or_notify_cancel(), which the executor calls when it eventually picks the work item off the queue. On a busy pool that can be delayed arbitrarily, so the wait never ends even though the future is already in a terminal state.

The consumer-side checks in wait(), as_completed() and _create_and_install_waiters() now treat CANCELLED as terminal alongside CANCELLED_AND_NOTIFIED and FINISHED. Nothing changes on the executor side: the worker still performs the notification when it processes the item, which is a no-op for any waiter that has already been removed.

Two existing tests asserted that a cancelled pending future must end up in not_done, which contradicts the documented behaviour, so they were updated rather than preserved. test_first_completed can now legitimately return before the first real future finishes (an already-cancelled future satisfies FIRST_COMPLETED immediately), so its assertions were relaxed to the deterministic subset instead of asserting exact sets.

written with devin (the ai tool) doing most of the implementation, verified across all the executor variants myself.

@python-cla-bot

python-cla-bot Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant