Skip to content

random: async-native zio.random / zio.randomSecure - #512

Merged
lalinsky merged 7 commits into
mainfrom
random-refactor
Jun 23, 2026
Merged

lalinsky merged 7 commits into
mainfrom
random-refactor

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Implements native zio.random and zio.randomSecure, aligned with the std.Io interface, and drops the previous delegation to std.Io.Threaded for entropy.

Design

Two primitives (src/random.zig):

  • random — fast, non-cryptographic bytes from a per-Executor CSPRNG (std.Random.DefaultCsprng), seeded once at executor startup and then filling with zero syscalls. One executor per thread → lock-free (a random() 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 (via blockInPlace) so the event loop is never stalled; runs inline when called outside a task.

We own the syscalls in src/os/ (os.getrandom):

Platform Mechanism
Linux getrandom(2)
BSD / macOS arc4random_buf (kernel-seeded; what std uses with libc)
Windows ProcessPrng (the modern API used by Go/Rust/Chromium)

The ev event-loop layer is intentionally not involved — the CSPRNG lives on Executor, not on Loop.

Left for later (per-backend async, skip the thread pool)

  • io_uring: async read of /dev/urandom (char device → io-wq punt, no zio pool slot)
  • Windows: NtDeviceIoControlFile(\Device\CNG, IOCTL_KSEC_GEN_RANDOM) via IOCP

Notes

  • The Windows ProcessPrng path is compile-dispatched but unexercised on the Linux dev box (the randomSecure test skips Windows).
  • Full suite: 485/487, with only the two pre-existing unrelated setSize failures.

Commits

  1. per-loop/executor non-secure CSPRNG (zio.random)
  2. own secure syscalls (zio.randomSecure)
  3. seed CSPRNG from own RNG, drop std dependency
  4. move CSPRNG to Executor and API to src/random.zig

lalinsky added 4 commits June 23, 2026 10:22
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.
@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a cross-platform OS getrandom layer (base.zig, posix.zig, windows.zig, root.zig), a new src/random.zig module defining RandomState, random, randomSecure, and RandomSecureError, seeds a per-Executor CSPRNG in runtime.zig, re-exports the new symbols from zio.zig, and fixes the io.zig vtable to call random_mod directly.

Changes

CSPRNG and OS getrandom subsystem

Layer / File(s) Summary
OS getrandom contract and platform implementations
src/os/base.zig, src/os/posix.zig, src/os/windows.zig, src/os/root.zig
Defines GetRandomError = error{EntropyUnavailable} in base.zig. POSIX implementation loops on system.getrandom (Linux with INTR retry) or uses arc4random_buf fallback. Windows implementation declares ProcessPrng from bcryptprimitives and wraps it with failure handling. root.zig routes to the correct platform via builtin.os.tag.
CSPRNG struct and random/randomSecure APIs
src/random.zig
RandomState wraps std.Random.DefaultCsprng. random() uses the executor's CSPRNG when available, falling back to os.getrandom — if entropy fails, seeds a std.Random.DefaultPrng from the monotonic timestamp to fill the buffer. randomSecure() delegates os.getrandom via blockInPlace with cancellation support. Tests cover nonzero distribution, successive-call uniqueness, and the spawned-task path.
Executor CSPRNG seeding
src/runtime.zig
Adds random_state: random_mod.RandomState to Executor, seeds it during Executor.init via random_mod.setup() — executor creation fails if entropy cannot be obtained.
Public re-exports and io.zig vtable fix
src/zio.zig, src/io.zig
zio.zig re-exports random, randomSecure, RandomSecureError from random.zig and extends the compile-time import check. io.zig drops the globalIo() delegation in the vtable and calls random_mod.random and random_mod.randomSecure directly.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🎲 Entropy from the kernel, bytes flowing free,
Per-executor CSPRNGs, no syscalls per call.
Linux loops tight with INTR retry in place,
Windows calls ProcessPrng, macOS gets arc4random_buf.
blockInPlace keeps the reactor from stalling—
Randomness wired, pragmatically won. 🎯

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'random: async-native zio.random / zio.randomSecure' directly and specifically describes the main change: implementing native async random functions to replace delegation to std.Io.Threaded.
Description check ✅ Passed The description clearly explains the implementation of zio.random and zio.randomSecure, design choices, platform-specific syscalls, and testing status—directly aligned with the changeset across all modified files.
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 random-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.

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.

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between b3bc41c and f4584cf.

📒 Files selected for processing (8)
  • src/io.zig
  • src/os/base.zig
  • src/os/posix.zig
  • src/os/root.zig
  • src/os/windows.zig
  • src/random.zig
  • src/runtime.zig
  • src/zio.zig

Comment thread src/random.zig Resolved
Comment thread src/os/posix.zig Resolved
Comment thread src/random.zig Resolved
Comment thread src/runtime.zig Resolved
Comment thread src/random.zig Resolved
- 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.
Comment thread src/random.zig Resolved
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.

@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.

🧹 Nitpick comments (1)
src/random.zig (1)

88-111: 📐 Maintainability & Code Quality | 🔵 Trivial

Move the fill into a spawned task to exercise the per-executor CSPRNG path.

Both tests initialize a Runtime but then call random(&buf) directly from the test thread. Since the test thread isn't running as an executor task, getCurrentExecutorOrNull() returns null and you hit the os.getrandom fallback—the CSPRNG path at line 37 never runs. The Runtime.init/deinit here 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1222ec8 and c4901f2.

📒 Files selected for processing (2)
  • src/random.zig
  • src/runtime.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/runtime.zig

@lalinsky
lalinsky merged commit 87eb691 into main Jun 23, 2026
30 checks passed
@lalinsky
lalinsky deleted the random-refactor branch June 23, 2026 09:32
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