Repository navigation
Fix 1 ms float drift in datetime-to-millisecond expiry conversions - #4595
Conversation
int(dt.timestamp() * 1000) lands 1 ms low for instants whose seconds part sits just above a power of two (e.g. 2038-01-19T03:14:08.002Z is sent as ...001 instead of ...002). Convert through the exact integer microseconds instead, reusing the integer arithmetic approach from redis#4571 and keeping the same truncation semantics. Adds argument-level regression tests for pxat/pexpireat/hpexpireat/spexpireat (sync and async).
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fd08f80f24
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| # and _timedelta_to_ms keeps the truncation toward zero that int() | ||
| # applied to pre-epoch instants. astimezone() interprets a naive datetime | ||
| # in the system timezone, the same way datetime.timestamp() does. | ||
| return _timedelta_to_ms(dt.astimezone(datetime.timezone.utc) - _UNIX_EPOCH) |
There was a problem hiding this comment.
Avoid astimezone overflow for boundary datetimes
When an aware datetime is at Python's representable boundary and its offset moves the UTC instant outside years 1–9999 (for example, datetime.max with a -01:00 offset), this raises OverflowError on every supported Python line (3.11–3.14). The previous timestamp() path produced a valid Redis millisecond integer, so PEXPIREAT, SET ... PXAT, HPEXPIREAT, and SPEXPIREAT now fail before sending a command; subtracting the epoch directly for aware values avoids materializing the out-of-range UTC datetime while retaining the local-time conversion for naive values.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Hey @0718lol, thank you for your contribution!
The fix is correct and covers every float millisecond conversion on master. One change before merge: in _datetime_to_unix_ms, please subtract _UNIX_EPOCH directly for timezone-aware datetimes and call astimezone() only for naive ones. Aware subtraction is already exact. This avoids building an extra datetime on every call and also removes the OverflowError the Codex bot pointed out, for aware values whose UTC instant falls outside years 1-9999. The old timestamp() path handled those. Please add a test for that boundary case.
Optional: the helper and test comments describe the old behavior ("landed 1 ms low"). Wording them as present-tense rationale would read better.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ad37fa2662
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| # Subtract the epoch for exact microsecond arithmetic. Converting an aware | ||
| # datetime to UTC first can overflow near the limits of datetime's range. | ||
| if dt.utcoffset() is None: | ||
| dt = dt.astimezone(datetime.timezone.utc) |
There was a problem hiding this comment.
Avoid overflowing naive boundary datetimes
When a naive value lies at the upper representable boundary, this conversion can still fail before any Redis command is sent: under the common TZ=UTC, datetime.max.timestamp() (the previous path) returns 253402300800.0, but datetime.max.astimezone(timezone.utc) raises ValueError because it tries to construct year 10000. Thus PEXPIREAT, SET ... PXAT, HPEXPIREAT, and SPEXPIREAT regress for a naive datetime.max even though the aware boundary case from the earlier review is now fixed; convert naive local time without materializing the out-of-range UTC datetime.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: eb0457e414
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
|
||
|
|
||
| def _datetime_to_unix_ms(dt: datetime.datetime) -> int: | ||
| if dt.utcoffset() is None: |
There was a problem hiding this comment.
Preserve TypeError for tzinfo objects without an offset
When a caller supplies a datetime with a non-None custom tzinfo whose utcoffset(dt) returns None, the previous datetime.timestamp() path raises TypeError on every supported Python version, but this condition now routes it through the local-time branch, strips the tzinfo, and sends a potentially incorrect expiration instead. Check dt.tzinfo is None before applying the naive conversion so PEXPIREAT, SET ... PXAT, HPEXPIREAT, and SPEXPIREAT retain their prior error semantics for this input.
AGENTS.md reference: AGENTS.md:L159-L163
Useful? React with 👍 / 👎.
petyaslavova
left a comment
There was a problem hiding this comment.
Thanks for the updates. Both boundary cases are handled now, and the tests cover them. About the latest Codex note on tzinfo objects whose utcoffset() returns None: Python's docs define such datetimes as naive, and astimezone() treats them the same way. So the local-time interpretation is correct, and no change is needed there. LGTM.
…4595) * Fix 1 ms float drift in datetime-to-millisecond expiry conversions int(dt.timestamp() * 1000) lands 1 ms low for instants whose seconds part sits just above a power of two (e.g. 2038-01-19T03:14:08.002Z is sent as ...001 instead of ...002). Convert through the exact integer microseconds instead, reusing the integer arithmetic approach from #4571 and keeping the same truncation semantics. Adds argument-level regression tests for pxat/pexpireat/hpexpireat/spexpireat (sync and async). * Avoid overflow when converting aware expiry datetimes * Preserve naive expiry datetimes at the upper boundary --------- Co-authored-by: 0718lol <[email protected]> Co-authored-by: petyaslavova <[email protected]>
Description of change
Datetime arguments to the millisecond expiry commands went through
int(dt.timestamp() * 1000), which is exact for most instants but lands1 ms low when the seconds part of the instant sits just above a power of
two. For example,
2038-01-19T03:14:08.002Z(unix time 2147483648 s +2 ms) is sent as
PEXPIREAT a 2147483648001instead of...002:timestamp()rounds to the nearest double, and in the binades where themilliseconds product has 512 times the ulp of the seconds value (the
seconds part is in
[2**k, 1.024 * 2**k), e.g. 2004-01-10 through2004-11-04 and 2038-01-19 through 2038-12-03), that rounding error
survives the
* 1000multiplication andint()truncates across theinteger boundary. Mid-binade instants are exact, which is why the drift
is easy to miss.
This is the same float-multiplication defect fixed for
timedeltaarguments in #4571; the four datetime call sites kept the old pattern:
redis/utils.pyextract_expire_flags(pxat=...)(used bySET ... PXAT,EXPIRE/GETEXand friends)pexpireathpexpireatspexpireatThe fix converts through the exact integer microseconds of the timedelta
to the epoch, reusing
_timedelta_to_msfrom #4571 so the truncationtoward zero that
int()applied to pre-epoch instants is preserved.astimezone()keeps naive datetimes meaning the system timezone, thesame way
datetime.timestamp()interprets them (verified to agree withtimestamp()on every existing wall-clock hour of 2026 in fivetimezones, including the 30-minute DST zone; nonexistent spring-forward
times resolve to the neighboring offset, which both APIs already did
arbitrarily).
exatis left alone:int(dt.timestamp())is exact forwhole seconds and correctly truncates sub-second parts.
The new tests are argument-level only (they mock
execute_commandon alazily-constructed client), so they run without a server; they fail on
the old conversion and pass with the helper, like the
spexpireargument-level tests added in #4571.
Pull Request check-list
Please make sure to review and check all of these items:
Transparency note: this PR was prepared with AI assistance (an automated
coding agent working from a documented reproduction script). The
reproduction, red/green test evidence and the reasoning above were
reviewed against the code at HEAD before submission; a human should
review it as with any contribution.
Note
Low Risk
Behavior change is limited to integer encoding of optional datetime expiry args; semantics stay the same except fixing off-by-one-ms cases. No auth or data-model impact.
Overview
Replaces
int(datetime.timestamp() * 1000)with a shared_datetime_to_unix_mshelper so millisecond absolute expiry arguments are encoded without the 1 ms drift that shows up near certain unix second boundaries (e.g. Y2038-style instants).The helper uses integer
timedeltamath (via existing_timedelta_to_ms) for timezone-aware datetimes and a seconds-plus-microseconds path for naive local times.pexpireat,hpexpireat,spexpireat, andextract_expire_flags(pxat=...)(SET/PXAT and related flows) now call it; second-granularityexatconversion is unchanged.Adds mocked argument-level tests for the commands plus
extract_expire_flagscases for edge instants, pre-epoch truncation, and extreme aware datetimes.Reviewed by Cursor Bugbot for commit b5fd2f7. Bugbot is set up for automated code reviews on this repo. Configure here.