Repository navigation
fix: propagate contextvars through thread_pool_exec - #16247
yuzhichang merged 1 commit into
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthrough
ChangesContextVar propagation fix in thread_pool_exec
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
common/misc_utils.py (1)
253-262: 🧹 Nitpick | 🔵 TrivialAdd a regression test for context variable propagation through
thread_pool_exec.The implementation correctly uses
contextvars.copy_context()andctx.run()wrapping, but no test currently validates this behavior. Since this addresses a Python 3.13-specific change toThreadPoolExecutor, add a test that:
- Sets a
ContextVarin the caller- Awaits
thread_pool_exec()with a function that reads theContextVar- 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
📒 Files selected for processing (1)
common/misc_utils.py
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
test/unit_test/common/test_misc_utils.py
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
yuzhichang
left a comment
There was a problem hiding this comment.
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 plainexecutor.submit(func, *args)with nocontextvarswrapping.asyncio.to_thread()is the API that explicitly propagates context viacontextvars.copy_context()andctx.run(...), and that behavior is not new in 3.13.- I could not find a
WorkerContextclass inconcurrent/futures/thread.pyin 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
ContextVarpropagation tothread_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.
2e94cc9 to
f738adc
Compare
|
@yuzhichang Thanks for the careful review — you're right, and I reproduced the same on Python 3.12 and 3.13:
So this is not a 3.13 regression —
The code change and tests are unchanged. (The branch name still contains |
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).
f738adc to
213ea62
Compare
Problem
thread_pool_exec()dispatches work vialoop.run_in_executor(), which submits the callable with a plainexecutor.submit(func, *args)and does not copy the caller'scontextvars.Context. So aContextVarset 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
ContextVarin async code and reads it inside a function dispatched viathread_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 whatasyncio.to_thread()does:This explicitly adds ContextVar propagation to the helper (it does not restore any prior behavior). Backward-compatible.
Tests
TestThreadPoolExeccovers propagation, the kwargs path, per-call isolation and the unset-default case.