Skip to content

Drain Linux socket error queue after nonblocking TCP connect - #1375

Merged
michael-grunder merged 4 commits into
redis:masterfrom
swills:fix-linux-connect-error-queue
Sep 21, 2026
Merged

michael-grunder merged 4 commits into
redis:masterfrom
swills:fix-linux-connect-error-queue

Conversation

@swills

@swills swills commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • drain the Linux socket error queue while a TCP connection is pending and after it completes
  • prevent a stale connect-time error from keeping POLLERR/EPOLLERR asserted
  • add a deterministic regression that verifies the connection remains usable

Problem

Linux can queue an ICMP connection error while a TCP socket is still in SYN state, even when the connection subsequently succeeds. The observed error had ee_errno == ECONNREFUSED and remained in sk_error_queue after the socket became established.

This does not rely on IP_RECVERR being enabled. Linux queued the observed error during the TCP connection attempt, and the regression explicitly verifies that IP_RECVERR is disabled.

The stale queue entry keeps POLLERR/EPOLLERR asserted while SO_ERROR is zero and normal recv() calls return EAGAIN. A level-triggered event loop can therefore dispatch the socket continuously without making progress.

Fix

During Linux TCP connection establishment, redisCheckConnectDone() now drains MSG_ERRQUEUE before returning either pending or successful completion. Blocking API connections are included because hiredis temporarily uses a nonblocking descriptor while connecting; if such a connection remains pending after an error-queue wakeup, redisContextWaitReady() re-polls using the remaining original timeout. Unix sockets, user-provided file descriptors, and non-Linux platforms retain their existing behavior.

The drain uses MSG_DONTWAIT, retries EINTR, stops when the queue is empty, and preserves the caller's errno. It runs only for library-managed TCP connections. Unix sockets, user-provided file descriptors, and non-Linux platforms retain their existing behavior.

Handling the queue at connect completion clears the stale condition before the async context is marked connected and begins normal command processing.

Testing

The Linux regression uses software TX timestamping to create the same sk_error_queue occupancy condition deterministically, without raw sockets or an ICMP timing race. It then disables timestamping and verifies that:

  • IP_RECVERR, SO_TIMESTAMPING, and SO_ERROR are zero
  • normal recv() returns EAGAIN
  • EPOLLERR remains asserted while the queue entry exists
  • successful connect completion clears EPOLLERR
  • the established connection remains usable and parses PONG

The regression failed before the fix and passed afterward.

  • Linux amd64: 181 tests passed, 0 skipped
  • Linux arm64: 181 tests passed, 0 skipped
  • FreeBSD strict C99 compilation and hiredis tests passed
  • all nine fork CI jobs passed, including Ubuntu, Rocky Linux with Valgrind, FreeBSD, macOS, Windows/Cygwin, and four CMake versions

Related: redis/redis#9956

CI: https://github.com/swills/hiredis/actions/runs/35277083630


Note

Medium Risk
Changes nonblocking TCP connect completion on Linux, which async clients rely on via redisCheckConnectDone, but scope is limited to Linux TCP and other platforms/paths are unchanged.

Overview
Fixes a Linux-only async networking bug where a stale socket error queue entry can leave EPOLLERR/POLLERR set after a nonblocking TCP connect succeeds, starving level-triggered event loops even though SO_ERROR is clear and reads return EAGAIN.

On Linux TCP connections, redisCheckConnectDone() now drains MSG_ERRQUEUE via a new redisDrainSocketErrorQueue() helper (non-blocking, EINTR-safe, preserves errno). Blocking connect waiting in redisContextWaitReady() was refactored to re-poll and re-check completion until the connect finishes or the timeout elapses, instead of treating a single poll wakeup as final.

Adds a Linux regression in test.c that uses software TX timestamping to populate the error queue deterministically, then asserts connect completion clears EPOLLERR and the socket can still read PONG.

Reviewed by Cursor Bugbot for commit 1083fa3. Bugbot is set up for automated code reviews on this repo. Configure here.

Linux can retain an ICMP error queued while a TCP socket is in SYN
state even when the connection subsequently succeeds. The stale queue
entry keeps EPOLLERR asserted while SO_ERROR is zero and recv() returns
EAGAIN, causing event loops to spin without making progress.

Drain MSG_ERRQUEUE after successful completion of library-managed
nonblocking TCP connections. Preserve errno and leave blocking,
Unix-socket, user-fd, and non-Linux behavior unchanged.

