Repository navigation
ev: track active per loop, move inflight tracking into backends - #602
Conversation
Rework the loop's two op counters so each has a single owner and a single meaning: - `active` (not-yet-finished completions) becomes a per-loop atomic on LoopState, incremented at the loop's submit sites and decremented in finishCompletion routed through `completion.loop`, the loop that owns the completion. Routing makes the counter exact even when the finish runs on another thread (epoll single-owner servicing, the shared IOCP port, a group finished by the loop that ran its last member), so the group-shared storage and the per-backend comptime split are gone. done() is per-loop: everything submitted on the loop holds it open. - `inflight` (ops a backend poll can complete) becomes backend-internal. Each backend counts accepted ops in its own storage (plain field for io_uring/poll, group-shared atomic for epoll/kqueue/iocp) and exposes hasInflight() for the loop's should-poll check, plus a decrInflight hook invoked via markCompletedFromBackend. The `is_multi_threaded` capability, which conflated these two concerns, is removed. The scheduler's shed quota switches from inflight to the per-loop active count, which also fixes it being a no-op on backends where inflight was group-shared (every loop read the same value, so no executor ever appeared above average).
📝 WalkthroughWalkthroughChangesThe event loop separates backend-owned inflight operation tracking from atomic per-loop active completion tracking. Backends expose inflight helpers, polling uses backend state, completion decrements follow ownership, load shedding reads active operations, and timer cancellation races receive regression coverage. Inflight and active accounting
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ 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
🧹 Nitpick comments (1)
src/ev/backends/io_uring.zig (1)
1025-1026: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winStale comment references the wrong field name.
This backend's counter is
self.inflight(see line 229/354-356), notinflight_io— that name belongs to the group-shared field in epoll/kqueue/iocp'sSharedState. Leftover from before the per-backend split; worth updating so a future debugging session doesn't go looking for a field that isn't here.✏️ Fix
- // Mark as completed (also decrements inflight_io) + // Mark as completed (also decrements `inflight`) state.markCompletedFromBackend(completion);🤖 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/io_uring.zig` around lines 1025 - 1026, Update the comment above state.markCompletedFromBackend(completion) to reference this backend’s self.inflight counter instead of the obsolete inflight_io field name.
🤖 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/poll.zig`:
- Around line 285-299: Move decrInflight and hasInflight above submit’s existing
documentation comment in the poll backend, so that comment immediately precedes
and documents submit. Preserve the new helper implementations and their own doc
comments unchanged.
---
Nitpick comments:
In `@src/ev/backends/io_uring.zig`:
- Around line 1025-1026: Update the comment above
state.markCompletedFromBackend(completion) to reference this backend’s
self.inflight counter instead of the obsolete inflight_io field name.
🪄 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 Plus
Run ID: 31f6995c-5b93-4154-af44-ceef7d2179aa
📒 Files selected for processing (9)
src/ev/backends/epoll.zigsrc/ev/backends/io_uring.zigsrc/ev/backends/iocp.zigsrc/ev/backends/kqueue.zigsrc/ev/backends/poll.zigsrc/ev/completion.zigsrc/ev/loop.zigsrc/ev/sockreg.zigsrc/runtime.zig
💤 Files with no reviewable changes (1)
- src/ev/completion.zig
A fired timer sits in a limbo window: checkTimers removes it from the heap and sets its result under the timer lock, but its markCompleted runs after unlocking, with timer.c.state still .running. A cross-thread Loop.clearTimer (a migrated task clearing its sleep timer on the loop that armed it) taking the lock in that window saw .running and: - called heap.remove on a timer no longer in the heap, corrupting the heap (or tripping the root assert / a null unwrap in safe builds), - decremented active a second time for the same timer (the pending finishCompletion decrements too), - cleared has_result, tripping markCompleted's asserts. Fix: under the timer lock, a running timer that already has its result is unambiguously mid-fire, so clearTimer leaves it alone; it is already on its way to completion. To keep that invariant airtight, cancelLocal now sets the Canceled result inside the timer lock (its unlock-to- markCompleted window is the same limbo shape), and Loop.setTimer drops a stale result when rearming a fired timer. Rearming concurrently with the fire itself has no coherent semantics and now trips an assert instead of corrupting the heap. With the temporarily reverted guard, the new regression test reproduces the original crash (null unwrap in heap.remove) reliably.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/ev/test/timer.zig (1)
212-212: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winUnbounded spin-waits will hang, not fail, on a real regression.
ready.load(Line 212) andfired.load(Line 240) spin forever viastd.Thread.yield(). If the exact bug this test targets ever comes back (callback dropped in the limbo window) or the runner exits early throughl.run(.once) catch return;(Line 202), the test just hangs until the CI job-level timeout kills it — no assertion failure, no message pointing at the actual cause. Bound the spin and fail loudly instead.🔁 Bound the spin with a failure message
- if (`@atomicLoad`(`@TypeOf`(timer.c.state), &timer.c.state, .acquire) != .new) { - while (!fired.load(.acquire)) std.Thread.yield() catch {}; - } + if (`@atomicLoad`(`@TypeOf`(timer.c.state), &timer.c.state, .acquire) != .new) { + var spins: usize = 0; + while (!fired.load(.acquire)) : (spins += 1) { + if (spins > 1_000_000) `@panic`("timer callback never fired (iteration " ++ "check `i`)"); + std.Thread.yield() catch {}; + } + }Same pattern applies to the
readywait at Line 212.Also applies to: 235-241
🤖 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/test/timer.zig` at line 212, Bound the spin-wait loops for ready and fired in the timer test instead of yielding indefinitely. Update the waits around ready.load and fired.load to use a finite timeout or iteration limit, and fail the test with a clear message when the condition is not reached; ensure the early l.run(.once) failure path also reports failure rather than returning silently.
🤖 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/ev/test/timer.zig`:
- Line 212: Bound the spin-wait loops for ready and fired in the timer test
instead of yielding indefinitely. Update the waits around ready.load and
fired.load to use a finite timeout or iteration limit, and fail the test with a
clear message when the condition is not reached; ensure the early l.run(.once)
failure path also reports failure rather than returning silently.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 44e9b692-6b55-44ff-82a9-2632477520c7
📒 Files selected for processing (3)
src/ev/backends/poll.zigsrc/ev/loop.zigsrc/ev/test/timer.zig
🚧 Files skipped from review as they are similar to previous changes (2)
- src/ev/backends/poll.zig
- src/ev/loop.zig
Rework of the loop's op accounting, first step of the Linux backend unification (runtime io_uring/epoll selection and later a hybrid mode).
active
std.atomic.Value(usize)onLoopState, replacing the comptime split between a plain per-loop field and group-shared storage in the backendSharedState.submit).finishCompletionrouted throughcompletion.loop, the loop that owns the completion. The finish can run on a different loop's thread (epoll single-owner servicing, the shared IOCP port, and notably a group/net_send_fileparent finished by whichever loop ran its last child) - routing keeps the counter exact in all of these with one uniform rule.done()is now per-loop: everything submitted on a loop holds that loop open, regardless of which loop services it. This is groundwork for the follow-up PR, where the epoll/kqueue park path will hand full completion custody (completion.loop, count included) to the fd's owner loop.inflight
LoopStateentirely; it is an internal backend optimization for skipping the poll syscall when nothing can arrive.backend.hasInflight()intickand tells the backend to drop one via thedecrInflighthook inmarkCompletedFromBackend.Removed
BackendCapabilities.is_multi_threaded- it conflated "where does active live" with "where does inflight live"; both questions now have per-backend answers and the flag has no readers left.Side effect
recomputeShedQuotanow compares per-loop active counts instead of inflight. On backends where inflight was group-shared, every executor read the same value (mine == avgalways), so load shedding was silently inert there; per-loop counts make it meaningful. The uniform +1 baseline from each executor's shutdown handle cancels out in the comparison.Testing
./check.sh(io_uring): 563/563-Dbackend=epoll: 563/563,-Dbackend=poll: 562/562./check.sh --target x86_64-windows --wine(iocp): 499/499x86_64-macoscross-compile (kqueue): builds./check.sh --full(examples): passesFollow-up (custody handover PR)
sockreg.parkhands full completion custody to the fd's owner loop: repointcompletion.loopand move the active count under the shard lock;detachreclaims both on a cancel win. Cancel routing then converges on the servicing thread.Bug fix: cross-thread clearTimer racing a firing timer (second commit)
A fired timer sits in a limbo window (removed from the heap and result set under the timer lock,
markCompletedafter unlock, state still.running). A cross-threadLoop.clearTimerin that window corrupted the timer heap, double-decrementedactive, and cleared the resultmarkCompletedasserts on. On main the double decrement panics (plainactive -= 1underflow); this PR's atomic counter would have silenced that symptom while leaving the corruption, so the fix belongs here. Under the lock,.running and has_resultnow unambiguously means mid-fire andclearTimerleaves the timer alone;cancelLocalsets its result inside the lock andLoop.setTimerdrops stale results on rearm to keep the invariant exact. A regression test reproduces the original crash reliably with the guard reverted. Cherry-pickable onto main if a hotfix release is needed before this PR merges.