Skip to content

Retry full Unix socket listen queues without blocking the event loop - #258

Merged
fcostaoliveira merged 18 commits into
redis:masterfrom
LINKIWI:nonblocking-socket-connect-errors
Oct 17, 2026
Merged

fcostaoliveira merged 18 commits into
redis:masterfrom
LINKIWI:nonblocking-socket-connect-errors

Conversation

@LINKIWI

@LINKIWI LINKIWI commented Jun 16, 2024 •

Copy link
Copy Markdown
Contributor

Problem

On Linux, a full Unix socket listen queue makes a nonblocking connect return EAGAIN. Memtier currently aborts preparation even if the server starts accepting a fraction of a second later. The original reproduction in this PR used a Redis Unix listener with a small backlog and many clients.

This branch includes #257's abstract Unix socket support for interaction coverage. Merge #257 first. Both filesystem and abstract addresses now recover from temporary listener backpressure.

Root cause

bufferevent_socket_connect() reports this Unix condition as a synchronous failure; unlike TCP EINPROGRESS, no connect is pending in the kernel. Repeating the call inline prevents the worker loop, connection timers and supervisor from running. The original PR loop consumed 0.504 CPU seconds during a 0.5-second backlog wait and spun until a four-second harness kill when the queue never drained.

Fix

Retry the same pending Unix connect on a 10 ms libevent timer. Disable the bufferevent while waiting so TLS does not busy-poll its handshake on an unconnected socket, then restore events after the connect starts. Reuse the exact stored address length, including short abstract socket names. Free the timer on success, a terminal error, disconnect and destruction.

A full queue does not consume reconnect attempts. The original connection timeout remains armed across all retries, and the setup-stage timeout and interruption remain effective. Other errors use the normal reconnect policy. Once a connection reaches steady state, with --reconnect-on-error and unlimited reconnect attempts, --test-time also stops an unsuccessful backlog wait at the existing #666 run deadline. Before any connection reaches steady state, the connection/setup-stage limits bound startup; disabling both permits waiting for the listener. Finite reconnect limits retain their existing policy. A debug message records the start of each backlog wait once, rather than every timer tick. No new options or output schema fields.

Tests

  • Current master bc8e316: a deterministic full listen queue aborts immediately with exit 1/EAGAIN; all four filesystem recovery/deadline/interrupt assertions fail on that baseline.
  • Original PR 7ff52af: delayed acceptance succeeds, but an indefinitely full queue consumes about four CPU seconds during a four-second timeout.
  • Final integrated tree: make -j4 check passes 14/14. RLTest test_unix_connect_backlog.py passes 10/10 in plaintext and 10/10 with TLS. Covers filesystem recovery, connection timeout, setup-stage timeout and SIGINT; short and maximum-length abstract names; abstract reconnect intervals, exhausted reconnect attempts and the run deadline. Successful recovery checks exact JSON operation counts. The timeout case checks JSON CPU usage to catch TLS handshake spinning.
  • Additional scripted controls pass for nonexistent sockets, listener removal while waiting, reconnect intervals, finite timeout/reconnect exhaustion and TLS recovery/timeout. A one-second TLS backlog timeout used about 0.005 CPU seconds, versus roughly one CPU second in the initial draft without bufferevent suspension.
  • The timed-backlog regression first completes one SET, then fills the listener queue before reconnect. With both connection limits disabled and unlimited reconnects, the run now ends at its one-second deadline with exactly one SET in JSON (subject to supervisor reporting cadence).

All fixtures use private Unix names and dummy authentication. Linux-specific backlog tests skip on other platforms. CI and the independent review lenses still gate merging.

Affected versions

The synchronous failure path was introduced by the bufferevent conversion in e22a4eadd83ff72537d2c13bc10658334b863d98, first released in 1.3.0, and remains in releases through 2.5.2 and master bc8e316. The actual reproductions above cover current master and the original PR head. Older releases used a different raw-connect path and were not runtime-tested here. The abstract-socket cases apply to the new support in #257.