Add a deterministic Linux regression using TX timestamping to reproduce
error-queue occupancy with IP_RECVERR disabled and verify that EPOLLERR
clears while the connection remains usable.
@swills swills changed the title Drain Linux socket error queue after connect Drain Linux socket error queue after nonblocking TCP connect Sep 18, 2026
@swills
swills marked this pull request as ready for review September 18, 2026 03:22
@swills

swills commented Sep 18, 2026

Copy link
Copy Markdown
Contributor Author

Additional upstream context: The need for this workaround is caused by a Linux kernel bug: IPv4 TCP sockets receive extended-error-queue entries during connection establishment even when hiredis has not enabled IP_RECVERR. This behavior was introduced by Linux commit 45af29ca761c, whose commit message says IP_RECVERR should be required, but the IPv4 path omitted that check. Eric Dumazet proposed adding the missing check in April 2024, but the patch was not merged after the subsequent discussion. Because the kernel fix was never merged, no upstream Linux release corrects the behavior, so the hiredis workaround cannot be gated on a fixed kernel version.

@michael-grunder

Copy link
Copy Markdown
Collaborator

Wow what a great find!

This sentinel 100% CPU issue has been a pain point for years but no one could ever track down why. Kernel bug sure would do it 😄

Since there not as of yet a way to gate it based on kernel the only prudent thing would be to merge the fix. Also iit's far less impactful to do this housekeeping on connect than doing it every recv.

I will play around the PR over the weekend and merge.

@uglide This may solve a years long redis-sentinel 100% CPU bug.

@michael-grunder

Copy link
Copy Markdown
Collaborator

Should we also drain in the EALREADY/EWOULDBLOCK branch? I suppose a pending error would keep triggering the event loop. It's not really critical since it would only spin untill the connection succeeds or fails but might be worth doing.

Comment thread net.c Resolved
Comment thread test.c Resolved
A queued extended error can keep POLLERR or EPOLLERR asserted while a
nonblocking TCP connection is still in progress. Drain MSG_ERRQUEUE
before returning the pending status so the event loop waits for real
connect progress instead of spinning.
Blocking contexts also use a nonblocking socket while connecting and can
receive error-queue wakeups before completion. Drain queued errors for all
TCP contexts and re-poll connections that remain pending while preserving
the original timeout deadline.

Extend the regression to verify that blocking-mode connect completion
clears EPOLLERR.
Some Linux environments, including QEMU user emulation, do not support
SO_TIMESTAMPING. Skip the error-queue regression when setsockopt reports
ENOPROTOOPT while preserving failures for every other error.

Use the common cleanup path for both skipped and completed tests.
@swills

swills commented Sep 19, 2026

Copy link
Copy Markdown
Contributor Author

Should we also drain in the EALREADY/EWOULDBLOCK branch? I suppose a pending error would keep triggering the event loop. It's not really critical since it would only spin untill the connection succeeds or fails but might be worth doing.

Good point. Added this in 055752d: pending nonblocking TCP connects now drain the error queue before returning completed == 0, preventing the queued error from repeatedly waking the event loop while the handshake continues.

@michael-grunder michael-grunder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM. I'll give the Redis guys time to weigh in but don't see any blockers myself.

@michael-grunder

Copy link
Copy Markdown
Collaborator

I see there is a subsequent fix we need too? Unless anyone has objections I'll merge this one and then go through the second PR.

@michael-grunder
michael-grunder merged commit 004ec00 into redis:master Sep 21, 2026
17 checks passed
@sundb

sundb commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

@swills Because we need to pick this fix to old version, can you pick this PR to redis?

@igr-zimmer

Copy link
Copy Markdown

Thanks @swills for tracking this down. We hit this in production on Kubernetes (Sentinel on 7.0.5, 8.2.1 and 8.8.0) and confirmed on a stuck Sentinel that the spinning sockets had IP_RECVERR=0, SO_ERROR=0 and one ICMP port unreachable in the error queue; draining it stopped the spin. I opened redis/redis#15908 to track getting this into deps/hiredis, cc @sundb.

sundb pushed a commit to redis/redis that referenced this pull request Oct 10, 2026
## Issue

Sentinel can enter a busy loop when a stale Linux socket error queue
entry remains after TCP connection succeeds.

Related Issue: 
- #9956
- #15908

## Change

Port [hiredis#1375](redis/hiredis#1375) into
`deps/hiredis`.

Drain the Linux error queue when TCP connect is pending or completed,
preserving `errno`. Blocking connections continue polling with the
remaining original timeout.
Add the upstream timestamping regression to verify that `EPOLLERR`
clears and the connection still reads `PONG`.

---------

Co-authored-by: Steve Wills <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants