Skip to content

io_uring: replace getSqe with hybrid deferred-submission model - #409

Merged
lalinsky merged 3 commits into
mainfrom
io-uring-deferred-submit
May 26, 2026
Merged

lalinsky merged 3 commits into
mainfrom
io-uring-deferred-submit

Conversation

@lalinsky

@lalinsky lalinsky commented May 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • When the SQ is full, completions are now queued in a pending list and retried after io_uring_enter2 empties the SQ, replacing the old approach of polling recursively (which could deadlock when rearmWaker also needed an SQE)
  • rearmWaker runs before drainPending so the waker always claims the first available SQE slot after the ring drains
  • If the waker couldn't be armed, the blocking timeout is capped to 10ms to avoid stalling indefinitely without a wake mechanism
  • EINTR completions are re-queued through pending rather than resubmitted directly, preserving waker priority

Test plan

  • ./check.sh passes (442/446, 4 pre-existing failures in file stat/setLength and childWait)
  • New test group: large batch exceeding queue size exercises deferred pending list submits 96 pipe_close ops (6× queue size of 16) in a single Group and confirms all complete successfully

Fixes #354

When the submission queue is full, instead of polling recursively (which
could deadlock if rearmWaker also needs an SQE), completions are now
queued in a pending list and retried after io_uring_enter2 empties the SQ.

rearmWaker is called before drainPending so the waker always gets the
first available SQE slot. If the waker couldn't be armed, the blocking
timeout is capped to 10ms to avoid stalling indefinitely. EINTR
completions also go through the pending list so the waker retains priority.

Adds a test that submits 6x the queue size of pipe_close operations in a
single Group to exercise the deferred pending list.
@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@lalinsky, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 17 minutes and 14 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: dc6d80ca-3b0b-4330-abc9-ee4992361702

📥 Commits

Reviewing files that changed from the base of the PR and between 406e27d and afb245e.

📒 Files selected for processing (1)
  • src/ev/test/group.zig
📝 Walkthrough

Walkthrough

The io_uring backend defers SQE allocation failures into a new pending Completion queue via getSqeOrDefer(), updates submit() branches to early-return when deferred, and drains/retries pending items from poll() after waker rearm; EINTR completions are also deferred. A test exercises large-batch overflow.

Changes

io_uring SQE Deferral Strategy

Layer / File(s) Summary
Pending queue field and waker context
src/ev/backends/io_uring.zig
Added pending: Queue(Completion) and made FUTEX_WAIT SQE staging resilient to get_sqe() failure so poll() can apply fallback timeout logic.
Core deferral helper and cancel behavior
src/ev/backends/io_uring.zig
Added getSqeOrDefer() to enqueue completions when SQE allocation fails; updated cancel() to acquire a cancel SQE directly and no-op if one can't be obtained.
Submit operation refactoring: network, file, directory, and pipe
src/ev/backends/io_uring.zig
Converted submit() branches (net_*, file open/create/read/write/stat, dir ops, pipe ops, process_wait) to use getSqeOrDefer() so SQE-full scenarios are deferred to pending instead of failing with error.Unexpected.
Poll effective timeout and pending queue draining
src/ev/backends/io_uring.zig
poll() uses an effective_timeout when the waker isn't armed, rearms the waker on zero CQEs, and introduced drainPending() which swaps the pending list, completes canceled items with -ECANCELED, and re-submits others.
EINTR deferred completion
src/ev/backends/io_uring.zig
CQEs returning EINTR are now pushed into pending for retry via drainPending() instead of immediate resubmission.
Test: large batch queue overflow
src/ev/test/group.zig
Added a test that creates many pipe pairs with a small Loop queue size and closes them in bulk via a .gather Group to validate pending deferral under overflow.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • lalinsky/zio#312: Related futex-waker plumbing changes; touches rearm/waker interaction used by this PR.
  • lalinsky/zio#299: Related changes to pipe SQE submission paths in io_uring backend.
  • lalinsky/zio#223: Related EINTR handling in CQE processing paths.

Poem

When SQEs run scarce the pending queue stays,
Each completion waits its measured phase,
Poll rearms the world and calls drain again,
Resubmit, defer — repeat until when,
All closes complete and the loop finds its praise.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: replacing getSqe logic with a deferred-submission model that queues operations when the SQ is full.
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.
Description check ✅ Passed The description clearly explains the core changes: deferred-submission model replaces recursive polling, waker priority handling, timeout capping for armed failures, and EINTR handling.

✏️ 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 io-uring-deferred-submit

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/ev/backends/io_uring.zig (2)

717-730: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Don't drop cancel requests when the SQ is saturated.

If get_sqe() fails here, a .running op that is already in the kernel never gets another cancel attempt. The requested bit only gets consumed in drainPending() for deferred submissions, so an in-flight request can now ignore cancellation until it completes on its own. Please either queue failed cancels for retry from poll() or reserve an SQE for cancel/waker traffic.

🤖 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 717 - 730, When get_sqe() fails in
the .running cancel path, do not drop the cancel: either enqueue the cancel for
retry and have poll() attempt it again (add a pending_cancel queue entry
containing the target user_data and ensure drainPending() or poll() will
re-attempt submission), or implement a reserved SQE/waker slot used solely for
cancel/USER_DATA_CANCEL traffic so cancel submissions never fail due to SQ
saturation; update the .running cancel branch to push failed cancels into the
pending structure and adjust drainPending()/poll() to consume and retry those
pending cancels until submitted.

757-765: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Cap the fallback timeout instead of overwriting shorter deadlines.

When waker_needs_rearm is true, this turns any shorter timeout into 10 ms, including timeout == 0. That makes a nonblocking poll sleep and can delay timer processing. Use min(timeout, 10ms) here.

🛠️ Proposed fix
-    const effective_timeout = if (self.waker_needs_rearm)
-        Duration.fromMilliseconds(10)
-    else
-        timeout;
+    const fallback_timeout = Duration.fromMilliseconds(10);
+    const effective_timeout = if (self.waker_needs_rearm and timeout.value > fallback_timeout.value)
+        fallback_timeout
+    else
+        timeout;
🤖 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 757 - 765, The current logic
unconditionally replaces timeout with 10ms when self.waker_needs_rearm, which
turns shorter deadlines (including timeout == 0) into a blocking 10ms sleep;
change the calculation of effective_timeout in io_uring.zig so it caps the
timeout to 10ms instead of overwriting it — compute effective_timeout = if
(self.waker_needs_rearm) min(timeout, Duration.fromMilliseconds(10)) else
timeout, referencing the existing symbols effective_timeout,
self.waker_needs_rearm, Duration.fromMilliseconds, and timeout and ensuring
non-blocking polls (timeout == 0) remain zero.
🤖 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.

Outside diff comments:
In `@src/ev/backends/io_uring.zig`:
- Around line 717-730: When get_sqe() fails in the .running cancel path, do not
drop the cancel: either enqueue the cancel for retry and have poll() attempt it
again (add a pending_cancel queue entry containing the target user_data and
ensure drainPending() or poll() will re-attempt submission), or implement a
reserved SQE/waker slot used solely for cancel/USER_DATA_CANCEL traffic so
cancel submissions never fail due to SQ saturation; update the .running cancel
branch to push failed cancels into the pending structure and adjust
drainPending()/poll() to consume and retry those pending cancels until
submitted.
- Around line 757-765: The current logic unconditionally replaces timeout with
10ms when self.waker_needs_rearm, which turns shorter deadlines (including
timeout == 0) into a blocking 10ms sleep; change the calculation of
effective_timeout in io_uring.zig so it caps the timeout to 10ms instead of
overwriting it — compute effective_timeout = if (self.waker_needs_rearm)
min(timeout, Duration.fromMilliseconds(10)) else timeout, referencing the
existing symbols effective_timeout, self.waker_needs_rearm,
Duration.fromMilliseconds, and timeout and ensuring non-blocking polls (timeout
== 0) remain zero.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6279510c-3199-4bf9-8531-4fc4bab99698

📥 Commits

Reviewing files that changed from the base of the PR and between e67b9b9 and 406e27d.

📒 Files selected for processing (1)
  • src/ev/backends/io_uring.zig

@lalinsky
lalinsky merged commit a9d9d32 into main May 26, 2026
26 of 27 checks passed
@lalinsky
lalinsky deleted the io-uring-deferred-submit branch May 26, 2026 05:24
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.

bug: ev.Group in .gather mode panics when children exceed io_uring SQ depth

1 participant