Repository navigation
Fix: query_task doesn't find tasks scheduled with an ETA/countdown (#5321) - #10535
Conversation
…elery#5321) A task with an eta/countdown is only added to the worker's request registry once its ETA elapses (in Consumer.apply_eta_task), even though it's already visible to `inspect scheduled` via the consumer timer. This meant `inspect query_task <id>` returned nothing for a task the whole time it was waiting on its ETA/countdown. Register the request in worker_state.requests as soon as it's scheduled into the timer (celery.worker.strategy.default), via a new task_scheduled() helper that mirrors task_reserved() without adding the request to reserved_requests, so `inspect reserved` keeps excluding scheduled tasks as documented.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #10535 +/- ##
==========================================
+ Coverage 89.04% 89.06% +0.01%
==========================================
Files 153 153
Lines 20108 20133 +25
Branches 2365 2370 +5
==========================================
+ Hits 17906 17931 +25
Misses 1896 1896
Partials 306 306
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
This PR fixes inspect query_task <id> not finding ETA/countdown tasks before their ETA elapses by registering those requests in celery.worker.state.requests at scheduling time (instead of only when the ETA fires), aligning query_task behavior with what inspect scheduled already exposes.
Changes:
- Register ETA/countdown tasks in worker global state via a new
task_scheduled()helper, called when scheduling into the timer queue. - Add regression tests ensuring scheduled tasks are visible to
query_taskand are not counted as reserved. - Update user docs and
Control.query_taskdocstring to reflect that scheduled tasks can be queried.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
celery/worker/state.py |
Adds task_scheduled() to register scheduled requests without marking them reserved. |
celery/worker/strategy.py |
Calls task_scheduled(req) when ETA/countdown tasks are placed into the timer. |
t/unit/worker/test_strategy.py |
Adds regression test asserting scheduled ETA tasks are present in state.requests pre-ETA. |
t/unit/worker/test_control.py |
Adds regression test asserting query_task can find scheduled tasks. |
docs/userguide/monitoring.rst |
Updates inspect query_task docs to mention scheduled tasks. |
celery/app/control.py |
Updates query_task docstring to include scheduled tasks. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01N6Vr4HaqH5ojjZndR6HSZb
query_task previously reported scheduled tasks as 'ready' since _state_of_task only checked active_requests/reserved_requests, and on_close() never purged them from state.requests on connection loss since they were never added to reserved_requests. Add a dedicated scheduled_requests set, wired into task_scheduled/task_reserved/ task_ready, _state_of_task, and Consumer.on_close.
|
Pushed corrective commit following copilot suggestions |
auvipy
left a comment
There was a problem hiding this comment.
lastly it would be great to add additional smoke or integration tests or both to verify the changes work properly togather
…elery#5321) The regression tests added alongside the fix only exercised individual modules in isolation (state, strategy, control, consumer) with mocks. Add two tests that verify the whole lifecycle works together: - t/unit/worker/test_query_task_integration.py drives strategy, state, control and consumer.Consumer together (no broker) through the full scheduled -> reserved -> ready lifecycle, plus the connection-loss purge path. - t/unit/contrib/test_worker.py::test_query_task_eta_smoke runs a real embedded worker over memory:// (via start_worker), mirroring the reproduction script posted on the issue: schedule a task with a countdown and confirm inspect().query_task() finds it while it's still pending, not only once it starts running. Both were verified to fail against the pre-fix code and pass with the fix.
… into issue-5321-query-task-not-found
|
Pushed now smoke and integrations tests |
|
I found some merge conflicts and tried to fixed them, also figured out smoke test were added in not a best place |
There was a problem hiding this comment.
🟡 Changes recommended
Sync-loop reconnects can retain ETA callbacks, and some tests leak global worker state.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
- Files reviewed: 12/12 changed files
- Comments generated: 3
- Review effort level: Balanced
- Cancel the pending ETA/countdown timer entry in Consumer.on_close() instead of only dropping bookkeeping, so a stale callback can't fire after the connection is torn down (synloop's error path doesn't clear the timer the way asynloop does) and repopulate state.requests. - Reset state.requests via the canonical state.reset_state() in the test_state.py and test_strategy.py fixtures, fixing state leakage between tests introduced by task_scheduled(). - Move the ETA/countdown query_task smoke test out of t/unit/contrib/test_worker.py into its own file under t/smoke/, rewritten against the Docker-based celery_setup fixture used by the rest of that suite.
|
Pushed commit with your feedback about the position of the file @auvipy and the feedbacks from copilot |
|
the smoke test added in this pr seems to be failing, so I pulled from the main branch again to cross check |
There was a problem hiding this comment.
🟡 Changes recommended
Timer registration and connection-loss cleanup have a race that can allow stale ETA delivery.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
- Files reviewed: 12/12 changed files
- Comments generated: 1
- Review effort level: Balanced
|
@MehrazRumman can you try and review this, please? |
Copilot review feedback on PR celery#10535: task_scheduled() ran before call_at(), so a concurrent on_close() (celery.utils.timer2.Timer runs on its own thread for non-eventloop pools) could observe the request in scheduled_requests with _eta_timer_entry not yet set, drop its bookkeeping without cancelling anything, and leave the just-installed entry with nothing left to cancel it. Reorder so the entry is attached to the request first and task_scheduled() (which is what makes it visible to on_close()/query_task()) runs last. This doesn't eliminate every cross-thread race around worker/state.py's plain dict/set structures (that's a pre-existing, broader concern -- e.g. apply_eta_task()'s task_reserved() call already races with on_close()'s existing reserved_requests cleanup on these pools, independent of this PR) but it closes the specific half-registered window this diff introduced.
Covers the fix in 3d36d41: task_scheduled() must run after the timer entry is attached to the request, so on_close() never observes a half-registered scheduled request.
… into issue-5321-query-task-not-found
|
Sorry for the late reply here — life got busy and I didn't see the notification until today. Picking this back up now. |
|
thanks a lot! I think we can now move forward after the ci is green |
|
@auvipy checking this one ! |
MehrazRumman
left a comment
There was a problem hiding this comment.
Thanks for this, and for the thorough test coverage. Overall the approach is right:
registering ETA/countdown requests in state.requests through a separate
task_scheduled() helper keeps inspect reserved correct, _state_of_task gains a
sensible scheduled state, and the on_close() cleanup was a necessary addition that
the first version of this fix would have leaked without. I checked out the branch and
ran the full t/unit/worker suite locally on top of current main: all green. I also
verified that every timer implementation (timer2, kombu hub timer, eventlet, gevent)
exposes cancel(tref) and that cancelling an already-fired entry is harmless, so the
cancellation path in on_close() is safe across pools.
One correctness issue I'd like addressed before merge:
on_close()can drop an active task fromstate.requests. The new loop over
scheduled_requestspops fromrequestsunconditionally, while the reserved loop above
it skipsactive_requests. With a threaded timer (timer2, used for non-async transports
and on Windows), an ETA already in the past fires on the timer thread immediately, so
apply_eta_task()->task_reserved()can run before the strategy reaches
task_scheduled(). The request is then re-added toscheduled_requestswhile it is
actually reserved/active, and on reconnecton_close()removes it fromrequestswhile
it is still running. Suggest mirroring the guard (if r not in active_requests and r not in reserved_requests) and/or makingtask_scheduled()a no-op when the request is
already reserved.
Things worth clarifying or documenting:
- Rate-limited + ETA tasks report
scheduledafter the ETA elapses._limit_post_eta()
puts the request in the token bucket without callingtask_reserved(), so it stays in
scheduled_requestseven thoughinspect scheduledno longer lists it. Not a regression,
but thescheduled_requestsdocstring ("hasn't elapsed yet") is now inaccurate. Either
document it or discard fromscheduled_requestsin_limit_post_eta(). - Revoke now reaches scheduled tasks. Because they live in
state.requests,
revoke(terminate=True)finds them via_find_requests_by_id()and sets
_terminate_on_ack, andrevoke_by_stamped_headersiterates them too. I traced it and it
looks safe sinceexecute_using_pool()checksrevoked()first, but it's a behavior
change that should be mentioned in the PR description and covered by a test. req._eta_timer_entryis an ad-hoc attribute set instrategy.pyand read in
consumer.py; it only works becauseRequest.__slots__includes__dict__. Declaring it
onRequestwith aNonedefault would make the contract explicit and remove the
getattr(..., None)fallback.versionchanged:: 5.7in monitoring.rst: main is at 5.6.2, so please confirm with
maintainers which release this lands in.
Test structure nits (non-blocking):
t/unit/worker/test_query_task_integration.py: the "integration" name is confusing given
the realt/integrationtree; considertest_eta_query_task.pyor folding into
test_control.py. Also_RealConsumer.__init__bypassesConsumer.__init__entirely
and hand-sets attributes, which will silently break when the consumer grows a new one.- The three new
on_closetests intest_consumer.pyrepeat the same Mock/FakeRequest
setup; a small helper would cut that. Their docstrings are long and cite other PRs by
number; trimming to what each assertion checks would help readability. - Smoke test: the
founddict is unnecessary, the predicate canreturn any(...).
Happy to re-review once the on_close() guard is in.
|
@ghirailghiro would you mind giving the last review a cross check? |
A request can legitimately end up in both ``scheduled_requests`` and ``reserved_requests``/``active_requests``: with a threaded timer (``celery.utils.timer2.Timer``, used by the non-eventloop pools and on Windows) an ETA already in the past fires on the timer thread right away, so ``apply_eta_task()`` -> ``task_reserved()`` can run before the strategy reaches ``task_scheduled()``. The ``scheduled_requests`` loop in ``Consumer.on_close()`` popped from ``state.requests`` unconditionally, unlike the reserved loop above it, so on reconnect a still-running task was removed from ``state.requests`` and became invisible to inspect/revoke while it executed. Guard both ends: ``task_scheduled()` is now a no-op for a request that's already reserved or active, and ``on_close()`` mirrors the reserved loop's ``active_requests``/``reserved_requests`` check before dropping anything. Also from review: - Declare ``Request._eta_timer_entry = None`` on the class instead of relying on the ad-hoc attribute, and drop the ``getattr()`` fallback in ``on_close()``. - Document that a rate-limited ETA task stays in ``scheduled_requests`` until a token frees up, so the previous "hasn't elapsed yet" wording is no longer accurate. - Cover the ``revoke(terminate=True)`` behavior change: scheduled requests now live in ``state.requests``, so revoke reaches them before their ETA. - Rename ``test_query_task_integration.py`` to ``test_eta_query_task.py``, fold the repeated ``on_close`` test setup into an ``on_close_ctx`` fixture, and simplify the smoke-test predicate. Fix an unrelated pre-existing test leak while here: ``import_state()`` in ``test_state_configuration`` reimports ``celery.worker.state``, which also rebinds the ``state`` attribute on the ``celery.worker`` package. ``patch.dict(sys.modules)`` doesn't restore that, so every later ``from celery.worker import state`` got the throwaway copy -- with its own empty ``requests``/``*_requests`` containers -- while the rest of celery kept using the real ones, making six ``test_consumer.py`` tests fail depending on collection order.
16849af to
5b3455a
Compare
|
Thanks @MehrazRumman — good catch on the on_close() race, fixed in task_scheduled() is now a no-op if the request is already reserved/active, and the scheduled loop has the same active_requests/reserved_requests guard as the reserved one. Also did the rest (docstring, revoke test, _eta_timer_entry on Request, test renames/cleanup). |
|
thanks for handling this old and big issue! |
…elery#5321) (celery#10535) * Fix: query_task doesn't find tasks scheduled with an ETA/countdown (celery#5321) A task with an eta/countdown is only added to the worker's request registry once its ETA elapses (in Consumer.apply_eta_task), even though it's already visible to `inspect scheduled` via the consumer timer. This meant `inspect query_task <id>` returned nothing for a task the whole time it was waiting on its ETA/countdown. Register the request in worker_state.requests as soon as it's scheduled into the timer (celery.worker.strategy.default), via a new task_scheduled() helper that mirrors task_reserved() without adding the request to reserved_requests, so `inspect reserved` keeps excluding scheduled tasks as documented. * Track scheduled (ETA/countdown) requests as their own worker state query_task previously reported scheduled tasks as 'ready' since _state_of_task only checked active_requests/reserved_requests, and on_close() never purged them from state.requests on connection loss since they were never added to reserved_requests. Add a dedicated scheduled_requests set, wired into task_scheduled/task_reserved/ task_ready, _state_of_task, and Consumer.on_close. * Add integration and smoke tests for the ETA/countdown query_task fix (celery#5321) The regression tests added alongside the fix only exercised individual modules in isolation (state, strategy, control, consumer) with mocks. Add two tests that verify the whole lifecycle works together: - t/unit/worker/test_query_task_integration.py drives strategy, state, control and consumer.Consumer together (no broker) through the full scheduled -> reserved -> ready lifecycle, plus the connection-loss purge path. - t/unit/contrib/test_worker.py::test_query_task_eta_smoke runs a real embedded worker over memory:// (via start_worker), mirroring the reproduction script posted on the issue: schedule a task with a countdown and confirm inspect().query_task() finds it while it's still pending, not only once it starts running. Both were verified to fail against the pre-fix code and pass with the fix. * Address PR celery#10535 review feedback for celery#5321 - Cancel the pending ETA/countdown timer entry in Consumer.on_close() instead of only dropping bookkeeping, so a stale callback can't fire after the connection is torn down (synloop's error path doesn't clear the timer the way asynloop does) and repopulate state.requests. - Reset state.requests via the canonical state.reset_state() in the test_state.py and test_strategy.py fixtures, fixing state leakage between tests introduced by task_scheduled(). - Move the ETA/countdown query_task smoke test out of t/unit/contrib/test_worker.py into its own file under t/smoke/, rewritten against the Docker-based celery_setup fixture used by the rest of that suite. * Address more PR celery#10535 review feedback - docs: add versionadded:: 5.7 note for the query_task scheduled-tasks behavior change. - t/smoke/tests/test_query_task.py: cut the smoke test's countdown from 5s to 2s (the window only needs to be long enough for the scheduling round trip to be observable) and tighten the polling interval, to reduce how much it adds to the smoke suite's runtime. * Cancel ETA timer entries through the timer API, not directly Copilot review feedback on PR celery#10535: calling entry.cancel() directly bypasses Timer.cancel(), which the Eventlet timer relies on to catch GreenletExit (its entries are greenlets). An uncaught GreenletExit here would abort on_close() before it finishes clearing state and restarting the consumer. Route cancellation through self.timer.cancel(entry) instead, guarded against a missing timer and a broad exception so a failing cancellation can't abort the rest of on_close(). Updated the regression test to assert on self.timer.cancel(entry) rather than entry.cancel(). * Fix flaky smoke test and add coverage for on_close's cancel-error path - t/smoke/tests/test_query_task.py: the 2s countdown from the previous "speed up the smoke suite" pass left no margin over real control-command round-trip latency in CI, so the task could already be done and gone from worker state by the time query_task() polled for it (observed failing on the redis broker/backend combo). Back the countdown up to 10s and fold the query_task()+scheduled() checks into a single poll iteration so they can't race each other past the same deadline either, per Copilot's review. - t/unit/worker/test_consumer.py: add a regression test exercising the exception path in Consumer.on_close()'s timer cancellation (closes the 2-line patch coverage gap Codecov flagged); on_close() must keep clearing state even if cancelling one request's timer entry raises. * Fix smoke test: task was never routed to the worker's queue Ran the smoke suite locally against real containers to verify the previous fix, and it still failed with both brokers. Root cause: the task was never routed to the worker's queue at all, since every other smoke test explicitly passes queue=celery_setup.worker.worker_queue on apply_async and this one didn't -- it went to the default 'celery' queue instead, which the worker isn't consuming from. The countdown value was a red herring; the worker never received the message to begin with. Verified locally: both parametrizations (redis and rabbitmq brokers) now pass. * Attach the ETA timer entry before making the request visible Copilot review feedback on PR celery#10535: task_scheduled() ran before call_at(), so a concurrent on_close() (celery.utils.timer2.Timer runs on its own thread for non-eventloop pools) could observe the request in scheduled_requests with _eta_timer_entry not yet set, drop its bookkeeping without cancelling anything, and leave the just-installed entry with nothing left to cancel it. Reorder so the entry is attached to the request first and task_scheduled() (which is what makes it visible to on_close()/query_task()) runs last. This doesn't eliminate every cross-thread race around worker/state.py's plain dict/set structures (that's a pre-existing, broader concern -- e.g. apply_eta_task()'s task_reserved() call already races with on_close()'s existing reserved_requests cleanup on these pools, independent of this PR) but it closes the specific half-registered window this diff introduced. * Add regression test for ETA timer entry registration order Covers the fix in 3d36d41: task_scheduled() must run after the timer entry is attached to the request, so on_close() never observes a half-registered scheduled request. * Don't let on_close() drop a running task that's also scheduled A request can legitimately end up in both ``scheduled_requests`` and ``reserved_requests``/``active_requests``: with a threaded timer (``celery.utils.timer2.Timer``, used by the non-eventloop pools and on Windows) an ETA already in the past fires on the timer thread right away, so ``apply_eta_task()`` -> ``task_reserved()`` can run before the strategy reaches ``task_scheduled()``. The ``scheduled_requests`` loop in ``Consumer.on_close()`` popped from ``state.requests`` unconditionally, unlike the reserved loop above it, so on reconnect a still-running task was removed from ``state.requests`` and became invisible to inspect/revoke while it executed. Guard both ends: ``task_scheduled()` is now a no-op for a request that's already reserved or active, and ``on_close()`` mirrors the reserved loop's ``active_requests``/``reserved_requests`` check before dropping anything. Also from review: - Declare ``Request._eta_timer_entry = None`` on the class instead of relying on the ad-hoc attribute, and drop the ``getattr()`` fallback in ``on_close()``. - Document that a rate-limited ETA task stays in ``scheduled_requests`` until a token frees up, so the previous "hasn't elapsed yet" wording is no longer accurate. - Cover the ``revoke(terminate=True)`` behavior change: scheduled requests now live in ``state.requests``, so revoke reaches them before their ETA. - Rename ``test_query_task_integration.py`` to ``test_eta_query_task.py``, fold the repeated ``on_close`` test setup into an ``on_close_ctx`` fixture, and simplify the smoke-test predicate. Fix an unrelated pre-existing test leak while here: ``import_state()`` in ``test_state_configuration`` reimports ``celery.worker.state``, which also rebinds the ``state`` attribute on the ``celery.worker`` package. ``patch.dict(sys.modules)`` doesn't restore that, so every later ``from celery.worker import state`` got the throwaway copy -- with its own empty ``requests``/``*_requests`` containers -- while the rest of celery kept using the real ones, making six ``test_consumer.py`` tests fail depending on collection order. --------- Co-authored-by: Asif Saif Uddin {"Auvi":"অভি"} <[email protected]>
* Fix reference cycle between Request and its ETA timer entry (#11139) Request._eta_timer_entry (added in #10535) held a strong reference to the timer Entry, whose args hold the Request. The resulting cycle kept finished ETA/countdown requests, with their message bodies, alive until a full GC run, which made worker memory grow under steady countdown load. Store a weak reference to the entry instead. The timer's own queue keeps the entry alive until it fires or is cancelled, so Consumer.on_close() can still cancel it, and the fix does not depend on timer firing order. * Skip the ETA request GC regression test on PyPy PyPy has no reference counting, so objects are only freed by the GC and the test cannot observe an immediate free. --------- Co-authored-by: Asif Saif Uddin {"Auvi":"অভি"} <[email protected]>
Summary
Fixes #5321.
inspect query_task <id>returned nothing for a task with aneta/countdownuntil the ETA actually elapsed, even thoughinspect scheduledshowed it the whole time.query_tasklooks upcelery.worker.state.requests, which was only populated onceConsumer.apply_eta_task()fires at ETA time. Before that, the task only existed in the consumer's timer queue, which is whatinspect scheduledreads directly.The fix registers the request in
state.requestsas soon as it's scheduled into the timer, via a newtask_scheduled()helper that mirrorstask_reserved()but doesn't add the request toreserved_requests, soinspect reservedstill correctly excludes scheduled tasks.Test plan
t/unit/worker/test_strategy.pyandt/unit/worker/test_control.pythat fail without the fixtox -e 3.12-unit)app.control.inspect()