Repository navigation
Add the request context to task_failure in case of lost worker - #9720
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #9720 +/- ##
=======================================
Coverage 89.28% 89.28%
=======================================
Files 153 153
Lines 20385 20388 +3
Branches 2430 2430
=======================================
+ Hits 18200 18203 +3
Misses 1881 1881
Partials 304 304
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
auvipy
left a comment
There was a problem hiding this comment.
I think adding an integration test for this will be also helpful. as I am not 100% sure about the push/pop mechanism
which one line you are trying to mean please? |
537ae59 to
9a60aab
Compare
Hi. thanks for the review, and I asked my colleague @jpprins1 and this was meant for a different PR, so please ignore it! I'll check if I can add an integration test. I was wondering if there is any multithreading going on in the main thread (in situations where the WorkerLostError can occur)? Because my code is not threadsafe. |
There was a problem hiding this comment.
Pull request overview
This PR aims to make the task execution context (task.request) available to task_failure signal handlers when Request.on_failure() runs in the parent process after a worker is lost (i.e., when the child process didn’t run the usual tracing path).
Changes:
- Pushes
Request._contextontotask.request_stackaroundsignals.task_failure.send(...)inRequest.on_failure(). - Updates the unit test for
WorkerLostErrorto validate that the signal sender sees the expected request context, and that the request stack is cleared afterward.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| celery/worker/request.py | Temporarily pushes request context onto task.request_stack so task_failure handlers can access task.request during worker-lost failure handling. |
| t/unit/worker/test_request.py | Adjusts the worker-lost failure test to verify request context visibility during task_failure and stack cleanup after. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
@GangEunzzang @phanky1 can you review this please |
MehrazRumman
left a comment
There was a problem hiding this comment.
Thanks @caspervdw, I checked this out locally. The approach is right and the updated test is a real regression test, it fails on main without the change. A few things before this can go in:
- Wrap the push in try/finally. Signal.send only catches Exception, so a BaseException like KeyboardInterrupt or WorkerShutdown skips the pop and leaks the context onto the stack for good. I reproduced it on this branch. celery/app/trace.py:567 already does it this way:
self.task.request_stack.push(self._context)
try:
signals.task_failure.send(...)
finally:
self.task.request_stack.pop()
-
Two other call sites have the same gap. The Reject branch at request.py:669 and the hard time limit in on_timeout at request.py:564 also send task_failure from the parent, and I confirmed both still hand handlers an empty Context. The timeout one matters most since that block also calls
task.on_failure()andafter_return(), which nearly always read self.request. -
On your threading question: you are fine. request_stack is a LocalStack keyed by celery.utils.threads.get_ident, which is greenlet-aware, so the push is only visible to the thread running on_failure. Under prefork that is the parent main thread, which never runs tasks. Under threads/gevent/eventlet the callback does land on a task-running thread, but trace has already popped by then, so it stays balanced. That is exactly why point 1 matters there: an unbalanced pop would poison a live worker thread.
-
Tests. @auvipy's integration test ask is doable in t/integration/, since celery_session_worker runs in-process with prefork, so a task_failure receiver in the test will fire. Add a task that os.kill(os.getpid(), SIGKILL)s itself, then assert the captured sender.request.id matches the AsyncResult id. Also worth one unit test that a receiver raising leaves request_stack.top as None.
Small nit: captured_request[0] == req._context is an identity check since Context has no eq. Use is to make that explicit.
GangEunzzang
left a comment
There was a problem hiding this comment.
@auvipy @caspervdw I checked a846e7314 with a real prefork worker on Python 3.12/macOS, using a memory broker. The task terminated its own process with SIGKILL; the task_failure receiver ran in the parent and saw the correct sender.request.id, args, kwargs, custom headers, and root ID. The stack was restored after the handler returned. On main (5ea4a4919), the same probe received the signal, but those request fields were empty. The request context reaches the receiver in this worker-loss case, so this could make a useful integration test.
I also independently reproduced the cleanup issue @MehrazRumman raised. Normal callbacks, a callback raising ValueError, and nested failure callbacks restored a previously pushed context correctly. A callback raising KeyboardInterrupt or WorkerShutdown left the failed request on top of it. I agree with putting the pop in finally; a regression test should check restoration of the previous context when a BaseException escapes.
For the threading question, two simultaneous on_failure calls for the same Task kept their request contexts separate across 10 synchronized runs. I haven't tested gevent/eventlet. The hard-timeout and non-requeued Reject paths still expose an empty request, but I reproduced those on main too, so they are remaining gaps rather than regressions from this change.
The request, trace, and thread unit tests passed together (163 tests), and the updated worker-loss test failed on main at the context assertion.
your review comments were not addressed yet |
Thought it was good to go ! |
|
@MehrazRumman Thanks for the review, I addressed your comments. Can you enable the workflows so that we can see if the CI still passes completely? |
|
it still pass |
|
@caspervdw can you come with additional smoke test for this changes in a separate pr? that would be really great |
Description
This partially addresses #8969 by making the task context (
task.request) available in theon_failuresignal handler in case it is called after a worker is lost.I cannot oversee if this has unintended side-effects, so I am curious to what a maintainer has to say about this.