Skip to content

Fix 1 ms float drift in datetime-to-millisecond expiry conversions - #4595

Merged
petyaslavova merged 4 commits into
redis:masterfrom
0718lol:fix-datetime-pxat-float-drift
Nov 12, 2026
Merged

petyaslavova merged 4 commits into
redis:masterfrom
0718lol:fix-datetime-pxat-float-drift

Conversation

@0718lol

@0718lol 0718lol commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Description of change

Datetime arguments to the millisecond expiry commands went through
int(dt.timestamp() * 1000), which is exact for most instants but lands
1 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 2147483648001 instead of ...002:

>>> from datetime import datetime, timezone
>>> dt = datetime(2038, 1, 19, 3, 14, 8, 2000, tzinfo=timezone.utc)
>>> int(dt.timestamp() * 1000)
2147483648001

timestamp() rounds to the nearest double, and in the binades where the
milliseconds 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 through
2004-11-04 and 2038-01-19 through 2038-12-03), that rounding error
survives the * 1000 multiplication and int() truncates across the
integer boundary. Mid-binade instants are exact, which is why the drift
is easy to miss.

This is the same float-multiplication defect fixed for timedelta
arguments in #4571; the four datetime call sites kept the old pattern:

  • redis/utils.py extract_expire_flags(pxat=...) (used by SET ... PXAT,
    EXPIRE/GETEX and friends)
  • pexpireat
  • hpexpireat
  • spexpireat

The fix converts through the exact integer microseconds of the timedelta
to the epoch, reusing _timedelta_to_ms from #4571 so the truncation
toward zero that int() applied to pre-epoch instants is preserved.
astimezone() keeps naive datetimes meaning the system timezone, the
same way datetime.timestamp() interprets them (verified to agree with
timestamp() on every existing wall-clock hour of 2026 in five
timezones, including the 30-minute DST zone; nonexistent spring-forward
times resolve to the neighboring offset, which both APIs already did
arbitrarily). exat is left alone: int(dt.timestamp()) is exact for
whole seconds and correctly truncates sub-second parts.

The new tests are argument-level only (they mock execute_command on a
lazily-constructed client), so they run without a server; they fail on
the old conversion and pass with the helper, like the spexpire
argument-level tests added in #4571.

Pull Request check-list

Please make sure to review and check all of these items:

  • Do tests and lints pass with this change?
  • Do the CI tests pass with this change (enable it first in your forked repo and wait for the github action build to finish)?
  • Is the new or changed code fully tested?
  • Is a documentation update included (if this change modifies existing APIs, or introduces new ones)? - no API change; docstrings unchanged
  • Is there an example added to the examples folder (if applicable)? - not applicable

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_ms helper 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 timedelta math (via existing _timedelta_to_ms) for timezone-aware datetimes and a seconds-plus-microseconds path for naive local times. pexpireat, hpexpireat, spexpireat, and extract_expire_flags(pxat=...) (SET/PXAT and related flows) now call it; second-granularity exat conversion is unchanged.

Adds mocked argument-level tests for the commands plus extract_expire_flags cases 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.

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).
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T15:41:51.925215Z b5fd2f7 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread redis/utils.py Outdated
# 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@petyaslavova petyaslavova left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread redis/utils.py Outdated
# 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread redis/utils.py


def _datetime_to_unix_ms(dt: datetime.datetime) -> int:
if dt.utcoffset() is None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 petyaslavova left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@petyaslavova
petyaslavova merged commit 250d2d9 into redis:master Nov 12, 2026
petyaslavova added a commit that referenced this pull request Nov 16, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants