Skip to content

Add Duration type and simplify sleep - #201

Merged
lalinsky merged 8 commits into
mainfrom
sleep-refactor
Jan 14, 2026
Merged

lalinsky merged 8 commits into
mainfrom
sleep-refactor

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Simplify sleep implementation to use runIo directly instead of manual timeout handling
  • Add Duration type with Go-style formatting and parsing
  • Update Timeout.set and timedWaitForIo to use Duration

Changes

  • Duration struct with fromNanoseconds, fromMicroseconds, fromMilliseconds, fromSeconds, fromMinutes constructors
  • Duration.format for Go-style output (e.g., "1h23m45.123456789s", "1.5ms")
  • Duration.parse for parsing duration strings
  • Duration.zero and Duration.max constants
  • Simplified Executor.sleep from 17 lines to 3 lines

Test plan

  • All existing tests pass
  • New Duration format/parse tests added

@coderabbitai

coderabbitai Bot commented Jan 14, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR introduces a new Duration type to replace raw u64 nanosecond/millisecond timeout parameters across the runtime and synchronization primitives. Changes include a comprehensive Duration implementation with constructors, conversions, formatting, and parsing, plus updates to sleep and timeout APIs throughout the codebase.

Changes

Cohort / File(s) Summary
Duration Type
src/time.zig
New 348-line Duration struct with nanosecond-backed storage, unit constructors (fromMilliseconds, fromSeconds, etc.), converters, Go-style formatting/parsing, and overflow saturation. Includes ParseError type and comprehensive tests.
Runtime Sleep Migration
src/runtime.zig, src/io.zig
Executor and Runtime sleep signatures changed from milliseconds: u64 to duration: Duration. Executor.sleep now creates timer from duration.toMilliseconds() and runs via runIo. timedWaitForIo parameter changed from timeout_ns to timeout parameter of type Duration.
Sync Primitives Timeout Update
src/sync/Condition.zig, src/sync/Futex.zig, src/sync/Notify.zig, src/sync/ResetEvent.zig
timedWait signatures updated to accept timeout: Duration instead of timeout_ns: u64. Internal timeout variable renamed to timer. All timeout setup, checks, and assertions adjusted to use timer instance.
Semaphore Timing Logic
src/sync/Semaphore.zig
timedWait changed to Duration-based API. Added std.time.Timer for elapsed tracking; remaining timeout computed as Duration.fromNanoseconds(timeout_ns - elapsed). Passes remaining duration to condition timedWait.
Signal and I/O Timeout Updates
src/signal.zig
Signal.timedWait signature changed from timeout_ns: u64 to timeout: Duration. Internal timeout handling refactored to timer variable with corresponding updates to initialization and cleanup.
Test and Example Updates
examples/producer_consumer.zig, examples/signal_demo.zig, examples/sleep.zig, src/select.zig, src/runtime/group.zig, src/runtime/timeout.zig, src/zio.zig
All sleep and timeout call sites updated to use Duration constructors (.fromMilliseconds, .fromSeconds). Timeout.set signature changed to accept Duration. src/zio.zig exports Duration constant.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

⏱️ Time flows in types, not raw bytes anymore,
Duration builders make the meaning clear,
From milliseconds to nanoseconds' core,
A timer object banishes the fear! 🕐

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly describes the main changes: adding a Duration type and simplifying the sleep implementation, which are the primary objectives of this PR.
Description check ✅ Passed The description covers the key changes including the Duration type, its methods, and the simplified sleep implementation, aligning with the actual file modifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch sleep-refactor

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: 3

🤖 Fix all issues with AI agents
In `@src/common.zig`:
- Around line 23-41: The Duration constructors (fromNanoseconds,
fromMicroseconds, fromMilliseconds, fromSeconds, fromMinutes) currently multiply
inputs by ns constants and can overflow for large u64 values; change them to
detect and handle overflow by using a saturating multiply or mulWithOverflow
check from std.math and clamp the result to Duration.max (or return
Duration.max) instead of letting the value wrap, ensuring each constructor
returns a capped .{ .ns = Duration.max } on overflow.

In `@src/io.zig`:
- Around line 178-184: Remove the explicit call to timer.clear(rt) inside the
executor.yield error handler and rely on the existing defer at the top of the
function (the defer that calls timer.clear(rt)) to perform timer cleanup; keep
the classification via rt.checkTimeout(&timer, err), call cancelIo(rt,
completion) as before, and return the classified_err, so all timer cleanup is
centralized in the defer rather than duplicated in the error path.
🧹 Nitpick comments (1)
src/sync/Futex.zig (1)

