Skip to content

Convert timedelta to milliseconds with integer arithmetic - #4571

Merged
petyaslavova merged 3 commits into
redis:masterfrom
ericdelorefice:fix-timedelta-expiry
Nov 6, 2026
Merged

petyaslavova merged 3 commits into
redis:masterfrom
ericdelorefice:fix-timedelta-expiry

Conversation

@ericdelorefice

@ericdelorefice ericdelorefice commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Title: Convert timedelta to milliseconds with integer arithmetic

Description of change

Passing a timedelta to a millisecond command goes through a float and can come out 1 ms low. timedelta(milliseconds=1001) is sent as 1000, because 1.001 * 1000 is 1000.9999999999999 and int() truncates it. For whole millisecond values from 1 to 100000, 741 come out one short.

What master sends, with execute_command stubbed to return its arguments:

pexpire("k", timedelta(milliseconds=1001))        -> ('PEXPIRE', 'k', 1000)
psetex("k", timedelta(milliseconds=1001), "v")    -> ('PSETEX', 'k', 1000, 'v')
hpexpire("h", timedelta(milliseconds=1001), "f")  -> ('HPEXPIRE', 'h', 1000, 'FIELDS', 1, 'f')
set("k", "v", px=timedelta(milliseconds=1001))    -> ('SET', 'k', 'v', 'PX', 1000)

Before #916 this was worked out from days, seconds and microseconds, so positive values came out exact. #916 (Drop Python 2.6 support) switched it to int(td.total_seconds() * 1000). This PR goes back to integer arithmetic.

I added a small private helper, _timedelta_to_ms, in redis/utils.py and used it in pexpire, psetex, hpexpire, spexpire and the px path of extract_expire_flags (which set, getex, hsetex, hgetex and the other px= methods go through). saddex, increx and msetex take the same px path; they are covered by the extract_expire_flags unit test only. It does td // timedelta(milliseconds=1), and for a negative timedelta it still truncates toward zero the way int() did. The seconds commands (expire, setex, hexpire, sexpire and the ex path) are not touched.

Tests: sync and async tests for pexpire, psetex and hpexpire check the argument sent and then run the command against the server. A unit test covers the px path, and another pins negative values (-1001 ms to -1001, -1500.3 ms to -1500, -0.5 ms to 0). spexpire has sync and async argument-level tests only, since SPEXPIRE needs Redis 8.11.240 and my local server is 8.10.3. The new tests fail on master. Verified on Redis 8.10.3.

Pull Request check-list

  • Do tests and lints pass with this change? (ruff check, ruff format --check and vulture are clean. Locally the full non-cluster suite fails the same tests on master and on this branch. Those need things my setup doesn't have, like modules, sentinel and TLS, plus a few geo and CLIENT SETINFO tests that differ on 8.10.3.)
  • 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.)
  • Is there an example added to the examples folder (if applicable)? (Not applicable.)

I used Claude Code to help with this; I've checked and can explain every line.


Note

Low Risk
Tightens millisecond TTL math for timedelta inputs with behavior intended to match prior truncation semantics; low risk beyond subtly longer/shorter expirations for some edge timedeltas.

Overview
Fixes millisecond conversions for timedeltas so they no longer lose 1 ms due to floating-point scaling.

This introduces _timedelta_to_ms in redis/utils, using integer floor division (with a symmetric path for negatives that still truncates toward zero like int()). It replaces int(td.total_seconds() * 1000) in pexpire, psetex, spexpire, and hpexpire, and switches the px= timedelta branch in extract_expire_flags (used by SET, GETEX, field/hash setters, etc.) to the helper.

Adds targeted sync/async tests that assert the exact Redis argument for tricky values like 1001ms, plus unit tests for negative deltas in extract_expire_flags.

Reviewed by Cursor Bugbot for commit a8cfae8. Bugbot is set up for automated code reviews on this repo. Configure here.

pexpire, psetex, hpexpire and set(px=...) converted a timedelta with
int(td.total_seconds() * 1000). That goes through a float and can land
1 ms low: timedelta(milliseconds=1001) was sent as 1000.

Use timedelta floor division instead, keeping truncation toward zero
for negative values. Seconds-based conversions are unchanged.
@ericdelorefice
ericdelorefice marked this pull request as ready for review November 4, 2026 15:56
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-06T12:37:39.355542Z a8cfae8 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.

@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 @ericdelorefice, thank you for your contribution!

The bug is real: a timedelta that should go out as 1001 ms is sent as 1000, and integer division fixes it.

Before merging, please:

  • Apply _timedelta_to_ms in spexpire too, with an argument-level test like the pexpire one. That covers all the millisecond conversions in this mixin.
  • Hoist timedelta(milliseconds=1) and timedelta(0) to module-level constants, so the helper does not create them on every call.

Please leave the "0 deletes" question out of this PR. If you want to pursue it, open an issue for it.

spexpire converted a timedelta with int(td.total_seconds() * 1000) too.
Route it through _timedelta_to_ms and add sync and async argument-level
tests. Make timedelta(0) and timedelta(milliseconds=1) module-level
constants so the helper does not build them on every call.
@ericdelorefice

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @petyaslavova. The two code changes are in fe9ed34:

  • spexpire now goes through _timedelta_to_ms, with sync and async argument-level tests like the pexpire ones. Unlike those, they don't call the server, because SPEXPIRE needs 8.11.240 and I have 8.10.3 locally. They fail with the old conversion and pass with the helper.
  • timedelta(0) and timedelta(milliseconds=1) are now module-level constants in redis/utils.py.

I also took the "0 deletes" question out of the description.

@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 changes look good, so I'm approving this.

@petyaslavova
petyaslavova merged commit e1aa4e6 into redis:master Nov 6, 2026
petyaslavova added a commit that referenced this pull request Nov 12, 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]>
petyaslavova added a commit that referenced this pull request Nov 16, 2026
* Convert timedelta to milliseconds with integer arithmetic

pexpire, psetex, hpexpire and set(px=...) converted a timedelta with
int(td.total_seconds() * 1000). That goes through a float and can land
1 ms low: timedelta(milliseconds=1001) was sent as 1000.

Use timedelta floor division instead, keeping truncation toward zero
for negative values. Seconds-based conversions are unchanged.

* Use the integer conversion in spexpire, hoist helper constants

spexpire converted a timedelta with int(td.total_seconds() * 1000) too.
Route it through _timedelta_to_ms and add sync and async argument-level
tests. Make timedelta(0) and timedelta(milliseconds=1) module-level
constants so the helper does not build them on every call.

---------

Co-authored-by: petyaslavova <[email protected]>
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