Repository navigation
random: async-native zio.random / zio.randomSecure - #512
Conversation
Step 1 of the random refactor. Implement the non-secure `random` natively instead of delegating to std.Io.Threaded. - ev.Random: thin per-loop wrapper over std.Random.DefaultCsprng (sync fill, no completion queue; lives in ev only to give the RNG state a per-loop, per-thread, lock-free home). - Loop gains a `random` field + `Options.random_seed`, seeded at init. - Executor.init draws an independent secure seed per loop. For now the seed is sourced from std's blocking global backend; a later step swaps this for zio's own blocking secure RNG. - Public zio.random(buffer); io.zig random vtable routes to it. Outside any executor it falls back to the blocking global source. randomSecure still delegates to the global backend; that is step 2.
Step 2 of the random refactor. Stop delegating randomSecure to
std.Io.Threaded; own the OS entropy syscalls in src/os/.
- os.getrandom: blocking secure-entropy primitive.
Linux -> getrandom(2)
BSD/macOS -> arc4random_buf (kernel-seeded, what std uses with libc)
Windows -> ProcessPrng (the modern API used by Go/Rust/Chromium)
Shared GetRandomError{EntropyUnavailable} in os/base.zig.
- runtime.randomSecure: delegates the blocking syscall to the thread pool
via blockInPlace so the event loop is never stalled; runs inline when
called outside a task. The result slot defaults to Canceled so a pre-run
cancel surfaces cancellation rather than a bogus value.
- io.zig randomSecure vtable routes to it; zio.randomSecure exported.
- random()'s no-loop fallback now uses os.getrandom too (the per-loop
CSPRNG is purely an async-path optimization), dropping std from that path.
Minimal, thread-pool-only for now. Per-backend async paths (io_uring
/dev/urandom reads, Windows \Device\CNG via IOCP) are left for later.
Step 3 of the random refactor. Executor.init now seeds each loop's non-secure CSPRNG from zio's own blocking secure RNG (os.getrandom) instead of std.Io.Threaded.global_single_threaded. If the OS cannot provide entropy at startup, executor creation now fails rather than continuing with a predictable seed. The random feature no longer depends on std.Io.Threaded for entropy at all.
Refactor: keep the ev layer free of the random concern. - Remove ev.Random and the per-loop CSPRNG field/seed option from ev.Loop; delete src/ev/random.zig. - Move the CSPRNG (now `random.Csprng`) onto Executor, seeded in Executor.init via os.getrandom. - Move random / randomSecure / RandomSecureError (and their tests) out of runtime.zig into a new src/random.zig. - io.zig and zio.zig point at src/random.zig. No behavior change; entropy still comes from zio's own os.getrandom.
📝 WalkthroughWalkthroughAdds a cross-platform OS ChangesCSPRNG and OS getrandom subsystem
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes 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 |
std.os.windows.BOOL is a distinct Bool(c_int) type that can't be compared to an integer literal, which broke the Windows build. Declare ProcessPrng as returning the ABI-identical c_int so the `== 0` check compiles. Verified with a cross-compile to x86_64-windows.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/random.zig`:
- Around line 51-56: The random() function currently returns deterministic zero
bytes when os.getrandom() fails outside an executor context, which is unsafe.
Replace the catch handler that calls `@memset`(buffer, 0) with either a panic
statement (fail-closed approach) using `@panic`() with a descriptive error
message, or implement a proper fallback random source that provides
non-deterministic output. Do not allow the function to silently return all-zero
bytes as that defeats the purpose of a random API.
🪄 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: 7cd488a3-8e06-40b4-a568-fd8be9b3d62b
📒 Files selected for processing (8)
src/io.zigsrc/os/base.zigsrc/os/posix.zigsrc/os/root.zigsrc/os/windows.zigsrc/random.zigsrc/runtime.zigsrc/zio.zig
- Remove the empty Csprng forwarding struct; use std.Random.DefaultCsprng directly (exposed as `random.Csprng` alias). - Extract executor CSPRNG seeding into `random.setup()` (pub fn in random.zig, not exposed via zio); Executor.init just calls it. - random()'s no-executor path no longer zeros on the (near-impossible) getrandom failure: it seeds an ad-hoc PRNG from the monotonic clock so it never returns predictable zeros.
Replace the bare CSPRNG field/return with a RandomState struct initialized in place via random.setup(&state). RandomState currently only holds the non-secure CSPRNG, but gives the secure path a home for the to-be-opened /dev/urandom fd and Windows CNG handle so it can later skip the thread pool.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/random.zig (1)
88-111: 📐 Maintainability & Code Quality | 🔵 TrivialMove the fill into a spawned task to exercise the per-executor CSPRNG path.
Both tests initialize a
Runtimebut then callrandom(&buf)directly from the test thread. Since the test thread isn't running as an executor task,getCurrentExecutorOrNull()returns null and you hit theos.getrandomfallback—the CSPRNG path at line 37 never runs. TheRuntime.init/deinithere is wasted setup for what these tests actually exercise.Wrap the test body in a spawned task (following the pattern the
n()tests already use) so the executor context activates and the CSPRNG fast path gets hit.♻️ Move the fill into a spawned task to hit the CSPRNG path
test "random: fills buffer with varying bytes" { const rt = try Runtime.init(std.testing.allocator, .{}); defer rt.deinit(); - var buf: [64]u8 = `@splat`(0); - random(&buf); - // Probabilistically asserts we actually filled the buffer. - var nonzero: usize = 0; - for (buf) |b| if (b != 0) { - nonzero += 1; - }; - try std.testing.expect(nonzero > 32); + const Task = struct { + fn run() anyerror!void { + var buf: [64]u8 = `@splat`(0); + random(&buf); + // Probabilistically asserts we actually filled the buffer. + var nonzero: usize = 0; + for (buf) |b| if (b != 0) { + nonzero += 1; + }; + try std.testing.expect(nonzero > 32); + } + }; + var handle = try spawn(Task.run, .{}); + try handle.join(); }🤖 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/random.zig` around lines 88 - 111, In both test functions "random: fills buffer with varying bytes" and "random: successive calls produce different output", the direct calls to random() from the test thread bypass the CSPRNG fast path because getCurrentExecutorOrNull() returns null. Wrap the buffer filling and random() calls inside a spawned task using the same pattern as the existing n() tests, so the executor context is active and the CSPRNG code path at line 37 actually executes instead of falling back to os.getrandom.
🤖 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.
Nitpick comments:
In `@src/random.zig`:
- Around line 88-111: In both test functions "random: fills buffer with varying
bytes" and "random: successive calls produce different output", the direct calls
to random() from the test thread bypass the CSPRNG fast path because
getCurrentExecutorOrNull() returns null. Wrap the buffer filling and random()
calls inside a spawned task using the same pattern as the existing n() tests, so
the executor context is active and the CSPRNG code path at line 37 actually
executes instead of falling back to os.getrandom.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 3ab69897-7964-4ccc-84d7-e58518ac3f16
📒 Files selected for processing (2)
src/random.zigsrc/runtime.zig
🚧 Files skipped from review as they are similar to previous changes (1)
- src/runtime.zig
Implements native
zio.randomandzio.randomSecure, aligned with thestd.Iointerface, and drops the previous delegation tostd.Io.Threadedfor entropy.Design
Two primitives (
src/random.zig):random— fast, non-cryptographic bytes from a per-ExecutorCSPRNG (std.Random.DefaultCsprng), seeded once at executor startup and then filling with zero syscalls. One executor per thread → lock-free (arandom()call never suspends mid-fill). The CSPRNG is purely an async-path optimization; outside an executor it falls back to the secure syscall.randomSecure— cryptographically secure entropy obtained fresh from the OS on every call. The blocking syscall is delegated to a thread-pool worker (viablockInPlace) so the event loop is never stalled; runs inline when called outside a task.We own the syscalls in
src/os/(os.getrandom):getrandom(2)arc4random_buf(kernel-seeded; what std uses with libc)ProcessPrng(the modern API used by Go/Rust/Chromium)The
evevent-loop layer is intentionally not involved — the CSPRNG lives onExecutor, not onLoop.Left for later (per-backend async, skip the thread pool)
/dev/urandom(char device → io-wq punt, no zio pool slot)NtDeviceIoControlFile(\Device\CNG, IOCTL_KSEC_GEN_RANDOM)via IOCPNotes
ProcessPrngpath is compile-dispatched but unexercised on the Linux dev box (therandomSecuretest skips Windows).setSizefailures.Commits
zio.random)zio.randomSecure)Executorand API tosrc/random.zig