114-114: Nit: Inconsistent initialization style.

The implementation uses var timer: Timeout = .{}; while tests use var timeout: Timeout = .init;. Both work, but picking one style across the file would be cleaner. Not a blocker.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7050ec1 and bccb155.

📒 Files selected for processing (16)
  • examples/producer_consumer.zig
  • examples/signal_demo.zig
  • examples/sleep.zig
  • src/common.zig
  • src/io.zig
  • src/runtime.zig
  • src/runtime/group.zig
  • src/runtime/timeout.zig
  • src/select.zig
  • src/signal.zig
  • src/sync/Condition.zig
  • src/sync/Futex.zig
  • src/sync/Notify.zig
  • src/sync/ResetEvent.zig
  • src/sync/Semaphore.zig
  • src/zio.zig
🧰 Additional context used
🧠 Learnings (9)
📚 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/zio.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/zio.zig
  • src/io.zig
  • src/common.zig
📚 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/zio.zig
  • src/runtime/group.zig
  • examples/sleep.zig
  • src/select.zig
  • src/runtime.zig
  • src/sync/Condition.zig
  • examples/producer_consumer.zig
  • src/io.zig
  • src/runtime/timeout.zig
  • src/sync/Futex.zig
  • src/sync/Notify.zig
  • examples/signal_demo.zig
  • src/signal.zig
  • src/sync/ResetEvent.zig
  • src/sync/Semaphore.zig
  • src/common.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/zio.zig
  • src/runtime/group.zig
  • examples/sleep.zig
  • src/select.zig
  • src/runtime.zig
  • src/sync/Condition.zig
  • examples/producer_consumer.zig
  • src/io.zig
  • src/runtime/timeout.zig
  • src/sync/Futex.zig
  • src/sync/Notify.zig
  • examples/signal_demo.zig
  • src/signal.zig
  • src/sync/ResetEvent.zig
  • src/sync/Semaphore.zig
  • src/common.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.

Applied to files:

  • src/select.zig
  • src/sync/Condition.zig
  • src/io.zig
  • src/runtime/timeout.zig
  • src/sync/Futex.zig
  • src/sync/ResetEvent.zig
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.

Applied to files:

  • src/runtime.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.

Applied to files:

  • src/runtime.zig
📚 Learning: 2026-01-08T21:08:29.443Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-08T21:08:29.443Z
Learning: Use `zig env` to get the path to the Zig standard library when needed for reference checks

Applied to files:

  • src/runtime/timeout.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.

Applied to files:

  • src/sync/Futex.zig
  • src/signal.zig
  • src/sync/ResetEvent.zig
  • src/sync/Semaphore.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). (1)
  • GitHub Check: test (windows-latest)
🔇 Additional comments (58)
src/common.zig (5)

16-21: Solid foundation for the Duration type.

Using u64 nanoseconds gives ~584 years of range which is plenty. The max sentinel using maxInt(u64) is a good choice for "wait forever" semantics.


43-61: Accessors look correct.

Using @divTrunc for the conversions is the right call - matches Go's integer division semantics for duration conversions.


70-168: Format helpers are well-structured.

Filling the buffer from the end and returning the start index is a clean approach. The trailing zero removal in fmtFrac and the separate handling of sub-second vs multi-unit durations matches Go's time.Duration formatting behavior.


242-304: Tests provide good coverage of the happy path.

The round-trip cases for format/parse are solid. Consider adding a test for Duration.max formatting and perhaps an overflow edge case if you add overflow handling.


63-68: The code is correct. std.Io.Writer (with capital I) is the actual type in Zig 0.15.2's standard library. The README explicitly states this project targets Zig 0.15.2 and references the official documentation for std.Io.Reader and std.Io.Writer. This signature is used consistently throughout the codebase in multiple files and compiles without issues.

Likely an incorrect or invalid review comment.

src/select.zig (1)

522-527: Sleep calls correctly updated to Duration API.

All test sleep calls consistently use .fromMilliseconds(N) - the anonymous struct literal syntax is clean and the timing values are preserved.

src/runtime/timeout.zig (2)

37-58: Duration.max bypass and rounding logic look correct.

The early return for Duration.max avoids setting a timer when waiting forever - good optimization.

