Skip to content

Re-route staged cluster monitor lines when the slot map changes - #885

Open
fcostaoliveira wants to merge 28 commits into
masterfrom
claude/monitor-staged-reroute-835
Open

fcostaoliveira wants to merge 28 commits into
masterfrom
claude/monitor-staged-reroute-835

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #835.
Fixes #836 for staged monitor lines. Routed built-in keys (m_key_index_pools) on a retired or demoted connection are still cleared, as before; that is now #889.

Problem

With --cluster-mode --monitor-input, a monitor line was routed once, when it was staged, and nothing checked the committed slot map again before it was sent. The replay cursor had already moved past each staged line, so every line lost here was never sent. Later selections then wrapped and repeated earlier lines. Totals Count and the exit code stayed the same, so nothing reported it. There were four ways to lose or misroute lines:

Change

  • Record the slot: each staged line now records its hash slot.
  • Re-route on commit: right after a new map is committed, and before connections are retired, reroute_staged_monitor_commands() moves each line to its slot's current primary.
    • Lines for one slot share a queue and move together, so a slot that had an owner whenever its lines were staged keeps its selection order. Lines staged while the slot had no owner merge in connection order.
    • Lines for a slot the new map leaves unowned stay on a primary of the new map, or move to the fallback primary.
  • Counting: m_reqs_generated is unchanged for moved lines. A line is dropped only when the primary it would be sent from was given up on (and, for an unowned slot, no other primary is live or reconnecting). A move never drops a line, even past the staging cap: the cap bounds new staging, and a producer still sends a line itself rather than stage it on a queue at the cap. A dropped line no longer counts toward --requests, but it now counts as an error, is logged to --failed-keys-file (slot-owner-down-for-monitor-line; unroutable-monitor-line for a keyless line, which only a staging bug could stage), and prints one warning per map commit. "Given up on" is one test, primary_given_up(), shared by the re-route, the replay hand-off and the unowned fallback, and it asserts (asserts are live in release builds; configure.ac doesn't define NDEBUG) that an awaiting-redial mark implies a down connection with no timer; the fallback additionally counts a given-up primary while the seed refreshes SLOTS, since that commit redials it. The error count and failed-keys logging match hand_off_replay_requests(). Before, these drops were silent.
  • Lines left on a primary that was given up on: the given-up check (disconnected, no reconnect timer) runs for every line, not only lines that move. A line already on its given-up owner is dropped and counted the same way, and an unowned line there moves to a live primary. Before, such a line stayed counted with nothing to send it, so a --requests run never finished. Master has the same hang.
  • A main connection whose dial fails at once: cluster_client::connect() now returns client::connect()'s error instead of 0. A main-connection dial that fails before reaching the event loop (a resolve or socket error, or a connect() error that libevent 2.1 doesn't report through the event loop) is retried on its reconnect timer every time and counted against --max-reconnect-attempts. It is no longer taken for a dial in progress and left down with no timer. A shard that left its redial to the main connection keeps waiting while the main connection retries; once the main connection is given up on, the shard's staged lines are dropped and counted. Master leaves both connections down in this case.
  • Given up between commits: under --read-preference other than primary, a primary can be given up on while its thread keeps running. A new handle_connection_given_up() hook runs the re-route at that point, so its staged lines are dropped or moved at once instead of staying counted until the next commit. A give-up while handle_cluster_slots() is parsing a reply is left to that reply's commit. A shard whose reconnect timer left its redial to a CLUSTER SLOTS refresh has no timer but isn't given up on: it is marked as awaiting that redial, and the re-route keeps its lines. The mark ends when the shard is dialed again, when a map retires it, or when it or the main connection is given up on; the main connection's give-up re-routes, so lines that waited on it are dropped. Dropped lines also wake every producer, since uncounting them can let a producer parked at the --requests cap continue.
  • "Primary" comes from the committed map: a node demoted while its reconnect timer is pending still has role_primary on its connection, so the re-route reads the new map's shard groups instead.
  • Retire path after Don't count connection rejections as replies #897: the retire body now lives in release_retired_connection(), shared with Don't count connection rejections as replies #897's handle_connection_retired(). It clears the awaiting-redial mark before disconnect() and re-routes staged lines instead of flushing them.
  • No more flushes: handle_moved() no longer flushes the staged queue. A replica redial or a promotion keeps staged monitor lines; a redial to a different endpoint still clears both queues.
  • Cost: the send path is unchanged. A run without --monitor-input pays one empty-queue check per connection per topology commit.

Results

Scripted 3-node peer, sequential 20-line monitor file replayed with --requests=40 (alternating PING and the monitor line), pipeline 1 and 4. Each cell shows lines missing / duplicated / misrouted for that case:

Case master this PR
Slot moved (new or already-connected owner) up to 7 / 3 / 2 0 / 0 / 0
Owner retired up to 8 / 4 / – 0 / 0 / 0
Owner demoted (with or without MOVED, silent, while redialing or reconnect-pending, with an unowned slot) lines lost, or up to 8 sent to the replica 0 / 0 / 0

Totals Count was 40 and the exit code 0 in every run, on both builds.

On a real 3-primary cluster (Redis 8.6.0, 1,000,000 INCR lines, pipeline 16, --retry-on-error), slot migration, failover, a drained primary's retirement and a paused takeover lost 1 to 63 lines per run on master and 0 with this PR.

Release notes