Co-Authored-By: Claude Opus 5.5 [email protected]


Note

Medium Risk
Changes Unix/TLS connect startup and timer lifecycle in the hot connection path; behavior is well-tested but affects when benchmarks fail vs wait.

Overview
Fixes immediate connect failure when a Unix (or abstract Unix) listener’s accept queue is full: EAGAIN/EWOULDBLOCK from bufferevent_socket_connect() is now treated as a pending connect, not a fatal error.

shard_connection arms a 10 ms libevent timer to retry the same connect without blocking the worker loop. While waiting, the bufferevent is disabled so TLS does not spin on handshake I/O on an unconnected socket. Queue-full retries do not increment --max-reconnect-attempts; the original --connection-timeout timer stays armed across retries. At --test-time deadline (with unlimited reconnects), backlog waits stop like other late connects. Other errors still use normal reconnect/disconnect paths. --debug logs once per attempt when the queue is full.

README documents listen-queue behavior and how it interacts with connection/stage timeouts.

tests/test_unix_connect_backlog.py (Linux) exercises filesystem and abstract sockets, plaintext and TLS: recovery after the queue drains, connection/stage timeouts, SIGINT, reconnect limits, and run deadline with saturated queue after first SET.

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

CI compatibility: fork PRs can receive an empty vars.SMOKE_TEST_IMAGES; that prevented the distro matrix from being created while all visible jobs passed. The workflow now falls back to the same seven images currently configured upstream. An explicit repository variable still takes precedence. Independent focused build review and actionlint pass; fresh matrix execution is required.

🤖 Generated with Claude Code

@LINKIWI
LINKIWI force-pushed the nonblocking-socket-connect-errors branch from 2a27e54 to 7ff52af Compare January 22, 2025 14:14
@github-actions

github-actions Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review — a human maintainer's review is still required before merge.

Thanks for this, and for carrying it forward after #257. Retrying on a timer instead of looping inline seems like the right shape. Keeping the original connection timeout armed across retries, and not charging EAGAIN against --max-reconnect-attempts, both look correct to me. The new tests/test_unix_connect_backlog.py checks JSON counts and CPU usage, not just stderr, and the description says it fails on master. That's the bar I'd want for a connect-path change. A few comments:

  • handle_unix_connect_retry(): I may be wrong, but I think the success branch also runs in a case that isn't a success. If the listener goes away mid-wait and the socket file is still there, connect() returns ECONNREFUSED. libevent's bufferevent_socket_connect() reports that as a 0 return. It then schedules a deferred BEV_EVENT_ERROR and calls bufferevent_disable(bev, EV_READ|EV_WRITE) itself. Our branch would free the timer and immediately call bufferevent_enable(m_bev, EV_READ | EV_WRITE) again on an unconnected socket. The deferred error should still win and attempt_reconnect() dedups, so this may be harmless. With TLS, though, I wonder if it can start a handshake attempt and log extra errors. Was the "listener removal while waiting" control run with the socket file left in place (refused), or only with it unlinked (ENOENT)?
  • Related: on the normal connect path, the fresh bufferevent only has its default events enabled until BEV_EVENT_CONNECTED. Here we enable EV_READ | EV_WRITE explicitly. Did you consider saving bufferevent_get_enabled() before the bufferevent_disable() and restoring exactly that? That way the retry path leaves the bufferevent in the same state as a connect that never hit the backlog.
  • Nitpicking: in the README section, the line starting "Before steady state, ..." is much longer than the rest. It looks like it lost its wrapping during a merge.

The core fix looks solid. I'd mainly like the refused-connect case above confirmed (or covered by a test) before this merges.

(would file this as a comment, not a formal block)

