Skip to content

Add the request context to task_failure in case of lost worker - #9720

Merged
auvipy merged 14 commits into
celery:mainfrom
caspervdw:on_failure_worker_lost
Sep 21, 2026
Merged

auvipy merged 14 commits into
celery:mainfrom
caspervdw:on_failure_worker_lost

Conversation

@caspervdw

@caspervdw caspervdw commented May 22, 2025 •

Copy link
Copy Markdown
Contributor

Description

This partially addresses #8969 by making the task context (task.request) available in the on_failure signal 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.

@caspervdw
caspervdw marked this pull request as ready for review May 22, 2025 11:25
@codecov

codecov Bot commented May 22, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.28%. Comparing base (7f74405) to head (05d2132).
⚠️ Report is 2 commits behind head on main.

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           
Flag Coverage Δ
unittests 89.26% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

jpprins1

This comment was marked as off-topic.

@Nusnus
Nusnus self-requested a review May 23, 2025 20:12

@auvipy auvipy 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.

I think adding an integration test for this will be also helpful. as I am not 100% sure about the push/pop mechanism

@auvipy auvipy added this to the 5.7.0 milestone May 28, 2025
@auvipy

auvipy commented May 28, 2025

Copy link
Copy Markdown
Member

Lijkt me prima, 1 regel kan weg denk ik.

Begin me wel steeds meer af te vragen of Celery en Kubernetes een goede match zijn, misschien moeten we het echt alleen beperken tot taken die heel snel moeten worden afgehandeld.

which one line you are trying to mean please?

@Nusnus
Nusnus force-pushed the on_failure_worker_lost branch from 537ae59 to 9a60aab Compare May 31, 2025 21:13
@caspervdw

Copy link
Copy Markdown
Contributor Author

Lijkt me prima, 1 regel kan weg denk ik.
Begin me wel steeds meer af te vragen of Celery en Kubernetes een goede match zijn, misschien moeten we het echt alleen beperken tot taken die heel snel moeten worden afgehandeld.

which one line you are trying to mean please?

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.

@auvipy
auvipy requested a lite review from Copilot August 26, 2026 17:52

Copilot AI 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.

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._context onto task.request_stack around signals.task_failure.send(...) in Request.on_failure().
  • Updates the unit test for WorkerLostError to 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.

Comment thread t/unit/worker/test_request.py Resolved
@auvipy

auvipy commented Sep 12, 2026

Copy link
Copy Markdown
Member

@GangEunzzang @phanky1 can you review this please

@auvipy auvipy modified the milestones: 5.8.0, 5.7.0 Sep 12, 2026
@auvipy auvipy added the Worker label Sep 12, 2026

@MehrazRumman MehrazRumman 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.

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:

  1. 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()
  1. 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() and after_return(), which nearly always read self.request.

  2. 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.

  3. 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.

Comment thread celery/worker/request.py Resolved
Comment thread t/unit/worker/test_request.py Resolved

@GangEunzzang GangEunzzang 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.

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

@MehrazRumman MehrazRumman 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.

LGTM

@auvipy

auvipy commented Sep 12, 2026

Copy link
Copy Markdown
Member

LGTM

your review comments were not addressed yet

@MehrazRumman

Copy link
Copy Markdown
Contributor

LGTM

your review comments were not addressed yet

Thought it was good to go !

auvipy
auvipy previously approved these changes Sep 12, 2026
@auvipy
auvipy dismissed their stale review September 12, 2026 12:40

need another look

@auvipy auvipy modified the milestones: 5.7.0, 5.7.x Sep 13, 2026
@auvipy auvipy modified the milestones: 5.7.x, 5.7.0 Sep 20, 2026
@caspervdw

Copy link
Copy Markdown
Contributor Author

@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?

@auvipy auvipy modified the milestones: 5.7.x, 5.7.0 Sep 21, 2026
@auvipy

auvipy commented Sep 21, 2026

Copy link
Copy Markdown
Member

it still pass

@auvipy
auvipy merged commit beef13a into celery:main Sep 21, 2026
18 of 19 checks passed
@auvipy

auvipy commented Sep 21, 2026

Copy link
Copy Markdown
Member

@caspervdw can you come with additional smoke test for this changes in a separate pr? that would be really great

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants