Skip to content

Return the exact fractional utcoffset() instead of rounding it - #10625

Merged
auvipy merged 6 commits into
celery:mainfrom
bodapatisaikrishna:fix/utcoffset-fractional-hour-truncation
Sep 18, 2026
Merged

auvipy merged 6 commits into
celery:mainfrom
bodapatisaikrishna:fix/utcoffset-fractional-hour-truncation

Conversation

@bodapatisaikrishna

@bodapatisaikrishna bodapatisaikrishna commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Description

celery.utils.time.utcoffset() computes the local UTC offset in whole hours
from time.timezone/time.altzone (seconds west of UTC) using floor
division (// 3600). For any fractional-hour, east-of-UTC timezone
(India, Sri Lanka, Iran, Afghanistan, Myanmar, Nepal, parts of Australia, all
at a 30- or 45-minute offset), this rounds the magnitude up instead of
truncating:

>>> -19800 // 3600      # UTC+5:30 (India), floor-divided
-6                       # implies UTC+6:00, a full hour off

That's a full-hour error for east-of-UTC zones. West-of-UTC fractional zones
don't hit this specific floor-vs-truncation asymmetry (floor and truncation
agree for positive dividends), but they're not correct on main either —
they're still truncated to a whole hour, which is 15-30 minutes off from the
real offset. main is only exact for whole-hour zones.

This PR fixes both: instead of rounding to a whole hour at all, utcoffset()
now returns the exact fractional offset via true division:

>>> -19800 / 3600
-5.5                     # exact, matches UTC+5:30

utcoffset() feeds celery/events/dispatcher.py (attached to every worker
event) and celery/events/receiver.py's adjust_timestamp() (used to
normalize event timestamps across workers in different timezones), and
adjust_timestamp() does pure arithmetic on this value, so keeping it exact
rather than rounded avoids skewing cross-timezone timestamp correction for
any fractional-hour zone, east or west.

Whole-hour zones now get a float back (e.g. 5.0 instead of 5) rather
than an int. This doesn't change the arithmetic anywhere utcoffset() is
consumed, and the function was already annotated -> float, so this brings
the implementation in line with the type it already claimed to return.

