Skip to content

Retry cluster shard connections that fail to dial synchronously - #574

Merged
fcostaoliveira merged 2 commits into
masterfrom
fix/refresh-connect-failure-reconnect
Oct 13, 2026
Merged

fcostaoliveira merged 2 commits into
masterfrom
fix/refresh-connect-failure-reconnect

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

In cluster mode, when a CLUSTER SLOTS refresh dials a shard connection and the dial fails synchronously, nothing schedules a retry. Examples are a getaddrinfo error, or EMFILE or ENETUNREACH from socket() or connect(). connect_shard_connection() returns false, and all four call sites in handle_cluster_slots() ignore it. No connection event reports the failure, and no reconnect timer is pending, because the refresh only dials connections that have none (!is_reconnect_pending()).

What happens next depends on the connection's role:

  • Primary: every key routed to the dead primary triggers another refresh, and each refresh dials it again straight away. There is no backoff, and --max-reconnect-attempts is never consulted. On master, with one primary announcing 224.0.0.1 (TCP connect fails with ENETUNREACH right away) and --reconnect-on-error --max-reconnect-attempts=3 --test-time=3, memtier made 10,642 failed dials and about 10.6k CLUSTER SLOTS refreshes in 3 s and exited 0.
  • Replica: a dead replica does not trigger a refresh, so it stays dead until something else does. This comes from reading the code; I did not run it.

Root cause

The issue's diagnosis is confirmed, with one addition: the bug is not only in shard_connection::connect(). The getaddrinfo failure path in connect_shard_connection() returns before connect() is even called.

The comment in shard_connection::connect() ("Cancel it only now, so a failed attempt above still leaves it to retry") only holds for a setup_socket() failure. A failing bufferevent_socket_connect() calls disconnect(), which frees the timer. Either way, since #560 no timer is pending when a refresh dials a connection, so nothing is left to retry it.

