Skip to content

Keep celery beat running when a schedule entry fails, and reject impossible crontab dates - #10896

Merged
auvipy merged 6 commits into
celery:mainfrom
Kavin-Nithil:fix/beat-survive-failing-schedule-entries
Oct 20, 2026
Merged

auvipy merged 6 commits into
celery:mainfrom
Kavin-Nithil:fix/beat-survive-failing-schedule-entries

Conversation

@Kavin-Nithil

@Kavin-Nithil Kavin-Nithil commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

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 beat

Scheduler.populate_heap() and Scheduler.tick() called is_due() for each entry without error handling, and Service.start() only catches KeyboardInterrupt/SystemExit. Any exception from one entry, such as the solar TypeError reported 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.

[...: ERROR/MainProcess] beat: Cannot calculate the next run of 'bad-entry', trying again in 5.00 minutes.
Traceback (most recent call last):
  ...

Tested with a real celery beat process, using the solar('dawn_astronomical', -62.2, -58.9) entry from the issue next to a healthy 2s entry:

main this PR
beat process exits at startup (exit code 1) keeps running
healthy entry never sent sent every 2s
bad entry n/a error logged, retried after max_interval

2. 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 in roll_over() with RuntimeError: unable to rollover, time specification is probably invalid, which also made beat exit.

The constructor now raises ValueError if no day in day_of_month occurs in any month in month_of_year, in the same way it already rejects e.g. crontab(minute=61). February counts as 29 days, so day_of_month=29, month_of_year=2 is still accepted.

>>> crontab(day_of_month=30, month_of_year=2)
ValueError: Invalid crontab: day_of_month 30 never occurs in month_of_year 2.

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 versionchanged note 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 a timedelta to an ephem.Date (a float), which raised TypeError and 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_astronomical entry 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 from last_run_at, the entry then becomes due every night. For example, a London dawn_astronomical entry would run on 15 and 16 June, when there is no astronomical dawn.

Now, on CircumpolarError, solar moves on to the next antitransit (one day later) and tries again. It returns the first real occurrence of the event. The search goes up to max_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 cover is removed.

