Skip to content

ev/iocp: use shared atomic counters for active/inflight_io - #480

Merged
lalinsky merged 2 commits into
mainfrom
fix-iocp-shared-counters
Jun 7, 2026
Merged

lalinsky merged 2 commits into
mainfrom
fix-iocp-shared-counters

Conversation

@lalinsky

@lalinsky lalinsky commented Jun 7, 2026

Copy link
Copy Markdown
Owner

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.

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

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2cc7608e-9735-4d97-9b7f-b7ac7d51bddb

📥 Commits

Reviewing files that changed from the base of the PR and between d0fdef1 and b6da7f8.

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

📝 Walkthrough

Walkthrough

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

Changes

Unified counter abstraction for single and multi-threaded event loops

Layer / File(s) Summary
LoopState counter helpers and markCompletedFromBackend
src/ev/loop.zig
LoopState gains six new methods: incrActive, decrActive, loadActive, incrInflight, decrInflight, and loadInflight. These transparently use atomic shared counters for multi-threaded backends and local fields otherwise. markCompletedFromBackend switches to decrInflight.
IOCP and backend submit paths
src/ev/backends/iocp.zig, src/ev/backends/epoll.zig, src/ev/backends/io_uring.zig, src/ev/backends/kqueue.zig, src/ev/backends/poll.zig
IOCP's SharedState gains atomic active and inflight_io counters for scenarios where multiple loops share an IOCP port. All backend submit() paths (epoll, io_uring, kqueue, poll, iocp) replace direct state.active += 1 with state.incrActive().
Loop completion, timers, and submission paths
src/ev/loop.zig
finishCompletion, timer activation, timer clear, Loop.done, and all addInternal submission paths (cancellation, group, async, work, net_send_file) are updated to call helper methods instead of mutating counters directly. Loop.done now reads active via loadActive().
Operation routing and polling decisions
src/ev/loop.zig
File streaming, regular backend operation routing, thread-pool fallback error path, and tick's polling decision now use incrInflight and loadInflight, ensuring multi-threaded backends read inflight state through shared atomics.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • lalinsky/zio#219: Touches finishCompletion/markCompleted lifecycle code related to completion and cancel_state, which is closely related to the completion/accounting changes here.

Poem

Counters swap secrets, local or shared,
Threads agree on numbers once dared,
Helpers decide which path to take,
No more direct adds to break,
Quiet atomics hum—safe and spared. 🧮✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: replacing direct counter increments with shared atomic counters in IOCP backend.
Description check ✅ Passed The description clearly explains the problem (wrong LoopState decrement in multi-threaded IOCP), the solution (shared atomic counters with compile-time dispatch), and the impact (fixes Windows IOCP crash).
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 fix-iocp-shared-counters

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

📥 Commits

Reviewing files that changed from the base of the PR and between afc0ac9 and d0fdef1.

📒 Files selected for processing (6)
  • src/ev/backends/epoll.zig
  • src/ev/backends/io_uring.zig
  • src/ev/backends/iocp.zig
  • src/ev/backends/kqueue.zig
  • src/ev/backends/poll.zig
  • src/ev/loop.zig

Comment thread src/ev/backends/iocp.zig
Comment on lines +204 to +208
/// 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),

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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