Skip to content

gh-159964: Propagate contextvars to ThreadPoolExecutor tasks - #160024

Closed
methatp0 wants to merge 1 commit into
python:mainfrom
methatp0:fix-threadpool-contextvars-submit
Closed

methatp0 wants to merge 1 commit into
python:mainfrom
methatp0:fix-threadpool-contextvars-submit

Conversation

@methatp0

@methatp0 methatp0 commented Oct 21, 2026 •

Copy link
Copy Markdown

Fixes gh-159964.

Capture a copy of the submitting thread's context for each submitted task and execute the callable within that context. This prevents a task from inheriting stale context from whichever worker happened to start first and keeps context-variable rebinding in one task isolated from subsequent tasks.

The change includes a regression test for context propagation across reused workers, documentation, and a NEWS entry.

Validation: lint and the C API documentation check pass. The full CI matrix is running; the local CPython test suite could not be run in this environment.

@python-cla-bot

Copy link
Copy Markdown

The following commit authors need to sign the Contributor License Agreement:

CLA not signed

@bedevere-app

bedevere-app Bot commented Oct 21, 2026

Copy link
Copy Markdown

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@methatp0 methatp0 changed the title Fix ThreadPoolExecutor context propagation gh-159964: Propagate contextvars to ThreadPoolExecutor tasks Oct 21, 2026
@methatp0
methatp0 force-pushed the fix-threadpool-contextvars-submit branch from 8731f40 to 526dfe8 Compare October 21, 2026 05:25
@methatp0
methatp0 marked this pull request as ready for review October 21, 2026 05:25
@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #35288083 | 📁 Comparing 526dfe8 against main (b577a54)

  🔍 Preview build  

2 files changed
± library/concurrent.futures.html
± whatsnew/changelog.html

@ngoldbaum

Copy link
Copy Markdown
Contributor

Thanks for the patch. I was planning to work on this issue, and I’ll take it from here. The proposed change fixes the reproducer, but unconditional context propagation also changes downstream behavior. I want to think about compatibility questions and performance before settling on an implementation. I’m closing this PR to avoid parallel work; I’ll follow up on the issue.

@ngoldbaum ngoldbaum closed this Oct 21, 2026
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.

ThreadPoolExecutor tasks see the context of whichever submit() call started their worker thread

2 participants