Skip to content

Continue to fire timers for heartbeat during thread pool shutdown - #10182

Open
owenmjones wants to merge 4 commits into
celery:mainfrom
owenmjones:fix-thread-pool-shutdown
Open

owenmjones wants to merge 4 commits into
celery:mainfrom
owenmjones:fix-thread-pool-shutdown

Conversation

@owenmjones

Copy link
Copy Markdown

Description

This extends the fix to the issue of broker heartbeats not being sent on worker shutdown, reported in Issue #5998 and fixed by @weetster in PR #9986 the context of the default prefork pool type. Here this fix is applied to the threads pool type, which still exhibits the bug, and an integration test is added to validate the fix.

I have refactored the code as far as possible to avoid code duplication, and have used pytest fixtures to apply the same test to both prefork and threads pool types (this test refactor is the only part of the PR for which I used AI assistance, with Claude Opus helping me with the fixture syntax and debugging a thread-locking problem in the test).

It is possible that the issue persists in the context of eventlet and/or gevent async pool types, but my understanding of these pool types is insufficient to allow me to propose a fix for them.

@owenmjones
owenmjones force-pushed the fix-thread-pool-shutdown branch 3 times, most recently from 812da5c to 413ec1e Compare March 6, 2026 17:50
@auvipy
auvipy requested review from auvipy and Copilot March 7, 2026 14:25

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

did you check this PR? #10151

