Skip to content

geventreactor: fix close() race causing EBADF errors#701

Open
dkropachev wants to merge 1 commit intomasterfrom
fix/gevent-close-race-614
Open

geventreactor: fix close() race causing EBADF errors#701
dkropachev wants to merge 1 commit intomasterfrom
fix/gevent-close-race-614

Conversation

@dkropachev
Copy link
Collaborator

@dkropachev dkropachev commented Feb 14, 2026

Summary

Fixes a race condition in GeventConnection where close() could cause [Errno 9] Bad file descriptor errors during node-down events.

Root cause: close() calls kill(block=False) which schedules GreenletExit for the next yield point, then immediately closes the socket. If the greenlet is still mid-I/O when the socket is closed, the read/write handlers raise EBADF instead of shutting down gracefully.

Changes:

  • Handle GreenletExit in handle_read() and handle_write() to exit cleanly (matching eventletreactor pattern)
  • Set last_error in close() when connected_event is not yet set, so connection attempts get a proper error
  • Set last_error on server-initiated close (EOF) in handle_read()

Fixes #614

@dkropachev dkropachev marked this pull request as draft February 14, 2026 16:40
@dkropachev dkropachev force-pushed the fix/gevent-close-race-614 branch from a3a0bbd to a2aa296 Compare February 16, 2026 13:02
GeventConnection.close() uses kill(block=False) which schedules
GreenletExit for the next yield point, then closes the socket
immediately. If close() is called from a non-gevent thread, the
greenlet may still be mid-I/O when the socket is closed, causing
EBADF.

- Add is_closed/is_defunct guards in handle_read() and handle_write()
  error paths to silently exit during shutdown
- Add GreenletExit exception handling in both I/O handlers for
  graceful greenlet termination (matching eventletreactor pattern)
- Set last_error in close() when connected_event is not yet set to
  prevent factory() from returning a dead connection
- Set last_error on server-initiated close (EOF) in handle_read()
@dkropachev dkropachev force-pushed the fix/gevent-close-race-614 branch from a2aa296 to 7163caa Compare February 16, 2026 13:09
@dkropachev dkropachev changed the title Fix GeventConnection close() race causing EBADF errors geventreactor: fix close() race causing EBADF errors Feb 16, 2026
@dkropachev dkropachev marked this pull request as ready for review February 16, 2026 13:33
@dkropachev dkropachev self-assigned this Feb 16, 2026
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.

Driver reported "[Errno 9] Bad file descriptor"

1 participant