Fix

  • When a dial fails, connect_shard_connection() now calls sc->attempt_reconnect("Connection failed"), the same handling an asynchronous connection error gets. The connection then retries with backoff through reconnect() and a slot map refresh (the Reconnect only the dropped cluster connection, and only once #560 path), and each attempt counts against --max-reconnect-attempts.
  • This covers every synchronous failure on that path: getaddrinfo, setup_socket() (socket/fcntl, e.g. EMFILE), and bufferevent_socket_connect().
  • attempt_reconnect() is now public.
  • The comment in shard_connection::connect() is corrected.

Timers and attempt counting:

  • One timer at most. The refresh only dials connections with no pending timer, and attempt_reconnect() won't arm a timer while m_reconnecting is set. It also calls disconnect() first, which frees any timer.
  • One attempt per failed dial. When the timer fires, reconnect() returns 1 (refresh requested), and that path does not increment m_reconnect_attempts.

Behaviour change: without --reconnect-on-error, a synchronous dial failure now ends the worker thread ("Maximum reconnection attempts (0) exceeded ..."). Before, the connection stayed dead or kept being redialed. This matches what an asynchronous failure such as ECONNREFUSED on the same connection already does. The --read-preference exception in attempt_reconnect() (leave the connection dead while peers are still in setup) still applies.

This also applies to a transient resource failure such as EMFILE: without --reconnect-on-error the thread ends rather than running on with one shard's connection silently dead, which would skew the results. The non-cluster client already treats a failed dial as fatal (prepare: failed to connect, test aborted). With --reconnect-on-error, the failure is retried with backoff.

Stats change: attempt_reconnect() calls update_connection_error(), so synchronous dial failures are now counted in the connection-error stats and output. Before, they were not counted at all.

Test evidence

New test: test_reconnections.py::test_cluster_shard_dial_failure_honors_max_reconnect_attempts. It runs on cluster only, and sets cluster-announce-ip 224.0.0.1 on a non-seed primary, so dialing that primary fails synchronously with ENETUNREACH. It then runs memtier with --reconnect-on-error --max-reconnect-attempts=2 and checks that:

  • the number of synchronous dial failures is at most max+1. It counts the "Connection failed" lines that attempt_reconnect() logs, so the bound holds whichever step fails (getaddrinfo, setup_socket() or bufferevent_socket_connect()). The "connect failed" lines from bufferevent_socket_connect() are bounded too;
  • "Maximum reconnection attempts (2) exceeded for Connection failed" appears;
  • memtier exits non-zero.

It restores the announce IP in a finally block and asserts that the change propagates, so a poisoned topology fails this test rather than a later one.

Build Result
master (667f187) FAIL: "unreachable shard dialed 71304 times with --max-reconnect-attempts=2", exit 0
this PR PASS (about 9 s; 7 s after the test was tightened in 23974ef, rebased on f33599f)

Manual runs with this PR:

  • --max-reconnect-attempts=3 gives four failed dials, each at a 1 s backoff ("attempting reconnection 1/3 … 3/3"). Then the attempts are exhausted and the thread ends.
  • With --reconnect-backoff-factor=2 the backoff goes 2 s, 4 s, 8 s.
  • Recovery: with an unlimited budget, I cleared cluster-announce-ip mid-run. The next refresh connected the shard and traffic resumed: about 49.5k SETs on each of the three primaries in 8 s.

Regression check: test_reconnections.py and test_read_preference_failover.py on a local 3-shard OSS cluster: 12/12 passed.

Note: this test relies on TCP connect to a multicast address failing synchronously. Linux returns ENETUNREACH. The cluster suites only run on Linux CI.

Fixes #570

Affected versions: 2.4.0–2.5.2 and master (code history; widened by #560)

🤖 Generated with Claude Code


Note

Medium Risk
Touches cluster connection setup and reconnect accounting; behavior changes when synchronous dials fail without --reconnect-on-error (worker may exit instead of leaving a dead connection). Core reconnect path is shared with existing async errors.

Overview
Fixes cluster mode when a shard dial fails before the event loop (DNS/getaddrinfo, EMFILE, ENETUNREACH, etc.) during CLUSTER SLOTS handling. Those failures used to return from connect_shard_connection() with no reconnect timer, so refreshes could redial on every slot-map update without honoring --max-reconnect-attempts or backoff (#570).

connect_shard_connection() now calls attempt_reconnect("Connection failed") on any non-success path, matching async connection errors: backoff via reconnect(), attempts counted against --max-reconnect-attempts, and refresh-driven redials skipped while a timer is pending.

attempt_reconnect is public on shard_connection (moved out of private). Comments in shard_connection::connect() clarify when the reconnect timer is cleared vs left for the caller to schedule retry.

Adds cluster integration test test_cluster_shard_dial_failure_honors_max_reconnect_attempts (unreachable cluster-announce-ip) to assert bounded dials and exhausted-attempts exit.

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

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

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

Thanks for this. I went through the fix and the four call sites in handle_cluster_slots(), and I think the approach is right. A synchronous dial failure now goes through the same attempt_reconnect() path as an async connection error, instead of being redialed on every refresh. The single-timer argument also holds: attempt_reconnect() calls disconnect() first, and every caller already gates on !is_reconnect_pending() or on a freshly created connection. set_address_port() runs before getaddrinfo, so a connection that fails to resolve still matches on the next refresh rather than being created again. The test fails on master and passes here, which is the bar we want for this kind of fix.

One question, on the behaviour change you already flagged. Replicas are dialed from CLUSTER SLOTS whatever --read-preference is. With the default --read-preference=primary and no --reconnect-on-error, I think a replica whose announced hostname doesn't resolve from the client host now ends the worker thread, even though nothing is ever routed to it. Before, the run kept going against the primaries. I agree it matches what an async ECONNREFUSED on that replica already does, so it's consistent. But unresolvable announced hostnames (cluster-announce-hostname behind NAT, split DNS) seem like a fairly realistic deployment to start failing outright after an upgrade. Did you consider leaving a dead replica alone under rp_primary, like the existing --read-preference carve-out does for peers still in setup? Or is the stricter behaviour intentional here? This may be worth a second look from whoever owns the cluster connection lifecycle.

Nitpicking: the if/else restructure in connect_shard_connection() re-indents the whole body. Keeping the early return and calling sc->attempt_reconnect("Connection failed") just before it, plus once after sc->connect(), would make the diff smaller. Not a big deal either way.

The core fix looks solid. I'd just like the replica/default-config question answered before this merges.

fcostaoliveira and others added 2 commits October 13, 2026 17:42
When a CLUSTER SLOTS refresh dials a shard connection and the dial fails
before reaching the event loop (a getaddrinfo error, or EMFILE or
ENETUNREACH from socket()/connect()), connect_shard_connection() only
returned false and every caller ignored it. No connection event reports
such a failure and no reconnect timer was pending, since a refresh only
dials connections without one. The connection was left dead with nothing
to retry it: it was redialed with no backoff on every refresh that a key
routed to it triggered, ignoring --max-reconnect-attempts, or never, for
a replica, which triggers no refresh.

Handle the failure like a connection error with attempt_reconnect(), so
the connection is retried with backoff through a slot map refresh and
counts against --max-reconnect-attempts.

Fixes #570.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Assert that the announce IP is reverted in the test's finally block, so a
topology left poisoned fails here rather than in a later cluster test.

Count every synchronous dial failure through the "Connection failed"
lines that attempt_reconnect() logs, whichever step failed, and require
the exhaustion message to name that context. The "connect failed" count,
which only covers bufferevent_socket_connect(), stays as a second bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira
fcostaoliveira force-pushed the fix/refresh-connect-failure-reconnect branch from 7cc08aa to 23974ef Compare October 13, 2026 16:44
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. I rebased onto current master (f33599f, with #571–#573) without conflicts. The fix commit is now 0a99e87 and is unchanged apart from the rebase. The test changes are in 23974ef.

1. EMFILE without --reconnect-on-error: yes, this is intended for resource exhaustion as well. Without --reconnect-on-error, every other connection error is already fatal: refused, dropped, timed out. The non-cluster client also aborts when its dial fails (prepare: failed to connect, test aborted). The old behaviour was worse: the run kept going with one shard's connection dead, or redialed it on every refresh, and nothing reported it. That skews the results without any warning. With --reconnect-on-error, a short-lived EMFILE is now retried with backoff, which is the right fix for it. I added this reasoning to the "Behaviour change" paragraph in the description.

2. Connection-error stats: agreed. Synchronous dial failures now go through update_connection_error() and appear in the connection-error stats and output. I added a "Stats change" line to the description.

3. wait_announced(False) in finally: the test now asserts on it: announced address 224.0.0.1 was not reverted. A poisoned topology now fails this test, not a later one (23974ef).

4. Counting only "connect failed": tightened in 23974ef. Every synchronous dial failure goes through attempt_reconnect("Connection failed"), whichever step fails (getaddrinfo, setup_socket() or bufferevent_socket_connect()). The test now counts the Connection failed, attempting reconnection lines, plus the terminal exhaustion line, and bounds that count by max+1. It also requires the exhaustion message to read ... exceeded for Connection failed, so it must come from the synchronous path. I kept the "connect failed" count as a second bound.

I ran the test locally on a 3-shard OSS cluster and it passes.

🤖 Generated with Claude Code

@fcostaoliveira
fcostaoliveira merged commit 240b2e2 into master Oct 13, 2026
126 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 13, 2026
hand_off_replay_requests() runs inside a CLUSTER SLOTS reply handler,
possibly the one of the connection that now owns the slot. Resending
from there pushed onto that connection's pipeline mid-process_response(),
before its m_cluster_slots was setup_done. adopt_replay_request() now
only queues the request and calls schedule_fill(); fill_pipeline()
resends it once the connection is connected and set up. A connection
that isn't connected yet still resends it when it connects.

Drop and uncount, with a --failed-keys-file line, a request that:
- is held under --transaction, as MOVED/ASK do, since resending it on
  another connection would split its MULTI/EXEC block or land inside
  one that connection has open;
- targets a primary that is disconnected with no reconnect pending.
  The refresh dials every primary without a pending timer, and since
  #574 a failed dial schedules one, so this is a primary that
  attempt_reconnect() gave up on (no --reconnect-on-error, or
  --max-reconnect-attempts reached).

adopt_replay_request() asserts the replay queue exists instead of
silently dropping the request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 13, 2026
hand_off_replay_requests() runs inside a CLUSTER SLOTS reply handler,
possibly the one of the connection that now owns the slot. Resending
from there pushed onto that connection's pipeline mid-process_response(),
before its m_cluster_slots was setup_done. adopt_replay_request() now
only queues the request and calls schedule_fill(); fill_pipeline()
resends it once the connection is connected and set up. A connection
that isn't connected yet still resends it when it connects.

Drop and uncount, with a --failed-keys-file line, a request that:
- is held under --transaction, as MOVED/ASK do, since resending it on
  another connection would split its MULTI/EXEC block or land inside
  one that connection has open;
- targets a primary that is disconnected with no reconnect pending.
  The refresh dials every primary without a pending timer, and since
  #574 a failed dial schedules one, so this is a primary that
  attempt_reconnect() gave up on (no --reconnect-on-error, or
  --max-reconnect-attempts reached).

adopt_replay_request() asserts the replay queue exists instead of
silently dropping the request.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

Cluster: synchronous connect failure on the slot-refresh path leaves the shard with no reconnect timer

1 participant