The rounding formula (timeout.ns +| ns_per_ms / 2) / ns_per_ms rounds to nearest millisecond with saturating add to prevent overflow. One thing to note: sub-millisecond timeouts (< 500μs) will round to 0ms, causing immediate timeout. If that's not desired, you could use @max(1, ...) to ensure at least 1ms, but this might be intentional behavior.


95-270: Test updates are consistent with the new Duration API.

All timeout.set() and rt.sleep() calls now use .fromMilliseconds(N) with the same numeric values as before. The tests exercise the same timing scenarios.

examples/producer_consumer.zig (2)

21-21: Producer sleep updated correctly.


39-39: Consumer sleep updated correctly.

examples/signal_demo.zig (1)

26-26: Sleep call updated to Duration API.

src/zio.zig (1)

19-19: Clean addition to the public API.

Re-exporting Duration alongside Cancelable and Timeoutable keeps the public surface consistent. Users can now access the type via zio.Duration.

examples/sleep.zig (1)

10-10: Good migration to the Duration API.

.fromSeconds(1) is clearer than the old raw millisecond value. The intent is immediately obvious.

src/runtime/group.zig (1)

329-336: Test code correctly migrated to Duration.

Both sleep calls preserve the original timing behavior. The explicit .fromMilliseconds() constructor makes the time units unambiguous.

src/signal.zig (4)

10-10: Import added for Duration type.

Required for the new timeout signature.


319-341: Timeout handling refactored to use Duration.

The implementation follows the standard pattern:

  1. Stack-allocated Timeout with init
  2. defer timer.clear(rt) ensures cleanup
  3. timer.set(rt, timeout) configures the duration
  4. rt.checkTimeout(&timer, err) classifies cancellation vs timeout errors

This is consistent with the timeout pattern used elsewhere in the codebase.


350-350: Error classification uses the timer reference.

rt.checkTimeout(&timer, err) correctly passes the timer to determine whether the cancellation was due to timeout expiry or user cancellation.


414-414: Test code migrated to Duration constructors.

All sleep and timedWait calls in tests now use .fromMilliseconds() or .fromSeconds() as appropriate. The test timing semantics are preserved.

Also applies to: 460-460, 485-485, 525-530, 577-577, 608-608, 637-637, 665-665

src/io.zig (2)

14-14: Import added for Duration type.

Required for the updated function signature.


155-162: Function signature and timeout setup updated for Duration.

The pattern matches what's used in src/signal.zig for timedWait. Clean migration.

src/sync/Condition.zig (5)

56-56: LGTM!

Import added for the new Duration type. Consistent with the codebase-wide migration to Duration-based timing APIs.


165-165: LGTM on the API change.

Signature update from raw nanoseconds to Duration is cleaner and type-safe. Callers now express intent more clearly with .fromMilliseconds(10) instead of magic numbers.


177-180: Good rename from timeout to timer.

Avoids shadowing/confusion with the timeout: Duration parameter. The init/set/clear pattern is consistent with other sync primitives in this PR.


200-219: LGTM!

All references properly updated to use timer instead of timeout. The assertion at line 219 correctly checks timer.triggered to ensure the timer didn't fire if we exited the happy path.


323-323: LGTM!

Test updated to use Duration literal. Clean and readable.

src/sync/Notify.zig (6)

54-54: LGTM!

Duration import added.


151-162: LGTM!

The timedWait signature and timer setup follow the same pattern as Condition.zig. The defer timer.clear(runtime) ensures cleanup on all exit paths.


185-193: LGTM!

Error handling and final assertion properly reference timer. The flow is: on error, check if our timer triggered (return Timeout) or it was user cancellation (propagate Canceled).


366-366: LGTM!

Test updated to Duration literal.


392-392: LGTM!

Test updated to Duration literal.


424-424: LGTM!

Test updated to Duration literal.

src/runtime.zig (10)

14-14: LGTM!

Duration import added.


38-38: LGTM!

Import for runIo added to support the simplified sleep implementation.


614-617: Nice simplification!

Went from manual timeout handling to a clean 3-liner. The Timer takes milliseconds, so duration.toMilliseconds() is the right conversion. runIo handles the async wait and cancellation.


973-975: LGTM!

Runtime.sleep now forwards the Duration directly to the executor. Clean delegation pattern.


1210-1210: LGTM!

Test updated to use Duration literal.


1230-1230: LGTM!

Test updated to use Duration literal.


1243-1243: LGTM!

Test updated to use Duration literal.


1263-1263: LGTM!

Test updated to use Duration literal.


1279-1279: LGTM!

