Skip to content

fix: propagate contextvars through thread_pool_exec - #16247

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
vincentlambert:fix/thread-pool-exec-contextvar-python313
Jun 23, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
vincentlambert:fix/thread-pool-exec-contextvar-python313

Conversation

@vincentlambert

@vincentlambert vincentlambert commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Problem

thread_pool_exec() dispatches work via loop.run_in_executor(), which submits the callable with a plain executor.submit(func, *args) and does not copy the caller's contextvars.Context. So a ContextVar set in the async caller is not visible inside the function running in the worker thread.

This differs from asyncio.to_thread(), which runs the callable inside a copied context. run_in_executor() has never propagated context (verified on Python 3.12 and 3.13) — so this is a pre-existing gap in the helper, not a regression or a Python-version compatibility issue.

Concretely, any code that sets a ContextVar in async code and reads it inside a function dispatched via thread_pool_exec (request tracing, per-task state, Langfuse trace propagation, etc.) silently loses that context.

Fix

Copy the current context before submitting and run the callable inside it with ctx.run(), matching what asyncio.to_thread() does:

async def thread_pool_exec(func, *args, **kwargs):
    loop = asyncio.get_running_loop()
    ctx = contextvars.copy_context()
    if kwargs:
        inner = functools.partial(func, *args, **kwargs)
        return await loop.run_in_executor(_thread_pool_executor(), ctx.run, inner)
    return await loop.run_in_executor(_thread_pool_executor(), ctx.run, func, *args)

This explicitly adds ContextVar propagation to the helper (it does not restore any prior behavior). Backward-compatible.

Tests

TestThreadPoolExec covers propagation, the kwargs path, per-call isolation and the unset-default case.

Note: the branch name still contains python313 for historical reasons; the change is unrelated to any Python version.

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. python Pull requests that update python code labels Jun 22, 2026
@coderabbitai

coderabbitai Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 34d08e89-bc7c-464d-8574-bf90e88f0a47

📥 Commits

Reviewing files that changed from the base of the PR and between f738adc and 213ea62.

📒 Files selected for processing (2)
  • common/misc_utils.py
  • test/unit_test/common/test_misc_utils.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • common/misc_utils.py
  • test/unit_test/common/test_misc_utils.py

📝 Walkthrough

Walkthrough

common/misc_utils.py adds import contextvars and updates thread_pool_exec to explicitly copy the current context via contextvars.copy_context() and invoke the callable through ctx.run(...) inside loop.run_in_executor. A new comprehensive test suite validates that ContextVar values propagate correctly into worker threads across scenarios including missing kwargs, kwargs via partial, consecutive calls with different context, and unset ContextVar defaults.

Changes

ContextVar propagation fix in thread_pool_exec

Layer / File(s) Summary
Import and thread_pool_exec context propagation
common/misc_utils.py
Adds import contextvars; rewrites thread_pool_exec to call contextvars.copy_context() before scheduling work and wraps the callable in ctx.run(...) so ContextVar values from the calling coroutine are visible in thread-pool workers under Python 3.13+.
Test suite for ContextVar propagation
test/unit_test/common/test_misc_utils.py
Adds contextvars and thread_pool_exec imports; introduces TestThreadPoolExec with five tests covering no-kwargs calls, kwargs via partial, consecutive calls with different context, and unset ContextVar defaults, all validating the fix via asyncio.run.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐇 Hopping through threads, context in paw,
No lost variables — that's the new law!
copy_context() tucked under my ear,
ctx.run() carries the values from here.
Five tests verify the journey's complete —
The rabbit ensures context never skips a beat! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.46% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding contextvars propagation to thread_pool_exec to match asyncio.to_thread() behavior.
Description check ✅ Passed The description comprehensively covers the problem, solution, implementation details, backward compatibility, and test coverage, though it lacks explicit type-of-change checkbox selection.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
common/misc_utils.py (1)

253-262: 🧹 Nitpick | 🔵 Trivial

Add a regression test for context variable propagation through thread_pool_exec.

The implementation correctly uses contextvars.copy_context() and ctx.run() wrapping, but no test currently validates this behavior. Since this addresses a Python 3.13-specific change to ThreadPoolExecutor, add a test that:

  • Sets a ContextVar in the caller
  • Awaits thread_pool_exec() with a function that reads the ContextVar
  • Asserts the worker thread observes the caller's value

This prevents silent regressions in context propagation, which would otherwise go undetected.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@common/misc_utils.py` around lines 253 - 262, Add a new test function that
validates context variable propagation through the thread_pool_exec function.
The test should create a ContextVar, set it to a specific value in the test's
async context, then define an inner function that reads and returns that
ContextVar's value, pass this inner function to thread_pool_exec, and finally
assert that the returned value matches the original value set in the caller.
This ensures that context variables are correctly propagated from the async
caller into the worker thread when using thread_pool_exec, covering the Python
3.13-specific behavior mentioned in the function's comments.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@common/misc_utils.py`:
- Around line 253-262: Add a new test function that validates context variable
propagation through the thread_pool_exec function. The test should create a
ContextVar, set it to a specific value in the test's async context, then define
an inner function that reads and returns that ContextVar's value, pass this
inner function to thread_pool_exec, and finally assert that the returned value
matches the original value set in the caller. This ensures that context
variables are correctly propagated from the async caller into the worker thread
when using thread_pool_exec, covering the Python 3.13-specific behavior
mentioned in the function's comments.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e2fa62d4-1e34-4e8e-acae-e7a478ba68e5

