Skip to content

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

Closed

Description

@Kavin-Nithil

Checklist

  • I have verified that the issue exists against the main branch of Celery.
  • This has already been asked to the discussions forum first.
  • I have read the relevant section in the
    contribution guide
    on reporting bugs.
  • I have checked the issues list
    for similar or identical bug reports.
  • I have checked the pull requests list
    for existing proposed fixes.
  • I have checked the commit log
    to find out if the bug was already fixed in the main branch.
  • I have included all related issues and possible duplicate issues
    in this issue (If there are none, check this box anyway).
  • I have tried to reproduce the issue with pytest-celery and added the reproduction script below.

Mandatory Debugging Information

  • I have included the output of celery -A proj report in the issue.
  • I have verified that the issue exists against the main branch of Celery.
  • I have included the contents of pip freeze in the issue.
  • I have included all the versions of all the external dependencies required
    to reproduce this bug.

Optional Debugging Information

  • I have tried reproducing the issue on more than one Python version
    and/or implementation.
  • I have tried reproducing the issue on more than one message broker and/or
    result backend.
  • I have tried reproducing the issue on more than one version of the message
    broker and/or result backend.
  • I have tried reproducing the issue on more than one operating system.
  • I have tried reproducing the issue on more than one workers pool.
  • I have tried reproducing the issue with autoscaling, retries,
    ETA/Countdown & rate limits disabled.
  • I have tried reproducing the issue after downgrading
    and/or upgrading Celery and its dependencies.

Related Issues and Possible Duplicates

Related Issues

Possible Duplicates

  • None. I searched for "CircumpolarError", "AlwaysUpError", "NeverUpError", "unable to rollover", "solar ephem.Date" and "beat crash invalid schedule".

Environment & Settings

Celery version: 5.7.0rc1 (collider), main @ 0731c05

celery report Output:


software -> celery:5.7.0rc1 (collider) kombu:5.7.0rc1 py:3.12.13
            billiard:4.3.1 memory:N/A
platform -> system:Linux arch:64bit, ELF
            kernel version:6.8.0-138-generic imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:memory results:disabled

broker_url: 'memory://:********@localhost//'
deprecated_settings: None
beat_schedule:
    'bad-entry': {   'schedule': <crontab: 0 0 30 2 * (m/h/dM/MY/d)>,
                     'task': 'beatapp.ping'},
    'healthy-every-10s': {'schedule': 10.0, 'task': 'beatapp.ping'}}

Steps to Reproduce