@fcostaoliveira fcostaoliveira changed the title shard_connection: Handle non-blocking I/O errors on Unix socket client connect Retry full Unix socket listen queues without blocking the event loop Oct 17, 2026
@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Addressed in dea97a2, on current master plus #257:

  • A full listen queue is still one pending connect. Each 10 ms EAGAIN does not consume a reconnect attempt; connection timeout is armed once for the entire wait. Added the comment explaining this. Once that timeout or a real error occurs, normal reconnect/backoff/attempt limits apply. The finite-attempt regression covers this distinction. --reconnect-interval remains its separate workload-request-count policy.
  • Added one debug message when each backlog wait starts, rather than on every timer tick. README explains both timeout controls and their disabled state.
  • The End a --test-time run at its deadline while reconnecting to a dead server #666 distinction matters: before any connection reaches steady state, run_deadline() deliberately has no deadline, so the connection/setup-stage limits bound startup. Disabling both permits an initial wait; this PR preserves that policy. Once steady state exists, the retry callback now checks the same established run deadline under the same unlimited-reconnect policy. The regression completes one SET, fills the accept queue before reconnect, and uses --test-time=1 with both connection limits disabled. Removing only the callback's deadline guard makes it exceed the eight-second harness limit; the fix ends with exactly one SET in JSON. Finite reconnect limits retain their existing policy.
  • The retry timer is explicitly freed before terminal-error/deadline handling. Current master after End a --test-time run at its deadline while reconnecting to a dead server #666 also has end_thread() call disconnect(), so both paths are covered.
  • Retained the CPU assertion: it compares consumed CPU with elapsed wall time, so a loaded runner tends to reduce the measured ratio rather than inflate it. The fixed TLS timeout used about 0.005 cores locally, versus roughly one full core without bufferevent suspension; the 0.5 threshold leaves substantial headroom. Sanitizer CI is still a required gate, not claimed to have passed yet.

Final local validation: 14/14 unit tests, 10/10 backlog cases through RLTest in plaintext and 10/10 with TLS. The address-length interaction is covered for short and 107-byte abstract names; #257 should land first. Full independent reviews and fresh CI remain required before merge.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Rechecked the edited 06:18:43Z review:

  • Scope is intentional dependency integration: the Problem section explicitly identifies shard_connection: Support abstract Unix socket clients #257 and says to merge it first. Abstract-socket support remains its own PR, with its own seven reviews. This branch carries it so the new retry callback can be tested against both address forms. Once shard_connection: Support abstract Unix socket clients #257 lands, its feature changes disappear from this PR's effective diff.
  • The Linux @ interpretation is an explicit shard_connection: Support abstract Unix socket clients #257 decision, including the alternatives and migration path; see the compatibility decision and evidence. Retaining the familiar convention avoids another permanent endpoint option; filesystem-existence fallback would make endpoint selection depend on unrelated filesystem state and could silently connect to the wrong peer. ./@NAME preserves access to filesystem names. No new interpretation is introduced by the backlog change.
  • Overlong-name handling is also covered by shard_connection: Support abstract Unix socket clients #257's independent probes: setup fails during preparation, at the first client, before worker threads launch, including with unlimited reconnects. It exits 1 promptly with one diagnostic. The stored-length sentinel is checked before socket creation; duplicating the platform capacity check in main adds no different failure behavior.
  • Considered backoff. This is one pending connect, with no server connection yet; I kept a modest fixed delay so a briefly full accept queue does not inherit the normal reconnect's one-second delay or consume its attempt budget. Large connection counts still incur timer/connect work, so this is not a scalability-performance claim. Actual errors continue to use configured reconnect backoff. A shared scheduler or adaptive cadence would be a separate measured optimization.
  • Restored the README title underline in 6c79ab4; it was an accidental conflict-resolution edit.
  • int matches libevent's bufferevent_socket_connect(..., int socklen) interface. The bounded Unix address size fits it, so no further type conversion is needed.

