Skip to content

ev: track active per loop, move inflight tracking into backends - #602

Merged
lalinsky merged 3 commits into
mainfrom
ev-active-per-loop
Jul 23, 2026
Merged

lalinsky merged 3 commits into
mainfrom
ev-active-per-loop

Conversation

@lalinsky

@lalinsky lalinsky commented Jul 23, 2026 •

Copy link
Copy Markdown
Owner

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

  • Per-loop std.atomic.Value(usize) on LoopState, replacing the comptime split between a plain per-loop field and group-shared storage in the backend SharedState.
  • Incremented at the loop's submit sites (backends no longer do any accounting in submit).
  • Decremented in finishCompletion routed through completion.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_file parent 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

  • Removed from LoopState entirely; it is an internal backend optimization for skipping the poll syscall when nothing can arrive.
  • Each backend counts ops it accepted in its own storage: plain field for io_uring/poll (single-threaded ownership, no atomics), group-shared atomic for epoll/kqueue/iocp (a completion can be finished by another loop of the group).
  • The loop asks backend.hasInflight() in tick and tells the backend to drop one via the decrInflight hook in markCompletedFromBackend.

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

recomputeShedQuota now compares per-loop active counts instead of inflight. On backends where inflight was group-shared, every executor read the same value (mine == avg always), 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/499
  • x86_64-macos cross-compile (kqueue): builds
  • ./check.sh --full (examples): passes

Follow-up (custody handover PR)

  • sockreg.park hands full completion custody to the fd's owner loop: repoint completion.loop and move the active count under the shard lock; detach reclaims both on a cancel win. Cancel routing then converges on the servicing thread.
  • epoll/kqueue inflight becomes per-instance (how many ops THIS poller is responsible for producing) instead of group-shared, transferred at the same park/detach points. A loop with nothing parked then correctly skips the poll syscall instead of polling because some other loop has work.

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, markCompleted after unlock, state still .running). A cross-thread Loop.clearTimer in that window corrupted the timer heap, double-decremented active, and cleared the result markCompleted asserts on. On main the double decrement panics (plain active -= 1 underflow); 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_result now unambiguously means mid-fire and clearTimer leaves the timer alone; cancelLocal sets its result inside the lock and Loop.setTimer drops 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.

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

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

The 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

Layer / File(s) Summary
Capability and backend counter contracts
src/ev/completion.zig, src/ev/backends/*
Backend capabilities remove is_multi_threaded, add native_wall_timers, and define backend-local or group-shared inflight state.
Backend submission and completion accounting
src/ev/backends/*
epoll, io_uring, IOCP, kqueue, and poll increment backend inflight counters on accepted operations and expose decrement and presence helpers.
Loop active counter and completion ownership
src/ev/loop.zig, src/ev/sockreg.zig
LoopState replaces loop inflight APIs with atomic active APIs, routes completion decrements through the owning loop, and polls through backend inflight state.
Timer cancellation and completion races
src/ev/loop.zig, src/ev/test/timer.zig
Timer rearming and clearing handle firing-state limbo, with a cross-thread regression test covering repeated races.
Scheduler load measurement
src/runtime.zig
Shed-quota computation measures active operations instead of loop inflight operations.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • lalinsky/zio#480: Refactors related IOCP inflight and active bookkeeping.
  • lalinsky/zio#581: Modifies bookkeeping used by scheduler load-shedding decisions.
  • lalinsky/zio#593: Modifies the completion finalization path around active-count handling.

Poem

Counters split where completions fly,
Backends know what waits nearby.
Owners clear the work they keep,
Quiet polls when queues sleep.
Timers race—and tests don’t blink.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main refactor: per-loop active accounting and backend-owned inflight tracking.
Description check ✅ Passed The description is directly about the accounting refactor and related timer fix, so it matches the changeset.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ev-active-per-loop

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.

@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 (1)
src/ev/backends/io_uring.zig (1)

1025-1026: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Stale comment references the wrong field name.

This backend's counter is self.inflight (see line 229/354-356), not inflight_io — that name belongs to the group-shared field in epoll/kqueue/iocp's SharedState. 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

📥 Commits

Reviewing files that changed from the base of the PR and between a8a88c0 and 6cfea55.

📒 Files selected for processing (9)
  • 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/completion.zig
  • src/ev/loop.zig
  • src/ev/sockreg.zig
  • src/runtime.zig
💤 Files with no reviewable changes (1)
  • src/ev/completion.zig

Comment thread src/ev/backends/poll.zig Resolved
lalinsky added 2 commits July 23, 2026 09:51
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.

@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/ev/test/timer.zig (1)

212-212: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Unbounded spin-waits will hang, not fail, on a real regression.

ready.load (Line 212) and fired.load (Line 240) spin forever via std.Thread.yield(). If the exact bug this test targets ever comes back (callback dropped in the limbo window) or the runner exits early through l.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 ready wait 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6cfea55 and 4ed767b.

📒 Files selected for processing (3)
  • src/ev/backends/poll.zig
  • src/ev/loop.zig
  • src/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

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