Skip to content

fix: unblock Enroll after poller shutdown and release duplicated fd on failure - #766

Open
hazyhaar wants to merge 2 commits into
panjf2000:devfrom
hazyhaar:fix/unblock-enroll-and-release-dup-fd
Open

hazyhaar wants to merge 2 commits into
panjf2000:devfrom
hazyhaar:fix/unblock-enroll-and-release-dup-fd

Conversation

@hazyhaar

Copy link
Copy Markdown

Description

This PR fixes two related lifecycle issues:

  1. Enroll blocking indefinitely when called during or after engine shutdown.
  2. Leak of the duplicated socket file descriptor when Enroll fails before the connection is opened.

Fixes #765

Root Cause Analysis & Solution

  1. Poller retirement and task cleanup:

    • When pollers exit upon ErrEngineShutdown, wakeupCall was left set, and abandoned tasks were neither executed nor returned to the pool.
    • inShutdown is now published before waking pollers.
    • Trigger returns ErrEngineShutdown once stopped is set.
    • A Done() channel is signaled upon poller retirement, and awaitPollerRegister ensures waiting callers wake up cleanly rather than hanging.
  2. FD Leak Prevention:

    • The duplicated socket descriptor from socket.Dup is tracked with a single defer until poller registration succeeds.
    • If an error occurs or close executes on an unopened connection, releaseUnopened releases the descriptor and resets fd = -1 to prevent double-closes.

How Has This Been Tested?

Regression tests added:

  • TestTriggerAfterPollingReturns in pkg/netpoll/
  • TestEnrollAfterStopReturns in client_shutdown_unix_test.go
  • TestCloseUnopenedReleasesFD in client_shutdown_unix_test.go

Ran:

go test -race -count=1 -run TestTriggerAfterPollingReturns ./pkg/netpoll/...
go test -race -count=1 -run 'TestEnrollAfterStopReturns|TestCloseUnopenedReleasesFD' .

Both PASS.

@panjf2000 panjf2000 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Please fix the lint issues first.

Comment thread pkg/netpoll/poller_epoll_default.go Outdated
efd int // eventfd
efdBuf []byte // efd buffer to read an 8-byte integer
wakeupCall int32
stopped atomic.Bool // set when Polling returns; Trigger fails afterwards

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Use sync.Once instead

Comment thread pkg/netpoll/poller_epoll_ultimate.go Outdated
epa *PollAttachment // PollAttachment for waking events
efdBuf []byte // efd buffer to read an 8-byte integer
wakeupCall int32
stopped atomic.Bool // set when Polling returns; Trigger fails afterwards

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

ditto

Comment thread pkg/netpoll/poller_epoll_default.go Outdated
//
// Note that asyncTaskQueue is a queue of low-priority whose size may grow large and tasks in it may backlog.
func (p *Poller) Trigger(priority queue.EventPriority, fn queue.Func, param any) (err error) {
if p.stopped.Load() {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

I wonder whether we really need two fields, stopped and done, it looks redundant at first glance. Also, Poller.Close() and the new Poller.retire() seem to overlap, how should we coordinate these two methods?

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

Copilot review overview

🟡 Changes recommended

Shutdown-state semantics, poller retirement races, and descriptor double-closing remain unresolved.

Review effort: Balanced
Findings: 2 High severity · 1 Medium severity

Open (3)
What changed in this PR

Fixes enrollment hangs during shutdown and duplicated socket descriptor leaks.

Changes:

  • Adds poller retirement signaling and task cleanup.
  • Tightens duplicated-FD ownership and cleanup.
  • Adds shutdown and FD lifecycle regression tests.
File Description
pkg/​netpoll/​poller_shutdown_unix.go Adds retirement signaling and queue cleanup.
pkg/​netpoll/​poller_shutdown_ultimate_test.go Tests optimized poller retirement.
pkg/​netpoll/​poller_shutdown_test.go Provides shared retirement assertions.
pkg/​netpoll/​poller_shutdown_default_test.go Tests default poller retirement.
pkg/​netpoll/​poller_kqueue_ultimate.go Integrates retirement into optimized kqueue.
pkg/​netpoll/​poller_kqueue_default.go Integrates retirement into default kqueue.
pkg/​netpoll/​poller_epoll_ultimate.go Integrates retirement into optimized epoll.
pkg/​netpoll/​poller_epoll_default.go Integrates retirement into default epoll.
eventloop_unix.go Handles registration retirement and unopened descriptors.
engine_unix.go Publishes shutdown earlier.
client_unix.go Prevents enrollment hangs and FD leaks.
client_shutdown_unix_test.go Adds enrollment and descriptor regression tests.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread eventloop_unix.go Outdated
Comment on lines +399 to +401
if !c.opened {
el.releaseUnopened(c)
return nil
Comment thread pkg/netpoll/poller_shutdown_unix.go Outdated
Comment on lines +35 to +39
if !p.stopped.CompareAndSwap(false, true) {
return
}
atomic.StoreInt32(&p.wakeupCall, 0)
p.dropQueue(p.urgentAsyncTaskQueue)
Comment thread engine_unix.go Outdated
// Publish shutdown before waking pollers. Register and Enroll consult this
// flag; storing it only after Wait left a window where Trigger reported
// success and the waiter blocked on a task that would never run.
eng.inShutdown.Store(true)
@hazyhaar
hazyhaar force-pushed the fix/unblock-enroll-and-release-dup-fd branch from 3702fef to e3dfc2d Compare September 29, 2026 21:46
@codecov

codecov Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 48.57143% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 84.20%. Comparing base (441457f) to head (e3dfc2d).

Files with missing lines Patch % Lines
eventloop_unix.go 39.13% 11 Missing and 3 partials ⚠️
client_unix.go 55.55% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #766      +/-   ##
==========================================
- Coverage   84.80%   84.20%   -0.61%     
==========================================
  Files          22       22              
  Lines        2422     2450      +28     
==========================================
+ Hits         2054     2063       +9     
- Misses        252      264      +12     
- Partials      116      123       +7     
Flag Coverage Δ
unittests 84.20% <48.57%> (-0.61%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread pkg/netpoll/poller_shutdown_unix.go Outdated
// every Trigger already past the stopped check, and setting stopped under it
// rejects every later one, so the drain below is final.
func (p *Poller) retire() {
p.retireMu.Lock()

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Why would you replace atomic CAS with RW lock?

Comment thread pkg/netpoll/poller_shutdown_unix.go Outdated

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

This file seems needless; Let's put these methods in defs_poller.go

@github-actions

Copy link
Copy Markdown

This PR is marked as stale because it has been open for 21 days with no activity.

You should take one of the following actions:

  • Manually close this PR if it is no longer relevant
  • Push new commits or comment if you have more information to share

This PR will be automatically closed in 7 days if no further activity occurs.

@github-actions github-actions Bot added stale and removed stale labels Oct 23, 2026
@hazyhaar

Copy link
Copy Markdown
Author

Updated the PR to eabca9e8 with the revised enrollment/poller lifecycle, reactor startup cleanup, and poll_opt attachment-escape fixes, plus regression tests.

The exact application tree was qualified in this fork CI run: all 23 jobs passed, including 18 native Linux/macOS/Windows combinations on Go 1.20 and 1.26. The temporary qualification workflow is not included in this PR.

GitHub is holding all seven upstream workflows at action_required, pending maintainer approval (test run). Could a maintainer approve these runs so that the upstream CI and Codecov checks can evaluate the updated revision?

@github-actions

Copy link
Copy Markdown

This PR is marked as stale because it has been open for 21 days with no activity.

You should take one of the following actions:

  • Manually close this PR if it is no longer relevant
  • Push new commits or comment if you have more information to share

This PR will be automatically closed in 7 days if no further activity occurs.

@github-actions github-actions Bot added the stale label Nov 17, 2026
1. Polling returned on ErrEngineShutdown without draining queued tasks or
   preventing concurrent Trigger admissions, leaving Enroll blocked on an
   unclosed channel after Stop. Coordinate Poller admission, retirement,
   and physical Close under retireMu in defs_poller.go around the done
   channel and closed flag: Polling retires queues and closes done on
   exit, Close returns EBUSY while Polling is active and closes underlying
   descriptors idempotently once Polling has returned or if Polling never
   started, and Trigger spans queue insertion and wakeup under retireMu
   while re-arming saturated eventfd edges and resetting wakeupCall on
   write errors.

2. Track engine shutdown start via stopping before waking pollers while
   preserving inShutdown as the post-close completion signal, prepare all
   pollers and listeners before launching reactor goroutines so startup
   failures clean up descriptors without racing active loops, and transfer
   duplicated socket ownership in Enroll/enroll through connRegistration
   until register0 attaches the descriptor (leaving unopened connections
   untouched in eventloop.close).
Add unit and integration tests covering Poller retirement races, active
Close rejection (EBUSY), wakeup ordering and saturated eventfd progress,
zero-value Poller safety, connRegistration descriptor ownership across
retirement and submission errors, engine startup failure cleanup under
EMFILE/EPERM, closed-connection wake ordering, and byteslice pool
independence, and adapt the netpoll example to both build variants.
@hazyhaar

Copy link
Copy Markdown
Author

Apologies for omitting explicit inline replies when pushing the previous revision. The branch has been squashed down to 2 commits on top of dev (441457f0) per CONTRIBUTING.md, with the test suite consolidated into idiomatic files. Point-by-point summary of how each review comment is addressed:

  1. Lint issues (#pullrequestreview-5347073756)
    Resolved across default, -tags=poll_opt, -tags=gc_opt, and -tags=poll_opt,gc_opt builds (golangci-lint run -v -E gocritic -E misspell -E revive -E godot).

  2. Move shutdown helpers into defs_poller.go (#discussion_r4154695642)
    Instead of keeping a separate pkg/netpoll/poller_shutdown_unix.go (from the initial PR revision), pollerLifecycle and its lifecycle methods (Done, isRetiredLocked, beginPolling, enqueue, retire, retireLocked, closePoller, dropQueue) live in pkg/netpoll/defs_poller.go and are embedded in Poller across all four Unix epoll/kqueue implementations.

  3. Why a mutex (retireMu) is used instead of an atomic.Bool CAS or sync.Once (#discussion_r4129086059, #discussion_r4129087291, #discussion_r4154573863)

    • With a lock-free atomic.Bool check or sync.Once alone, a concurrent Trigger can pass the admission check, stall while retire() drains both task queues and closes done, and then enqueue a task after the final drain — returning nil with no consumer left to run or recycle the task.
    • Releasing an RWMutex before the wakeup syscall also left two races: Close() could close the wakeup eventfd/pipe while an admitted Trigger was writing to it, and a second concurrent Trigger could observe wakeupCall == 1 and return nil while the first Trigger's wakeup write failed before resetting wakeupCall to 0.
    • Holding retireMu (sync.Mutex) across enqueue and the wakeup write in Trigger, as well as in retire() and closePoller(), orders every admitted wakeup before queue drainage and descriptor closure. This is covered by TestPollerTriggerRacesRetire (pkg/netpoll/poller_lifecycle_default_test.go and pkg/netpoll/poller_lifecycle_ultimate_test.go, via checkTriggerRacesRetire in pkg/netpoll/poller_lifecycle_test.go), TestPollerTriggerGateOrdersWakeBeforeClose, and TestPollerWakeFatalWriteResetsAdmissionForNextWake (pkg/netpoll/poller_epoll_lifecycle_linux_test.go).
  4. Coordinating Poller.retire() with Poller.Close(), and removing the redundant stopped boolean (#discussion_r4129134391)

    • The redundant stopped field has been removed from pollerLifecycle: retirement state is tracked through done and closed under retireMu (isRetiredLocked()), with safe handling of zero-value Poller instances (TestZeroValuePollerLifecycle in pkg/netpoll/poller_lifecycle_default_test.go and pkg/netpoll/poller_lifecycle_ultimate_test.go).
    • retire() and Close() cover two distinct stages coordinated under retireMu via retireLocked():
      • Polling() sets polling = true in beginPolling() and defers p.retire(). When Polling() exits, retire() clears polling and runs retireLocked() (draining queued tasks and closing done so Enroll waiters unblock immediately) without closing the epoll/kqueue descriptors yet, because the event loop still cleans up its registered connections after Polling() returns.
      • Close() (closePoller) returns EBUSY if called while polling == true (TestPollerCloseActivePreservesTasksAndDescriptors), avoiding concurrent queue drainage or descriptor closure underneath an active Polling loop. Once Polling has returned — or if Polling never started, such as during an engine startup failure (TestPollerCloseBeforePollingClosesDone, TestEngineStartupCleanup in engine_startup_linux_test.go) — closePoller runs retireLocked() and closes the underlying descriptors once (TestPollerRepeatedClosePreservesReusedDescriptor).
  5. Duplicated descriptor ownership and shutdown flags (#discussion_r4129159658, #discussion_r4129159695, #discussion_r4129159730)
    connRegistration (registration_unix.go) owns the duplicated descriptor until register0 attaches it, ensuring single closure across submission failures, poller retirement, and stale callbacks after a published submission failure without mutating c.fd on published connections (TestRetiredRequestDiscardsDupOnce, TestWakeErrorStaleCallbackCannotTouchReuse, TestSubmissionPublicationPrecedesCallback, TestAwaitResultRetirementOwnsFinalization in registration_lifecycle_linux_test.go). eng.stopping rejects new enrollments as soon as shutdown begins while keeping eng.inShutdown as the post-close completion signal (engine_unix.go).

@hazyhaar
hazyhaar force-pushed the fix/unblock-enroll-and-release-dup-fd branch from eabca9e to 9b18722 Compare November 17, 2026 13:15
@github-actions github-actions Bot removed the stale label Nov 18, 2026
@panjf2000 panjf2000 added this to the v2.11.0 milestone Nov 23, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pending development Requested PR owner to improve code and waiting for the result waiting for response waiting for the response from commenter

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Shutdown returns from poller without unblocking Enroll, and failed Enroll leaks duplicated socket fd

3 participants