Repository navigation
Optimize beat scheduler tick loop by rebuilding heap only on schedule invalidation - #10167
AsymptotaX wants to merge 10 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
This PR optimizes the celery beat scheduler's hot path by replacing the per-tick O(n) schedule comparison (via schedules_equal + copy.copy) with an explicit heap invalidation flag (_heap_invalidated). The heap is now rebuilt only when the schedule is actually mutated (via add, update_from_dict, merge_inplace, or set_schedule), rather than on every tick. The benchmark cited in the description claims ~55× throughput improvement.
Changes:
celery/beat.py: Removesold_schedulerstracking andcopyimport; introduces_heap_invalidatedflag set at construction and cleared afterpopulate_heap(); each schedule-mutating method now sets the flag.celery/beat.py: Adds_heap_invalidated = TruetoPersistentScheduler.set_schedule()to keep the subclass consistent.t/unit/app/test_beat.py: Adds a regression test verifying that repeated ticks on an unchanged schedule do not trigger additionalpopulate_heapcalls.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
celery/beat.py |
Core optimization: replaces per-tick schedule diffing with explicit _heap_invalidated flag; removes now-unused copy import and old_schedulers; adds flag-setting to all schedule-mutating methods in both Scheduler and PersistentScheduler |
t/unit/app/test_beat.py |
New test validating that populate_heap is called exactly once for consecutive due ticks without a schedule change |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #10167 +/- ##
=======================================
Coverage 88.23% 88.24%
=======================================
Files 153 153
Lines 19569 19593 +24
Branches 2249 2252 +3
=======================================
+ Hits 17267 17289 +22
- Misses 2004 2006 +2
Partials 298 298
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. |
|
@ChickenBenny whenever you have some time, feel free to have a look into it |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
You can also share your feedback on Copilot code review. Take the survey.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
You can also share your feedback on Copilot code review. Take the survey.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
You can also share your feedback on Copilot code review. Take the survey.
Co-authored-by: Copilot <[email protected]>
…rride compatibility
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
6d4a20e to
a213605
Compare
| # Backward compatibility: custom scheduler implementations may override | ||
| # schedules_equal() and expect tick() to call it to detect updates. | ||
| if self._has_custom_schedules_equal(): | ||
| if (self._last_schedule is None or | ||
| not self.schedules_equal(self._last_schedule, self.schedule)): | ||
| self._heap_invalidated = True |
There was a problem hiding this comment.
In the custom-override path, tick() won’t call schedules_equal() when _last_schedule is None because the or expression short-circuits. Previously schedules_equal(None, self.schedule) was invoked, so subclasses overriding schedules_equal() could rely on being called on the first tick too. Consider calling schedules_equal() unconditionally (even with old_schedules=None) to preserve the historical override contract while still using heap invalidation for performance.
| def test_tick_calls_custom_schedules_equal_override(self): | ||
| class CustomScheduler(mScheduler): | ||
| def __init__(self, *args, **kwargs): | ||
| super().__init__(*args, **kwargs) | ||
| self.schedules_equal_called = 0 | ||
| self.force_not_equal = False | ||
|
|
||
| def schedules_equal(self, old_schedules, new_schedules): | ||
| self.schedules_equal_called += 1 | ||
| if self.force_not_equal: | ||
| return False | ||
| return super().schedules_equal(old_schedules, new_schedules) | ||
|
|
||
| scheduler = CustomScheduler(app=self.app) | ||
| scheduler.add(name='test_tick_calls_custom_schedules_equal_override', | ||
| schedule=always_due) | ||
|
|
||
| with patch.object( | ||
| scheduler, 'populate_heap', wraps=scheduler.populate_heap, | ||
| ) as populate_heap: | ||
| scheduler.tick() | ||
| initial_populate_calls = populate_heap.call_count | ||
|
|
||
| scheduler.force_not_equal = True | ||
| scheduler.tick() | ||
| scheduler.tick() | ||
|
|
||
| assert scheduler.schedules_equal_called == 2 | ||
| assert populate_heap.call_count > initial_populate_calls |
There was a problem hiding this comment.
This test bakes in the new short-circuit behavior where schedules_equal() isn’t called on the first tick when _last_schedule is None. If the goal of the PR is backward compatibility for custom schedules_equal() overrides, the test should instead expect schedules_equal(None, schedule) to be invoked on the initial tick as it was previously.
Description
I’d like to propose a small change in beat that gives a pretty big performance win on the scheduler hot path.
Right now Scheduler.tick() can end up doing expensive schedule comparison/rebuild work over and over, even when the schedule hasn’t changed.
This PR switches that logic to explicit heap invalidation: we rebuild only when needed (initial build or actual schedule mutation), and keep using the existing heap otherwise.
In practice this means less CPU spent on bookkeeping inside beat, especially for installations with large periodic schedules and frequent ticks.
My Environment
Mac mini (M4)
macOS-26.3-arm64
Python 3.13.5
Celery 5.6.2
Redis: Docker container running locally on the same host
benchmark
So the intent is straightforward: keep behavior the same, but stop paying O(n)-style scheduler overhead on every tick when nothing changed.
Important note about schedule mutations
This optimization relies on explicit heap invalidation.
So the expected contract is that schedule changes go through scheduler APIs:
add(...)update_from_dict(...)merge_inplace(...)set_schedule(...)Direct in-place mutation of
scheduler.schedule(bypassing these methods) may result in a stale heap until the next explicit invalidation.This is not a regression for normal or documented usage, but an explicit assumption introduced by this optimization.