With --monitor-input in --cluster-mode, an already-selected monitor line that can no longer be sent (its slot's primary was given up on) is now counted as an error and logged to --failed-keys-file instead of being skipped silently. This changes the reported error counts, not the exit code.

In --cluster-mode, a dial of the main connection that fails before reaching the event loop (for example an unreachable network, which libevent 2.1 doesn't report through the event loop) is now handled as without --cluster-mode. With --reconnect-on-error, every retry counts against --max-reconnect-attempts, instead of the connection being left down with no retry. At startup, such a failure now aborts at once with "prepare: failed to connect, test aborted.", as without --cluster-mode (a startup dial is not retried, even with --reconnect-on-error). The exit code is unchanged.

Tests

  • New tests: three tests in tests/test_cluster_unowned_slots.py, covering 19 cases.
    • They check that every file line is sent exactly once, to its owner, in order.
    • Where two primaries drain at once, order is checked per key.
    • They fail on master and pass with this PR, 3/3 each.
  • Unit test: tests/unit/cluster_transaction_test.cpp expected a replica redial or a promotion to clear staged monitor lines, which is the redialing-demote loss above. It now expects them to be kept. New unit blocks cover the drop wake, the parse-window skip, the awaiting-redial mark (both reconnect paths, the main connection's give-up, the shard's own timer, and an unreachable main connection with a cap of 1, 2 and unlimited), a move onto a queue at the staging cap, and the shared given-up test.
  • Startup abort: test_cluster_startup_dial_failing_at_once_aborts seeds --cluster-mode with 255.255.255.255, whose connect() fails before the event loop. It checks for exit 1 and "prepare: failed to connect, test aborted." within 10 s, and skips with a reason where that dial wouldn't fail at once. Master instead launches the thread and ends it with no request sent.
  • Error accounting end to end: test_given_up_primary_monitor_drops_are_reported gives a primary up mid-run while a replica is still in setup, so its staged lines are dropped. It checks the slot-owner-down-for-monitor-line records in --failed-keys-file and that the Errors count under ALL STATS equals the number of failed-keys records (the drops plus any request held for resend when the thread ended). The fake servers order the drops from evidence, so a line is staged on the primary while its redial is in setup. A 3-try loop is kept only as a margin. It fails on master and on a mutant that skips the error count.
  • Mutants: 37 of 40 are caught. They include dropping a moved line at the staging cap, the main connection's retry after a dial that fails at once (returning connect()'s error, starting that retry from a shard's reconnect(), and marking the shard before it), the two given-up rules added in 08fab58, the live-primary fallback added in f87277c (its unit block reproduces Bugbot's dead-primary case), the wake on a drop, the parse-window skip, the fallback's use of the shared given-up test, and every part of the awaiting-redial mark: setting it on both reconnect paths, honouring it, and clearing it on a redial, a retirement and the main connection's give-up. A unit test reaches the drop path and checks the error count and the failed-keys record, and a pending-reconnect case catches the role-based rule. Three survive. Marking the shard after connect() but before that retry is equivalent on libevent 2.1, where the give-up can't run inside connect(). The wake of the target connection can't be seen in the unit harness, and every fixture wakes the target some other way. The replay hand-off using the old given-up test is equivalent, since it runs right after the commit's redials.
  • Related suites: standalone 104/104, 3-shard cluster 47/47, cluster with replicas 35/35, and make check 18/18.
  • Merge with Back off CLUSTERDOWN topology refreshes per client #877: the merge is clean, with make check 18/18 and 63/63 RLTest, including Back off CLUSTERDOWN topology refreshes per client #877's tests.

Affected versions

The staging queue, and with it the slot-move and retire losses, came in with 38a5369 (#395, cluster --monitor-input), released in 2.4.0 through 2.5.2. Since 38a5369 any redial cleared staged lines. #799 (4018396, unreleased) kept them for same-endpoint primary redials but still cleared them on a replica redial, demotion included, and began staging during refresh and backoff, which widened the window.

🤖 Generated with Claude Code


Note

High Risk
Changes cluster monitor replay, topology commit, reconnect/give-up handling, and request accounting during failovers—areas that can hang runs or mis-count ops if wrong.

Overview
Cluster --monitor-input replay now keeps unsent monitor lines aligned with the slot map instead of flushing them on failover, redial, or -MOVED.

Each staged line records its hash slot; on every committed CLUSTER SLOTS map (and when a primary is given up mid-run), reroute_staged_monitor_commands() moves lines to the slot’s current primary while preserving per-slot order. Lines are dropped only when no viable primary exists (primary_given_up()): they are uncounted for --requests, counted as errors, and logged to --failed-keys-file. Replica redials still clear routed read keys only; staged monitor writes survive same-endpoint primary redials, demotion, and promotion. Shards waiting on a seed refresh use awaiting_slots_redial so they are not treated as permanently dead.

Other fixes: cluster_client::connect() propagates immediate dial failures (startup abort; main-connection retries bounded by --max-reconnect-attempts); handle_moved() no longer clears the staged monitor queue. README documents the new semantics. Integration tests (_Failover, given-up primary drops) and expanded cluster_transaction_test.cpp cover the behavior.

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

In cluster --monitor-input mode a monitor line is routed once, when it is
staged on its owner primary's queue, and is counted as generated then.
Since #799 lines are also staged on a primary while it refreshes CLUSTER
SLOTS or redials. A refresh committed before the queue drains could
leave the lines on the wrong connection:

- the slot moved: the lines went to the old owner and got -MOVED, and
  handle_moved() then cleared and uncounted the rest of the queue (#835);
- the owner was retired: the commit loop cleared and uncounted its queue
  (#836);
- the owner was demoted: the lines drained on a replica connection, or,
  if it was redialing, the replica reset cleared them (#836).

The replay cursor had already moved past cleared lines, so they were
never sent, and later selections wrapped and repeated earlier lines.
Totals Count stayed exact, so nothing reported it. On a scripted 3-node
peer replaying 20 SET lines, master missed up to 8 and duplicated up to
4 per run, and sent up to 8 to a node that did not own their slot.

Each staged line now keeps its slot, and committing a map moves every
line to the slot's current primary, as hand_off_replay_requests() does
for held replays. A slot's lines are on one queue and move together, so
each slot keeps its selection order. They stay counted. An unowned slot
keeps its lines on a primary that is still one, or goes to the fallback
primary. Only a line whose new primary was given up on, or whose queue is
full, is dropped and uncounted, as before. handle_moved() and the
demoted-replica redial keep the queue for that re-route; a redial to a
different endpoint still clears it. The work happens only at commit
time, so the drain path and non-monitor runs do not change.

test_cluster_unowned_slots.py adds a scripted primary/replica/spare
fixture that moves a slot, retires the primary or demotes it (with and
without -MOVED, after a silent change, while redialing, and with an
unowned slot), at pipeline 1 and 4. It checks that every file line is
sent exactly once, to its slot's owner, in order, with Totals Count 40
and exit 0. The queue-ownership unit test now expects demotion and
promotion to keep staged monitor lines.

Fixes #835
Fixes #836

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

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

Thanks for this. It's a big one, but the description and commit messages make it easy to follow, and the scripted failover fixtures plus the fails-on-master unit blocks are what I'd want for a change to accounting and routing. A few questions:

  1. Different-endpoint redial still clears staged lines. connect_shard_connection() still calls reset_shard_queues(id, !same_endpoint), so a connection redialed to a different endpoint inside the handle_cluster_slots() node loop loses its staged monitor lines silently: they're uncounted, with no error and no failed-keys record. A few lines later, reroute_staged_monitor_commands() runs on the same commit and could have moved them. Is there a reason not to keep them there too, now that the commit always re-routes? Otherwise this looks like the same skipped-line class as Cluster --monitor-input: a staged monitor command is sent to the connection it was staged on even after a newer slot map moved its slot. The MOVED that follows flushes the rest of that queue. #835/Cluster --monitor-input: when a slot-map refresh retires or demotes a primary, its staged monitor lines are silently dropped and replaced (or sent to the demoted node) #836, just a narrower case. I may be missing why a reused connection id can't hold them.

  2. Scope. I'm a bit hesitant about bundling the cluster_client::connect() return-value change with this fix. It changes startup behavior for every --cluster-mode run, not just --monitor-input: an immediate dial failure now aborts with "prepare: failed to connect", where before the thread was launched. I agree it's the right behavior, it matches non-cluster mode, and it's in the release notes and tested. Did you consider splitting it out, though? It would bisect more cleanly if someone's cluster startup changes and they go looking for why.

  3. Cost of the re-route on a commit. reroute_staged_monitor_commands() swaps every non-empty queue out and pushes each line back, even when nothing moves. Usually only a few lines are staged, but during a migration each -MOVED leads to a refresh and a commit, and queues can grow up to m_staged_monitor_queue_max (and past it on a move now). I wonder if a cheap first pass that skips a queue when every line would stay is worth it, or if you've measured that it doesn't matter.

  4. Reported errors. Counting dropped lines as Errors and logging them to --failed-keys-file is a visible change to the reported numbers. I think it's justified, since silently skipping lines was worse and the exit code doesn't change. Just flagging it so the release note keeps that wording.

  5. State added along the way. The given-up logic picked up m_awaiting_slots_redial, m_parsing_slot_map and the handle_connection_given_up() hook over several Bugbot rounds. Folding it all into primary_given_up() helps a lot. Is the invariant that function asserts (mark ⇒ disconnected, no timer) also checked anywhere the mark is set, so a future caller can't set it on a live connection and only find out much later?

Nitpicking: test_cluster_unowned_slots.py parses CLUSTERDOWN_REFRESH_INTERVAL_USEC from cluster_client.h with a regex. It fails with a clear message, which is good, but it ties the test to how the header is written. Also, the 3-try loop in test_given_up_primary_monitor_drops_are_reported could hide a regression that only makes the drop rarer. Maybe log when a retry was needed, so CI flakiness shows up?

The core re-route looks right to me, and the per-slot ordering argument holds. I'd like the different-endpoint question answered before this merges, and since this is cluster-routing territory, a second look from whoever owns cluster topology handling would be good.

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

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

Stale Bugbot comment from a previous run.

Comment thread cluster_client.cpp Resolved
fcostaoliveira and others added 4 commits October 25, 2026 13:44
reroute_staged_monitor_commands() kept a staged line for an unowned slot
on its connection if that connection's role was primary. A node the new
map lists as a replica while its reconnect timer is pending is not
relabeled (set_shard_role() runs only when it is redialed), so it still
looked like a primary. Its unowned lines stayed on it until the timer
fired and the next refresh moved them, after lines selected later had
been sent, so the slot's selection order was lost.

Decide "primary" from the committed map's shard groups instead of the
connection's role. A retired connection is not in the map, so the
retired vector is no longer needed.

A line the re-route drops, because its new primary was given up on or
its queue is full, is now logged to --failed-keys-file, warned about
once per commit and counted as an error, as hand_off_replay_requests()
does for replays. Before, it was only uncounted.

The README says that lines already sent are resent only with
--retry-on-error, and that each slot keeps its selection order.

test_cluster_unowned_slots.py adds a demote-hole case where A closes
instead of answering the refresh and R's CLUSTERDOWN commits the map
while A's reconnect timer is pending. Before this change, lines 4 and 6
were sent after line 19. The unit test calls the re-route with a
given-up primary and checks that the line is dropped and uncounted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The warning for staged monitor lines the re-route drops said "that no
primary can send", which is wrong when the primary is up and only its
queue is full. It now names both reasons.

The --failed-keys-file record for such a line used the command label
MONITOR, while the same line failing after it is sent is logged as
ARBITRARY. It now uses ARBITRARY too, so one monitor line has one label.

The unit test for a line whose new primary was given up on now also
checks that the drop counts as an error and is logged to
--failed-keys-file with its key and reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The README and the re-route comments said every slot keeps its
selection order. That holds for a slot that had an owner whenever its
lines were staged: they are all on one queue and move together. Lines
staged while the slot had no owner went to fallback_primary_conn_id(),
which can change between selections, so once the slot has an owner they
merge in connection order. The text now says so. Behaviour is
unchanged.

reroute_staged_monitor_commands() now asserts that a staged line has a
slot. Only keyed lines are staged, and a keyless UINT_MAX slot would be
dropped as slot-owner-down-for-monitor-line, so a later change to the
staging condition would fail loudly instead.

In test_cluster_unowned_slots.py, _Node defines the ping_reply and
set_reply hooks that _Failover overrides, instead of the handler
probing for them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The pending=True case held R's third PING after A's refresh, closed A
after a 0.3 s sleep and answered that PING with CLUSTERDOWN 1.3 s after
A's first SET. Under CPU load it failed about 1 run in 10 on its
node.held check. If A's CLUSTERDOWN reached memtier late, R had already
filled the in-flight budget with lines staged on A. It stalled with
nothing outstanding on R, sent no PING after the refresh, and the map
was committed only by A's reconnect timer. Delaying A's first SET reply
by 0.5 s reproduced it 5 times in 9.

Before the refresh, R's PINGs are now answered only once A has received
the lines selected before them, so R cannot stall. After the refresh, R
holds the first PING behind which an unowned line is staged on A.
Because the client alternates PING and monitor line, that is any line
selected before the PING that no node has received. A closes its refresh
once that PING is held, and the PING gets CLUSTERDOWN one second after
A's SLOTS request arrived. That request bounds memtier's last
CLUSTERDOWN poll, so the reply is always acted on. The 0.3 s sleep and
the 1.3 s guess are gone, and node.held is still asserted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the careful read. Answers in order, with lines at c5889c3; the follow-ups are 2e850ed (wording, assert, nit) and 3376ad7 (fixture).

Queue-full drop on reroute. You're right that the cap isn't needed here. STAGED_MONITOR_QUEUE_MAX_SIZE (cluster_client.cpp:59) came in with 38a5369 to stop a producer from growing a target queue without limit, matching KEY_INDEX_QUEUE_MAX_SIZE. The reroute doesn't produce anything: it moves lines that are already counted and in memory. Nothing on the drain side depends on the cap. create_request() pops one line at a time (2704), hold_pipeline() only checks whether the queue is empty, and reset_shard_queues() uncounts the real size (316). In practice neither cap check can fire. hold_pipeline() keeps generated minus processed under pipeline × connections (1647-1659), and --pipeline is capped at 1024 (memtier_benchmark.cpp:1730), so a queue reaches 1M lines only with about 1,000 shard connections in one client. So the staged-monitor-queue-full branch (2949) can't be reached in a test. Letting the target overshoot is the better rule: it never loses a selected line and adds no memory. I'd rather make that change in a small follow-up than grow this PR, but I can fold it in if you prefer.

Order for slots that used to be unowned. Correct, and it wasn't covered. Lines staged while the slot had no owner went to fallback_primary_conn_id() (2935, 507-526). If that changes between selections, the lines sit on two queues, and once the slot has an owner the reroute merges them in connection order. 2e850ed narrows the README and the comments in cluster_client.cpp/.h: selection order is kept for a slot that had an owner whenever its lines were staged. Behaviour is unchanged. Keeping order across unowned periods would need a per-slot sequence number, and I don't think this edge case is worth that.

Re-processing moved lines. It's intended, and it's safe because the target rule is idempotent. An owned line resolves to slot_primary_conn_id(slot), which depends only on the committed map. An unowned line moved off i goes to fallback_primary_conn_id(), which only returns primaries of that map. So when the loop reaches j, keeps is true and the line stays on j (2928-2937). It's re-pushed in the same order, and the drop checks under target != i (2939) don't run again. A line moved to a lower j isn't revisited, and the loop is a single pass over indices, so it always ends. A future rule that isn't idempotent (round-robin fallback, role-based keeps) could move a line twice, and that would be a visible change to this function.

Keyless sentinel. Agreed. Only keyed lines are staged: slot is set only for a non-empty first key (2811-2823), and the queue-full path sends the line instead of staging it (2850). 2e850ed adds assert(staged.front().slot != UINT_MAX) with a comment at the top of the reroute loop. assert is already used throughout cluster_client.cpp.

Fixture timing. Good call; it wasn't solid. In CI on c5889c3 the case passed in all 6 cells that run the file, ASAN, TSAN and UBSan included, on the first attempt. Locally, under load (one CPU, two busy loops, nice 19), it failed 1 run in 10 on its node.held check, though every line was still delivered once and in order. Injecting delays found the cause. When A's CLUSTERDOWN reached memtier late, R had already filled the in-flight budget with lines staged on A and stalled with nothing outstanding on R. So no PING came after the refresh, and the map was committed only when A's reconnect timer fired. Delaying A's first SET reply by 0.5 s reproduced it 5 times in 9. 3376ad7 replaces the counts and sleeps with a condition shared by the fixture's handlers. Before the refresh, R's PONG waits until A has received the lines selected before that PING, so R can't stall. After the refresh, R holds the first PING behind which an unowned line is staged on A; since the client alternates PING and monitor line, that is any line selected before the PING that no node has received. A closes its refresh only once that PING is held. The PING gets CLUSTERDOWN one second after A's SLOTS request arrived, which bounds memtier's last CLUSTERDOWN poll, so the reply is always acted on. node.held stays a strict assert. With it, the pending case passed 20/20 under the same load and 27/27 across nine delay-injection points, including the one that reproduced the failure. The whole file passes 28/28. The old round-1 role rule (A demoted while its timer is pending still keeps unowned lines) still fails the case 5/5, with lines 4 and 6 sent last.

Nit. Done in 2e850ed: _Node defines ping_reply() and set_reply = None, and the handler calls them directly.

Release notes. Agreed. --monitor-input cluster runs can now show errors and --failed-keys-file rows (slot-owner-down-for-monitor-line / staged-monitor-queue-full) where those lines used to be lost silently. I'll add a line for the release notes to the PR body.

🤖 Generated with Claude Code

reroute_staged_monitor_commands() checked for a given-up primary
(disconnected with no reconnect timer) only when a line moved. A line
whose slot's primary is the connection it is already on stayed there.
Nothing sends from that connection or uncounts the line, so a
--requests run would never finish. The commit redials such a primary
before the re-route, so this needs that redial to fail at once and the
connection to be left dead. The check now runs for every line. An
unowned line on a given-up primary no longer stays: it moves to another
primary, as from any connection that is not a primary of the map.

The unit test checks both cases: the owned line is dropped, uncounted
and counted as an error, and the unowned line moves to the primary that
is still dialing. stage_unsent() now sets the slot of the line it
stages (the slot the second shard owns) instead of leaving it 0.

The pending=True fixture comment names the C++ CLUSTERDOWN throttle
(m_last_clusterdown_refresh, 1000000 us, in handle_response()) that its
one-second wait depends on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the second pass. Line numbers are at 08fab58, which follows 3376ad7.

Malformed or stale refresh. The churn is bounded, and it is the same as on master. handle_moved() returns at once while the connection's own refresh is in flight (cluster_slots_state != setup_done, cluster_client.cpp:2878). So there is one refresh per connection at a time, and MOVEDs that arrive during it are ignored. A malformed reply doesn't drain anything. With !any_valid_shard, handle_cluster_slots() returns false, and the connection stays in setup_sent (shard_connection.cpp:1644 and on). It then retries, or once the run has started, ends the thread or reconnects with backoff (retry_cluster_slots_after_error(), 2567). It never returns to setup_done, so staged lines don't go to the old owner. A stale reply does drain them there. Each MOVED that arrives with no refresh in flight starts one refresh, as for any keyed command routed by a stale map. I measured it with scripted peers: one primary answers every SET with -MOVED, and its SLOTS replies are stale or all-malformed. Base 29f63de vs this branch, CLUSTER SLOTS requests: stale 200/200 (N=200, pipeline 1), 1000/1000 (N=1000, p1), 51/51 (N=200, p4), 251/251 (N=1000, p4) and 64/64 (N=1000, p16). Malformed: 3/3 before the thread ends without --reconnect-on-error, and 6/6 with three reconnects. SETs, connections and exit codes match too. So it's at most one refresh per pipeline window of MOVEDs, never more than one per line, and keeping the staged lines adds no extra refreshes.

target == i on a given-up primary. Mostly pre-existing, but worth closing. A committed map that lists a disconnected primary with no timer redials it before the re-route runs (1196-1207). So this needs that redial to fail at once and the connection to be left dead: attempt_reconnect() does that only under --read-preference with peers still mid-setup. In that state the lines never drained on master either. hold_pipeline() skips a disconnected connection, and a --requests run waits on them (client.cpp:346). 08fab58 runs the given-up check for every line (2930-2958). A line on its own given-up owner is now dropped like a moving one: uncounted, counted as an error and logged. An unowned line there moves to another primary. Two new unit blocks cover this, and the first one fails on 3376ad7.

Release note. Agreed. The PR body now has a line about drops counting as errors.

Throttle comment. Done. The wait comment names m_last_clusterdown_refresh and the 1000000 us check in cluster_client::handle_response() (3362), and says the test must change if the throttle does.

stage_unsent(). Done. It now takes the slot explicitly: the slot it gives the second shard, or staged_slot, which that shard owns in those blocks.

Checks on 08fab58: make check 18/18, the whole test file 28/28, the pending case 5/5 under load, and clang-format clean.

🤖 Generated with Claude Code

handle_moved() no longer flushes a connection's staged monitor lines:
they wait for a committed map to move them. A connection that runs out
of reconnect attempts usually ends its thread, and the run then
abandons what is left and fails. Under --read-preference other than
primary, with a peer still in setup, attempt_reconnect() and the
reconnect timer instead leave the connection dead and the thread goes
on. Its staged lines stayed counted with nothing to send them, so a
--requests run waited on them until some other commit came. Master
flushed the lines staged before the -MOVED, but kept those staged
after it.

Both branches now call handle_connection_given_up(). cluster_client
runs the re-route there: lines of the dead primary's own slots are
dropped, uncounted, logged and counted as errors, and the rest move to
their slot's primary.

The unit test gives up a primary with a staged line while a peer is
still dialing, and checks that the line is dropped and uncounted and
counts as an error. On 08fab58 the line stayed counted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

fcostaoliveira commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thanks. Line numbers are at 4d6f516, which follows 08fab58.

-MOVED, then given up. In the usual case nothing hangs, and it's the same as master. A connection that runs out of reconnect attempts calls end_thread() (shard_connection.cpp:2178-2186, reached at 2297), which breaks the event loop. client_group::run() then abandons what is left (client.cpp:1524-1539, abandon_replay_requests at 1533), the run is marked invalid, and main() returns 1 (memtier_benchmark.cpp:5030, 6785). I reproduced it with scripted peers. One primary answers every SET with -MOVED, then closes when asked for CLUSTER SLOTS and refuses redials, with --reconnect-on-error --max-reconnect-attempts=1 (and 5), --requests=40, p1 and p4. Master bc1708a and this branch both end the thread with "results of this run are not valid" and rc=1 within 2-6 s. But you're right that there was a gap. Under --read-preference other than primary, with a peer still in setup, attempt_reconnect() and the reconnect timer leave the connection dead and the thread goes on (2290, 2716). Its staged lines then stayed counted with nothing to send them. Master flushed the lines staged before the -MOVED but kept those staged after it, so the exposure isn't new, only wider here. 4d6f516 adds a handle_connection_given_up() hook in both branches (2294, 2720). cluster_client runs the re-route there (cluster_client.cpp:3314): lines of the dead primary's own slots are dropped, uncounted, logged and counted as errors, and the rest move. A new unit block gives up a primary with a staged line while a peer is dialing. It fails on 08fab58.

The other cases' sleep(0.3). I ran all 18 non-pending _Failover cases 10 times under load (one CPU, two busy loops, nice 19): 180/180 passed. The sleep only keeps A's refresh pending a bit longer, so more lines get staged on A. Those cases assert only the outcome (each line once, never on a non-owner after the refresh, order kept), never how many lines were staged. So load can thin their coverage but can't make them fail. The pending case was different: it needed a specific event order and asserted it (node.held), and that's why it got gated.

Exit code. A re-route drop doesn't change it. main() returns 2 for a connection-stage abort, 1 if a worker thread ended early or output or verification failed, and 0 otherwise (memtier_benchmark.cpp:6780-6792). The error count isn't consulted. Suggested release note: "With --monitor-input in --cluster-mode, an already-selected monitor line that can no longer be sent (its slot's primary was given up on, or the target's staged queue is full) is now counted as an error and logged to --failed-keys-file instead of being skipped silently; this changes the reported error counts, not the exit code."

Checks on 4d6f516: make check 18/18, the whole test file 28/28, and clang-format clean.

🤖 Generated with Claude Code

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

Stale Bugbot comment from a previous run.

Comment thread cluster_client.cpp Resolved
reroute_staged_monitor_commands() sent an unowned line on a primary
that is not kept to fallback_primary_conn_id(), and dropped it if that
primary was given up on. While the seed is refreshing CLUSTER SLOTS,
fallback_primary_conn_id() also counts a primary that is disconnected
with no reconnect timer, because the refresh may redial it. So a
given-up primary listed first won over a later one that was dialing or
reconnect-pending, and the line was dropped instead of moved
(Cursor Bugbot).

The re-route now picks its own fallback once per call: the first
connected primary of the map, else the first one that is not given up
on. A line is dropped only if there is none. fallback_primary_conn_id()
and its other callers are unchanged.

The unit test gives up the first of two primaries while the second
dials and the seed refreshes SLOTS, and checks that the unowned line
moves to the second. It failed on 4d6f516.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the careful pass. Line numbers are at f87277c.

handle_moved() with --pipeline > 1. There is a gate, in fill_pipeline() rather than hold_pipeline(). handle_moved() calls set_cluster_slots() (cluster_client.cpp:2903, which sets setup_none, shard_connection.h:216). Every pass of the fill loop first checks !is_conn_setup_done() and, if so, sends the setup commands and returns (shard_connection.cpp:1934-1941). That is before hold_pipeline() and before create_request() (1967). is_conn_setup_done() needs m_cluster_slots == setup_done (1375-1379), which only a committed reply sets again (1648). Staged lines drain only from create_request() (cluster_client.cpp:2700-2705), so none is sent on that connection between the -MOVED and the commit. The only -MOVEDs are requests already on the wire when it arrived, as on master. The one exemption is an open pinned --transaction MULTI (1381-1385, #569). The fixture measures this: misrouted lists any SET sent to a non-owner after A was asked for the map (tests/test_cluster_unowned_slots.py:1108, asserted empty at 1116). It was clean in all 6 CI cells and in 180/180 runs under load, with the in-flight casualties bounded by the pipeline.

Re-entrancy. It's safe. attempt_reconnect() runs from event and timer callbacks, setup and SLOTS reply handling, or a synchronous connect failure (cluster_client.cpp:396). None of these runs inside the staged-line drain, and process_staged_monitor_command() pops the line before it sends (2746-2747). The only loop over the staged queues is the re-route itself, and it never re-enters reconnect logic. It only swaps and pushes queues, logs, updates counters (abandon_requests(), client.h:214-218) and arms deferred fills. The one synchronous nesting is a redial failing inside the handle_cluster_slots() node loop. That loop holds no queue reference, and the commit's own re-route runs afterwards (1518). I'm happy to add a comment saying so at the hook.

Shared drop helper. Feasible. The accounting is already shared through abandon_requests(), but the two blocks differ in label, key source, retry count and ownership (delete req vs pop), and the given-up predicate is duplicated as well (3220-3221 vs 2930-2934). Doing it properly is a small refactor across both functions, so I'd rather do it as a follow-up than grow this PR.

Error counts. Agreed. The exit code doesn't change (memtier_benchmark.cpp:6780-6792), and it's in the release notes.

Fixture and throttle. Fair point. If the throttle grew, the case would most likely still pass, just exercise less, so the risk is lost coverage rather than a confusing failure. Stderr can't help, because memtier logs nothing when it throttles a CLUSTERDOWN. The clean option is a fixture-side assert, with no wall clock involved: R's CLUSTER SLOTS (the commit) must arrive before A's second connection, with a message naming the throttle. It's about five lines, and I can add it here or in a follow-up. Suite time: the file runs in 6 CI cells and adds 0.4-0.85 min per cell. Under the sanitizers the 19 cases take about 48 s, and the existing tests and the OSS-CLUSTER jobs are unchanged.

reset_shard_queues bool. Agreed. I'll make it an enum (or /* staged= */ at cluster_client.cpp:330 and 349) in a follow-up.

🤖 Generated with Claude Code

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

Stale Bugbot comment from a previous run.

Comment thread cluster_client.cpp Resolved
fcostaoliveira and others added 2 commits October 25, 2026 19:23
reroute_staged_monitor_commands() uncounts the lines it drops, which
lowers m_reqs_generated below --requests again, but it scheduled a fill
only on connections that received a moved line. After a drop-only pass,
whether at a commit or from the give-up hook, a producer that had paused
at the --requests cap in hold_pipeline() had no reply left to wake it,
and a primary given up on wakes no peer.

When any line is dropped, schedule a fill on every connection that is
not disconnected, as the commit does after retiring a connection.

The unit test parks a connected producer at the cap, drops a line on
the given-up primary through each entry point, and checks that the
producer's deferred fill is armed. It failed on f87277c (Cursor Bugbot).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The comment above the deferred-fill forward declaration had lost its
first half, and the harness comment still said the test never runs the
event loop, which finish_dial() now does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Most of this was answered in the earlier replies, so here is the short version with pointers.

Rejected refresh after -MOVED. This is intentional, and I measured it in the round-5 reply (comment 6400995820, numbers at 08fab58).

  • Malformed or non-array reply: handle_cluster_slots() returns false, so the connection stays in setup_sent. It never returns to setup_done, and fill_pipeline() sends nothing past the setup check while it is in that state (see the round-8 reply, 6401838602). Staged lines therefore don't drain to the stale owner. The connection retries the refresh, ends the thread, or reconnects with backoff.
  • Stale but valid reply: this one is committed, and the re-route runs against it. A line whose slot the stale map still gives to the old owner can drain there and get -MOVED.
    • That line isn't lost silently: it is sent and answered with an error reply, which counts as an error like any other -MOVED.
    • With --retry-on-error it is resent.
    • It also starts at most one refresh per pipeline window. CLUSTER SLOTS request counts were identical to master in every stale and malformed cell I measured.
  • Compared with before: the old flush uncounted these lines without sending them, which is the silent loss this PR fixes.

Release notes. Yes. The PR body's release-notes line says drops now count as errors and are written to --failed-keys-file, and that the exit code doesn't change. It will go into the next release notes.

Give-up hook re-entrancy. Agreed, and two independent reviews checked it. The re-route only swaps and pushes queues, logs, adjusts counters and arms deferred fills; it never re-enters reconnect logic or holds a queue reference across a send. Details are in the round-8 reply.

reset_shard_queues bool. Agreed. I'll name it in a follow-up rather than grow this PR.

pending=True under sanitizers. The case passed first time in the ASAN, TSAN and UBSan cells on every head CI has run, including the event-gated fixture since 3376ad7. Locally:

  • the event-gated version passed 20/20 and 10/10 under heavy CPU starvation;
  • an ASAN/UBSan build passed 5/5 under load;
  • deliberate delays at nine points passed 27/27.

A fixture-side assert that names the throttle if it ever changes is in the follow-up list.

🤖 Generated with Claude Code

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

Stale Bugbot comment from a previous run.

Comment thread cluster_client.cpp Resolved
handle_cluster_slots() dials the nodes of a reply before it commits the
reply's map. A dial that fails at once (connect_shard_connection() ->
attempt_reconnect()) can leave a primary dead under --read-preference
other than primary, and the give-up hook then re-routed its staged
monitor lines by the map about to be replaced. A line whose slot the
reply moves to a live primary was dropped as
slot-owner-down-for-monitor-line, and the commit could not bring it
back (Cursor Bugbot).

The hook now does nothing while handle_cluster_slots() walks the reply.
The flag is set before the node loop and cleared before the
every-shard-malformed return and before the commit, whose own re-route
then runs in the same call. Every shard that dials a node reaches
any_valid_shard = true, so a skipped hook is never left without that
commit.

The unit test redials a given-up primary at a multicast address, which
Linux refuses at once, inside handle_cluster_slots(), and checks that
its line moves to the slot's new primary. It failed on 2153722. It also
checks the deferred hook directly, and that a malformed reply clears
the flag.

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

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

Stale Bugbot comment from a previous run.

Comment thread cluster_client.cpp Resolved
When a shard's reconnect timer fires, cluster_client::reconnect() hands
the redial to a CLUSTER SLOTS refresh over the main connection and the
timer is freed. Until that reply is committed the shard is disconnected
with no reconnect timer, which is what the re-route takes for given up.
A give-up of another connection in that window ran the re-route at once
and dropped the shard's lines as slot-owner-down-for-monitor-line,
although the commit was about to redial it and keep them (Cursor
Bugbot).

While the refresh is in flight (slots_refresh_in_flight(), now shared
with fallback_primary_conn_id()), the give-up hook only records that a
re-route is due. The commit's own re-route runs it. If the reply is
empty, an error or rejected, handle_cluster_slots_rejected() runs it
before the refresh is retried, so the lines are dropped as before. If
the main connection is lost with the request, the next give-up runs it,
including the main connection's own with nothing staged on it.

The unit test leaves the slot's owner waiting on the seed's refresh,
gives up another connection holding a line for that slot, and commits
a reply that redials the owner. Both lines must still be on it. It
failed on 02f67b0. Two more blocks check the rejected refresh and the
lost main connection.

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

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

Stale Bugbot comment from a previous run.

Comment thread cluster_client.cpp Resolved
Comment thread cluster_client.cpp Resolved
handle_cluster_slots_rejected() ran the re-route left to a SLOTS
refresh for any connection's empty, error or rejected reply. Other
primaries ask for CLUSTER SLOTS too (after -MOVED or CLUSTERDOWN), so
such a reply arriving while the main connection's refresh was still in
flight dropped the lines of a primary waiting on that refresh to redial
it: the case e9cdaf6 fixed, through a narrower window. Found in review.

It now takes the connection whose reply was rejected. For another
connection it does nothing while the main connection's refresh is in
flight. Once the main connection is lost, the flag outlives its
refresh, and any connection's rejection still runs it.

Tests: another connection's rejection during the refresh keeps the
lines, failing on e9cdaf6; a rejection with nothing deferred keeps
them; and after the main connection is lost a rejection runs the
re-route. A probe drives the seed's real reply ("*0" and a reply with
no usable shard) through shard_connection, so both call sites are
covered. The parse-window block now runs with no main refresh in
flight, since a refresh in flight defers the give-up on its own. Each
end of a deferral is also checked to use the flag up.
Review nits: comments, a has_staged local, and listen_any() reused.

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

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

Stale Bugbot comment from a previous run.

Comment thread cluster_client.cpp Resolved
Comment thread cluster_client.cpp Resolved
When a shard's reconnect timer fires, cluster_client::reconnect()
leaves the redial to a CLUSTER SLOTS refresh: the shard is then
disconnected with no reconnect timer, which the re-route took for given
up. e9cdaf6 and 18929b9 inferred the wait from the main connection's
refresh state instead, and missed two cases (Cursor Bugbot): the main
connection reconnecting, when no refresh is in flight yet its next one
redials the shard, so the shard's lines were dropped; and the main
connection given up on with nothing staged, which ran no re-route, so
the shard's counted lines kept a --requests run open.

reconnect() now marks the shard as awaiting a SLOTS redial. The re-route
does not take a marked shard for given up, so its lines stay and lines
for its slots move to it. The mark is cleared when the shard is dialed
again (connect_shard_connection(), as a commit's redial does), when a
commit retires it, and when it or the main connection is given up on.
The main connection's give-up then re-routes, so lines that waited on
it are dropped. A shard's lines thus wait exactly as long as the shard
itself does.

This replaces the deferral of e9cdaf6 and 18929b9:
m_reroute_after_refresh, slots_refresh_in_flight() and
handle_cluster_slots_rejected() are gone. A rejected reply no longer
drops a waiting shard's lines; the refresh is retried and a later map
redials it. The parse-window skip (02f67b0) and the drop wake (ab4c642)
stay.

The unit test marks the shard through reconnect() and checks that a
give-up keeps its lines, that the commit redials it and keeps them, that
a map without it moves them, and that a give-up while the seed waits on
its reconnect timer keeps them, which failed on 18929b9. It also checks
that the seed's give-up with nothing staged drops them, which also
failed on 18929b9.

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

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

Stale Bugbot comment from a previous run.

Comment thread cluster_client.cpp Resolved
The re-route, the replay hand-off and the unowned fallback each tested
"nothing will dial this primary again" their own way, and the re-route
was bitten twice by the gap between them. They now share
cluster_client::primary_given_up(): disconnected, no reconnect timer,
and no redial left to a SLOTS refresh. Review feedback.

- The replay hand-off runs at a commit, right after the redials, when no
  target can still be awaiting one, so it is unchanged.
- The unowned fallback keeps its deliberate difference: while the seed
  refreshes SLOTS it also counts a primary given up on, which that
  commit redials. It now counts a shard waiting on a SLOTS redial too,
  as the re-route does, also while the seed waits on its reconnect timer.

Also from review:
- A keyless staged line, which only a staging bug could produce, is
  dropped as unroutable-monitor-line instead of looking like a failover
  in --failed-keys-file.
- A comment says why the give-up hook may return early during a parse
  even for the main connection.
- The 1 s CLUSTERDOWN throttle is CLUSTERDOWN_REFRESH_INTERVAL_USEC in
  cluster_client.h, which the pending fixture reads.

Unit tests: the shard's reconnect while the seed is down (the seed is
redialed and the shard waits on it), a shard on its own reconnect timer,
and the fallback counting a waiting shard, which failed on 916813f.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Fixed in a27888f; answers to the rest below.

  • Mark set after connect(): a real bug, fixed. reconnect() now marks the shard before connect() and clears the mark if connect() fails (cluster_client.cpp:270-287). One correction to the mechanism: the main connection is dialed through client::connect(), not connect_shard_connection().
    • With libevent 2.0, a dial that fails at once is reported from inside bufferevent_socket_connect(), so the give-up can run inside connect() exactly as you describe.
    • With libevent 2.1 there's no callback, and cluster_client::connect() drops the error. The main connection was then left dead with no timer, never retried or given up on, and the shard waited on it forever. (On master both connections were already left dead in that case.)
    • The fix also handles that: if the dial failed before reaching the event loop, reconnect() retries the main connection the way connect_shard_connection() retries a shard. --max-reconnect-attempts then bounds it, and its give-up clears the mark and drops the shard's lines.
    • The new unit block (tests/unit/cluster_transaction_test.cpp:989-1031) dials an unreachable seed that has no attempts left. It fails on 3bf0804, and so do both mutants: no retry, and marking after connect().
    • The other synchronous paths out of that connect() (a resolve error, a socket setup failure, end_thread) either leave the main connection without a timer, which the retry now covers, or end the thread.
  • Where the mark changes: listed at its declaration (shard_connection.h:504-510).
  • Test comment: reworded to "Without the cap the run outlives this timeout". It also says why the 2 s stage timeout is raised: the seed fails setup on every reconnect, so on a loaded host the stage supervisor could end the run before the cap does.
  • Regex read of CLUSTERDOWN_REFRESH_INTERVAL_USEC: intentional, so the fixture can't drift from the header. It is read lazily, by the pending fixture only. If the define is renamed, that fixture fails and the error names the define and the header.
  • pending=True stability: on 3bf0804 it passed under ASAN, TSAN and UBSan in CI (Single Endpoint TCP Plaintext, shard 2/2), along with the other 145 checks. Locally it passed 49 of 49 runs with memtier sharing one core with two busy loops. The fixture is gated on events (3376ad7), not sleeps; the one timing-based version that flaked (1 in 10 under the same load) was replaced for that reason.

🤖 Generated with Claude Code

cluster_client::connect() dropped client::connect()'s result and always
returned 0. A dial of the main connection that failed before reaching
the event loop (a resolve or socket setup error, or a connect() error
that libevent 2.1 doesn't report) therefore looked like a dial in
progress. When the main connection's own reconnect timer fired,
handle_reconnect_timer_event() logged "connecting" and armed nothing,
so the main connection and any shard waiting on its refresh stayed
down. With --max-reconnect-attempts of 2 or more, or unlimited, the cap
was never reached. The fallback in a27888f only covered the first
retry.

Return that result. The timer's failed-reconnect path then counts and
re-arms each retry, up to the cap, and gives the main connection up at
the cap. A shard's reconnect() keeps the shard waiting on the main
connection and starts its first retry, instead of retrying the shard
itself. At startup, client::prepare() now aborts on such a failure, as
it does without --cluster-mode, and a --reconnect-interval reconnect
that fails exits as it does there.

With libevent 2.0 the failure is reported from inside connect(), but
connect()'s disconnect() then frees any timer that callback armed and
clears m_reconnecting, so the retry above is not skipped.

Unit cases: a cap of 2, where the timer fires again and the seed ends
given up on, and an unlimited cap, where the timer stays armed. Both
fail on a27888f.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Follow-up in af66a36. The recheck found that a27888f's fix only bounded the first retry, and corrects one claim of mine.

  • Every retry now counts against the cap. cluster_client::connect() returned 0 even when client::connect() failed. With libevent 2.1, the main connection's own retry therefore looked like a dial in progress, and the timer armed nothing more. connect() now returns that error (cluster_client.cpp:179-182), so each failed retry is counted and re-armed up to --max-reconnect-attempts (shard_connection.cpp:2660-2733), and at the cap the main connection is given up on.
    • A shard waiting on the main connection stays marked while it retries (cluster_client.cpp:268-283). Its lines are dropped once the main connection is given up on.
    • New unit cases cover a cap of 2 (fires twice, then given up) and an unlimited cap (keeps retrying, line kept); both fail on a27888f (tests/unit/cluster_transaction_test.cpp:989-1057).
    • Startup and --reconnect-interval now handle such a failure as standalone mode does: the run aborts at prepare, or exits.
  • libevent 2.0's stale m_reconnecting: it doesn't happen. disconnect() clears the flag when it frees the timer (shard_connection.cpp:901), and connect()'s failure path calls it. At worst, 2.0 counts one failure twice, which the cap still bounds.
  • Correction: I said both mutants fail. Marking after connect() but before the retry is equivalent on libevent 2.1 and survives. Only 2.0, which can give up inside connect(), exercises that ordering. Marking after the retry, a connect() that returns 0, and dropping the retry are all caught.

🤖 Generated with Claude Code

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

One correction to my last comment: --cluster-mode rejects --reconnect-interval (memtier_benchmark.cpp:1643), so the "a failed --reconnect-interval reconnect exits" line doesn't apply to cluster runs. The release note in the PR body now only mentions the startup abort, and says a startup dial isn't retried even with --reconnect-on-error, the same as without --cluster-mode.

🤖 Generated with Claude Code

Add an RLTest case where a primary is given up on mid-run while a replica
is still in setup, so the thread goes on and the monitor lines staged on
the primary are dropped. It checks the slot-owner-down-for-monitor-line
records in --failed-keys-file, and that the Errors count under ALL STATS
matches the failed-keys records. It fails on master, which records no
such line, and on a mutant that uncounts the lines without counting them
as errors.

Call primary_given_up() directly in reroute_staged_monitor_commands()
instead of through a forwarding lambda, and let the test's header regex
accept any whitespace in the #define.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Answers below; the integration check and the nits are in 5cd86ff.

  1. Splitting out connect(): I'd keep it here. Without it, a shard waiting on the main connection is stranded whenever the main connection's redial fails at once: that was the hole found in a27888f. --reconnect-interval isn't affected: cluster mode rejects it (memtier_benchmark.cpp:1643). What's left for other cluster users is a startup dial that fails before the event loop: it now aborts at prepare, as standalone does, and the exit code is 1 either way. If you'd rather review it separately, I can land it first as its own small PR and rebase this one on it. It can't go after.
  2. A real shard timer instead of the flag: I looked at it, and it doesn't hold up.
    • The commit's node loop deliberately skips connections with a pending reconnect timer, to keep their backoff and --max-reconnect-attempts (cluster_client.cpp:1228-1233, 1420). So a shard on a timer wouldn't be redialed by the map it's waiting for. Each firing would just ask for another refresh.
    • Counting those firings would give up a shard whose refresh is merely slow (the seed's backoff goes up to 60 s), dropping lines the commit would have sent. Not counting them is the same flag plus a periodic wake-up.
    • Each firing also re-runs reconnect(). With the main connection down, that redials it and cancels its own backoff timer (shard_connection.cpp:710-717). With it up, it requests CLUSTER SLOTS again.
    • Telling those timers apart from real backoff, in the node loop and in the main connection's give-up, needs the flag anyway.
  3. reconnect() returning 1: that's what master did too. Its branch was return connect() < 0 ? -1 : 1;, but master's cluster_client::connect() always returned 0, so the -1 path never ran. On master too, such a shard had no timer and stayed dead once the main connection was given up on. This PR keeps that and drops the lines it held. It's intended: no map will come, and redialing the shard on its own would also redial the given-up seed.
  4. End-to-end check: added test_given_up_primary_monitor_drops_are_reported (tests/test_cluster_unowned_slots.py:716-796). It asserts the slot-owner-down-for-monitor-line records in --failed-keys-file, and that Errors under ALL STATS equals the number of records. The JSON only reports Errors with --retry-on-error, so the test sets it. It fails on master and on a mutant that drops without counting the error.
  5. Header regex: intentional, so the wait tracks the real interval. It's now whitespace-tolerant (line 20), read lazily, and fails with the define and the header named.
  6. Nits: the lambda is gone; it calls primary_given_up() directly. I kept the assert plus the if for release builds.

🤖 Generated with Claude Code

Whether a line is staged on A before A is given up on depends on
scheduling, and no peer can observe it: a line staged on A stalls the
client at pipeline 1. So A's redial now stays in setup for two seconds
(X's for five), and the scenario runs up to 3 times until memtier
reports "dropped N staged monitor line(s)". The PR base never does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. A peer can't tell when a line is staged on A, and holding A until it is deadlocks the client at --pipeline=1 (the in-flight budget, cluster_client.cpp:1689-1701). I tried six gates and each one hung or flaked. So the test now keeps A's redial in setup for 2 s and reruns the scenario up to 3 times, until memtier reports dropped N staged monitor line(s). The docstring says this (tests/test_cluster_unowned_slots.py:725-730, loop at :732).
Starved, at nice 19 against 14 busy loops: 30/30 (24 passed on the first try, 5 on the second, 1 on the third). It still fails on the PR base after 3 tries (0 > 0 at :739), and on the uncount-without-error mutant (1 == 3 at :743). On the nit: the comment at :741-742 now says what is asserted, Errors equal to all failed-keys records (the drops plus requests held for resend when the thread ends). The body is fixed to match.

🤖 Generated with Claude Code

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Answers for the updated review:

  • Splitting out the connect() change: same answer as before. This PR needs it: without it, a shard waiting on the main connection is stranded whenever the main connection's redial fails at once (the a27888f hole). It can land first as its own small PR with this one rebased on top, but it can't come after. I'd rather keep them together, with the separate release-note paragraph.
  • How often one try misses: in starved runs (test at nice 19 against 8-14 busy loops), 41 of 50 runs dropped a line on the first try, 8 needed a second and 1 needed a third. None missed all three. Idle, every run dropped on the first try.
    • Holding A's setup until a line is staged can't work. A line staged on A is never sent, so no peer can see it, and at --pipeline=1 the lines staged on A fill the in-flight budget (cluster_client.cpp:1689-1701). The client then sends nothing else, and a gate waiting on a peer deadlocks. Six gates were tried; each hung or flaked.
    • The retry loop stops on the drop message itself (cluster_client.cpp:3035), and every assertion runs on the final try. So it can't hide a regression: the PR base never prints the message and fails all three tries, and the uncount mutant fails on the try that drops.
  • Re-entrancy from attempt_reconnect() / the reconnect timer: checked at 4cd3552. Nothing up the stack holds a reference into m_staged_monitor_commands:
    • The drain (process_staged_monitor_command(), :2788) moves the front out and pops it before formatting or sending.
    • Staging (:2886) pushes and only calls schedule_fill(), which is deferred.
    • The re-route (:2960) swaps each queue into a local before moving lines, and itself only pushes and calls schedule_fill(), never a reconnect. So it can't re-enter itself.
    • A give-up while a slot map is being parsed is left to that map's commit (the m_parsing_slot_map guard).
  • Header regex: kept deliberately, so the fixture's wait tracks the real interval. It's whitespace-tolerant and read lazily, and it fails with the define and the header named if either changes.

🤖 Generated with Claude Code

The CI plain job needed all 3 tries. On a fast client, A and X dropped
together, before any SLOTS refresh: R went idle while A was disconnected
(no line is selected then), and nothing woke it once A's redial was in
setup, so no line was staged on A.

Now X's first PONG is held, so X sees its drop at once, and X is dropped
only once A's redial is accepted. X's refresh then lands while A is in
setup and wakes R, whose next line is staged on A. A's third SET waits
until X holds its PING, for starved hosts. The 3-try loop stays as a margin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

fcostaoliveira commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Test reliability update in 75906f6: on 4cd3552, test_given_up_primary_monitor_drops_are_reported needed all 3 tries in the plain CI job. The misses were the client being fast, not slow. A and X dropped together, before any SLOTS refresh. R was idle, since no line is selected while A is disconnected (cluster_client.cpp:1971-1983), and nothing woke it once A's redial was in setup, so nothing was staged on A.

The test now drives that from evidence. X's first PONG is held, so X sees its drop at once (tests/test_cluster_unowned_slots.py:771), and X is dropped only when A's redial is accepted (:781). X's refresh then lands while A is in setup and wakes R, whose next line is staged on A. A's third SET waits until X holds its PING, for starved hosts (:820).

Per try: idle 100/100, starved 100/100 (nice 19, 8 busy loops). The base fails every try (0/10, then 0 > 0 at :748); the uncount mutant fails 1 == 2 at :752. The 3-try loop stays only as a margin.

🤖 Generated with Claude Code

The cap bounds memory for new staging. A re-route only moves lines that
are already selected and counted, so dropping one there for the merged
queue's size brought back the loss this PR removes (e.g. a retired
primary's slots all landing on one survivor). Producers still never
stage on a queue at the cap: they send the line themselves.

The cap is now a member so a unit test can lower it; the test fails
with the old queue-full drop. primary_given_up() also asserts that an
awaiting-redial mark implies a down connection with no timer, and the
assert before the UINT_MAX branch says why both exist.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Pushed e89036c.

  1. connect() return value: it stays in this PR, because reconnect() depends on it. When a shard leaves its redial to the main connection, reconnect() checks that return value (cluster_client.cpp:279). If the main connection's dial failed at once, it gets a reconnect timer from there, so every retry counts toward --max-reconnect-attempts. Its give-up then ends the shard's wait. With master's constant 0, the failed main connection was left down with no timer, and the shard waited on it forever: a --requests hang. The startup abort ("prepare: failed to connect") is the same change seen at the first dial. I'll put both in the release notes.

  2. The queue cap: agreed, it shouldn't drop moved lines. The cap bounds memory for new staging. A re-route only moves lines already selected and counted, and moves allocate nothing. So the re-route no longer checks the cap (cluster_client.cpp:3001-3003). A move can take a queue past the cap, but new lines can't follow: a producer still stages only while the target queue is under the cap (:2889), and otherwise sends the line itself. Every queue past the cap got there by moves alone, so the total staged never grows past what was staged under the cap. --requests counting is unchanged, since a moved line stays counted.

    • The staged-monitor-queue-full reason is gone. The README (README.md:614) and the PR body are updated.
    • The cap is now a member (m_staged_monitor_queue_max, cluster_client.h:101), so a unit block can lower it to 1 and move a line onto a full queue (tests/unit/cluster_transaction_test.cpp:577). That block fails with the old queue-full drop.
  3. The awaiting-redial invariant: added as a debug assert in primary_given_up() (cluster_client.cpp:532), the one place the mark is read, so every re-route and fallback decision checks it. It asserts that awaiting implies disconnected with no reconnect timer. The mark is set only on a connection that is down with no timer. The timer callback clears its flag before it calls reconnect(), and connect_shard_connection() clears the mark before a redial arms anything. make check, test_cluster_unowned_slots.py and test_monitor_cluster.py (3-shard cluster) pass with asserts on.

    • I left out "the main connection is not given up on". reconnect() marks the shard before the main connection's dial, and a dial that fails at once has a short window with no main-connection timer before the retry is armed. The give-up hook already ends the wait in that case by clearing every mark.
  4. Nit: added a one-line note next to the assert (cluster_client.cpp:3008).

🤖 Generated with Claude Code

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Two corrections to my previous reply:

  • The bound: "the total staged never grows past what was staged under the cap" is wrong. Repeated SLOTS refreshes that keep moving filled slots onto a primary that isn't draining can add up to one more cap's worth each time. What bounds the total is the in-flight gate in hold_pipeline() (cluster_client.cpp:1663-1705, pipeline × connections), not the per-queue cap. The cap only stops new staging onto a full queue.
  • Where the mark is read: primary_given_up() is not the only place. The mark is also read at cluster_client.cpp:279 and :3396. The assert sits in primary_given_up() because every re-route and fallback decision goes through it.

🤖 Generated with Claude Code

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks.

  1. PR body: it was updated with e89036c. It no longer names staged-monitor-queue-full, and the Release notes paragraph only drops a line whose slot's primary was given up on. The Counting bullet says a move never drops a line, even past the staging cap. You may have read the body from before that edit.
  2. connect(): it stays here for the reason in my earlier reply: reconnect() depends on it to give a failed main-connection dial its retry timer. Without it, a --requests run can hang. It has its own release-note paragraph. You're right that only the retry and cap side has coverage. I'll add an integration test for the cluster-mode startup abort ("prepare: failed to connect") in the next push.
  3. The ceiling: not quite connections × cap. As in my correction, a queue can only pass the cap through moves, but repeated slot-map refreshes that keep moving filled slots onto a primary that isn't draining can each add up to one more cap's worth. What bounds the total is the in-flight gate in hold_pipeline() (pipeline × connections). That bound holds without the queue-full drop, and nothing new is allocated by a move.
  4. The test: agreed, it would fail rather than skip if all 3 tries missed. Since the drops are ordered from evidence, it passes on the first try in 100/100 runs idle and in 100/100 starved (nice 19, 8 busy loops). I'll watch CI for it.

🤖 Generated with Claude Code

A --cluster-mode seed at the broadcast address fails connect() before
the event loop (ENETUNREACH or EACCES without SO_BROADCAST). Since
cluster_client::connect() passes the failure on, prepare aborts with
"prepare: failed to connect, test aborted." and exit 1, within the
10s bound. Master launches the thread and ends it with no request sent.

The test probes the address first and skips, with the reason, where
connect() would not fail at once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
#897 moved the retire body into release_retired_connection() and added
handle_connection_retired(). Both connection hooks are kept. The helper
now carries this branch's retire path: it clears the awaiting-redial
mark before disconnect(), re-routes staged monitor lines instead of
flushing them (only a replica retired by the hook can still hold any,
and none do today), and keeps the key-pool uncount and the replay
hand-off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
The OSS-CLUSTER TLS cell's Run tests step took 2393 s on master 33ff193,
7 s under its 40-minute limit, and timed out on #885. Split both full-suite
cluster cells into two file shards with utils/select_test_shard.py, and
validate the split with utils/check_test_shards.py, as the sanitizer
workflows already do.

Fixes #898

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks.

  1. Asserts: you're right, they are live. configure.ac doesn't define NDEBUG, so the "debug builds" wording in the description was wrong; I've fixed it. I'm keeping the assert in primary_given_up(), as for the other invariants in cluster_client.cpp, which has 26 live asserts. If that invariant ever broke, the mark would hold a shard as awaiting a redial that never comes, which is the silent --requests hang this PR closes. An abort with a crash report is easier to diagnose than that. Five review passes traced every set and clear site and found no path that fires it, and it stays quiet across make check and the cluster suites. The UINT_MAX branch only matters for a build that defines NDEBUG; the comment says so.
  2. Scope: same answer as before: reconnect() depends on connect() returning the dial error to give a failed main-connection dial its retry timer. Without it, a shard waiting on that connection hangs a --requests run, so the two can't be split. The release note covers it, and a new integration test pins the startup abort.
  3. Errors count: agreed; the release note says error counts can go up while the exit code stays the same.
  4. New state: agreed that it's worth a second look from whoever owns cluster reconnect handling.

🤖 Generated with Claude Code

fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
ci: run the OSS-CLUSTER full-suite cells as two shards each (#899)

The OSS-CLUSTER TLS cell's Run tests step reached its 40-minute limit (2393 s on master 33ff193; timed out on #885). Both full-suite cluster cells now run as two file shards, chosen by utils/select_test_shard.py and checked by utils/check_test_shards.py, as the sanitizer workflows already do. Each shard runs in 17-23 minutes, and the 922 tests are each assigned exactly once.

Fixes #898

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Picks up the two-shard split of the OSS-CLUSTER full-suite CI cells; only
.github/workflows/ci.yml changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

bugbot run

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

Stale Bugbot comment from a previous run.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks.

  • Other paths that could dial a marked shard: I checked each place a connection is dialled at 3546d67.

    • A non-main shard is only redialled through connect_shard_connection() (cluster_client.cpp:1247, 1260, 1425, 1500), which clears the mark first (:354).
    • The two other connect() callers are the --reconnect-interval reconnect (shard_connection.cpp:1856) and its transaction-boundary variant (:1902, gated by transaction_reconnect_due(), which needs reconnect_interval, client.cpp:523). Both require --reconnect-interval, which cluster mode rejects at startup (memtier_benchmark.cpp:1643). Both also go through client::connect(), which dials only the main connection, and the mark is never set on the main connection.

    So no path dials a marked shard, and the assert stays. If a future change added one, the alternative to aborting would be a shard waiting for a redial that never comes, the silent --requests hang this PR closes.

  • connect() split: same answer as before. reconnect() depends on that return value to give a failed main-connection dial its retry timer, so the two can't ship separately without reopening the hang. It has its own release-note paragraph and its own integration test (test_cluster_startup_dial_failing_at_once_aborts).

  • Accounting: agreed.

  • Nits: both are noted for a follow-up (the drop warning's wording for the unroutable-monitor-line case, and the in-class initializer). Neither changes behavior, and another push now would restart CI.

🤖 Generated with Claude Code

Picks up 14 master commits, including the connect-failure changes in
#855 (libevent 2.1.8's error callback from a failing connect), #823
(hardened libevent failures), #822 (TLS error reporting) and the
libevent compatibility CI from #545. No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

bugbot run

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit a054ad2. Configure here.

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

None yet

Projects

None yet

1 participant