Test updated to use Duration literal.


1358-1358: LGTM!

Test updated to use Duration literal.

src/sync/Semaphore.zig (4)

47-47: LGTM!

Duration import added.


115-129: LGTM!

Different approach than Condition/Notify/ResetEvent, but makes sense here. Semaphore needs to loop and recalculate remaining time for each cond.timedWait call. Using std.time.Timer for elapsed tracking and computing Duration.fromNanoseconds(timeout_ns - elapsed) for remaining is the right pattern.


201-201: LGTM!

Test updated to Duration literal.


227-227: LGTM!

Test updated to Duration literal.

src/sync/ResetEvent.zig (7)

52-52: LGTM!

Duration import added.


165-165: LGTM!

Signature updated to accept Duration. Consistent with other sync primitives.


191-194: LGTM!

Timer setup follows the standard pattern: init, defer clear, set with Duration.


203-211: LGTM!

Error handling and final assertion properly reference timer. Same pattern as Condition and Notify.


310-310: LGTM!

Test updated to Duration literal.


397-397: LGTM!

Test updated to Duration literal.


414-416: LGTM!

Tests updated to Duration literals.

src/sync/Futex.zig (6)

35-35: LGTM!

Import added for Duration from common.zig — consistent with existing imports from the same module.


81-86: LGTM!

Using Duration.max for the unbounded wait is the right call. The unreachable for error.Timeout is correct — that path can't fire with a maximum duration.


101-152: LGTM!

The refactor from raw u64 nanoseconds to Duration is clean:

  • Signature change is straightforward
  • Timer lifecycle is handled correctly with defer timer.clear(runtime)
  • checkTimeout integration looks proper
  • The assertion on line 151 correctly validates invariants when yield succeeds

The API now matches the rest of the codebase's Duration-based timeout handling.


232-234: LGTM!

Test updated to use the new Duration.fromMilliseconds(10) syntax. The timeout setup pattern is consistent.


301-303: LGTM!

Timeout setup migrated to Duration — consistent with other tests in this file.


345-347: LGTM!

Duration-based timeout setup is consistent across all tests.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment thread src/common.zig Resolved
Comment thread src/common.zig Resolved
Comment thread src/io.zig Resolved

@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: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bccb155 and bc886a7.

📒 Files selected for processing (11)
  • src/io.zig
  • src/runtime.zig
  • src/runtime/timeout.zig
  • src/signal.zig
  • src/sync/Condition.zig
  • src/sync/Futex.zig
  • src/sync/Notify.zig
  • src/sync/ResetEvent.zig
  • src/sync/Semaphore.zig
  • src/time.zig
  • src/zio.zig
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/io.zig
  • src/sync/Futex.zig
  • src/sync/Notify.zig
🧰 Additional context used
🧠 Learnings (8)
📚 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/time.zig
  • src/runtime/timeout.zig
  • src/runtime.zig
  • src/sync/Condition.zig
  • src/sync/Semaphore.zig
  • src/signal.zig
  • src/sync/ResetEvent.zig
  • src/zio.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/time.zig
  • src/runtime/timeout.zig
  • src/runtime.zig
  • src/sync/Condition.zig
  • src/sync/Semaphore.zig
  • src/signal.zig
  • src/sync/ResetEvent.zig
  • src/zio.zig
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.

Applied to files:

  • src/runtime/timeout.zig
  • src/sync/Condition.zig
  • src/sync/ResetEvent.zig
📚 Learning: 2026-01-08T21:08:29.443Z
Learnt from: CR
Repo: lalinsky/zio PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-08T21:08:29.443Z
Learning: Use `zig env` to get the path to the Zig standard library when needed for reference checks

Applied to files:

  • src/runtime/timeout.zig
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.

Applied to files:

  • src/runtime.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.

Applied to files:

  • src/runtime.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.

Applied to files:

  • src/sync/Semaphore.zig
  • src/signal.zig
  • src/sync/ResetEvent.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/zio.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). (1)
  • GitHub Check: test (windows-latest)
🔇 Additional comments (34)
src/zio.zig (1)

20-21: LGTM!

Clean re-export of Duration from time.zig, consistent with how other types are exposed in this module.

src/signal.zig (4)

10-10: LGTM!

Duration import added correctly.


319-341: LGTM!

Good rename from timeout to timer — avoids shadowing/confusion with the timeout: Duration parameter. The setup pattern (Timeout.init, defer timer.clear, timer.set) is consistent with other sync primitives in this PR.


