Skip to content

Wall-clock timers: per-clock heaps + std.Io sleep/futex/batch integration - #515

Merged
lalinsky merged 5 commits into
mainfrom
clock-timer-heaps
Jun 23, 2026
Merged

lalinsky merged 5 commits into
mainfrom
clock-timer-heaps

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Stacked on #513 (clock-resolution).

Makes awake/boot/real timers behave distinctly and wires the clock through every std.Io timeout, 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.Timer carries a clock; 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).
  • 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 — an idle heap reads no clock, 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 bound oversleep.

std.Io integration

The vtable has exactly three timeout entry points; all now thread the clock:

  • sleep — sleepImpl carries the clock; fromStd now 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, timed Future.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 *Clock variants (Waiter.timedWaitClock, Futex.timedWaitClock, timedWaitForIoClock) that the existing .awake callers delegate to unchanged, plus Clock.fromStd / Clock.fromStdTimeout helpers.

Testing

  • ev: boot (duration) and real (absolute deadline) timers fire via the fallback path.
  • std.Io: io.sleep on boot/real, and sleeping until an absolute realtime deadline (would have hung at Duration.max before the fromStd fix).
  • Full suite green (492/492); Windows (wine) and macOS compile verified earlier in the series.

Known minor gaps (acceptable, noted in comments)

  • The no-task timedWaitFutex fallback is monotonic-only, so boot/real degrade to awake when there's no fiber.
  • The frozen-slice now is 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, kqueue EVFILT_TIMER), gated by a native_wall_timers capability that makes checkTimers stop folding boot/real into the poll timeout for that backend.

@coderabbitai

coderabbitai Bot commented Jun 23, 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: 43d8a1d8-6705-423b-a3db-8b75dd7d505f

📥 Commits

Reviewing files that changed from the base of the PR and between 0412973 and 5903833.

📒 Files selected for processing (7)
  • src/common.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/test/timer.zig
  • src/io.zig
  • src/sync/Futex.zig
  • src/time.zig
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/ev/completion.zig
  • src/time.zig
  • src/sync/Futex.zig
  • src/ev/test/timer.zig
  • src/common.zig
  • src/io.zig
  • src/ev/loop.zig

📝 Walkthrough

Walkthrough

Adds selectable clock sources (awake, boot, real) to timer completions, all timed-wait primitives, and every I/O timeout path. The event loop's single monotonic timer heap and now timestamp are replaced with per-wall-clock-domain arrays. Timeout.fromStd deadline semantics shift from monotonic-relative offsets to clamped absolute nanoseconds. Clock gains explicit u8 backing for direct array indexing.

Changes

Clock-aware timer and timeout support

Layer / File(s) Summary
Clock type infrastructure and Timeout contract
src/time.zig
Clock becomes enum(u8) with contiguous explicit values enabling array indexing. fromStd and fromStdTimeout map std.Io types to zio Clock. Timeout.fromStd deadline handling changes from monotonic-relative duration to clamped absolute nanoseconds via a new clampNanos helper.
Timer completion clock field and per-clock loop state
src/ev/completion.zig, src/ev/loop.zig
Timer gains a clock field defaulting to .awake with initClock constructor. LoopState's single now/TimerHeap become arrays indexed by Clock: now[wall_clock_count], now_tick[wall_clock_count] for lazy validation, tick for scan epochs, and timers[wall_clock_count] for per-domain heaps. clockIndex/indexClock map Clock to array indices (panic on CPU clocks). timer_mutex protects all per-domain state.
Scan-based caching, per-clock timer routing, and multi-domain firing
src/ev/loop.zig, src/ev/test/timer.zig
updateNow advances scan tick and refreshes awake timestamp (now[0]). nowFor(clock) lazily refreshes per-domain cached time on scan changes. setTimer/clearTimer route to correct heap via clockIndex, compute deadlines using nowFor. Loop.wall_clock_cap bounds oversleep for non-awake clocks. Loop.now() returns now[0]. checkTimers rewrites to iterate per-domain: advances scan once, peeks/fires timers per clock, accumulates earliest next_timeout across domains. Two timer tests verify .boot and .real absolute-deadline timers reach .dead state with correct elapsed time.
Clock-aware wait primitives
src/sync/Futex.zig, src/common.zig
Futex.timedWait wraps timedWaitClock(.awake); new timedWaitClock passes clock to Waiter.timedWaitClock. Waiter.timedWait delegates to timedWaitClock; task path calls ev.Timer.initClock(timeout, clock). futexTimeout helper converts wall-clock deadlines to monotonic-relative via Timestamp.now(clock).durationTo(deadline). timedWaitForIo delegates to timedWaitForIoClock which creates a race group with ev.Timer.initClock(timeout, clock).
Clock threading through io.zig operations and tests
src/io.zig
timedWaitForIoClock alias added. futexWaitImpl, operateImpl/operateInner, fileReadStreamingImpl, fileWriteStreamingImpl, batchAwaitConcurrentImpl, netReceiveImpl, nowImpl, clockResolutionImpl, and sleepImpl all accept and propagate time.Clock. nowImpl/clockResolutionImpl compute using time.*(.fromStd(clock)). sleepImpl uses Waiter.timedWaitClock. Tests cover io.sleep on .boot/.real and sleeping to absolute realtime deadlines.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • lalinsky/zio#194: Modifies the same LoopState.setTimer, clearTimer, and checkTimers paths to add mutex protection — directly adjacent to this PR's per-domain heap routing changes.
  • lalinsky/zio#238: Refactors Timer deadline handling in completion.zig and loop.zig timer scheduling, the exact structures this PR extends with clock selection.
  • lalinsky/zio#387: Introduces timedWaitForIo-based I/O timeout primitives in operateImpl/netReceiveImpl that this PR extends to the clock-aware timedWaitForIoClock variants.

Poem

⏰ One clock was never enough,
boot and real deserve their heaps.
nowFor checks the tick, no bluff,
each domain wakes from different sleeps.
The deadline's absolute now — no drift,
just clamped nanos, clean and swift.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: introducing per-clock timer heaps and integrating clock support into std.Io timeout mechanisms.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, explaining the implementation approach, integration points, and testing 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 clock-timer-heaps

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.

@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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

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 | 🟠 Major

Use clock-aware wait helper for connect timeouts.

Line 2102 calls timedWaitForIo, which hardcodes .awake as the clock. If options.timeout specifies an absolute deadline on .real or .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

📥 Commits

Reviewing files that changed from the base of the PR and between 842e5b4 and 0412973.

📒 Files selected for processing (7)
  • src/common.zig
  • src/ev/completion.zig
  • src/ev/loop.zig
  • src/ev/test/timer.zig
  • src/io.zig
  • src/sync/Futex.zig
  • src/time.zig

Comment thread src/common.zig Resolved
Comment thread src/ev/loop.zig Resolved
Base automatically changed from clock-resolution to main June 23, 2026 19:57
lalinsky added 5 commits June 23, 2026 21:59
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).
@lalinsky
lalinsky force-pushed the clock-timer-heaps branch from 0412973 to 5903833 Compare June 23, 2026 20:10
@lalinsky
lalinsky merged commit 48c4fc5 into main Jun 23, 2026
27 checks passed
@lalinsky
lalinsky deleted the clock-timer-heaps branch June 23, 2026 20:18
dimenus pushed a commit to dimenus/zio that referenced this pull request Nov 16, 2026
…-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]>
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