Skip to content

time: round Duration.to*() conversions up instead of truncating - #499

Merged
lalinsky merged 2 commits into
mainfrom
fix/timer-timeout-rounding
Jun 21, 2026
Merged

lalinsky merged 2 commits into
mainfrom
fix/timer-timeout-rounding

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Problem

Duration.to{Microseconds,Milliseconds,Seconds,Minutes}() floored when converting to a coarser unit. As a result a sub-millisecond timer deadline (e.g. ~0.2ms) converted to a 0ms timeout.

The blocking event-loop polls take a millisecond timeout:

  • epoll_wait / poll (Linux) and IOCP (Windows) — all millisecond-granularity.

So when the next timer was less than 1ms away, the loop was handed timeout = 0, epoll_wait returned immediately, and the loop busy-spun (~400k iterations/sec in the repro) until the deadline actually arrived. kqueue and io_uring use nanosecond timespecs and were unaffected — which is exactly why the high CPU was only reported on the epoll backend.

Fix

Round these conversions up so a non-zero duration never collapses to a zero wait. The saturating add keeps Duration.max from overflowing.

This eliminates the truncation regardless of timer distribution. In the repro from the issue, epoll wakeups drop ~1000× and CPU returns to normal.

Added a unit test covering the round-up behavior (sub-unit, exact, and saturation cases).

Refs #493

A sub-unit duration was floored, so a sub-millisecond timer deadline became
a 0ms timeout. Timeout-based polls (epoll_wait, poll, IOCP) then return
immediately and busy-spin until the deadline actually arrives, burning CPU.
kqueue/io_uring use nanosecond timespecs and were unaffected, which is why
high CPU was only observed on the epoll backend.

Round up in to{Microseconds,Milliseconds,Seconds,Minutes}() so a non-zero
duration never converts down to a zero wait. The addition saturates so the
maximum value does not overflow.

Refs #493

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9feb4382-39e2-4eea-ad40-3c55e206b225

📥 Commits

Reviewing files that changed from the base of the PR and between 1c4b3e8 and 660a5ae.

📒 Files selected for processing (1)
  • src/time.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/time.zig

📝 Walkthrough

Walkthrough

Duration's unit conversion methods (toMicroseconds, toMilliseconds, toSeconds, toMinutes) switch from truncating division to ceiling division. A new internal ceilDiv helper computes value / divisor + (value % divisor != 0). The conversion methods apply this helper in branches where the target unit is coarser than the internal nanosecond unit. A new test verifies ceiling behavior for sub-unit remainders and confirms Duration.max conversions don't overflow.

Duration ceiling rounding

Layer / File(s) Summary
Ceiling division helper, conversion method updates, and test
src/time.zig
New ceilDiv(value, divisor) helper handles ceiling arithmetic. Conversion methods toMicroseconds, toMilliseconds, toSeconds, and toMinutes use ceilDiv instead of truncating division in coarser-unit branches. Test Duration: to* rounds sub-unit remainders up asserts that non-zero sub-unit remainders round up by 1 in the target unit, and validates that Duration.max.toMilliseconds() produces the mathematically correct ceiling value without overflow.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • lalinsky/zio#201: Introduced the Duration type and its initial conversion methods (toMicroseconds/toMilliseconds/toSeconds/toMinutes) that this PR directly modifies.

Poem

A nanosecond remainder won't disappear,
ceilDiv rounds it up, crystal clear.
No truncation games, just honest math,
Even Duration.max walks the safe path. 🕐
Round up or lose precision—that's the pragmatic way.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: rounding Duration conversion methods up instead of truncating when converting to coarser units.
Description check ✅ Passed The description clearly explains the problem (truncation causing busy-spinning), the root cause (millisecond-granularity timeouts), the fix (rounding up), and includes test coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/timer-timeout-rounding

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/time.zig`:
- Around line 803-805: The test for maximum Duration value in the ceiling
saturation boundary is incomplete. The call to Duration.max.toMilliseconds()
only verifies the function executes without crashing but does not assert the
actual returned value. Capture the return value from the toMilliseconds() method
call on Duration.max and add an explicit assertion to verify it matches the
expected maximum milliseconds value, ensuring the saturation behavior is
correctly tested for regressions.
- Around line 84-85: The ceiling division logic at lines 84-85 (and repeated at
lines 93-94, 102-103, and 111-112) uses saturating addition before division,
which produces incorrect results when the saturating pre-add overflows, making
the result 1 unit too small. Replace the saturating add approach with
quotient/remainder ceiling logic instead: calculate the quotient of self.value
divided by divisor, then calculate the remainder; if the remainder is non-zero,
add 1 to the quotient to get the correct ceiling value. Apply this fix pattern
to all four affected division blocks that currently use the (self.value +|
(divisor - 1)) / divisor pattern.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: caa09d8e-78da-4f7b-ba00-6e10daa1d2e7

📥 Commits

Reviewing files that changed from the base of the PR and between 30a00d5 and 1c4b3e8.

📒 Files selected for processing (1)
  • src/time.zig

Comment thread src/time.zig Resolved
Comment thread src/time.zig Resolved
The (value +| (divisor - 1)) / divisor form saturates the pre-add near
TimeInt max, swallowing the rounding term and yielding floor instead of
ceiling for the largest durations. Replace with quotient/remainder ceiling
(value / divisor + (value % divisor != 0)), which never overflows, and assert
the exact Duration.max result in the test.

Addresses CodeRabbit review on #499.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@lalinsky
lalinsky merged commit 19b8299 into main Jun 21, 2026
27 checks passed
@lalinsky
lalinsky deleted the fix/timer-timeout-rounding branch June 21, 2026 16:51
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.

1 participant