348-351: LGTM!

checkTimeout correctly references the renamed timer variable.


414-414: LGTM!

Test correctly uses .fromMilliseconds(10) for the sleep duration.

src/sync/Condition.zig (4)

56-56: LGTM!

Duration import added.


165-180: LGTM!

Clean migration to Duration-based API. The timeout → timer rename keeps things unambiguous.


199-219: LGTM!

The early timer.clear(runtime) before reacquiring the mutex is a sensible choice — prevents the timer from firing spuriously while waiting on the lock. The assertion on line 219 correctly validates that if we reach the success path, the timer shouldn't have triggered.


323-323: LGTM!

Test correctly uses Duration constructor.

src/runtime.zig (5)

14-14: LGTM!

Duration import added.


38-38: LGTM!

runIo import added for the simplified sleep implementation.


973-975: LGTM!

Runtime.sleep now delegates with the Duration parameter directly.


1210-1210: LGTM!

Test correctly uses .fromMilliseconds(10).


614-617: Clean simplification of the sleep method.

Three lines: init the timer, run async I/O, done. The Duration.toMilliseconds() call works as expected and runIo handles the event loop integration.

src/runtime/timeout.zig (3)

7-7: LGTM!

Duration import added.


37-51: Good stuff.

The Duration.max early-exit saves a timer allocation for the "wait forever" case. The saturating add for rounding (+|) handles edge cases where timeout.ns is near u64 max without overflow.


95-95: LGTM!

Test correctly uses .fromMilliseconds(100).

src/sync/ResetEvent.zig (5)

52-52: LGTM!

Import of Duration from the new time module aligns with the API migration.


165-165: Clean API change.

Switching from timeout_ns: u64 to timeout: Duration makes call sites more readable and self-documenting.


203-203: Consistent naming update.

References to timer instead of the old timeout variable are correct.

Also applies to: 211-211


310-310: Test updates are correct.

Using .fromMilliseconds(...) is the right pattern for the new Duration-based API.

Also applies to: 397-397, 414-416


191-194: Timer setup is correct.

The Timeout.set API confirms it accepts Duration as the third parameter. The init pattern and defer cleanup are properly structured.

src/sync/Semaphore.zig (3)

47-47: Import added correctly.


201-201: Test updates look correct.

Switched to .fromMilliseconds(...) for the Duration-based API.

Also applies to: 227-227


115-129: Correct approach for looping with timeout.

Semaphore correctly uses std.time.Timer for wall-clock tracking and decrements the remaining timeout across multiple condition waits. The timer.read() gives elapsed nanoseconds, and the remaining duration is correctly computed as timeout_ns - elapsed and passed to cond.timedWait.

src/time.zig (9)

1-8: Good attribution.

Proper licensing and source attribution for the Go-derived formatting code.


13-17: Clean struct definition.

zero and max as compile-time constants are useful. Using u64 for nanoseconds gives a range of ~584 years which is plenty.


19-37: Saturating multiplication is the right call.

Using *| prevents overflow panics and clamps to Duration.max instead. This matches the test expectations in lines 329-348.


67-125: formatBuf implementation is solid.

Building the string from the end of the buffer and returning the start index is an efficient approach - avoids shifting characters or allocations. The branching logic for sub-second vs multi-unit durations is clear.


129-164: Helper functions are clean.

fmtFrac handles trailing zero suppression elegantly. fmtInt is straightforward.


169-245: Parse implementation has thorough overflow protection.

The overflow checks at lines 184, 187, 231, and 240 cover:

  1. Integer part digit accumulation overflow
  2. Multiplication by unit overflow
  3. Accumulation across multiple units overflow

The use of +|= (saturating add) at line 236 for the fractional part is a nice touch - prevents panic on float-to-int edge cases.


276-327: Parse tests are comprehensive.

Good coverage of:

  • Valid inputs (various units, combinations, fractional parts)
  • Error cases (empty, invalid unit, missing unit)
  • Overflow edge cases (integer overflow, multiplication overflow, accumulation overflow)
  • Max u64 boundary case

329-348: Overflow saturation tests verify the *| behavior.

These confirm that constructors clamp to Duration.max on overflow rather than panicking.


59-64: No changes needed — std.Io.Writer is correct for modern Zig.

Zig's I/O module was refactored in version 0.15+, and the current standard uses std.Io (capital I), not std.io. The codebase is consistent throughout with this modern API. The code will compile correctly.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment thread src/time.zig Resolved
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