The latest commit changes only that README underline; the validated runtime remains dea97a2. Fresh final-head CI and the seven independent #258 reviews still gate merge.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Follow-up on the latest review:

  • The Linux @NAME interpretation is deliberate and documented as a compatibility change in the PR release notes, README, help and man page. ./@NAME keeps the filesystem meaning. A separate flag/prefix was considered; the established @ notation keeps one Unix endpoint option. An automatic fallback could connect to a different endpoint and is not appropriate.
  • Overlong-name validation runs during preparation, before worker launch. The default 4-thread/50-client case was independently tested: it exits 1 with exactly one length diagnostic. The constructor sentinel lets the socket layer reject it before creating a descriptor; duplicating the same platform-specific address rule in main is unnecessary. Filesystem truncation is pre-existing and tracked separately.
  • The CI fallback directly fixes the gating failure encountered on this fork PR (run 39008083816: matrix fromJSON received empty input). Keeping this small integration fix here lets the required seven distro jobs execute. Its literal exactly matches today's upstream configuration, while configured values always win; the default list is maintained with the workflow. Independent BUILD recheck and actionlint pass.
  • Retry relies on the retained Linux AF_UNIX descriptor after EAGAIN; the existing retry comment explains that EAGAIN never queued a kernel connection, so connect must be retried after the timer. Both plaintext and TLS tests exercise this path. Every current reconnect path disconnects and frees the previous timer first. Independent lifetime probes cover active-timer cancellation, timeout races, allocation/arming failures, destruction and repeated reconnects: 212 timers allocated/freed with no residual events or sanitizer errors. A defensive assertion would be optional, not a fix for a current leak.
  • Waiting indefinitely when both startup limits are explicitly disabled is intentional; once steady state begins, the existing timed-run deadline remains effective for unlimited reconnects.
  • The earlier empty-name question was independently checked: a Linux abstract socket with an empty name can be bound and connected to, so rejecting -S @ would reject a valid endpoint. The fixed 10 ms retry is deliberate for prompt recovery; CPU controls catch spinning, and adaptive backoff can be evaluated separately. The README line was wrapped in 6c79ab4.

@cursor cursor 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.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 58a4789. Configure here.

Comment thread shard_connection.cpp Resolved
@fcostaoliveira

Copy link
Copy Markdown
Collaborator

Confirmed the distinct retained-path refusal case independently. The fixtures first fill the real Unix queue until EAGAIN, then close the listener without unlinking its pathname; a raw connect confirms ECONNREFUSED. All16 final-head/sanitizer process cases pass across plaintext/TLS and startup/established finite/unlimited retry policies, with exact error/reconnect counts, no extra TLS errors and no hang or spin (maximum3.044s and0.0243CPU cores).

A separate ASan/LSan/UBSan probe repeated the actual timer sequence800times: plaintext/TLS × restoring READ|WRITE/restoring the saved WRITE mask. Every case produced exactly one deferred error, zero TLS handshake starts, zero TLS error entries and zero residual events. libevent’s TLS enable path schedules event monitoring; it does not synchronously start a handshake here. The queued failure then reaches the existing cleanup/reconnect handler. The bot’s description of libevent returning0 for a scheduled refusal is correct; it did not produce an unsafe success path.

Restoring the old mask made no observable difference in this case, so I kept the reviewed implementation instead of adding state without a demonstrated need. The earlier ENOENT control alone was insufficient; this followup explicitly covers ECONNREFUSED. A generic TLS “Operation not supported” diagnostic is also present in direct refusals that never enter backlog handling, and is separate from this change. The README’s long line is a wrapping nit and does not change its documented policy.

The normal master merge49be62a resolves the post-#257 conflicts. Independent comparison confirms all production/test/doc entries match the previously tested combined tree; the sole difference is the already-approved CI fallback. All seven approvals and focused callback/refusal checks converge; fresh CI remains required.

@fcostaoliveira
fcostaoliveira merged commit d362619 into redis:master Oct 17, 2026
131 checks passed
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