entry last run before this PR: next run
solar('dawn_astronomical', 51.5074, -0.1278) (London) 2026-06-15 TypeError, beat exits 2026-07-22 00:30 UTC
solar('dawn_nautical', 59.3293, 18.0686) (Stockhol, beat exits 2026-07-29 23:14 UTC
solar('sunrise', 69.6492, 18.9553) (Tromsø, polar night) 2026-12-15 TypeError, beat exits 2027-01-15 10:34 UTC

I 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 loading self._store['entries'] raisesValueError, and beat would exit at startup after upgrading.

PersistentScheduler._create_schedule() now treats this ValueError as it already treats a corrupt or old DB (KeyError, UnpicklingError, …). It resets the stored entries, aeat_schedule. As with the other reset cases, thestored last_run_at` of all entries is lost.

Add these bullets to the existing Tests section:

  • test_schedules.py (solar):
    • London/June (dawn_astronomical), Stockholm/June December (sunrise) return the first real occurrenceof the event, not an error or a made-up time;
    • a London dawn_astronomical entry last run on 15 e one-line fix would make it due every night);
    • if the event isn't found within 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:
    • a failing entry during populate_heap(): beat keeps going, the healthy entry is sent, and the failing entry is rescheduled after max_interval;
    • a failing entry in tick(): beat returns max_interval instead of raising.
  • test_schedules.py:
    • impossible day/month combinations, and empty day_of_month/month_of_year, raise ValueError;
    • possible combinations (Feb 29, '30,31' in '2,3', …) are accepted.
  • test_invalid_specification now expects the ValueError. Its infinite-loop guard for roll_over() is kept in a new test_rollover_gives_up_on_invalid_date, which bypasses the constructor check.
  • The new tests fail on main and pass with this change. pre-commit (flake8, isort, mypy, codespell, pyupgrade) passes.

@auvipy
auvipy self-requested a review October 19, 2026 08:29
@auvipy

auvipy commented Oct 19, 2026

Copy link
Copy Markdown
Member

I would suggest you fix all 3 part here, as I could not see the other part being handled by the ID you mentioned

@auvipy auvipy added this to the 5.7.0 milestone Oct 19, 2026
@codecov

codecov Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.59%. Comparing base (3611b8f) to head (476101c).

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     
Flag Coverage Δ
unittests 90.57% <100.00%> (+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.

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
@Kavin-Nithil

Copy link
Copy Markdown
Contributor Author

Thanks @auvipy, done. All 3 parts are now fixed in this PR:

  1. solar: on CircumpolarError, the schedule now moves on to the next antitransit (one day later) and tries again. It returns the first real occurrence of the event, searching up to a year ahead. If none is found, it returns a "check again" time instead of a made-up event time. The broken branch (ephem.Date + timedelta → TypeError) and its # pragma: no cover are gone. Tests cover London/June (dawn_astronomical), Stockholm/June (dawn_nautical) and Tromsø/December (sunrise). Changing that one line to ephem.Date(... + ephem.minute) would have stopped the crash, but the entry would then run every night in summer, so I didn't do that.
  2. beat: an entry that fails in is_due() is logged and retried after max_interval, and the other entries keep running.
  3. crontab: impossible dates such as the 30th of February are rejected with ValueError when the crontab is created.

Because of (3), I also made PersistentScheduler reset the schedule DB when a stored entry contains a crontab that is now invalid. Otherwise beat would exit at startup after upgrading.

I've updated the description and changed it to Fixes #10893.

@auvipy

auvipy commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

@HassanRady @phanky1 @GangEunzzang @MehrazRumman please feel free to review? @Amli ?

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

Checked at 8cf9598.

What checks out

  • t/unit/app/test_beat.py and t/unit/app/test_schedules.py pass (400 passed, 1 skipped). Running this branch's versions of both files against main's source gives 15 failures, so the new tests exercise all three fixes.
  • solar: the old CircumpolarError branch 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) with last_run_at = 2026-05-01. main raises TypeError; this branch returns the first sunset 115 days later. That search walks about 115 antitransits and still takes only about 2.3 ms per remaining_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 as main.
  • beat: populate_heap() and tick() now both survive a failing is_due() and reschedule that entry after max_interval, and the other entries keep running. Logging with exc_info keeps the actual error visible, which matters because the next point turns more errors into retries.

Things worth a look

  1. except Exception around is_due() also catches errors that aren't schedule bugs. For example, a custom scheduler's entry that reads from a database or cache inside is_due() used to crash beat on an outage and get restarted by the process manager. Now it logs a traceback every max_interval and keeps going. That is probably the better behaviour, but it is a change for custom schedulers, so it deserves a line in the changelog/versionchanged note next to the crontab one.
  2. Downstream: django-celery-beat. Its DatabaseScheduler.all_as_schedule() builds each entry inside try: ... except ValueError: pass, and ModelEntry.__init__ reads model.schedule, which constructs crontab(...). After this change, an existing CrontabSchedule row 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 new ValueError message anywhere. It may be worth a heads-up issue or note for django-celery-beat so it can log the skip.
  3. The DB reset in _create_schedule is broad. Catching ValueError around self._store['entries'] resets the whole store, losing last_run_at for every entry, for any ValueError raised 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 new beat_schedule being written) would make an unexpected loss of last_run_at easier 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.
@Kavin-Nithil

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @MehrazRumman, and for checking the Longyearbyen case and the per-call cost!

  • except Exception around is_due(): agreed, that's a behaviour change for custom schedulers. I've added a versionchanged note in "Using custom scheduler classes". It says that beat now logs the error with its traceback and retries the entry after max_interval instead of exiting, and uses an is_due() that reads from a database as the example.
  • Schedule DB reset: when the stored entries raise ValueError while loading, beat now logs a warning with the error before resetting them, so an unexpected loss of last_run_at can be traced. I kept the catch broad to match the other corrupt-DB cases. I didn't add logging to the KeyError path, because that's also how a brand-new DB starts and it would log on every first start. There's a test for each case, and the same versionchanged note documents the reset.

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

should we add extra integration test? or the changes are covered by the existing ones?

@Kavin-Nithil

Copy link
Copy Markdown
Contributor Author

The existing integration tests didn't cover this: t/integration/test_beat.py had nothing with a failing is_due(), solar, or an invalid crontab. So I've added test_beat_failing_entry::test_dispatches_other_entries_when_is_due_raises, following test_beat_tick_heap_top_changed. It adds a healthy entry and an entry whose is_due() raises, then checks:

  • populate_heap() doesn't raise, moves the failing entry max_interval ahead, and keeps the healthy one due;
  • with the failing entry on top of the heap, tick() doesn't raise and moves it back, and the next tick() sends the healthy task, whose result comes back from the worker;
  • the failing entry is never sent.

It passes on this branch and fails on main with the TypeError from the failing entry.

The crontab and solar changes are pure date calculations. Their unit tests in test_schedules.py run the real code with no mocks (real ephem for London, Stockholm and Tromsø), so I don't think an integration test would add much there.

@auvipy
auvipy merged commit c13d621 into celery:main Oct 20, 2026
500 checks passed
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.

celery beat exits when a single schedule entry fails: solar CircumpolarError raises TypeError, impossible crontab raises RuntimeError

4 participants