This is a different function from LocalTimezone.fromutc() (fixed in #10519
for a related but distinct negative-offset bug; that one lost the sign
entirely via timedelta.seconds, this one mis-rounds the magnitude for
fractional hours via //). LocalTimezone.__repr__ a few lines above the
function I'm fixing already reports the equivalent seconds-to-hours
conversion without floor-dividing (int(x.total_seconds() / 3600) truncates
toward zero rather than flooring); this fix goes one step further for
utcoffset() and skips rounding entirely.

Testing

Added test_utcoffset_whole_hour_unaffected (confirms no behavior change for
ordinary whole-hour zones, aside from the int → float type), plus
test_utcoffset_fractional_hour_offset and
test_utcoffset_quarter_hour_offset (regression tests for 30- and 45-minute
offsets, covering both STD and DST branches) to t/unit/utils/test_time.py.

$ pytest t/unit/utils/test_time.py -q
65 passed
$ pytest t/unit/events/ -q
100 passed, 1 skipped

Confirmed the new fractional-hour tests fail on current main and pass with
this fix.

flake8 and isort --check-only clean on both changed files.

time.timezone/time.altzone are seconds west of UTC. utcoffset()
converted them to whole hours with `// 3600`, which floor-divides:
for a fractional-hour, east-of-UTC zone (India/Sri Lanka/Iran at
UTC+5:30, seconds = -19800), this rounds the magnitude up
(-19800 // 3600 == -6) instead of truncating to the correct -5.
West-of-UTC fractional offsets are unaffected, since floor and
truncation agree for positive dividends -- this is a sign asymmetry,
not a general precision limitation.

utcoffset() feeds events/dispatcher.py (attached to every worker
event) and events/receiver.py's adjust_timestamp() (cross-timezone
event timestamp correction), so a worker in one of these locales
skews its reported offset by a full hour.

Different bug from LocalTimezone.fromutc() (celery#10517/celery#10519), which
lost the sign entirely via timedelta.seconds; this one only
mis-rounds the magnitude for fractional hours via `//`.
LocalTimezone.__repr__ a few lines above already truncates the
equivalent seconds-to-hours conversion -- this matches that existing
pattern instead of floor-dividing.

Added regression tests pinning both the fractional-hour case and
confirming whole-hour zones are unaffected.
@auvipy

auvipy commented Sep 14, 2026

Copy link
Copy Markdown
Member

@MehrazRumman you can review this

@MehrazRumman

Copy link
Copy Markdown
Contributor

OK @auvipy !

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

The sign-asymmetry analysis is right, but I don't think truncation is the correct target — it's a lateral move for :30 zones and a regression for :45 ones.

time.timezone / 3600 for UTC+5:30 is exactly -5.5. Floor gives -6, truncation gives -5; both are 30 minutes wrong, just in opposite directions. So calling -5 "correct" isn't quite right — neither value is. And for the quarter-hour zones truncation is strictly worse:

zone time.timezone true floor (main) trunc (PR) floor err PR err
India +5:30 -19800 -5.50 -6 -5 30m 30m
Iran +3:30 -12600 -3.50 -4 -3 30m 30m
Nepal +5:45 -20700 -5.75 -6 -5 15m 45m
Chatham +12:45 -45900 -12.75 -13 -12 15m 45m
Eucla +8:45 -31500 -8.75 -9 -8 15m 45m

Nepal, Chatham and Eucla get 30 minutes worse under this patch, and no listed zone gets better.

The rounding itself is what's unnecessary. utcoffset() is already annotated -> float, and its only consumer is

def adjust_timestamp(ts, offset, here=utcoffset):
    return ts - (offset - here()) * 3600

which is pure arithmetic. I grepped the tree: the value is placed in the event dict in events/dispatcher.py and read back through itemgetter in events/receiver.py, and nothing formats it as an int. So just dropping the rounding:

if localtime().tm_isdst:
    return time.altzone / 3600
return time.timezone / 3600

makes adjust_timestamp() exact for every zone, whole-hour and fractional alike, instead of trading one 30-minute error for another. Whole-hour zones are unaffected (18000 / 3600 == 5.0). adjust_timestamp's offset: int annotation would want widening to float, and a mixed old/new fleet still computes correctly since both sides are just doing arithmetic.

One note on the justification: LocalTimezone.__repr__ truncates because it formats with :+03d, which requires an int for display. That's not really a precedent for the arithmetic path.

As written, test_utcoffset_fractional_hour_offset pins -5 for India, which would lock in the 30-minute error and make the exact fix a test change later. Worth retargeting the test to -5.5 and covering Nepal too, since :45 is where the two roundings actually diverge.

Review on the previous commit (truncate instead of floor) showed
truncation is not actually a fix: for a :30 zone like India it is
30 minutes off, same as floor, just in the other direction, and for
a :45 zone (Nepal +5:45, Chatham/Eucla +8:45) truncation is 45
minutes off versus floor's 15 -- strictly worse, not better.

The rounding itself was never needed. utcoffset()'s only consumer,
adjust_timestamp(), does plain float arithmetic, and the value's
only other use is passed through the event dict in
events/dispatcher.py and read back via itemgetter in
events/receiver.py -- nothing requires an int. Returning
time.timezone/altzone / 3600 directly (no floor, no truncation) is
exact for every zone, fractional or whole-hour alike.

adjust_timestamp()'s offset parameter is widened from int to float
to match, since it now receives fractional values.

Tests updated: the India case now asserts the exact -5.5 instead of
pinning the previously-"fixed" but still-wrong -5, and a new test
covers a :45 zone (Nepal, -5.75), which is where floor and
truncation actually diverge in how wrong they are.
@bodapatisaikrishna

bodapatisaikrishna commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor Author

thanks you're right that truncation just trades one wrong direction for another, and is worse for the :45 zones. Pushed 8bdb29b, which drops the rounding entirely and returns the exact float (time.timezone / 3600, no int()). Verified the only consumers (adjust_timestamp and the event dict round-trip through dispatcher.py/receiver.py) are fine with a float widened adjust_timestamp's offset param to float to match.

Updated test_utcoffset_fractional_hour_offset to assert the exact -5.5 for India instead of pinning -5, and added test_utcoffset_quarter_hour_offset covering Nepal (+5:45 → -5.75), which is where floor and truncation actually diverge in severity.

Comment thread celery/utils/time.py Resolved
@bodapatisaikrishna bodapatisaikrishna changed the title Truncate utcoffset() toward zero instead of floor-dividing Return the exact fractional utcoffset() instead of rounding it Sep 15, 2026
@auvipy auvipy added this to the 5.6.x milestone Sep 16, 2026
@codecov

codecov Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.14%. Comparing base (4debc05) to head (dabf1cd).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10625   +/-   ##
=======================================
  Coverage   89.13%   89.14%           
=======================================
  Files         153      153           
  Lines       20284    20284           
  Branches     2403     2403           
=======================================
+ Hits        18080    18082    +2     
+ Misses       1898     1897    -1     
+ Partials      306      305    -1     
Flag Coverage Δ
unittests 89.12% <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 modified the milestones: 5.6.x, 5.7.x Sep 16, 2026
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

@MehrazRumman the fix from your review is in (8bdb29b) and CI is green across the board now. Let me know if there's anything else you'd like changed.

@auvipy

auvipy commented Sep 16, 2026

Copy link
Copy Markdown
Member

@Amli @GangEunzzang

@auvipy auvipy modified the milestones: 5.7.x, 5.7.0 Sep 17, 2026

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

@bodapatisaikrishna @auvipy I tried this out locally — it's a real bug, and this fix looks right to me.

One small correction to the description: west-of-UTC fractional zones aren't really fine on main either. Floor and truncation happen to agree there, but the result is still not exact:

zone main here
UTC+5:30 India 30 min off exact
UTC+5:45 Nepal 15 min off exact
UTC-3:30 Newfoundland 30 min off exact
UTC-9:30 Marquesas 30 min off exact

That's the offset a UTC receiver ends up applying to timestamp through adjust_timestamp.

One other thing I noticed: whole-hour zones now send 5.0 instead of 5. It doesn't affect the arithmetic, but it is visible to anything else consuming the event stream.

Nothing blocking from me. LGTM!

@bodapatisaikrishna

bodapatisaikrishna commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Good catch, thanks you're right that the description overstated things. West-of-UTC fractional zones were never actually exact on main, they just didn't hit the floor-vs-truncation asymmetry that east-of-UTC zones do. Rewrote the description to say that plainly and match what the code actually does now (exact fractional offset via true division, not truncation).

On the 5 -> 5.0 change: agreed it doesn't affect the arithmetic. Worth noting utcoffset() was already annotated -> float on main, it just happened to always return an int at runtime, so this brings the implementation in line with the type it already claimed.

@Amli

Amli commented Sep 17, 2026

Copy link
Copy Markdown

Looks good to me too, nothing to add, I could find no impact on changes on the crontab remaining_estimate conducted in parallel.

@auvipy
auvipy merged commit 208a803 into celery:main Sep 18, 2026
20 checks passed
bodapatisaikrishna added a commit to bodapatisaikrishna/bodapatisaikrishna that referenced this pull request Sep 18, 2026
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.

6 participants