Repository navigation
Wall-clock timers: per-clock heaps + std.Io sleep/futex/batch integration - #515
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (7)
🚧 Files skipped from review as they are similar to previous changes (7)
📝 WalkthroughWalkthroughAdds selectable clock sources ( ChangesClock-aware timer and timeout support
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/io.zig (1)
2100-2103: 🩺 Stability & Availability | 🟠 MajorUse clock-aware wait helper for connect timeouts.
Line 2102 calls
timedWaitForIo, which hardcodes.awakeas the clock. Ifoptions.timeoutspecifies an absolute deadline on.realor.boot, that deadline gets reinterpreted on the wrong clock epoch instead of timing out correctly.Use the clock-aware wait helper here too
- try timedWaitForIo(&connect_op.c, .fromStd(options.timeout)); + try timedWaitForIoClock( + &connect_op.c, + .fromStd(options.timeout), + .fromStdTimeout(options.timeout), + );🤖 Prompt for 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. In `@src/io.zig` around lines 2100 - 2103, The timedWaitForIo call on the connect_op operation is hardcoding the clock to .awake, which causes incorrect timeout behavior when options.timeout specifies an absolute deadline on .real or .boot clock types. Replace the timedWaitForIo call with a clock-aware wait helper function that properly respects the clock type specified in options.timeout, ensuring that absolute deadlines are evaluated against the correct clock epoch rather than being reinterpreted on .awake.
🤖 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/common.zig`:
- Around line 168-170: The early return path for the no-task case in
timedWaitFutex is dropping the clock parameter, causing wall-clock deadlines
(with `.real` or `.boot` clocks) to be compared against monotonic time later,
resulting in incorrect timeout durations. Before the early return that calls
timedWaitFutex on line 168, convert the deadline to a duration using the
provided clock parameter (similar to how it's done in the task path with the
timer initialization), then pass the converted duration instead of the raw
timeout. Apply the same fix to the similar code path mentioned at lines 188-196
where the same issue occurs.
In `@src/ev/loop.zig`:
- Around line 400-419: The setTimer and clearTimer methods incorrectly use
deadline.value > 0 to determine if a timer is already in the heap, but this
fails when a deadline is legitimately set to zero for an expired absolute
deadline, causing the timer to be inserted but marked as inactive and
potentially processed multiple times. Replace the deadline.value > 0 checks in
the conditional at the start of setTimer and the was_active assignment in
clearTimer with either a dedicated heap-membership flag or timer.c.state ==
.running to accurately track heap membership independent of deadline value.
---
Outside diff comments:
In `@src/io.zig`:
- Around line 2100-2103: The timedWaitForIo call on the connect_op operation is
hardcoding the clock to .awake, which causes incorrect timeout behavior when
options.timeout specifies an absolute deadline on .real or .boot clock types.
Replace the timedWaitForIo call with a clock-aware wait helper function that
properly respects the clock type specified in options.timeout, ensuring that
absolute deadlines are evaluated against the correct clock epoch rather than
being reinterpreted on .awake.
🪄 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: 71a68ba1-4d52-40ff-826a-7fed697bb335
📒 Files selected for processing (7)
src/common.zigsrc/ev/completion.zigsrc/ev/loop.zigsrc/ev/test/timer.zigsrc/io.zigsrc/sync/Futex.zigsrc/time.zig
Timers now carry a clock and live in one heap per wall-clock domain (awake/boot/real), since their deadlines are in different epochs and only comparable within a clock. CPU-time clocks are rejected (panic). - Clock gets explicit contiguous values so it indexes the heaps and the cached now[] directly via @intFromEnum. - now is cached per clock: awake refreshed eagerly each scan, boot/real lazily on first use and stamped with a scan counter, so an idle heap reads no clock and an active one reads at most once per scan. - No backend arms wall clocks natively yet, so boot/real fall back to folding their remaining into the poll timeout, bounded by wall_clock_cap (10s) so they re-evaluate across suspend/clock steps. The per-poll re-read of now(clock) is what makes the cap actually bound oversleep. Wiring backends natively (io_uring REALTIME/BOOTTIME, etc.) and the public sleep/timer APIs come in later steps.
Io.sleep / Clock.Timestamp.wait / Timeout.sleep carry a clock in Io.Timeout; thread it down to the timer so boot/real sleeps land in the right heap instead of all behaving as awake. - fromStd now keeps a deadline as a deadline (absolute, in its clock's epoch) instead of flattening it to a monotonic-relative duration. The old conversion subtracted the monotonic now from a possibly-foreign epoch, mishandling realtime deadlines; keeping the absolute value and comparing against now(clock) in the loop is both correct and simpler. - Waiter gains timedWaitClock; timedWait delegates with .awake, so the many existing callers are unchanged. - sleepImpl extracts the clock from the timeout and passes it through.
futexWait underlies every timed sync primitive (Mutex.timedLock, Condition.timedWait, Event.timedWait, timed Future await), so threading the clock here covers all of them. - Futex gains timedWaitClock; timedWait delegates with .awake. - Add Clock.fromStd (std.Io.Clock -> zio) and Clock.fromStdTimeout (pull the clock out of a std.Io.Timeout), replacing the io.zig-local zioClock helper and the duplicated extract-clock switches. Call sites use dot-inferred .fromStd / .fromStdTimeout.
The last vtable timeout entry point. Both batch paths now thread the clock instead of defaulting to awake: - multi-op wait loop uses Futex.timedWaitClock - single-op fast path threads the clock through operateInner into the file/net streaming impls via a new timedWaitForIoClock; timedWaitForIo delegates to it with .awake so the many non-batch I/O callers are unchanged. With sleep, futexWait and batchAwaitConcurrent all wired, every std.Io.Timeout now lands in the correct per-clock timer heap.
- Use timer.c.state == .running, not deadline.value > 0, as the in-heap flag. An absolute deadline can legitimately clamp to 0 (at/before the epoch), which the value sentinel mistook for inactive, leaking the timer in its heap and re-firing/spinning. The two agree everywhere else. - Convert a wall-clock (boot/real) deadline to a monotonic-relative duration before the no-task futex fallback; otherwise it compared an absolute realtime timestamp against monotonic time and waited for decades. Marked TODO to support boot/real natively there (Linux futex can wait on CLOCK_REALTIME).
0412973 to
5903833
Compare
…-4196)
## Problem
A timed wait on a plain thread (not a zio task), such as
`Event.waitTimeout(.{ .deadline = d })`, read the clock twice before it
started to wait:
1. `futexTimeout` turned the deadline into a duration:
`Timestamp.now(clock).durationTo(d)`.
2. `timedWaitFutex` turned that duration back into a deadline:
`timeout.toDeadline()`, on the monotonic clock.
A thread held up between the two reads waits that long past `d`. Shown
before any fix (ran): a test hook holds the thread between the two reads
until `d` has passed, with `d` 1 s ahead. Three runs at a26aae9 returned
1004, 1004 and 1003 ms after the deadline, each with the hold run once.
The second read was also on the monotonic clock, whatever clock the caller
named. `Clock.monotonic` is an alias of `Clock.awake` (`src/time.zig`), so
for an awake deadline (every `Event`, `Waiter.timedWait`) the two reads
are one clock and only the hold matters. For a boot or real deadline
(`std.Io` sleep and futex waits on a thread, `zio.Futex` with a clock),
the deadline was converted once and never looked at again.
The conversion came in with upstream 5903833 ("ev: address review on
per-clock timer heaps", PR lalinsky#515), as a fix for comparing a real deadline
with monotonic time. It is unchanged on upstream main at 9bef33d
(`src/common.zig:628`), with its own "best-effort" note.
## Changes
`src/common.zig`, `Waiter`:
- `timedWaitClock` turns a duration into a deadline on the caller's clock
once (`toDeadlineOn(clock)`) and passes the deadline and the clock to
`timedWaitFutex`. `futexTimeout` is removed.
- `timedWaitFutex` loops over `futexPass`: check the state, read the
caller's clock once, hand the time left straight to the kernel. It reads
the clock again after every return, a kernel timeout included, so a
timeout is only reported once the caller's own clock is at or past the
deadline.
- The doc comment on `timedWaitFutex` says what a relative kernel wait can
still add (below).
- `test_hold_before_futex`, a test-only thread-local hook, called only in
test builds (`builtin.is_test`), between taking in the timeout and the
wait.
`src/sync/Event.zig`, two tests on plain threads:
- "a plain thread held before its wait still times out at its deadline":
the hold above, then the wait must return Timeout less than 500 ms after
`d` (the defect returns about 1 s after it; never less, the clock is
monotonic). It asserts the hold ran once.
- "a plain thread's timeout never ends before its deadline": eight waits of
0.3 to 8.9 ms (odd lengths); after each Timeout the awake clock must be at
or past the deadline.
## Benefits
- One deadline, on the caller's clock, read once per kernel wait. The
reviewer's sequence (900 ms captured at 100 ms, held until 1.5 s, a new
deadline at 2.4 s) now returns at 1.5 s.
- A real deadline is checked again on the real clock after every kernel
return, so a wall clock step back no longer ends the wait early.
- No change on the task path or in the simulator: the change is inside the
`.thread` branch.
## What a relative kernel wait still adds (ran, and read)
- A thread held up between the one clock read and the futex call still
waits the full time it read. Shown (ran, not committed): the hook moved
into `futexPass` between the read and `n.timedWait`; three runs returned
1001, 1003 and 1002 ms late. A loop cannot close this. Only an absolute
kernel wait can: Linux FUTEX_WAIT_BITSET takes an absolute time on
CLOCK_MONOTONIC or CLOCK_REALTIME. Darwin's `__ulock_wait` takes only an
interval (read: `src/os/thread.zig`, `FutexDarwin.timedWait`).
- Each kernel wait times an interval on a clock that stops in a system
sleep (read: Linux FUTEX_WAIT without a clock flag is CLOCK_MONOTONIC;
on Darwin `awake` is CLOCK_UPTIME_RAW, and the ulock timeout runs on
mach absolute time, which I take from the platform documentation, not
from a run). An awake deadline is on that same clock, so a sleep moves
both and nothing is mixed. A boot or real deadline that passes during a
sleep is noticed when the current kernel wait ends, after its awake time
runs out. Not run: this Mac cannot be put to sleep in this sitting.
## Alternatives considered and rejected
- Convert once, onto the clock the futex waits on, and keep the rest.
Rejected: the conversion is the defect. For an awake deadline there is
nothing to convert, and for boot or real a one-time conversion loses
every later step or sleep.
- Linux FUTEX_WAIT_BITSET with an absolute deadline. It closes the last
window on Linux for awake and real deadlines. Not done here: it is a new
kernel call on one platform, Darwin has no equal, and the brief was to
keep this small. The upstream TODO this removes named the same call.
- Cap each kernel wait (for example 1 s) so a boot deadline is seen soon
after a system sleep. Rejected for now: it turns every long wait into a
poll, for a case no caller here has.
- Take upstream's fix. There is none: no commit, issue or PR on
lalinsky/zio changes or discusses this conversion after 5903833 (read:
`gh search issues`/`gh search prs` for futexTimeout, deadline, timedWait,
clock, monotonic, suspend, thread wait; the log of `src/common.zig` on
origin/main).
What this rests on: `Clock.monotonic == Clock.awake`; the kernel's
interval waits never end early on the awake clock (and if one does, the
loop waits again); the hook stands in for a deschedule at that one point
only.
## Mutants (ran, against both new tests)
- the old two-read conversion: killed (1004, 1004, 1003 ms late).
- Timeout with up to 1 ms left: killed (pass 0 ended 281944 ns early).
- read the real clock for an awake deadline: killed (297277 ns early).
- trust a kernel timeout without reading the caller's clock again:
survives. It differs only when a kernel wait ends before the caller's
clock reaches the deadline (a wall clock step back, or Darwin's interval
rounded down to whole microseconds and the kernel ending exactly on
time); neither happened in eight passes here.
- two reads moved inside `timedWaitFutex`: survives. The hook sits before
`timedWaitFutex`, so it cannot hold a thread between two reads that the
mutant adds after it.
## Statistics
- `src/common.zig`: +48 / -41
- `src/sync/Event.zig`: +66 / -0 (two tests)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Stacked on #513 (
clock-resolution).Makes
awake/boot/realtimers behave distinctly and wires the clock through everystd.Iotimeout, so boot/real sleeps and absolute realtime deadlines work end-to-end. Per-backend native arming (io_uring REALTIME/BOOTTIME, etc.) is intentionally not here — that's the next PR.Per-clock timer heaps (
ev)ev.Timercarries aclock; timers live in one heap per wall-clock domain (awake/boot/real), since their deadlines are in different epochs and only comparable within a clock. CPU-time clocks are rejected (panic).Clockgets explicit contiguous values so it indexes the heaps and the cachednow[]directly via@intFromEnum.nowis cached per clock:awakerefreshed eagerly each scan,boot/reallazily on first use and stamped with a scan counter — an idle heap reads no clock, an active one reads at most once per scan.boot/realfall back to folding their remaining into the poll timeout, bounded bywall_clock_cap(10s) so they re-evaluate across suspend/clock-steps. The per-poll re-read ofnow(clock)is what makes the cap bound oversleep.std.Io integration
The vtable has exactly three timeout entry points; all now thread the clock:
sleep—sleepImplcarries the clock;fromStdnow keeps a deadline as an absolute deadline (in its clock's epoch) instead of flattening it to a monotonic-relative duration. The old conversion subtracted the monotonic now from a possibly-foreign epoch, which mishandled realtime deadlines.futexWait— underlies every timed sync primitive (Mutex.timedLock,Condition.timedWait,Event.timedWait, timedFuture.await); wiring it covers all of them.batchAwaitConcurrent— both the multi-op wait loop and the single-op fast path (operateInner) thread the clock.Threading uses
*Clockvariants (Waiter.timedWaitClock,Futex.timedWaitClock,timedWaitForIoClock) that the existing.awakecallers delegate to unchanged, plusClock.fromStd/Clock.fromStdTimeouthelpers.Testing
boot(duration) andreal(absolute deadline) timers fire via the fallback path.io.sleeponboot/real, and sleeping until an absolute realtime deadline (would have hung atDuration.maxbefore thefromStdfix).Known minor gaps (acceptable, noted in comments)
timedWaitFutexfallback is monotonic-only, so boot/real degrade to awake when there's no fiber.nowis anchored at sleep-time, not wake-time (deliberate).Next PR
Per-backend native wall-clock arming (io_uring
IORING_TIMEOUT_ABS|REALTIME/BOOTTIME, epoll timerfd, IOCP waitable timer, kqueueEVFILT_TIMER), gated by anative_wall_timerscapability that makescheckTimersstop folding boot/real into the poll timeout for that backend.