Skip to content

Add xev.ThreadPool integration - #9

Merged
lalinsky merged 4 commits into
mainfrom
feature/threadpool-integration
Sep 27, 2025
Merged

lalinsky merged 4 commits into
mainfrom
feature/threadpool-integration

Conversation

@lalinsky

@lalinsky lalinsky commented Sep 27, 2025 •

Copy link
Copy Markdown
Owner

Summary

Adds intelligent ThreadPool integration to the Runtime with automatic backend detection.

Key Features

  • Smart Auto-Detection: Uses @hasField(xev.Loop, "thread_pool") to detect at compile-time which backends need ThreadPool
  • Automatic Configuration: ThreadPool enabled by default for backends that require it (epoll, kqueue)
  • Heap-Allocated for Stability: ThreadPool stored on heap to ensure stable pointer address regardless of Runtime movement
  • Backward Compatible: All existing code works with new .{} options parameter

Backend Support

Backend Platform ThreadPool Auto-Enabled
epoll Linux (fallback) Required ✅ Yes
kqueue macOS/FreeBSD Required ✅ Yes
io_uring Linux (default) Not used ❌ No
iocp Windows Not used ❌ No
wasi_poll WASI Not used ❌ No

API Examples

Default (auto-detection):

var runtime = try zio.Runtime.init(allocator, .{});
// ThreadPool enabled automatically on epoll/kqueue

Custom configuration:

var runtime = try zio.Runtime.init(allocator, .{
    .thread_pool = .{ 
        .enabled = true, 
        .max_threads = 8,
        .stack_size = 2 * 1024 * 1024,
    }
});

Explicit disable:

var runtime = try zio.Runtime.init(allocator, .{
    .thread_pool = .{ .enabled = false }
});

Changes Made

  • Added RuntimeOptions and ThreadPoolOptions configuration structs
  • Updated Runtime.init() signature to accept options parameter
  • Added compile-time backend detection function
  • Implemented heap-allocated ThreadPool with proper error handling
  • Updated all examples and tests for new API
  • Added smoke test for ThreadPool functionality

Test Plan

  • All existing tests pass
  • ThreadPool smoke test verifies creation and empty runtime execution
  • Auto-detection works correctly for current backend
  • Manual override options work as expected

Ready for review and testing across different platforms.

Summary by CodeRabbit

  • New Features

    • Configurable thread pool support with options to enable and set limits.
    • Runtime initialization now accepts an options parameter (empty by default).
  • Refactor

    • Enhanced shutdown to gracefully deinitialize the thread pool when used.
    • Updated examples and tests to use the new initialization pattern.
  • Tests

    • Added a smoke test covering runtime with thread pool enabled.
  • Chores

    • Expanded .gitignore to exclude build and cache directories/files.

- Add compile-time backend detection using @Hasfield(xev.Loop, "thread_pool")
- Auto-enable ThreadPool for backends that need it (epoll, kqueue)
- Heap-allocate ThreadPool for stable pointer address
- Add RuntimeOptions with ThreadPoolOptions configuration
- Update all examples and tests for new Runtime.init() signature
- Add smoke test for ThreadPool functionality

Backends supported:
- epoll (Linux): ThreadPool auto-enabled
- kqueue (macOS/FreeBSD): ThreadPool auto-enabled
- io_uring (Linux): ThreadPool auto-disabled
- iocp (Windows): ThreadPool auto-disabled
- wasi_poll (WASI): ThreadPool auto-disabled
@coderabbitai

coderabbitai Bot commented Sep 27, 2025 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds RuntimeOptions with optional thread pool support, changes Runtime.init signature to accept options, wires thread pool into xev.Loop with conditional creation/shutdown, updates deinit accordingly, and adjusts examples/tests to pass an empty options struct. Also updates .gitignore to ignore .claude, .zig-cache, and zig-out.

Changes