Required Dependencies

  • Minimal Python Version: 3.12.13 (tested)
  • Minimal Celery Version: 5.7.0rc1 (tested). The affected code has not changed in a long time; see Error when handling CircumpolarError in solar calculations #9514 (2025).
  • Minimal Kombu Version: N/A (reproduces with the memory:// transport)
  • Minimal Broker Version: N/A
  • Minimal Result Backend Version: N/A
  • Minimal OS and/or Kernel Version: Linux 6.8 (tested)
  • Minimal Broker Client Version: N/A
  • Minimal Result Backend Client Version: N/A

Python Packages

pip freeze Output:

-e git+https://github.com/celery/celery@0731c053b#egg=celery  # 5.7.0rc1
amqp==5.4.1
billiard==4.3.1
click==8.5.0
click-didyoumean==0.3.1
click-plugins==1.1.1.2
click-repl==0.4.1
ephem==4.2.1
kombu==5.7.0rc1
packaging==26.3
prompt-toolkit==3.0.53
python-dateutil==2.9.0.post0
six==1.17.0
tzdata==2026.4
tzlocal==5.4.4
vine==5.1.0
wcwidth==0.9.2

Other Dependencies

Details

ephem==4.2.1 is required for solar schedules.

Minimally Reproducible Test Case

Two triggers, one root problem: if any single schedule entry raises in is_due(), the whole celery beat process exits, and every periodic task stops.

Details

1. Each trigger raises inside Scheduler.tick(), even with a healthy entry next to it:

from datetime import datetime, timezone
from unittest.mock import patch

from celery import Celery
from celery.beat import Scheduler
from celery.schedules import crontab, solar

cases = {
    'solar: astronomical dawn, London, mid-June': (
        solar('dawn_astronomical', 51.5074, -0.1278),
        datetime(2026, 6, 15, 12, tzinfo=timezone.utc)),
    'solar: nautical dusk, Stockholm, mid-June': (
        solar('dusk_nautical', 59.3293, 18.0686),
        datetime(2026, 6, 15, 12, tzinfo=timezone.utc)),
    'solar: sunrise, Tromso, mid-December': (
        solar('sunrise', 69.6492, 18.9553),
        datetime(2026, 12, 15, 12, tzinfo=timezone.utc)),
    'crontab: February 30': (
        crontab(minute=0, hour=0, day_of_month=30, month_of_year=2),
        datetime(2026, 1, 15, 12, tzinfo=timezone.utc)),
    'crontab: 31st of Apr/Jun/Sep/Nov': (
        crontab(minute=0, hour=0, day_of_month=31, month_of_year='4,6,9,11'),
        datetime(2026, 1, 15, 12, tzinfo=timezone.utc)),
}

for name, (schedule, now) in cases.items():
    app = Celery(set_as_current=False, broker='memory://')
    app.conf.beat_schedule = {
        'healthy-every-minute': {'task': 'x', 'schedule': crontab()},
        'bad-entry': {'task': 'y', 'schedule': schedule},
    }
    with patch.object(Celery, 'now', lambda self, now=now: now):
        try:
            Scheduler(app).tick()
            result = 'ok'
        except Exception as exc:
            result = f'{type(exc).__name__}: {exc}'
    print(f'{name:45} -> {result}')

2. A real celery beat process exits (beatapp.py). The solar entry fails today (October), with no clock patching:

import os

from celery import Celery
from celery.schedules import crontab, solar

app = Celery('beatapp', broker='memory://')

bad = {
    'solar': solar('dawn_astronomical', -62.2, -58.9),  # King George Island, Antarctica
    'crontab': crontab(minute=0, hour=0, day_of_month=30, month_of_year=2),
}[os.environ['BAD']]

app.conf.beat_schedule = {
    'healthy-every-10s': {'task': 'beatapp.ping', 'schedule': 10.0},
    'bad-entry': {'task': 'beatapp.ping', 'schedule': bad},
}


@app.task
def ping():
    return 'pong'
$ BAD=solar   celery -A beatapp beat -S celery.beat:Scheduler -l info; echo "exit code: $?"
$ BAD=crontab celery -A beatapp beat -S celery.beat:Scheduler -l info; echo "exit code: $?"

Expected Behavior

  • One entry whose next run can't be computed should be logged and skipped (or retried later). The other periodic tasks should keep running.
  • solar: when the event doesn't happen on a given day (polar day/night, or astronomical/nautical twilight that never ends around the summer solstice), the entry should be not due. Beat should look for the next day on which the event actually happens.
  • crontab: a spec that can never match (Feb 30, Apr 31, …) should be rejected with a ValueError when the crontab is created, not crash beat at runtime.

Actual Behavior

Output of script 1:

solar: astronomical dawn, London, mid-June    -> TypeError: unsupported operand type(s) for +: 'ephem.Date' and 'datetime.timedelta'
solar: nautical dusk, Stockholm, mid-June     -> TypeError: unsupported operand type(s) for +: 'ephem.Date' and 'datetime.timedelta'
solar: sunrise, Tromso, mid-December          -> TypeError: unsupported operand type(s) for +: 'ephem.Date' and 'datetime.timedelta'
crontab: February 30                          -> RuntimeError: unable to rollover, time specification is probably invalid
crontab: 31st of Apr/Jun/Sep/Nov              -> RuntimeError: unable to rollover, time specification is probably invalid

With script 2, celery beat exits with exit code 1 at startup in both cases, and no task is ever sent, including the healthy 10s entry:

beat: Starting...
beat raised exception <class 'TypeError'>: TypeError("unsupported operand type(s) for +: 'ephem.Date' and 'datetime.timedelta'")
Traceback (most recent call last):
  File "celery/schedules.py", line 859, in remaining_estimate
    next_utc = getattr(self.cal, self.method)(
  File "ephem/__init__.py", line 518, in _find_rise_or_set
    raise AlwaysUpError('%r is above the horizon at %s'
ephem.AlwaysUpError: 'Sun' is above the horizon at 2026/10/19 03:40:38

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "celery/apps/beat.py", line 119, in start_scheduler
    service.start()
  File "celery/beat.py", line 1045, in start
    interval = self.scheduler.tick()
  File "celery/beat.py", line 347, in tick
    self.populate_heap()
  File "celery/beat.py", line 321, in populate_heap
    is_due, next_call_delay = entry.is_due()
  File "celery/beat.py", line 169, in is_due
    return self.schedule.is_due(self.last_run_at)
  File "celery/schedules.py", line 889, in is_due
    rem_delta = self.remaining_estimate(last_run_at)
  File "celery/schedules.py", line 872, in remaining_estimate
    self.cal.next_antitransit(self.ephem.Sun()) +
TypeError: unsupported operand type(s) for +: 'ephem.Date' and 'datetime.timedelta'

The crontab case is the same, ending in RuntimeError: unable to rollover, time specification is probably invalid.

Root cause

  1. solar: the CircumpolarError branch can never succeed (celery/schedules.py L868-L874):

    except self.ephem.CircumpolarError:  # pragma: no cover
        next_utc = (
            self.cal.next_antitransit(self.ephem.Sun()) +
            timedelta(minutes=1)
        )

    ephem.Date is a float (days), so adding a timedelta raises TypeError. The branch is excluded from coverage, so no test exercises it.

    This is not just a polar edge case. Astronomical/nautical twilight doesn't end for weeks around the summer solstice at roughly 49–60° latitude (London, Paris, Berlin, Amsterdam, Stockholm …), so a dawn_astronomical entry takes beat down every summer in much of Europe.

    The obvious one-line fix is not enough. If you only change it to ephem.Date(... + ephem.minute), the crash goes away, but the returned time is "1 minute after the next antitransit", which is not an occurrence of the event. Since the schedule always searches from last_run_at, the entry becomes due every night. With that one-line fix, a solar('dawn_astronomical', 51.5074, -0.1278) entry is due at 2026-06-15 02:00 UTC and again at 2026-06-16 02:00 UTC, although astronomical dawn never happens in London on those days.

  2. crontab: _expand_cronspec validates each field on its own (celery/schedules.py L482-L498). crontab(day_of_month=30, month_of_year=2) is therefore accepted, and only fails later in roll_over() with RuntimeError('unable to rollover, ...').

  3. No fault isolation in beat: Scheduler.populate_heap() (L321) and tick() call entry.is_due() for every entry with no error handling. Service.start() (L1045-L1053) only catches KeyboardInterrupt/SystemExit. One bad entry therefore stops all periodic tasks. Users deploying a schedule change typically see beat crash-loop under their process supervisor.

Suggested fix

I'm happy to send a PR, in three focused parts (they could be separate PRs if preferred):

  1. solar: on CircumpolarError, move start to the next antitransit and retry next_rising/next_setting/next_transit, up to about one year of days. Return the first real occurrence of the event. If none is found within that window, return a long "check again" delay instead of a fake event time. Remove the # pragma: no cover and add tests for London/June, Stockholm/June and Tromsø/December.
  2. crontab: in crontab.__init__, raise ValueError if no (month, day_of_month) pair in the spec is a valid date (allowing Feb 29), so the error shows up when the config is loaded.
  3. beat: in populate_heap() and tick(), catch exceptions from a single entry's is_due(), log them with logger.exception (naming the entry), and reschedule that entry after max_interval, so one bad entry can't stop the others.

Activity

  1. ag3ntsc4rn commented on Oct 19, 2026

    @ag3ntsc4rn

    Thanks for the detailed report. I can reproduce the solar part on main @ 0731c05 with ephem 4.2.1: all three of your solar cases raise the TypeError from the CircumpolarError branch.

    @Kavin-Nithil, you offered to send PRs. If you haven't started on the solar part, I have a fix ready that follows your suggestion 1. On CircumpolarError it resumes the search after the next anti-transit, one day at a time for up to 366 days, and returns the first real occurrence of the event. Results for your examples:

    Entry From Next run
    dawn_astronomical, London 2026-06-15 2026-07-22 00:30 UTC
    dusk_nautical, Stockholm 2026-06-15 2026-07-29 22:34 UTC
    sunrise, Tromsø 2026-12-15 2027-01-15 10:34 UTC
    dawn_astronomical, King George Island 2026-10-18 2027-02-24 04:39 UTC

    The entry is no longer due on the days in between, so it doesn't fire every night as it would with the one-line fix.

    I'd keep that PR to solar only and leave the crontab validation and beat fault isolation (your parts 2 and 3) to separate PRs, which I'm happy to leave with you. If you've already started on solar, tell me and I'll review yours instead.

  2. auvipy commented on Oct 19, 2026

    @auvipy
    Member

    @HassanRady can you check and fix this?

  3. Kavin-Nithil commented on Oct 19, 2026

    @Kavin-Nithil
    ContributorAuthor

    @ag3ntsc4rn thanks for confirming it, and for the fix! I haven't started on the solar part, so please go ahead with your PR. Your results match what I get for London, Stockholm and Tromsø.

    I'll take parts 2 and 3 in a separate PR that doesn't touch solar, so the two shouldn't conflict:

    • crontab: a spec whose day_of_month never occurs in its month_of_year (Feb 30, Apr 31, …) raises ValueError when it's created, the same way crontab(minute=61) already does. It no longer crashes beat at runtime.
    • beat: if one entry's is_due() raises, beat logs the error, names the entry, and tries that entry again after max_interval. The other periodic tasks keep running.

    Part 3 also keeps beat alive until the solar fix lands. With the King George Island entry from the report, beat on main exits immediately, and with the change it logs the TypeError and keeps sending the healthy entry.

  4. added a commit that references this issue on Oct 19, 2026
    8cf9598
  5. added this to the 5.7.0 milestone on Oct 19, 2026
  6. added theissue type on Oct 20, 2026
  7. added a commit that references this issue on Oct 20, 2026
    c13d621
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions