Skip to content

fix: EpollDel of a multishot poll that the kernel already ended - #700

Merged
romange merged 2 commits into
masterfrom
bobik/fix_epolldel
Nov 24, 2026
Merged

romange merged 2 commits into
masterfrom
bobik/fix_epolldel

Conversation

@vyavdoshenko

@vyavdoshenko vyavdoshenko commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

When the CQ overflows, the kernel ends a multishot poll and queues its last CQE without IORING_CQE_F_MORE. If EpollDel runs before that CQE is processed, POLL_REMOVE gets -ENOENT, no ECANCELED completion follows, and pending_epoll_removals_ stays incremented. The queued CQE then calls the callback of an owner that has already unsubscribed (e.g. after UringSocket::ResetOnRecvHook) and re-arms a poll that nobody removes, which keeps the file referenced; at teardown ~UringProactor fails with Pending epoll removals: 1. Dragonfly hits this in ClientKillTest.KillDuringConnectionMigration, which runs on a 16-entry ring.

Changes:

  • EpollDel clears the entry callback before POLL_REMOVE, so the owner gets no notifications after it unsubscribes.
  • Such an entry neither notifies nor re-arms; the last CQE of its request frees it and decrements pending_epoll_removals_, whether that CQE is ECANCELED from POLL_REMOVE or the end of a multishot poll by the kernel.
  • -ENOENT from POLL_REMOVE is expected and logged at VLOG(1); EpollDel no longer touches the entry after the wait, since it may already be freed.
  • FiberTest.EpollDelAfterKernelEndedPoll reproduces it deterministically: it fills the CQ ring with NOPs without reaping, so the kernel ends the poll that an eventfd write wakes, and then calls EpollDel. Without the fix it fails on every run with the same signature as Dragonfly's ClientKillTest.KillDuringConnectionMigration (EpollDel: unexpected result <fd> -2, callbacks after EpollDel, Pending epoll removals: 1); with it, both tests pass.

On a CQ overflow the kernel ends a multishot poll and queues its last CQE without
IORING_CQE_F_MORE. If EpollDel runs before that CQE is processed, POLL_REMOVE gets -ENOENT, no
ECANCELED completion follows and pending_epoll_removals_ stays incremented. The queued CQE then
calls the callback of an owner that has already unsubscribed and re-arms a poll that nobody
removes, so ~UringProactor fails with "Pending epoll removals: 1".

EpollDel now clears the entry callback before POLL_REMOVE. Such an entry neither notifies nor
re-arms, and the last CQE of its request frees it: ECANCELED from POLL_REMOVE or a multishot poll
that the kernel ended. ENOENT is expected and logged at VLOG(1), and EpollDel no longer touches
the entry after the wait.

Signed-off-by: Volodymyr Yavdoshenko <volodymyr@dragonflydb.io>
@vyavdoshenko vyavdoshenko self-assigned this Nov 24, 2026
@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The io_uring proactor now clears an epoll entry’s callback when removal begins and retains the entry until the final CQE. It handles final-completion errors and distinguishes -ENOENT from other removal errors in its logs. A Linux test checks that deletion prevents callback invocation.

Changes: io_uring poll removal

Layer / File(s) Summary
Callback clearing and completion cleanup
util/fibers/uring_proactor.cc, util/fibers/fibers_test.cc
EpollDel clears the callback while removal is pending. RearmEpoll ignores later notifications and frees the entry when the final CQE arrives. The final CQE logs errors other than -ECANCELED; EpollDel logs -ENOENT at VLOG level and other negative results as errors. The Linux test verifies that deletion and a later event do not invoke the callback.

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix

Possibly related PRs

  • romange/helio#696: Both changes update io_uring poll completion handling and callback behavior.

Suggested reviewers: kostasrim

Merge Risk: Minimal · up to b1fb6

This fixes a race in epoll removal under io_uring where a callback could fire after unsubscription and the proactor could fail at teardown. No actionable merge-blocking risk remains. A regression test covers the scenario.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the specific change: EpollDel handling of a multishot poll that the kernel already ended. The changeset clears the entry callback in EpollDel, treats -ENOENT as an already-ended poll, …
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 explains the bug (CQ overflow causes the kernel to end a multishot poll, so EpollDel gets -ENOENT and the pending removal count stays incremented), lists the concrete code changes (cle…
Full details: Title check

Explanation

The title names the specific change: EpollDel handling of a multishot poll that the kernel already ended. The changeset clears the entry callback in EpollDel, treats -ENOENT as an already-ended poll, and adds a regression test for that case. The title is short, specific, and uses the conventional fix: prefix.

Full details: Description check

Explanation

The description explains the bug (CQ overflow causes the kernel to end a multishot poll, so EpollDel gets -ENOENT and the pending removal count stays incremented), lists the concrete code changes (clearing the callback before POLL_REMOVE, freeing the entry on the final CQE, VLOG(1) for -ENOENT), and names the regression test FiberTest.EpollDelAfterKernelEndedPoll. It matches the changeset in util/fibers/uring_proactor.cc and fibers_test.cc, so it is not off-topic.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ebeaa659-d1aa-41e7-8042-183e040f8a7e
Commits

Reviewing files that changed from the base of the PR and between ed56eb2 and b1fb620.

Files selected for processing: 1

  • util/fibers/fibers_test.cc

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@qodo-code-review

qodo-code-review Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Fix EpollDel cleanup when a multishot poll has already ended

🐞 Bug fix 🕐 20-40 Minutes

Grey Divider

AI Description

• Stop notifications and re-arming after an epoll subscriber unsubscribes.
• Release pending removal state on the poll’s final completion, even when removal returns ENOENT.
• Treat ENOENT as expected when the kernel has already ended the poll.
Merge Risk 🔴 High

Blast radius 🔴 High 💥 2 capabilities

  • 2 affected capabilities span independent functional scopes: asynchronous DNS resolution integration, socket I/O receive integration.
  • UringSocket registers an io_uring EpollAdd callback for receive readiness and removes that registration when the receive hook is reset.
  • This is a distinct end-to-end socket receive behavior, not merely another implementation hop of DNS resolution.
  • The c-ares socket-state callback independently arms and disarms readiness notifications and wakes the DNS resolver condition variable.
  • Its outcome is DNS progress rather than application socket receive delivery, so it is an independent functional scope despite sharing UringProactor.
Sources

util/fibers/uring_socket.cc[641-648]

    recv_poll_id_ = proactor->EpollAdd(fd, std::move(epoll_cb), POLLIN);
  }
}

void UringSocket::ResetOnRecvHook() {
  if (recv_poll_id_) {
    Proactor* p = GetProactor();
    p->EpollDel(recv_poll_id_);
Behavioral complexity 🔴 High 🧩 Multiple interactions

  • Before: EpollDel issued POLL_REMOVE while the existing completion path could assume the entry remained valid through the removal sequence.
  • After: EpollDel clears the callback immediately, accepts ENOENT when the kernel already ended the poll, and leaves ownership of deletion to the first terminal CQE.
  • New correctness conditions: a callback may arrive after EpollDel but before POLL_REMOVE completes; multishot CQEs with IORING_CQE_F_MORE must not free the entry; the terminal CQE must free it exactly once and decrement pending_epoll_removals_; and both explicit cancellation and kernel-ended polls must preserve those ordering and ownership invariants.
  • The follow-up adds only a test of the kernel-ended-poll ordering; it introduces no production correctness condition.
  • The complexity remains due to coordinated asynchronous states, not merely existing io_uring helpers.
Potential damage 🟡 Medium 🩹 Temporary loss

  • If this lifecycle behavior regresses, an affected EpollEntry could be freed too early, retained indefinitely, or have removal accounting mishandled.
  • In the socket integration, that could stop or destabilize receive-readiness delivery until the socket is re-registered or the connection is recreated.
  • In the DNS integration, resolver progress could stall until c-ares re-arms the socket or the lookup is retried.
  • These are runtime capability losses without evidence of persistent application-state corruption or external side effects.
  • The added test strengthens evidence for the kernel-ended-poll case but does not alter the production consequence assessment.
  • Generally recoverable by re-registering the socket, recreating the connection, retrying the DNS operation, or restarting the affected proactor.
  • A code revert prevents new occurrences but may not clean up an already stranded in-memory entry; state repair would require the active proactor, socket operation, or DNS operation to be re-created or re-armed.
Sources

util/fibers/uring_socket.cc[641-648]

    recv_poll_id_ = proactor->EpollAdd(fd, std::move(epoll_cb), POLLIN);
  }
}

void UringSocket::ResetOnRecvHook() {
  if (recv_poll_id_) {
    Proactor* p = GetProactor();
    p->EpollDel(recv_poll_id_);
Assessed commit b1fb620
Diagram

graph TD
  A["Socket unsubscribe"] --> B["EpollDel"] --> C["Clear callback"] --> D["Poll removal"] --> E["Final poll CQE"] --> F{"Callback present?"}
  F -- "No" --> G["Release entry"]
  F -- "Yes" --> H["Notify or rearm"]
Loading
High-Level Assessment

The callback already represents subscription state, so clearing it before removal and deferring cleanup to the final poll CQE addresses both cancellation and an already-ended poll without new state. Synchronous cancellation was considered but does not resolve races with queued completions.

Files changed (1) +21 / -2

Bug fix (1) +21 / -2
uring_proactor.ccMake epoll removal safe when the kernel has ended a multishot poll +21/-2

Make epoll removal safe when the kernel has ended a multishot poll

• EpollDel clears the entry callback before submitting POLL_REMOVE and avoids dereferencing the entry after waiting. Completion handling suppresses notifications and re-arming for unsubscribed entries, then decrements pending removals and frees the entry on the final CQE. ENOENT from POLL_REMOVE is logged at VLOG(1) rather than treated as an unexpected error.

util/fibers/uring_proactor.cc

@augmentcode

augmentcode Bot commented Nov 24, 2026

Copy link
Copy Markdown
🤖 Augment PR Summary

Clears callbacks before poll removal and frees unsubscribed entries on their final CQE, including kernel-ended multishot polls, preventing stale notifications and leaked polls.
Treats POLL_REMOVE returning -ENOENT as expected and avoids accessing potentially freed entries after waiting.

🤖 Was this summary useful? React with 👍 or 👎

@augmentcode augmentcode Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review completed. No suggestions at this time.

Comment augment review to trigger a new review at any time.

@qodo-code-review

qodo-code-review Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. A callback can use freed captures 🐞 Bug ≡ Correctness
Description
EpollDel clears entry->cb even when RearmEpoll is currently executing that callback,
destroying the callable and its captured receive callback before the invocation returns. If a
receive callback calls ResetOnRecvHook() or Close() and then accesses one of its captures, that
capture may already have been freed.
Code

util/fibers/uring_proactor.cc[681]

+  entry->cb = nullptr;
Relevance

●● Moderate

Semantic lifetime concern about destroying the running callable; no close precedent in
uring_proactor history either way.

PR-#505
PR-#482

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The poll completion invokes entry->cb synchronously. The socket's stored callable owns and invokes
the user callback; that user callback can call ResetOnRecvHook, which reaches the new assignment
that destroys the stored callable before its invocation has unwound.

util/fibers/uring_proactor.cc[638-640]
util/fibers/uring_proactor.cc[679-682]
util/fibers/uring_socket.cc[636-643]
util/fibers/uring_socket.cc[645-652]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`EpollDel` destroys `entry->cb` while a receive callback can still be executing through it, freeing captures that the callback may access after unsubscribing.

## Fix Focus Areas
- util/fibers/uring_proactor.cc[627-643]
- util/fibers/uring_proactor.cc[679-682]

## Recommended Fix
Keep a separate owning copy of the callback alive throughout each invocation, while still marking the entry unsubscribed before submitting POLL_REMOVE. Ensure an unsubscribe cannot destroy the actively executing callable.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗



Remediation recommended

2. Unsubscribing in a callback leaks a poll 🐞 Bug ☼ Reliability
Description
The new entry->cb = nullptr state is not checked after entry->cb(res) returns, so a successful
final completion still reaches the unconditional RearmEpoll(entry). If that callback calls
EpollDel, removal can return -ENOENT for the already-ended request, after which the wrapper
installs an unowned multishot poll that retains the entry and pending-removal count until another
final completion.
Code

util/fibers/uring_proactor.cc[R679-681]

+  // No notifications from now on. The request's last CQE frees the entry, possibly before
+  // POLL_REMOVE completes, so the entry is not touched below.
+  entry->cb = nullptr;
Relevance

●● Moderate

Plausible real reliability bug in the PR's new EpollDel path, but no close historical accept or
reject precedent for this poll re-arm logic.

PR-#478
PR-#505

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
EpollDel now clears the callback and accepts -ENOENT when the request has ended. The completion
handler only checks for a null callback before invoking it; after invocation, a successful CQE
without MORE re-arms unconditionally. A newly re-armed poll with a null callback returns from the
new guard on MORE completions, while the destructor checks the outstanding count.

util/fibers/uring_proactor.cc[627-643]
util/fibers/uring_proactor.cc[679-695]
util/fibers/uring_proactor.cc[650-656]
util/fibers/uring_proactor.cc[130-134]
util/fibers/uring_socket.cc[636-652]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
When a callback unsubscribes during a successful final poll completion, the completion handler re-arms the entry despite its callback having been cleared.

## Fix Focus Areas
- util/fibers/uring_proactor.cc[627-643]
- util/fibers/uring_proactor.cc[679-695]

## Recommended Fix
After invoking the callback, re-check whether the entry is still subscribed before re-arming it. For a final completion whose callback unsubscribed, release the entry and balance `pending_epoll_removals_` without installing another poll; coordinate this with preservation of the active callback's lifetime.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


Grey Divider

Context sources
✅ Compliance rules (platform): 11 rules
✅ Cross-repo context — repo relationships
  Explored: repo: dragonflydb/dragonfly (sha: 6cbd2241) — View relationship
Review mode: Auto: ⚖️ Balanced: Concurrency-sensitive lifecycle fix with subtle asynchronous resource-management behavior.

Grey Divider

Tip of the day
💡 Did you know, you can show, collapse, or hide each part of a finding: code, evidence, and all

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread util/fibers/uring_proactor.cc Resolved
Comment thread util/fibers/uring_proactor.cc Resolved
@vyavdoshenko
vyavdoshenko requested a review from romange November 24, 2026 07:45
The test fills the CQ ring with NOPs without reaping, so the kernel ends the poll that an eventfd
write wakes, and then calls EpollDel. Without the fix POLL_REMOVE gets ENOENT, the queued last CQE
calls back and re-arms the poll, and ~UringProactor fails with "Pending epoll removals: 1".

Signed-off-by: Volodymyr Yavdoshenko <volodymyr@dragonflydb.io>
@romange
romange merged commit 4a76e32 into master Nov 24, 2026
12 checks passed
@romange
romange deleted the bobik/fix_epolldel branch November 24, 2026 14:12
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.

2 participants