Cohort / File(s) Summary
Ignore rules
/.gitignore
Add patterns to ignore /.claude, /.zig-cache, /zig-out.
Runtime core and tests
/src/runtime.zig
Introduce pub const RuntimeOptions and nested ThreadPoolOptions; modify Runtime to include optional thread_pool; change pub fn init(allocator, options) to accept options and conditionally create/configure xev.ThreadPool; update deinit to shutdown/free pool; add smoke test enabling thread pool.
Sync tests init callsites
/src/sync.zig
Update tests to call zio.Runtime.init(allocator, .{}). No logic changes.
Examples init callsites
/examples/*.zig → examples/mutex_demo.zig, examples/producer_consumer.zig, examples/sleep.zig, examples/tcp_client.zig, examples/tcp_echo_server.zig, examples/tls_demo.zig, examples/udp_echo.zig
Replace zio.Runtime.init(allocator) with zio.Runtime.init(allocator, .{}). No other changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor App as Application
  participant RT as Runtime.init
  participant XEV as xev.Loop
  participant TP as xev.ThreadPool

  App->>RT: init(allocator, options)
  RT->>RT: detect backendNeedsThreadPool
  alt ThreadPool enabled (options.thread_pool.enabled or backend)
    RT->>TP: create(config: max_threads, stack_size)
    TP-->>RT: pointer
    RT->>XEV: create(loop_opts with thread_pool)
  else No ThreadPool
    RT->>XEV: create(loop_opts without thread_pool)
  end
  RT-->>App: Runtime{ loop, thread_pool=? }

  note over RT,XEV: New: conditional creation and wiring of ThreadPool into Loop
Loading
sequenceDiagram
  autonumber
  actor App as Application
  participant RT as Runtime.deinit
  participant XEV as xev.Loop
  participant TP as xev.ThreadPool

  App->>RT: deinit()
  RT->>XEV: shutdown & deinit loop
  alt thread_pool present
    RT->>TP: shutdown()
    RT->>TP: deinit()
    RT->>RT: free thread_pool
  else
    RT->>RT: no-op for thread_pool
  end
  RT-->>App: done

  note over RT,TP: New: graceful pool teardown before full runtime teardown
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I twitch my ears at threads that spin,
A pool now hums, we dive right in.
With options neat and calls made two,
The loop now knows just what to do.
Git hides the crumbs, my paws stay clean—
Hop-hop, concurrency serene! 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title “Add xev.ThreadPool integration” succinctly captures the primary change of integrating a ThreadPool into the Runtime API, clearly reflecting the main focus of the pull request without extraneous details.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/threadpool-integration

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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b24aae8 and 74ce5ba.

📒 Files selected for processing (11)
  • .gitignore (1 hunks)
  • examples/future_demo.zig (1 hunks)
  • examples/mutex_demo.zig (1 hunks)
  • examples/producer_consumer.zig (1 hunks)
  • examples/sleep.zig (1 hunks)
  • examples/tcp_client.zig (1 hunks)
  • examples/tcp_echo_server.zig (1 hunks)
  • examples/tls_demo.zig (1 hunks)
  • examples/udp_echo.zig (1 hunks)
  • src/runtime.zig (5 hunks)
  • src/sync.zig (5 hunks)
🔇 Additional comments (5)
.gitignore (1)

1-3: Ignore the new Zig build artifacts

Adding entries for .claude, .zig-cache, and zig-out keeps transient tooling outputs out of version control. Nice housekeeping.

examples/tcp_client.zig (1)

33-34: Runtime.init options usage aligns with new API

Passing the empty options struct keeps the example compatible with the expanded Runtime.init signature without altering behavior. Looks good.

examples/mutex_demo.zig (1)

28-29: Example updated for RuntimeOptions

Supplying .{} here keeps the demo in sync with the updated runtime initializer while preserving existing semantics.

examples/tcp_echo_server.zig (1)

53-55: Echo server stays compatible with new init signature

The empty options argument ensures the example compiles against the revised runtime API with no functional change.

src/sync.zig (1)

166-168: Tests cover the new Runtime.init contract

Updating the test harness to pass .{} keeps it aligned with the new RuntimeOptions parameter and maintains the existing test coverage.

Comment thread examples/future_demo.zig Resolved
Comment thread examples/future_demo.zig Resolved
Comment thread src/runtime.zig Resolved
@lalinsky lalinsky changed the title Add ThreadPool integration with auto-detection Add xev.ThreadPool integration Sep 27, 2025
This file was not supposed to be included in the ThreadPool integration PR.

Co-authored-by: Lukáš Lalinský <[email protected]>
Repository owner deleted a comment from claude Bot Sep 27, 2025
Properly shutdown and deinit thread pool before destroying on init failure
to prevent leaking worker threads and resources.

Co-authored-by: Lukáš Lalinský <[email protected]>

@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

🧹 Nitpick comments (4)
src/runtime.zig (4)

15-18: Detect against Loop.Config, not Loop, for better portability

Safer to key auto-detection off the init config shape rather than the runtime struct.

-fn backendNeedsThreadPool() bool {
-    return @hasField(xev.Loop, "thread_pool");
-}
+fn backendNeedsThreadPool() bool {
+    return @hasField(xev.Loop.Config, "thread_pool");
+}

20-29: Make options future-proof and validate inputs

  • Consider a tri-state to disambiguate auto vs force-enable vs disable.
  • Validate non-null values (e.g., max_threads >= 1).

Example shape:

 pub const RuntimeOptions = struct {
-    thread_pool: ThreadPoolOptions = .{},
+    thread_pool: ThreadPoolOptions = .{},
 
     pub const ThreadPoolOptions = struct {
-        enabled: bool = backendNeedsThreadPool(),
+        // auto=detect, enabled=force on, disabled=force off
+        mode: enum { auto, enabled, disabled } = .auto,
         max_threads: ?u32 = null,  // null = CPU count
         stack_size: ?u32 = null,   // null = default stack size
     };
 };

If you prefer to keep boolean, add a small validator in init:

if (options.thread_pool.max_threads != null and options.thread_pool.max_threads.? == 0)
    return error.InvalidThreadCount;

Would you like me to wire the validator for you?


287-308: Teardown order is correct; consider small cleanups

  • Shutdown before loop teardown, then deinit+free after loop: good.
  • Optional: null out self.thread_pool after destroy to guard accidental double deinit patterns.
         if (self.thread_pool) |tp| {
             tp.deinit();
             self.allocator.destroy(tp);
+            self.thread_pool = null;
         }

457-473: Augment tests to cover auto and disable modes

This smoke test is good. Add:

  • Auto mode: const rt = try Runtime.init(testing.allocator, .{}); then comptime if (@hasField(xev.Loop.Config,"thread_pool")) testing.expect(rt.thread_pool != null) else testing.expect(rt.thread_pool == null).
  • Disabled mode: assert thread_pool == null even when backend supports it.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 74ce5ba and a432e66.

📒 Files selected for processing (1)
  • src/runtime.zig (5 hunks)
🔇 Additional comments (3)
src/runtime.zig (3)

247-247: Heap pointer for stability across moves: LGTM

The nullable heap-allocated ThreadPool pointer is the right choice to keep a stable address if Runtime moves.


268-272: Nice: fixed the error-path leak by shutting down + deinit before destroy

This resolves the earlier review about leaking worker threads/resources on init failure.


257-278: Gate .thread_pool in xev.Loop.init

-        // Initialize libxev loop with optional ThreadPool
-        const loop = try xev.Loop.init(.{
-            .thread_pool = thread_pool,
-        });
+        // Initialize libxev loop with optional ThreadPool (only when the field exists)
+        var loop: xev.Loop = undefined;
+        comptime if (@hasField(xev.Loop.Config, "thread_pool")) {
+            loop = try xev.Loop.init(.{ .thread_pool = thread_pool });
+        } else {
+            loop = try xev.Loop.init(.{});
+        }

Follow-ups—please verify against your pinned libxev version:
• Does xev.Loop.Config include a thread_pool field only for epoll/kqueue backends?
• What is the exact signature of xev.ThreadPool.init—does it return an error?
• Is a ThreadPool required for epoll/kqueue and simply ignored on io_uring/iocp/wasi?

Comment thread src/runtime.zig
Comment on lines +257 to 285
pub fn init(allocator: Allocator, options: RuntimeOptions) !Runtime {
// Initialize ThreadPool if enabled
var thread_pool: ?*xev.ThreadPool = null;
if (options.thread_pool.enabled) {
thread_pool = try allocator.create(xev.ThreadPool);

var config = xev.ThreadPool.Config{};
if (options.thread_pool.max_threads) |max| config.max_threads = max;
if (options.thread_pool.stack_size) |size| config.stack_size = size;
thread_pool.?.* = xev.ThreadPool.init(config);
}
errdefer if (thread_pool) |tp| {
tp.shutdown();
tp.deinit();
allocator.destroy(tp);
};

// Initialize libxev loop with optional ThreadPool
const loop = try xev.Loop.init(.{
.thread_pool = thread_pool,
});

return Runtime{
.allocator = allocator,
.loop = loop,
.thread_pool = thread_pool,
.main_context = undefined,
};
}

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.

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

Verify callsites updated for new init signature

Since Runtime.init now requires options, ensure all callsites pass the second argument.


🏁 Script executed:

#!/bin/bash
# Find Runtime.init callsites missing the options argument (heuristic).
rg -nP --no-heading '\bRuntime\.init\s*\(\s*[^,)\n]+\s*\)' -C2

Length of output: 2757


Add missing options parameter to all Runtime.init callsites

  • src/udp.zig:181
  • src/tcp.zig:425, 490, 550, 612, 675, 737
  • src/file.zig:257, 297, 341
  • README.md:24

Each of these should pass a RuntimeOptions value (e.g. `.{} for defaults) as the second argument.

🤖 Prompt for AI Agents
In src/runtime.zig around lines 257 to 285, Runtime.init now requires a second
parameter of type RuntimeOptions but multiple callsites were not updated; update
every Runtime.init call listed in the review — src/udp.zig:181; src/tcp.zig:425,
490, 550, 612, 675, 737; src/file.zig:257, 297, 341; and the README example at
line 24 — to pass a RuntimeOptions value (use .{} for defaults or a constructed
RuntimeOptions as appropriate) as the second argument, ensuring the call
signatures and any tests/docs compile with the new parameter.

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