Skip to content

Keep beat's tick delay within the entry's next check - #10908

Open
simpleqt wants to merge 1 commit into
celery:mainfrom
simpleqt:fix/beat-tick-delay-precision
Open

simpleqt wants to merge 1 commit into
celery:mainfrom
simpleqt:fix/beat-tick-delay-precision

Conversation

@simpleqt

@simpleqt simpleqt commented Oct 21, 2026 •

Copy link
Copy Markdown

Keep beat's tick delay within the entry's next check

Scheduler.tick() returns how long beat should sleep before looking at the
schedule again, and it computes that by subtracting two absolute epoch
timestamps built by _when():

return min(event[0] - now, max_interval)

At today's epoch magnitude a float resolves to only 2⁻²² s ≈ 0.24 µs, so that
difference comes back up to 0.12 µs longer than the delay the entry asked
for, and beat sleeps past the next check it just computed:

entry next check : 0.99
base  tick()     : 0.9900000095367432   <- longer than the entry's own next check
fixed tick()     : 0.99

This is the invariant beat's own tests assert. test_pending_tick and
test_ticks check that bound against the real clock, so on main they fail
only when the timestamp at that moment happens to round up — they are
timing-dependent rather than permanently red. (Raised by @MehrazRumman, who
measured 400/400 passes on macOS with Python 3.14; on this machine the
subtraction rounded up on every run I made.) The new fixed-clock test below is
the reliable regression check.

Change

A _delay_seconds(timestamp, now) helper truncates the recovered difference to
whole microseconds — the resolution of the datetimes the timestamps are built
from — and is used at the three tick() sites that subtract two _when()
timestamps:

def _delay_seconds(timestamp, now):
    return int((timestamp - now) * 1000000) / 1000000.0

int() truncates toward zero, so a delay is only ever shortened, never
lengthened. The min(adjust(reschedule_delay), max_interval) branch (the
negative-delay cases) is untouched.

The change can only make beat sleep less, so no caller can be delayed:
Service.start() (if interval and interval > 0.0: time.sleep(interval)), the
celery beat CLI, _Threaded, _Process and EmbeddedService (worker -B,
worker/components.py) all funnel through it.

Testing

This removes the rounding-up case behind two intermittent failures in beat's
own tests, and adds one deterministic regression test:

  • base (d6d754e2), untouched: pytest t/unit/app/test_beat.py -q → 2 failed, 165 passed
    on this machine, with the clock as it was during the run (these two are the
    timing-dependent pair above, so a run can also pass on main):
    • test_pending_tick — assert 0.9900000095367432 <= 0.99
    • test_ticks — assert 35.99000000953674 <= 35.99
  • with the fix: 168 passed
  • the new test_tick_delay_never_exceeds_the_entry_next_run uses a fixed clock
    and fails deterministically on the base source with
    assert 0.9900000095367432 == (1 - 0.01), so it does not depend on when it
    is run
  • whole suite, base → fix: 2 failed, 4732 passed, 242 skipped, 29 xfailed →
    4735 passed, 242 skipped, 29 xfailed (same skips/xfails; the only delta is
    the two failures plus the new test)
  • flake8 7.4.1 and isort 9.0.2 — the versions the repo pins — are clean

One caveat worth your call

The numeric effect is small (≤0.12 µs); its most visible consequence is removing
the intermittent failures in celery's own beat tests. If you would rather fix
the precision at the source (for example by keeping sub-microsecond information
out of _when() altogether) than truncate on read, say so and I will rework it
rather than have this land as a workaround.

Also: open PR #10167 edits celery/beat.py:tick() and
t/unit/app/test_beat.py for an unrelated optimisation, so whichever lands
second will need a small rebase.

AI assistance: this change was produced with AI assistance (an autonomous coding
agent); the analysis, the reproduction, the before/after test runs and the lint
runs were executed locally, and a human reviewed the result before submission.

Scheduler.tick() recovers the delay until the top entry's next check by
subtracting two absolute timestamps built by _when().  At today's epoch
magnitude a float only resolves to about 0.24 microseconds, so that
difference came back up to 0.12 microseconds longer than the delay the
entry had asked for -- a delay the scheduler, having no better value,
then slept past.

Cut the recovered delay back to the microsecond resolution of the
datetimes the timestamps are built from.  The invariant is covered by
test_beat's pending/ticks tests and by a new one that pins it with a
fixed clock.

Signed-off-by: simpleqt <[email protected]>
Copilot AI lite review requested due to automatic review settings October 21, 2026 15:30

Copilot AI 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.

🔵 Needs a closer look

Two moderate review comments remain regarding preserving requested precision and negative-delay behavior.

No open issues 🎉

What changed in this PR

This PR adjusts Celery Beat’s tick-delay calculation to prevent floating-point oversleeping.

Changes:

  • Adds microsecond delay truncation.
  • Applies it across relevant Scheduler.tick() paths.
  • Adds regression coverage.
File Summary
t/​unit/​app/​test_beat.py Adds precision regression coverage.
celery/​beat.py Implements and applies delay quantization.

Review effort: Lite

@codecov

codecov Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.63%. Comparing base (d6d754e) to head (a70c3b7).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10908   +/-   ##
=======================================
  Coverage   90.63%   90.63%           
=======================================
  Files         153      153           
  Lines       21471    21473    +2     
  Branches     2634     2634           
=======================================
+ Hits        19461    19463    +2     
  Misses       1697     1697           
  Partials      313      313           
Flag Coverage Δ
unittests 90.62% <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.

@auvipy
auvipy self-requested a review October 21, 2026 16:39

@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 a70c3b7. t/unit/app/test_beat.py: 168 passed.

The precision problem is real. The new fixed-clock test fails on main with assert 0.9900000095367432 == (1 - 0.01), so subtracting two absolute epoch floats from _when() can give a delay slightly longer than the entry's next check. Truncating to whole microseconds can only shorten the sleep, so it's a safe fix.

On the "two tests already fail on main" part: I couldn't reproduce that. On macOS with Python 3.14, test_pending_tick and test_ticks passed on main in 400 of 400 runs (pytest --count=200 on both). Those two tests use the real clock, so whether the subtraction rounds up depends on the timestamp at that moment. They are flaky rather than always failing, and CI on current main passes. The new fixed-clock test is the reliable regression check. It would help to reword that part of the description so it doesn't read as main being red.

On the open question: truncating on read is fine with me. Fixing it at the source would mean computing the delay from the datetimes before they become epoch floats, which touches _when() and the heap entries, a much bigger change for a sub-microsecond effect.

Looks good to me.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants