Repository navigation
ev/iocp: use shared atomic counters for active/inflight_io - #480
Conversation
When multiple loops (executor workers) share the same IOCP port, a completion packet may be dequeued by a thread that did not submit the I/O. processCompletion() then decrements inflight_io and active on the wrong LoopState, causing a usize underflow (integer overflow panic in ReleaseSafe) and a stranded counter on the source loop. Move active and inflight_io into iocp.SharedState as atomic u64 and add six helpers on LoopState (incrActive, decrActive, loadActive, incrInflight, decrInflight, loadInflight) that dispatch compile-time on Backend.capabilities.is_multi_threaded: IOCP uses the shared atomics, all other backends continue using the local counters. All increment/decrement sites in loop.zig and every backend were replaced with the helper calls. Non-IOCP backends see zero codegen change. Fixes the UAF-free regression test crash on Windows IOCP.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughCounter management in event loops is refactored from direct field mutations to helper methods that transparently route to atomic shared state on multi-threaded backends (IOCP) and local fields on single-threaded ones. IOCP's SharedState gains atomic counters for loop-sharing, and all backends and loop operations are updated to call the new LoopState helpers. ChangesUnified counter abstraction for single and multi-threaded event loops
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
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 |
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/ev/backends/iocp.zig`:
- Around line 204-208: Reset the shared atomic counters active and inflight_io
on SharedState when a fresh IOCP port is created in acquire(): in the branch
where refcount == 0 and you recreate the handle, set both std.atomic.Value(u64)
atomics to zero (using their store methods with appropriate memory order) so
stale counts aren't carried into the next Loop.init(); additionally add a
debug/assert in release() (safe builds) to ensure active and inflight_io are
zero before the final release completes to catch leaks.
🪄 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: 66e06e09-297f-47fa-98fb-0be7bc84d1cc
📒 Files selected for processing (6)
src/ev/backends/epoll.zigsrc/ev/backends/io_uring.zigsrc/ev/backends/iocp.zigsrc/ev/backends/kqueue.zigsrc/ev/backends/poll.zigsrc/ev/loop.zig
| /// Multi-threaded counters: multiple loops may submit and | ||
| /// complete I/O on the same IOCP port, so active/inflight_io | ||
| /// are shared atomics rather than per-LoopState fields. | ||
| active: std.atomic.Value(u64) = .init(0), | ||
| inflight_io: std.atomic.Value(u64) = .init(0), |
There was a problem hiding this comment.
Zero these shared counters when the IOCP port is recreated.
active and inflight_io now live on SharedState, so their lifetime is tied to LoopGroup, not LoopState. acquire()/release() never reset them, which means reusing the same external LoopGroup after the last loop shuts down can carry stale counts into the next Loop.init(). From there done() and the no-wait poll gating can start in a permanently busy state even though no new work was submitted.
I'd reset both atomics in the refcount == 0 branch of acquire() when creating a fresh IOCP handle, and ideally assert they reached zero before the last release() in safe builds.
Suggested fix
pub fn acquire(self: *SharedState) !void {
self.mutex.lock();
defer self.mutex.unlock();
if (self.refcount == 0) {
+ self.active.store(0, .monotonic);
+ self.inflight_io.store(0, .monotonic);
+
// First loop - create IOCP handle
self.iocp = windows.CreateIoCompletionPort(
windows.INVALID_HANDLE_VALUE,
null,
0,
@@
pub fn release(self: *SharedState) void {
self.mutex.lock();
defer self.mutex.unlock();
std.debug.assert(self.refcount > 0);
self.refcount -= 1;
if (self.refcount == 0) {
+ std.debug.assert(self.active.load(.monotonic) == 0);
+ std.debug.assert(self.inflight_io.load(.monotonic) == 0);
+
// Last loop - close IOCP handle
if (self.iocp != windows.INVALID_HANDLE_VALUE) {
_ = windows.CloseHandle(self.iocp);
self.iocp = windows.INVALID_HANDLE_VALUE;
}🤖 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/ev/backends/iocp.zig` around lines 204 - 208, Reset the shared atomic
counters active and inflight_io on SharedState when a fresh IOCP port is created
in acquire(): in the branch where refcount == 0 and you recreate the handle, set
both std.atomic.Value(u64) atomics to zero (using their store methods with
appropriate memory order) so stale counts aren't carried into the next
Loop.init(); additionally add a debug/assert in release() (safe builds) to
ensure active and inflight_io are zero before the final release completes to
catch leaks.
SharedState lives in LoopGroup and persists across full Runtime.deinit() / Runtime.init() cycles. If the last release left non-zero active/inflight_io (stale counters), the next acquire would carry them forward. Store zero when a fresh IOCP port is created.
When multiple loops (executor workers) share the same IOCP port, a completion packet may be dequeued by a thread that did not submit the I/O.
processCompletionthen decrementsinflight_ioandactiveon the wrongLoopState, causing ausizeunderflow (integer overflow panic in ReleaseSafe) and a stranded counter on the source loop.Move
activeandinflight_iointoiocp.SharedStateasatomic(u64)and add six helpers onLoopState(incrActive,decrActive,loadActive,incrInflight,decrInflight,loadInflight) that dispatch compile-time onBackend.capabilities.is_multi_threaded: IOCP uses the shared atomics, all other backends continue using the local counters.All increment/decrement sites in
loop.zigand every backend were replaced with the helper calls. Non-IOCP backends see zero codegen change.Fixes the UAF-free regression test crash on Windows IOCP.