Repository navigation
Keep celery beat running when a schedule entry fails, and reject impossible crontab dates - #10896
Conversation
…ssible crontab dates
|
I would suggest you fix all 3 part here, as I could not see the other part being handled by the ID you mentioned |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #10896 +/- ##
==========================================
+ Coverage 90.57% 90.59% +0.01%
==========================================
Files 153 153
Lines 21447 21469 +22
Branches 2633 2635 +2
==========================================
+ Hits 19426 19450 +24
+ Misses 1707 1706 -1
+ Partials 314 313 -1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
A schedule DB written by an older version can hold a crontab such as the 30th of February, which the crontab constructor now rejects. Treat the ValueError raised when it is unpickled like a corrupt DB, so beat recreates the entries instead of exiting at startup.
…g beat On CircumpolarError, adding a timedelta to an ephem.Date raised TypeError and stopped beat. This happens every summer for dawn_astronomical/dawn_nautical at roughly 49-60 degrees latitude (London, Stockholm, ...), and during polar night for sunrise/sunset. Search forward one day at a time, starting from each next anti-transit, and return the first real occurrence of the event, searching up to max_search_days (366) ahead. If none is found, return the time the search stopped, so beat checks again then instead of firing at a made-up time. Fixes celery#10893
|
Thanks @auvipy, done. All 3 parts are now fixed in this PR:
Because of (3), I also made I've updated the description and changed it to |
|
@HassanRady @phanky1 @GangEunzzang @MehrazRumman please feel free to review? @Amli ? |
MehrazRumman
left a comment
There was a problem hiding this comment.
Checked at 8cf9598.
What checks out
t/unit/app/test_beat.pyandt/unit/app/test_schedules.pypass (400 passed, 1 skipped). Running this branch's versions of both files againstmain's source gives 15 failures, so the new tests exercise all three fixes.- solar: the old
CircumpolarErrorbranch really did raise, and the new search returns a real occurrence. I tried an extreme case:solar('sunset', 78.22, 15.65)(Longyearbyen, midnight sun) withlast_run_at= 2026-05-01.mainraisesTypeError; this branch returns the first sunset 115 days later. That search walks about 115 antitransits and still takes only about 2.3 ms perremaining_estimate()call, so even far north the cost on every beat tick is negligible. - crontab: counting February as 29 days is right.
crontab(0, 0, day_of_month=29, month_of_year=2)is still accepted and, from 2026-03-01, gives the next leap day (730 days), the same asmain. - beat:
populate_heap()andtick()now both survive a failingis_due()and reschedule that entry aftermax_interval, and the other entries keep running. Logging withexc_infokeeps the actual error visible, which matters because the next point turns more errors into retries.
Things worth a look
except Exceptionaroundis_due()also catches errors that aren't schedule bugs. For example, a custom scheduler's entry that reads from a database or cache insideis_due()used to crash beat on an outage and get restarted by the process manager. Now it logs a traceback everymax_intervaland keeps going. That is probably the better behaviour, but it is a change for custom schedulers, so it deserves a line in the changelog/versionchangednote next to the crontab one.- Downstream: django-celery-beat. Its
DatabaseScheduler.all_as_schedule()builds each entry insidetry: ... except ValueError: pass, andModelEntry.__init__readsmodel.schedule, which constructscrontab(...). After this change, an existingCrontabSchedulerow for the 30th of February is silently dropped from the schedule rather than crashing beat. That is an improvement, but users there won't see the newValueErrormessage anywhere. It may be worth a heads-up issue or note for django-celery-beat so it can log the skip. - The DB reset in
_create_scheduleis broad. CatchingValueErroraroundself._store['entries']resets the whole store, losinglast_run_atfor every entry, for anyValueErrorraised while unpickling, not only the new crontab check. That is consistent with how the other corrupt-DB cases are handled, and in practice the user's config would already fail to load before beat reached this point. Logging which error caused the reset (the existing reset path is silent apart from the newbeat_schedulebeing written) would make an unexpected loss oflast_run_ateasier to trace.
CI
When I checked, 10 checks were still pending, and codecov/project was failing, probably on partial coverage uploads. It's worth looking at again once the run finishes.
Overall this looks good to me. The three parts fit together, and the docs versionchanged notes cover the user-visible changes.
…andling Log a warning with the error when stored entries can't be unpickled anymore, so an unexpected loss of last_run_at can be traced. Add a versionchanged note saying that beat now logs and retries an entry whose is_due() raises instead of exiting, which also affects custom schedulers.
|
Thanks for the thorough review @MehrazRumman, and for checking the Longyearbyen case and the per-call cost!
|
auvipy
left a comment
There was a problem hiding this comment.
should we add extra integration test? or the changes are covered by the existing ones?
|
The existing integration tests didn't cover this:
It passes on this branch and fails on The crontab and solar changes are pure date calculations. Their unit tests in |
Description
Fixes #10893.
Currently, a single periodic task whose next run can't be calculated stops
celery beat, and every other periodic task with it. This PR makes two changes:1. beat: an entry that fails in
is_due()no longer stops beatScheduler.populate_heap()andScheduler.tick()calledis_due()for each entry without error handling, andService.start()only catchesKeyboardInterrupt/SystemExit. Any exception from one entry, such as thesolarTypeErrorreported in #10893, therefore made beat exit.Now beat catches the error, logs it with the entry's name and the traceback, and tries that entry again after
max_interval. The other entries keep running.Tested with a real
celery beatprocess, using thesolar('dawn_astronomical', -62.2, -58.9)entry from the issue next to a healthy 2s entry:mainmax_interval2. crontab: impossible dates are rejected when the crontab is created
crontab(day_of_month=30, month_of_year=2)(or the 31st of April/June/September/November) was accepted, because each field is validated on its own. It then failed at runtime inroll_over()withRuntimeError: unable to rollover, time specification is probably invalid, which also made beat exit.The constructor now raises
ValueErrorif no day inday_of_monthoccurs in any month inmonth_of_year, in the same way it already rejects e.g.crontab(minute=61). February counts as 29 days, soday_of_month=29, month_of_year=2is still accepted.Behaviour change: schedules that contain such a crontab now fail when the config is loaded, instead of when beat calculates the next run. These specs could never run, and they made beat exit, so failing early seemed better. I've documented it with a
versionchangednote in the periodic tasks guide.3. solar: an event that doesn't happen on a given day no longer stops beat
When the sun doesn't reach the event's horizon on a given day, ephem raises
CircumpolarError. The handler for it was broken: it added atimedeltato anephem.Date(a float), which raisedTypeErrorand stopped beat. The branch had# pragma: no cover, so no test ran it.This doesn't only happen near the poles. Around the summer solstice, astronomical/nautical twilight lasts all night for weeks at roughly 49–60° latitude (London, Paris, Berlin, Amsterdam, Stockholm, …). So a
dawn_astronomicalentry stopped beat every summer in much of Europe.Changing the line to
ephem.Date(... + ephem.minute)isn't enough. That returns "1 minute after the next antitransit", which isn't an occurrence of the event. Because the schedule searches fromlast_run_at, the entry then becomes due every night. For example, a Londondawn_astronomicalentry would run on 15 and 16 June, when there is no astronomical dawn.Now, on
CircumpolarError,solarmoves on to the next antitransit (one day later) and tries again. It returns the first real occurrence of the event. The search goes up tomax_search_days(366) ahead. If nothing is found, it returns the time where the search stopped, so beat checks again then instead of running at a made-up time. The# pragma: no coveris removed.solar('dawn_astronomical', 51.5074, -0.1278)(London)TypeError, beat exitssolar('dawn_nautical', 59.3293, 18.0686)(Stockhol, beat exitssolar('sunrise', 69.6492, 18.9553)(Tromsø, polar night)TypeError, beat exitsI checked the expected times against ephem directly. I also added a short note to the solar section of the periodic tasks guide.
4. beat: the schedule DB is reset if a stored crontab is now invalid
Because of change 2, a schedule DB written by an older version can hold a crontab that the constructor now rejects, e.g. the 30th of February.
crontab.__reduce__calls the constructor aled, so loadingself._store['entries']raisesValueError, and beat would exit at startup after upgrading.PersistentScheduler._create_schedule()now treats thisValueErroras it already treats a corrupt or old DB (KeyError,UnpicklingError, …). It resets the stored entries, aeat_schedule. As with the other reset cases, thestoredlast_run_at` of all entries is lost.Add these bullets to the existing Tests section:
test_schedules.py(solar):dawn_astronomical), Stockholm/June December (sunrise) return the first real occurrenceof the event, not an error or a made-up time;dawn_astronomicalentry last run on 15 e one-line fix would make it due every night);max_search_days, the search stops and returns a "check again" time instead of raising.test_beat.py: a stored entry containing a crontab e schedule DB instead of raising.Tests
test_beat.py:populate_heap(): beat keeps going, the healthy entry is sent, and the failing entry is rescheduled aftermax_interval;tick(): beat returnsmax_intervalinstead of raising.test_schedules.py:day_of_month/month_of_year, raiseValueError;'30,31'in'2,3', …) are accepted.test_invalid_specificationnow expects theValueError. Its infinite-loop guard forroll_over()is kept in a newtest_rollover_gives_up_on_invalid_date, which bypasses the constructor check.mainand pass with this change.pre-commit(flake8, isort, mypy, codespell, pyupgrade) passes.