Repository navigation
Conversation
- ev.Timer.delay_ms replaced with ev.Timer.delay: Duration - Loop.setTimer now takes Duration instead of u64 milliseconds - os.time.sleep now takes Duration instead of i32 milliseconds - Added Duration.toTimespec() for POSIX timespec conversion - Moved Clock enum from os/time.zig to time.zig - Exported os.timespec
- Add Timestamp type for points in time (nanoseconds since epoch) - fromNanoseconds, fromMilliseconds, fromTimespec constructors - toTimespec, durationTo, addDuration, subDuration methods - format() for "YYYY-MM-DD HH:MM:SS" output - Add Timeout union type (none, duration, deadline) - Move Clock enum from os/time.zig to time.zig - Update os.time.now() to return Timestamp - Update ev.Loop.now() and Runtime.now() to return Timestamp - Update ev.Timer.deadline to use Timestamp instead of u64 - Update StackPool to use Timestamp and Duration for age tracking
Update all backend poll() signatures to accept Duration instead of u64 milliseconds. Fix integer overflow issues in Windows time calculations by reordering operations to avoid intermediate overflow.
📝 WalkthroughWalkthroughThis PR replaces millisecond integers with typed Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (2 inconclusive)
✅ Passed checks (1 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 |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/ev/backends/io_uring.zig`:
- Around line 766-792: In poll, guard against the Duration.max sentinel before
converting timeout.ns to linux.kernel_timespec: if timeout.ns is the "infinite"
sentinel (e.g., >= std.math.maxInt(u64) or Duration.max), do not populate ts and
instead set io_uring_getevents_arg.ts to 0 (null) so io_uring_enter2 will wait
forever; otherwise perform the existing conversion into kernel_timespec and set
arg.ts to the address of ts; update references in poll, including the ts
variable, arg (linux_os.io_uring_getevents_arg), and the io_uring_enter2 call
accordingly.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (20)
examples/ev_demo.zigsrc/coro/stack_pool.zigsrc/ev/backends/epoll.zigsrc/ev/backends/io_uring.zigsrc/ev/backends/iocp.zigsrc/ev/backends/kqueue.zigsrc/ev/backends/poll.zigsrc/ev/completion.zigsrc/ev/loop.zigsrc/ev/test/cancel.zigsrc/ev/test/dgram_server.zigsrc/ev/test/poll_server.zigsrc/ev/test/stream_server.zigsrc/ev/test/timer.zigsrc/ev/tests.zigsrc/os/root.zigsrc/os/time.zigsrc/runtime.zigsrc/runtime/autocancel.zigsrc/time.zig
🧰 Additional context used
🧠 Learnings (6)
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.
Applied to files:
src/ev/test/stream_server.zigsrc/os/root.zigsrc/ev/completion.zigsrc/runtime/autocancel.zigsrc/ev/backends/epoll.zigexamples/ev_demo.zigsrc/ev/test/timer.zigsrc/ev/backends/poll.zigsrc/ev/backends/kqueue.zigsrc/coro/stack_pool.zigsrc/ev/backends/io_uring.zigsrc/runtime.zigsrc/ev/test/poll_server.zigsrc/ev/backends/iocp.zigsrc/ev/test/cancel.zigsrc/ev/test/dgram_server.zigsrc/os/time.zigsrc/time.zigsrc/ev/tests.zigsrc/ev/loop.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.
Applied to files:
src/ev/test/stream_server.zigsrc/os/root.zigsrc/ev/completion.zigsrc/runtime/autocancel.zigsrc/ev/backends/epoll.zigexamples/ev_demo.zigsrc/ev/test/timer.zigsrc/ev/backends/poll.zigsrc/ev/backends/kqueue.zigsrc/coro/stack_pool.zigsrc/ev/backends/io_uring.zigsrc/runtime.zigsrc/ev/test/poll_server.zigsrc/ev/backends/iocp.zigsrc/ev/test/cancel.zigsrc/ev/test/dgram_server.zigsrc/os/time.zigsrc/time.zigsrc/ev/tests.zigsrc/ev/loop.zig
📚 Learning: 2026-01-07T13:15:48.677Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.
Applied to files:
src/ev/completion.zigsrc/ev/backends/epoll.zigsrc/ev/backends/poll.zigsrc/ev/backends/kqueue.zigsrc/ev/backends/io_uring.zigsrc/ev/backends/iocp.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/ev/backends/epoll.zigsrc/ev/backends/kqueue.zigsrc/runtime.zig
📚 Learning: 2026-01-08T21:08:29.474Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-08T21:08:29.474Z
Learning: Use `zig env` to get the path to the Zig standard library when needed for reference checks
Applied to files:
src/ev/backends/epoll.zigsrc/ev/backends/kqueue.zig
📚 Learning: 2026-01-08T21:08:29.474Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-08T21:08:29.474Z
Learning: Release process: Update version in build.zig.zon
Applied to files:
examples/ev_demo.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: test (0.15.2, ReleaseSafe, ubuntu-latest, x86_64-netbsd, netbsd)
- GitHub Check: test (0.15.2, ReleaseSafe, windows-latest, native)
- GitHub Check: test (0.15.2, Debug, windows-latest, native)
- GitHub Check: test (0.15.2, Debug, ubuntu-latest, x86_64-netbsd, netbsd)
- GitHub Check: test (windows-latest)
🔇 Additional comments (59)
src/runtime/autocancel.zig (3)
7-7: LGTM - Clean Duration type integration.The import and timer initialization with
.zeroinstead of raw0are consistent with the typed time API. Good.Also applies to: 20-20
37-58: LGTM - Timeout handling simplified.The
setmethod now takesDurationdirectly and passes it through tosetTimerwithout manual millisecond conversion. TheDuration.max.nscheck for "wait forever" semantics is correct.
96-306: Tests properly demonstrate the new Duration API.All test cases use
.fromMilliseconds()constructor for timeouts and.maxfor the infinite-duration case. Coverage looks solid for the nested timeouts, user-cancel priority, and re-set scenarios.examples/ev_demo.zig (2)
27-27: LGTM - Log format updated for Duration type.Using
{f}to formatself.timer.delay(now aDuration) leverages the struct'sformatmethod. Will output something like "500ms" instead of just "500".
59-69: LGTM - Timer construction uses typed Duration.
.fromMilliseconds(500)and.fromMilliseconds(1000)are correct for the Duration-based timer init API.src/time.zig (7)
13-16: LGTM - Clean Clock enum.Two clocks, no surprises.
65-70: LGTM - Duration.toTimespec conversion.Integer division and modulo are correct for splitting nanoseconds into sec/nsec.
275-278: Worth noting: signed-to-unsigned conversion with clamping.The
fromTimespeccomputation usesi64arithmetic, then clamps negative results to 0 before casting tou64. This handles edge cases like pre-epoch times or negative timespecs from certain system calls. The@max(ns, 0)ensures no wrap-around on unsigned cast.
287-297: LGTM - Saturating arithmetic for time calculations.
durationTo,addDuration, andsubDurationall use saturating operators (-|,+|). This prevents overflow/underflow panics and produces sensible clamped values at the bounds.
299-328: LGTM - Timestamp formatting using Howard Hinnant's algorithm.The civil date calculation is a well-known algorithm with good correctness properties. Output format "YYYY-MM-DD HH:MM:SS" is clear.
331-335: Timeout union looks useful.Three variants: no timeout, relative duration, absolute deadline. Clean way to express timeout semantics in APIs.
337-361: Tests cover the new Timestamp functionality.Arithmetic operations, formatting, and the existing Duration format tests are all exercised. Good coverage.
Also applies to: 385-388
src/coro/stack_pool.zig (5)
7-8: LGTM - FreeNode now stores typed Timestamp.Clean migration from raw integer to structured time type.
Also applies to: 15-16
31-34: LGTM - Config uses Duration for max_age.Default
.zeromeans no age limit (theif (self.config.max_age.ns > 0)check at line 134 handles this).
96-96: LGTM - release() takes Timestamp parameter.The timestamp flows through to node storage correctly.
Also applies to: 118-118
134-148: LGTM - Age expiration uses Duration semantics.
expired.timestamp.durationTo(timestamp)computes the age as aDuration, then compares.nsvalues directly. The saturating subtraction indurationTohandles any edge cases where timestamps might be out of order.
274-305: Tests updated for Duration/Timestamp API.The age-based expiration test uses
.fromMilliseconds()for both the config and the release timestamps. Logic is sound.src/os/time.zig (3)
5-8: LGTM - Type aliases from the central time module.Consolidates Clock, Duration, and Timestamp definitions in one place.
10-60: LGTM - now() returns Timestamp with platform-specific conversions.Windows monotonic uses QPC with a fast path for the common 10MHz frequency and a general 96-bit fixed-point path for others. Windows realtime correctly handles the 1601→1970 epoch offset. POSIX delegates to
fromTimespec().The epoch diff calculation
11644473600 * (std.time.ns_per_s / 100)represents the 100ns tick count between Windows and Unix epochs - looks correct.
63-84: LGTM - sleep() takes Duration with proper platform handling.Zero-duration early return avoids unnecessary syscalls. Windows path truncates to milliseconds (platform limitation). POSIX path correctly loops on
EINTRwith the remainder, usingnanosleepfor full nanosecond precision.src/os/root.zig (1)
15-15: Clean addition for POSIX time interoperability.Exporting
timespecalongside the existingiovectypes keeps the OS layer consistent. Good alignment with the broader time-type refactor.src/runtime.zig (9)
16-16: LGTM - standard import for the new time type.
76-76: Type-safe duration configuration.Using
.fromSeconds(60)makes the intent crystal clear compared to raw millisecond values.
327-327: Proper typed timestamp tracking.
Timestamp = .zerois the right way to initialize this field under the new type system.
566-569: Timer now takes Duration directly - good API.The timer initialization with a typed
Durationparameter is cleaner than passing raw integers.
1030-1038: Backoff logic correctly migrated to Duration type.The saturating multiplication (
*|) for doubling the backoff prevents overflow, and capping with@minagainstmax_backoff.nsis correct. Direct struct construction.{ .ns = ... }works fine here.
1129-1133: Return type now properly reflects the structured Timestamp.Returning
Timestampinstead of rawu64gives callers type safety and access to duration arithmetic methods.
1299-1308: Tests properly exercise the new Timestamp API.Using
start.ns,end.nsfor comparisons andstart.durationTo(end).toMilliseconds()for duration assertions is the right approach with the new type.
1326-1328: Consistent test pattern for Timestamp usage.
1353-1361: Same pattern, same approval.src/ev/test/poll_server.zig (1)
91-93: Correct adaptation to Timestamp struct.
time.now(.realtime)now returns aTimestamp, so accessing.nsfor the format specifier is necessary and correct.src/ev/test/stream_server.zig (1)
87-89: Same fix as poll_server - accessing.nsfor the path format.Consistent with the other test files.
src/ev/test/dgram_server.zig (2)
81-83: Server socket path correctly uses.nsfield.
240-242: Client socket path follows the same pattern.Both server and client paths in the dgram test correctly access
timestamp.nsfor unique path generation.src/ev/tests.zig (2)
59-59: Correct migration to Duration-based timer initialization.The test properly constructs a
Durationvia.fromMilliseconds(timeout_ms)matching the newTimer.initsignature. The surrounding wall-clock validation logic remains sound.
155-155: Sleep call updated to Duration type.Using
.fromMilliseconds(10)for the cross-thread sleep aligns with the new time API. The 10ms delay is reasonable for giving the async notification time to propagate.src/ev/test/timer.zig (4)
10-13: Timer initialization with.zeroand subsequentsetTimeris a valid pattern.Initializing with
.zerowhen the actual delay is set viasetTimeris fine — the delay field acts as a placeholder untilsetTimercomputes the deadline. The.fromMilliseconds(100)call correctly constructs the Duration.
32-35: Clear timer test uses the same initialization pattern.Timer initialized with
.zero, then armed with 1000ms. Test verifies cancellation works before expiration — the timing values are appropriate.
59-66: Multiple setTimer calls test looks good.Tests resetting a timer from 2000ms to 100ms. The
.fromMilliseconds()calls are correct, and the test validates that the shorter timeout takes effect.
86-94: Timer reuse test follows the established pattern.Set, clear, then reuse the timer with a new duration. The Duration construction is consistent with the rest of the test suite.
src/ev/test/cancel.zig (8)
25-25: Timer initialization migrated to Duration.
Timer.init(.fromMilliseconds(100))correctly constructs the timer with a 100ms delay for the cancellation test.
47-47: Consistent Duration usage in loop.cancel() test.Same pattern — 100ms timer that gets cancelled via
loop.cancel().
67-67: Double cancel and Cancel-then-loop.cancel tests updated.Both use 100ms timers, migrated correctly.
Also applies to: 85-85
104-104: 1ms timer for "completed before cancel" test.Short timeout to ensure completion before cancellation attempt. The Duration migration is correct.
121-121: Not-started cancellation tests migrated.Timer created but not added to loop — tests
NotStartederror path. Duration construction is correct.Also applies to: 133-133
443-443: Callback and flag tests use Duration correctly.Tests for
canceledflag,canceled_bypointer, and callback invocation all use the new Duration-based initialization.Also applies to: 461-461, 495-495
514-514: Race condition test with 1ms timer.Short timer to simulate race between completion and cancellation. Duration API is correctly applied.
531-533: Multiple timers test with varying durations.Three timers at 100ms, 200ms, 300ms — all correctly use
.fromMilliseconds(). The cancel-middle-timer logic remains unchanged.src/ev/backends/epoll.zig (3)
5-5: Duration import added for the new timeout type.Clean import from the time module.
176-176: No-wait poll uses.zeroDuration.Cleaner than the previous
0literal — makes intent explicit. Whenpending_changesexceeds capacity, this drains completions without blocking.
413-419: Poll signature and timeout conversion look correct.The conversion path:
Duration → toMilliseconds() → i32 cast → epoll_wait. If the duration exceeds i32 range, it saturates tomaxInt(i32)(~24.8 days), which is reasonable behavior for very long timeouts. The epoll_wait syscall is documented to accept milliseconds as a signed int.src/ev/completion.zig (2)
10-11: Duration and Timestamp imports added.These types from
time.zigprovide the structured time representation replacing raw milliseconds.
342-356: Timer struct migrated from raw milliseconds to typed Duration/Timestamp.Good change:
delay: Durationinstead ofdelay_ms: u64— caller constructs Duration explicitlydeadline: Timestamp = .zeroinstead ofdeadline_ms: u64 = 0— the loop sets this when adding the timerinit(delay: Duration)— type-safe constructorThis is the core API change driving all downstream test updates. The separation of
delay(relative) anddeadline(absolute) using different types makes the semantics clear.src/ev/backends/poll.zig (1)
6-6: Duration-based poll wiring looks consistent.
Using.zerofor non-blocking flush and convertingDurationto milliseconds preserves existing semantics.Also applies to: 189-189, 411-417
src/ev/backends/kqueue.zig (1)
6-6: Duration timeout handling in the kevent path looks good.
The.zeroflush and timespec conversion are aligned with the new API.Also applies to: 172-173, 346-355
src/ev/backends/iocp.zig (1)
5-5: Duration→millisecond mapping and timeout handling look solid.
Usingu32max matches INFINITE and the wake/timeout paths remain explicit.Also applies to: 1462-1491
src/ev/backends/io_uring.zig (1)
753-759: Non-blocking flush on SQ full is fine.
Using.zerokeeps the intent explicit and matches the other backends.src/ev/loop.zig (2)
10-11: Timer scheduling now fully Duration/Timestamp based — looks good.
deadline.nscomparisons plusaddDurationkeep ordering and rescheduling straightforward.Also applies to: 49-50, 116-209, 225-313, 319-327
523-564: Duration-based timeout selection intickis coherent.
durationTo+max_waitcomparisons and.zeroon wake are consistent with the new API.Also applies to: 709-728
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
No description provided.