the PR you are extending, had some regression. so we have to consider this carefully. @ChickenBenny it would be great if you can also have a look into this

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 extends the fix for broker heartbeats not being sent during graceful worker shutdown (Issue #5998, originally fixed for prefork in PR #9986) to also cover the threads pool type. It refactors the timer-thread-during-shutdown logic into a shared AsyncPoolShutdownMixin in celery/concurrency/base.py to avoid code duplication, and adds a parameterized integration test that validates the fix for both pool types.

Changes:

  • New AsyncPoolShutdownMixin class in celery/concurrency/base.py that encapsulates the pattern of spinning up a timer-firing thread during pool shutdown to maintain broker heartbeats.
  • Refactored prefork.TaskPool.on_stop() and updated thread.TaskPool.on_stop() to use the shared mixin instead of inline timer logic.
  • Parameterized the integration test to run against both prefork and threads pool types, with improved fixture cleanup.

Reviewed changes

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

File Description
celery/concurrency/base.py Added AsyncPoolShutdownMixin with start_timer_event_loop and shutdown_with_timer_loop methods
celery/concurrency/prefork.py Replaced inline timer-thread shutdown logic with mixin usage; removed now-unused imports
celery/concurrency/thread.py Applied mixin to TaskPool class; on_stop() now uses shutdown_with_timer_loop
t/integration/test_async_pool_shutdown.py Parameterized fixture/test for both prefork and threads pools; improved cleanup

Comment thread celery/concurrency/base.py Resolved
Comment thread celery/concurrency/prefork.py Resolved
Comment thread celery/concurrency/thread.py Resolved
@owenmjones
owenmjones force-pushed the fix-thread-pool-shutdown branch from 413ec1e to 33720a8 Compare March 7, 2026 16:58
@owenmjones

Copy link
Copy Markdown
Author

did you check this PR? #10151

the PR you are extending, had some regression. so we have to consider this carefully

@auvipy no, I didn't see that, thanks for bringing it to my attention. If my understanding is correct, the fix proposed here works with that change since the asynloop behaviour from #9986 is preserved in the normal shutdown case (and this code is not executed if any other Exception is raised). The changes made in this PR are all "downstream" of the asynloop exit, and pertain to the case where the event loop raises WorkerShutdown.

It's probably best if someone else verifies the shutdown behaviour of both prefork and threads pools on this branch when using Redis Sentinel, since I'm not really familiar with that broker.

@auvipy

auvipy commented Mar 7, 2026

Copy link
Copy Markdown
Member

it's alright

@codecov

codecov Bot commented Mar 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.29730% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 88.22%. Comparing base (7735d2b) to head (929ffa9).
⚠️ Report is 284 commits behind head on main.

Files with missing lines Patch % Lines
celery/concurrency/base.py 96.77% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10182   +/-   ##
=======================================
  Coverage   88.21%   88.22%           
=======================================
  Files         153      153           
  Lines       19547    19552    +5     
  Branches     2246     2247    +1     
=======================================
+ Hits        17244    17249    +5     
  Misses       2005     2005           
  Partials      298      298           
Flag Coverage Δ
unittests 88.19% <97.29%> (+<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.

@ChickenBenny

Copy link
Copy Markdown
Contributor

Great work on the refactoring! However, I have some concerns regarding the thread safety of this approach when applied to the threads pool.

In the prefork pool, we've already seen issues (like the regression in #10151) where the background Timer thread tries to send heartbeats while the main thread is simultaneously tearing down the broker connection. This leads to race conditions, such as RuntimeError or broken pipes.

If we apply this to the threads pool, the risk seems to multiply. During a graceful shutdown, we would have a three-way contention:

  1. The Main Thread initiating the shutdown sequence and cleaning up connection pools.
  2. Active Worker Threads finishing their tasks and concurrently writing results or sending ACKs to the broker.
  3. This new Timer Thread concurrently firing heartbeats over the same shared broker connection.

Since everything shares the same memory space in the threads pool, we are hitting the connection management logic from multiple angles while it's actively being destroyed.

Have we verified if the underlying broker transports (especially kombu with redis-py or Sentinel) can safely handle this level of concurrent access during the shutdown phase?1

@auvipy auvipy added this to the 5.7.0 milestone Mar 9, 2026
@owenmjones

Copy link
Copy Markdown
Author

@ChickenBenny I've just tested this locally using the redis broker, running in --pool=threads mode with --concurrency=4 and launching multiple long-running tasks. I added print statements at various points so we can see what's happening: here is the output.

...

[2026-03-11 09:52:56,432: WARNING/MainProcess] Sending heartbeat event worker-heartbeat

[2026-03-11 09:52:58,434: WARNING/MainProcess] Sending heartbeat event worker-heartbeat

[2026-03-11 09:53:00,440: WARNING/MainProcess] Sending heartbeat event worker-heartbeat

[2026-03-11 09:53:00,639: INFO/MainProcess] Task myproject.tasks.long_running_task[753288b2-3393-44e2-99db-202a04263734] received

[2026-03-11 09:53:00,640: WARNING/MainProcess] Started long-running task 1

[2026-03-11 09:53:00,642: INFO/MainProcess] Task myproject.tasks.long_running_task[e42e144d-fa37-4690-bf42-60043c08c9c5] received

[2026-03-11 09:53:00,643: WARNING/MainProcess] Started long-running task 2

[2026-03-11 09:53:00,645: INFO/MainProcess] Task myproject.tasks.long_running_task[78645c96-59c7-4981-96c9-6693d97608e2] received

[2026-03-11 09:53:00,646: WARNING/MainProcess] Started long-running task 3

[2026-03-11 09:53:00,647: INFO/MainProcess] Task myproject.tasks.long_running_task[d8b6dd3e-74ca-4a3a-a4f7-193545a080f6] received

[2026-03-11 09:53:00,648: WARNING/MainProcess] Started long-running task 4

[2026-03-11 09:53:02,446: WARNING/MainProcess] Sending heartbeat event worker-heartbeat

[2026-03-11 09:53:04,453: WARNING/MainProcess] Sending heartbeat event worker-heartbeat

[2026-03-11 09:53:06,456: WARNING/MainProcess] Sending heartbeat event worker-heartbeat


worker: Warm shutdown (MainProcess)

[2026-03-11 09:53:07,334: WARNING/MainProcess] Stopping Heart

[2026-03-11 09:53:07,334: WARNING/MainProcess] Sending heartbeat event worker-offline

[2026-03-11 09:53:07,340: WARNING/MainProcess] Shutting down thread TaskPool

[2026-03-11 09:53:07,341: WARNING/MainProcess] Starting timer thread

[2026-03-11 09:53:07,341: WARNING/MainProcess] Firing kombu hub timers from timer thread

[2026-03-11 09:53:07,843: WARNING/MainProcess] Firing kombu hub timers from timer thread

... (previous message repeated every 0.5s)

[2026-03-11 09:53:21,282: WARNING/MainProcess] Firing kombu hub timers from timer thread

[2026-03-11 09:53:21,552: WARNING/MainProcess] Finished long-running task 1

[2026-03-11 09:53:21,594: INFO/MainProcess] Task myproject.tasks.long_running_task[753288b2-3393-44e2-99db-202a04263734] succeeded in 21.04304429700005s: None

[2026-03-11 09:53:21,783: WARNING/MainProcess] Firing kombu hub timers from timer thread

[2026-03-11 09:53:22,283: WARNING/MainProcess] Firing kombu hub timers from timer thread

[2026-03-11 09:53:22,554: WARNING/MainProcess] Finished long-running task 2

[2026-03-11 09:53:22,569: INFO/MainProcess] Task myproject.tasks.long_running_task[e42e144d-fa37-4690-bf42-60043c08c9c5] succeeded in 22.015423068999553s: None

[2026-03-11 09:53:22,784: WARNING/MainProcess] Firing kombu hub timers from timer thread

[2026-03-11 09:53:23,284: WARNING/MainProcess] Firing kombu hub timers from timer thread

[2026-03-11 09:53:23,557: WARNING/MainProcess] Finished long-running task 3

[2026-03-11 09:53:23,574: INFO/MainProcess] Task myproject.tasks.long_running_task[78645c96-59c7-4981-96c9-6693d97608e2] succeeded in 23.017729862000124s: None

[2026-03-11 09:53:23,785: WARNING/MainProcess] Firing kombu hub timers from timer thread

[2026-03-11 09:53:24,285: WARNING/MainProcess] Firing kombu hub timers from timer thread

[2026-03-11 09:53:24,560: WARNING/MainProcess] Finished long-running task 4

[2026-03-11 09:53:24,577: INFO/MainProcess] Task myproject.tasks.long_running_task[d8b6dd3e-74ca-4a3a-a4f7-193545a080f6] succeeded in 24.018544253999607s: None

[2026-03-11 09:53:24,786: WARNING/MainProcess] Stopped timer thread

[2026-03-11 09:53:24,786: WARNING/MainProcess] Shut down thread TaskPool

So we can see the MainProcess and timer threads start and stop as expected, and that the tasks are indeed run concurrently and execute successfully in four worker threads.

If you have more specific concerns about a particular scenario which may cause problems (e.g. triggering a broker connection loss during shutdown) I can try to reproduce it.

@ChickenBenny

Copy link
Copy Markdown
Contributor

Thanks for taking the time to test this and sharing the detailed logs, @owenmjones! I really appreciate the effort. It’s good to see that the timer thread spins up and shuts down as expected in a happy-path scenario.

However, from a concurrency perspective, a simple local test with 4 tasks doesn't fully guarantee thread safety, especially when we are dealing with shared connection states. Here is why:

While Python has the GIL (Global Interpreter Lock), the GIL is intentionally released during I/O operations (like socket writes to Redis or network reads). This means that during the graceful shutdown phase, the following actions are executing truly concurrently at the OS and network level:

  1. Timer Thread: Actively requesting a connection from the pool to write a heartbeat to the socket.
  2. Worker Threads: Requesting connections to write task results and ACKs.
  3. Main Thread: Potentially tearing down the hub, closing the connection pools, and destroying the socket file descriptors.

The local test passes because the timing hasn't perfectly collided yet. The real edge case (and the root of many RuntimeError or BrokenPipeError issues we see in production) happens when the Timer Thread tries to write a heartbeat using a connection/socket that the Main Thread is exactly in the middle of tearing down.

To truly validate this approach for the threads pool, we shouldn't rely solely on execution logs. We need to look deeper into the underlying implementation of kombu.transport.redis and the redis-py connection pool. We need to answer: Are Kombu's asynchronous hub and the Redis connection pool strictly thread-safe when connections are being actively destroyed by another thread?

If the underlying transport isn't designed to handle concurrent teardown and writes from different threads, applying this mixin to the threads pool might introduce rare but severe race conditions in production.

@owenmjones

Copy link
Copy Markdown
Author

@ChickenBenny thanks for providing valuable extra context! Is there a reason you mention only redis/redis-py and not rabbitmq? Is rabbitmq thread-safe by construction whereas redis isn't?

@ChickenBenny

Copy link
Copy Markdown
Contributor

@owenmjones The main reason I mentioned Redis is simply because I recently fixed a concurrency issue related to it in #10151, so the context is very fresh in my mind! 😅

With redis-py, the connection pool is indeed thread-safe for standard operations. However, edge cases often arise during lifecycle state transitions, such as a graceful shutdown.

For example: when the main process attempts to tear down the pool and close all connections during a graceful shutdown, you might simultaneously have a worker thread trying to fire a task and another thread trying to store a result. Both threads are competing to acquire a connection from the shared pool. If no connections are available, they might attempt to instantiate new ones while the main process is in the middle of destroying the pool. Because these threads share the exact same connection pool instance without a strict lifecycle lock during teardown, it leads to a race condition. The connections can't be cleaned up properly, ultimately throwing a RuntimeError.

So, it's less about the protocol itself and more about how the shared pool's state is managed during these tricky lifecycle events!

@auvipy

auvipy commented Mar 12, 2026

Copy link
Copy Markdown
Member

is this in merge able state now?

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 5 out of 5 changed files in this pull request and generated no new comments.


You can also share your feedback on Copilot code review. Take the survey.

@owenmjones

Copy link
Copy Markdown
Author

@auvipy no, we either need someone with more expertise in the broker transports to look into this or else we need to come up with an alternative approach to guarantee thread-safety. See the comments by @ChickenBenny: as it stands there is too much risk that this would introduce a serious regression due to concurrency issues in some edge cases.

@auvipy auvipy removed this from the 5.7.0 milestone Aug 27, 2026
@auvipy auvipy added this to the 5.8.0 milestone Aug 27, 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants