Repository navigation
Implement terminate_job for the threads pool and fix cold shutdown - #10491
oliverhaas wants to merge 6 commits into
Conversation
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
There was a problem hiding this comment.
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_jobfor the threads pool usingPyThreadState_SetAsyncExc, tracking currently running thread IDs. - Adjust threads pool shutdown behavior to avoid waiting on running tasks during cold shutdown (
should_terminateset). - Ensure
Request.cancel()marks_already_cancelledbefore invokingterminate_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.
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]>
4947fb6 to
0836e4a
Compare
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.
There was a problem hiding this comment.
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_runningbefore 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 callcancel_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=threadsnow attempts to interrupt running tasks and coldon_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
| 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) |
| affected = ctypes.pythonapi.PyThreadState_SetAsyncExc( | ||
| ctypes.c_ulong(pid), ctypes.py_object(Terminated)) |
See #10490
I'll park this here already for feedback, but I double check with fresh eyes in a few days.