📥 Commits

Reviewing files that changed from the base of the PR and between 06ededb and f80d081.

📒 Files selected for processing (1)
  • common/misc_utils.py

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/unit_test/common/test_misc_utils.py`:
- Around line 109-168: The test methods in the TestThreadPoolExec class
(test_contextvar_propagated_to_thread, test_contextvar_propagated_with_kwargs,
test_contextvar_isolation_between_calls, and
test_unset_contextvar_returns_default) are missing pytest priority level
markers. Add pytest priority markers as decorators above each test method, using
either `@pytest.mark.p1` or `@pytest.mark.p2` to indicate their importance for the
ContextVar propagation compatibility fix.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bc84ca4a-4d2a-4ebb-9724-a9551a1c27ab

📥 Commits

Reviewing files that changed from the base of the PR and between f80d081 and d97a85b.

📒 Files selected for processing (1)
  • test/unit_test/common/test_misc_utils.py

@yuzhichang yuzhichang added the ci Continue Integration label Jun 23, 2026
@codecov

codecov Bot commented Jun 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (06ededb) to head (213ea62).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16247      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The fix itself looks reasonable to me, but I believe the Python-version rationale in the PR description and commit message is factually inaccurate.

I verified this against the stdlib sources on this machine with Python 3.13.13 and 3.12.12:

  • asyncio.BaseEventLoop.run_in_executor() in both 3.13 and 3.12 does a plain executor.submit(func, *args) with no contextvars wrapping.
  • asyncio.to_thread() is the API that explicitly propagates context via contextvars.copy_context() and ctx.run(...), and that behavior is not new in 3.13.
  • I could not find a WorkerContext class in concurrent/futures/thread.py in either 3.13 or 3.12.

So I do not think this is a Python 3.13 regression or compatibility fix. As written, thread_pool_exec() has likely never guaranteed ContextVar propagation.

That said, the code change still makes sense on its own merits: wrapping the submitted callable with copy_context().run(...) makes thread_pool_exec() behave more like asyncio.to_thread(), which is a reasonable and backward-compatible improvement if we want ContextVar state to flow into work dispatched through this helper.

Suggested follow-up for this PR:

  • keep the code change and tests
  • rewrite the PR description / commit message / title to avoid the "Python 3.13 changed this" claim
  • describe this instead as explicitly adding ContextVar propagation to thread_pool_exec(), rather than restoring pre-3.13 behavior

With that reframing, I think the patch is much easier to evaluate on its actual technical merits.

@vincentlambert
vincentlambert force-pushed the fix/thread-pool-exec-contextvar-python313 branch from 2e94cc9 to f738adc Compare June 23, 2026 06:07
@vincentlambert vincentlambert changed the title fix: propagate asyncio ContextVars into thread pool (Python 3.13 compat) fix: propagate contextvars through thread_pool_exec Jun 23, 2026
@vincentlambert

Copy link
Copy Markdown
Contributor Author

@yuzhichang Thanks for the careful review — you're right, and I reproduced the same on Python 3.12 and 3.13:

  • BaseEventLoop.run_in_executor() does a plain executor.submit(func, *args) with no contextvars wrapping (neither version).
  • There is no WorkerContext in concurrent/futures/thread.py.
  • asyncio.to_thread()'s copy_context() / ctx.run() propagation is not new in 3.13.

So this is not a 3.13 regression — thread_pool_exec() has simply never propagated context. I've reframed everything to describe it as explicitly adding ContextVar propagation (matching asyncio.to_thread), with no "restoring pre-3.13 behavior" claim:

  • PR title and description rewritten
  • commit message rewritten (branch squashed to a single commit)
  • in-code comment and test docstring updated

The code change and tests are unchanged. (The branch name still contains python313 for historical reasons — unrelated to any Python version.)

loop.run_in_executor() submits the callable without copying the caller's
contextvars — unlike asyncio.to_thread(), which runs the callable inside a
copied context. As a result, ContextVars set on the async caller (e.g. tracing
or per-request state) are not visible inside work dispatched via thread_pool_exec.

Copy the current context and run the callable inside it (copy_context().run),
matching asyncio.to_thread() semantics. This explicitly *adds* ContextVar
propagation to the helper — it is not a restoration of any prior/runtime-version
behavior (run_in_executor has never copied context on 3.12 or 3.13).

Includes unit tests for propagation, the kwargs path, per-call isolation and the
unset-default case (TestThreadPoolExec, marked p1).
@vincentlambert
vincentlambert force-pushed the fix/thread-pool-exec-contextvar-python313 branch from f738adc to 213ea62 Compare June 23, 2026 06:11
@yuzhichang
yuzhichang merged commit 11e14a8 into infiniflow:main Jun 23, 2026
3 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jul 9, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration python Pull requests that update python code size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants