Skip to content

Implement terminate_job for the threads pool and fix cold shutdown - #10491

Open
oliverhaas wants to merge 6 commits into
celery:mainfrom
oliverhaas:fix/threads-pool-cold-shutdown
Open

oliverhaas wants to merge 6 commits into
celery:mainfrom
oliverhaas:fix/threads-pool-cold-shutdown

Conversation

@oliverhaas

@oliverhaas oliverhaas commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

See #10490

I'll park this here already for feedback, but I double check with fresh eyes in a few days.

@codecov

codecov Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.96970% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 90.25%. Comparing base (357e629) to head (f4e50e3).

Files with missing lines Patch % Lines
celery/concurrency/thread.py 96.87% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10491      +/-   ##
==========================================
+ Coverage   90.23%   90.25%   +0.01%     
==========================================
  Files         153      153              
  Lines       21075    21105      +30     
  Branches     2543     2543              
==========================================
+ Hits        19017    19048      +31     
  Misses       1751     1751              
+ Partials      307      306       -1     
Flag Coverage Δ
unittests 90.23% <96.96%> (+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.

@auvipy
auvipy requested review from auvipy and a lite review from Copilot August 16, 2026 15:04

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

Implements best-effort task termination support for the threads pool to improve revoke(terminate=True) and cold-shutdown behavior, aligning the threads pool with other pool types that provide terminate_job semantics.

Changes:

  • Add TaskPool.terminate_job for the threads pool using PyThreadState_SetAsyncExc, tracking currently running thread IDs.
  • Adjust threads pool shutdown behavior to avoid waiting on running tasks during cold shutdown (should_terminate set).
  • Ensure Request.cancel() marks _already_cancelled before invoking terminate_job, and add unit tests covering ordering and the new threads-pool behavior.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
celery/concurrency/thread.py Implements terminate_job, tracks running threads, and changes shutdown wait behavior for cold shutdown.
celery/worker/request.py Sets _already_cancelled before terminating to avoid races with on_failure in pool threads.
t/unit/concurrency/test_thread.py Adds tests for thread termination semantics and cold-shutdown on_stop() behavior.
t/unit/worker/test_request.py Adds a regression test for cancel flag ordering relative to terminate_job.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread celery/concurrency/thread.py Resolved
oliverhaas and others added 2 commits August 20, 2026 21:38
The threads pool did not implement terminate_job, so the base class
raised NotImplementedError inside the cold shutdown signal handler
(on_cold_shutdown -> consumer.cancel_active_requests() ->
Request.cancel() -> pool.terminate_job()). The handler aborted before
state.should_terminate and pool.stop() ran, and the worker blocked
until every running task finished instead of exiting after the soft
shutdown timeout. Under a supervisor grace period the worker was then
SIGKILLed with its delivered-but-unacked messages still parked at the
broker (Redis transport: until visibility_timeout, one hour by default).

- terminate_job now terminates the task on a best-effort basis, by
  injecting Terminated into the thread with PyThreadState_SetAsyncExc.
  CPython delivers it once the thread next runs Python bytecode, so a
  task blocked in a system call keeps running until that call returns.
  on_apply reports the thread ident as the request's worker_pid to find
  the thread again, as the eventlet pool does with its greenlet id.
- ApplyResult.terminate cancels the wrapped future, so a task that has
  not started is genuinely cancelled. Request.cancel()/terminate() call
  it whenever the weakref is still alive.
- on_stop no longer waits for running threads while a cold shutdown is
  in progress, so the connection can be closed and unacked messages
  restored. Warm shutdown still waits, as before.
- on_terminate shuts the executor down without waiting, which the Pool
  bootstep terminate path never did.

Request.cancel sets _already_cancelled before terminating the job. A
pool that terminates by raising in the worker thread runs on_failure()
on that thread, which would otherwise revoke the task and acknowledge
the message the cancellation leaves for redelivery.
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@oliverhaas
oliverhaas force-pushed the fix/threads-pool-cold-shutdown branch 2 times, most recently from 4947fb6 to 0836e4a Compare August 20, 2026 19:39
The injected Terminated could land between started.set() and the try
block, so the except clause never ran. Assert on the future instead,
which holds wherever the exception arrives.
terminate_job checked membership and then injected without holding a
lock, so a task that finished in between could hand its thread to the
next queued task, which then took the Terminated. gevent has no such
window: nothing yields between its check and gevent.kill.

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

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

Suppressed comments (2)

celery/concurrency/thread.py:82

  • Could on_terminate() also terminate the threads in _running before shutting down the executor? shutdown(wait=False, cancel_futures=True) only cancels queued futures; it leaves running tasks untouched, and the hard-shutdown path (on_hard_shutdown() → Worker.terminate() → this method) does not call cancel_active_requests(). A running thread task can therefore keep the worker alive and continue executing after a hard shutdown request.
    def on_terminate(self) -> None:
        self.executor.shutdown(wait=False, cancel_futures=True)

celery/concurrency/thread.py:61

  • Could this user-visible change get a versionchanged:: 5.7/What's New entry? --pool=threads now attempts to interrupt running tasks and cold on_stop() no longer waits, but the current worker documentation does not describe the best-effort behavior or the blocked-system-call limitation. Without that note, users may assume a thread-pool cold shutdown actually terminates the process within the soft timeout.
    def terminate_job(self, pid: int, signal: int | None = None) -> None:
        """Raise :exc:`~celery.exceptions.Terminated` in the task's thread.

        CPython delivers it once that thread next runs Python bytecode,
        so a task blocked in a system call keeps running until the call

Comment on lines +85 to +87
terminating = (worker_state.should_terminate is not None
and worker_state.should_terminate is not False)
self.executor.shutdown(wait=not terminating, cancel_futures=True)
Comment on lines +72 to +73
affected = ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_ulong(pid), ctypes.py_object(Terminated))
@auvipy auvipy added this to the 5.8.0 milestone Aug 26, 2026

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants