Skip to content

Keep cluster workloads progressing across partial maps and primary reconnects - #799

Merged
fcostaoliveira merged 12 commits into
masterfrom
codex/fix685-unowned-slot-progress-20261023
Oct 24, 2026
Merged

fcostaoliveira merged 12 commits into
masterfrom
codex/fix685-unowned-slot-progress-20261023

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

A valid partial CLUSTER SLOTS map can leave a generated key without an owner. A request-count or timed workload targeting that hole spins without sending requests. Mixed owned/unowned keys silently skip the unowned keys and repeat others instead.

Root cause

The slot map uses UINT_MAX for an absent owner, but generation has already advanced the key cursor before routing returns not_available. No request is sent or counted, so the producer's pipeline limit and response-driven clock cannot stop it. The MGET producer cache separately omits unowned slots.

Fix

This also changes general primary reconnect and CLUSTERDOWN recovery behavior for fully owned maps, not only partial maps. Same-endpoint primary queue retention and the response-triggered topology refresh are described below and have separate follow-up commits and regressions.

Keep accepting partial maps. Send missing-owner writes and reads that permit primary routing to a known primary, retaining the exact key and allowing Redis to provide the routing response. MGET keeps those slots in its producer cache and uses that ready primary until the next topology/cache rebuild, preserving the producer and generated keys while other primaries finish setup. Transactions and monitor replay retain their existing primary routing. A replica seed is never used as the missing-owner write destination.

For strict secondary reads with error or reserved queue fallback, fail the run explicitly without sending to an unrelated replica or a primary. Use the normal event-loop failure/cleanup path. Missing-owner requests also fail explicitly if every primary is permanently disconnected. A primary still connecting, awaiting an armed reconnect, or awaiting the reconnect's SLOTS refresh remains eligible. Transactions park with their exact staged key while waiting.

Monitor replay waits before selecting a line while all primaries are in reconnect backoff. Already-selected monitor lines and ordinary routed keys stay queued, with unchanged generated-request counts, across redials to the same initialized primary address and port, including repeated setup failures. Replica redials (including demotion), fresh/different endpoints and topology retirement keep their existing reset and compensation policy. Before a replica becomes primary, its old queued work is cleared and compensated too, including live or pending-reconnect role transitions, so strict-secondary reads cannot bypass routing on the promoted endpoint. Request identity is not guaranteed across replica redials or promotion; this preserves established strict-secondary progress on other shards when a replica remains unavailable. Primary queue preservation applies to owned and unowned work alike.

Owned monitor routing (also changes fully owned maps). An owned monitor line is now staged on its known primary whenever that primary is not disconnected, including while it is in reconnect backoff or refreshing CLUSTER SLOTS. Before, a primary whose SLOTS state was not setup_done was skipped and the already-selected line was sent on the producer connection, which can be a replica seed. This is the same rule ordinary routed keys already follow: the command queues on its owner and drains after the owner's setup ladder completes. Disconnected owners and the staged-queue cap keep their existing fallback.

CLUSTERDOWN responses request a topology refresh at most once per second per client without discarding staged work, including when a formerly full map becomes stale without a disconnect. Each client owns its topology: -t 8 -c 50 permits up to 400 refreshes/second during sustained errors, in addition to bootstrap. A process-wide poll coordinator or recovery backoff is outside this fix. The missing-owner warning prints once per process, including across --run-count runs. The existing setup ladder waits until EXEC/DISCARD when MULTI is open. Ordinary workload-error accounting and configured retries apply.

Tests

  • Owned monitor routing (42ede4a): test_owned_monitor_waits_for_primary_refresh uses a replica seed, a CLUSTERDOWN reply from the primary and a delayed SLOTS refresh, alternating owned and unowned keys. It requires zero replica SETs, all 20 ordered values on the primary and 40 completed operations. With only the production hunk reverted, up to 19 of 20 SETs reach the replica; the pipeline-4 leg fails on every run and the pipeline-1 leg in about two thirds of runs (it depends on whether the next owned line is created before the refresh starts), so pipeline 4 is the deterministic leg.

On base 43ca07691b842cdd427c7006dbf4a85dce18f3ad, the all-unowned request and timed cases hit a six-second watchdog at approximately 100% of one CPU with zero data commands. A 1,000-request sequential workload over a half-covered key range sent only 501 distinct keys. The new request-count, exact-key-sequence, MGET, and full-map removal/recovery regressions fail on that base; the owned-key control passes.

With the fix:

  • 23 new scripted integration tests pass, covering request/time termination, sequential and parallel keys, normal and arbitrary commands, MGET, monitor replay, MULTI/EXEC, replica seeds, all read preferences, bounded retries, topology healing, mid-run removal/reconnect, full-map removal without a disconnect, warning deduplication across six clients, and two-primary MGET producer stability while the first advertised primary finishes setup.
  • The second-primary-seed MGET regression hit an eight-second watchdog before the producer fix, while owned MGET and missing-owner ordinary GET controls passed. After the fix, request-count, timed and pipeline-eight MGET cases preserve every generated request and key.
  • Earlier revision c9ff438 passed an owned Redis 8.6 two-primary cluster over both plaintext and TLS full-map and missing-slot controls: 100 SET requests and 100 MGET requests through the second primary seed each produce 100 counted CLUSTERDOWN failures; a two-second timed workload finishes; a 1,000-key sequential workload produces 999 stored keys plus exactly one failed key, preserving all 1,000 requests.
  • Three final focused tests also pass, including monitor replay from a replica seed while primary AUTH is delayed, stale-full-map recovery, and strict-secondary MGET/arbitrary failure.
  • 35 existing setup-rejection, malformed/empty topology, and refresh-overlap integration controls pass.
  • New disconnected-primary controls reproduce the transaction reconnect spin on c9ff438 (eight-second watchdog) and a monitor line discarded across reconnect. Fixed transaction recovery completes all 24 operations with eight exact-key SETs. Fixed monitor recovery sends all ten distinct replay values plus ten PINGs, with zero writes to the replica; owned-slot replay has the same recovery control. Terminal/no-reconnect cases fail promptly instead of staging work on a permanently dead primary. The fixture delays both READONLY and the reconnect's SLOTS response to cover the timer-to-refresh transition.
  • A repeated-setup-failure regression independently exposed a further identity bug in ec99479: after two AUTH socket closures, pipeline 1 sent nine monitor SETs with rotated values, and pipeline 4 sent seven instead of ten while replacing the rest with PINGs. Ordinary routed writes similarly skipped early keys. The final fix preserves all ten distinct monitor values plus ten PINGs, and ordinary exact keys 1..20, for owned and unowned slots after one/two setup failures. The committed controls retain pipeline 1/4 and delay the reconnect SLOTS reply. A queue-ownership unit checks fresh, same and different endpoints plus unchanged/compensated counts; another distinguishes a live seed's pending refresh from a disconnected seed. Linking against ec99479 fails queue preservation; removing refresh eligibility fails the new refresh unit.
  • The exact existing real three-primary/three-replica disconnect regression passes on ec99479, fails on 53af982 at 15,945/16,000 operations after the 60-second watchdog, and passes again with primary-only queue retention (all 16,000 operations, 20 seconds including harness setup). Same-endpoint replica retention had stranded counted reads on a permanently unavailable strict-secondary target. New unit controls check primary retention, replica reset, demotion, promotion, and unchanged/compensated counts; linking the new unit with the 53af982 production object fails the replica-reset assertion.
  • Independent promotion testing exposed an additional policy regression at 8020ebb: with strict secondary/error, a replica closed on its first GET and was promoted by SLOTS; retained queues sent 2/8/32 reads to the new primary at pipelines 4/16/64. The committed regression fails on that head and passes after clearing the old replica queues before changing role: zero primary reads and 1,000 completed operations in each case. New units check promotion compensation before role change and preservation only for work staged after promotion; removing the promotion reset fails that unit. The exact real replica-disconnect control still completes 16,000 operations (25 seconds including harness).
  • All unit programs (16 at that head, 17 after master integration) pass. The transaction unit additionally checks an actual armed reconnect timer, parked retained key, canceled timer and explicit terminal failure; linking the new unit against c9ff438 fails its wait assertion. make format-check, Ruff F, and git diff --check pass.

After normally integrating master through #810, head c47fc40 passes a clean build, all 17 unit programs, formatting, and 26 actual RLTest functions (22 missing-slot routing, 3 bounded stderr logging, and weighted aggregate latency), in 103 seconds on authenticated private Redis. The four PR implementation/test files remain byte-identical to reviewed 1174655; master supplies the logging prerequisite and merged statistics/topology fixes. Initial local incremental validation used stale objects with dummy dependency files; a clean rebuild and an independent single-stale-object control confirmed and resolved that local build artifact.

These are correctness and termination measurements, not a throughput comparison. The new head needs all seven focused rechecks and its own full CI. Earlier ASan/TSan timeouts are not waived; issue #482 remains open pending this CI result.

Affected versions

The missing-owner sentinel behavior was introduced by ee757e7152a537f91861f29d272a36eabf20c3c0 (#456), first released in 2.5.0; 2.5.0–2.5.2 and current master are affected. The request-count/identity regression is established against the preceding routing behavior; older timed-run liveness problems are not claimed to originate in that commit.

Fixes #685

🤖 Generated with Claude Code


Note

High Risk
Changes core cluster routing, reconnect queue accounting, and failure modes across GET/MGET, transactions, monitor replay, and read-preference policies.

Overview
Cluster mode no longer stalls or drops keys when CLUSTER SLOTS is partial or goes stale. Unowned slots route writes and primary-eligible reads to a fallback primary while keeping the generated key; strict secondary with error/queue fallback fails the run instead of misrouting. MGET keeps hole slots on their producer primary until the next topology rebuild.

Reconnect and queue policy is refined: same-endpoint primary redials retain staged keys, monitor lines, and request counts; replica redials, endpoint changes, and replica→primary promotion still clear unsent queues with generated-count compensation so strict-secondary reads cannot drain on a new primary.

-CLUSTERDOWN triggers a per-client topology refresh (rate-limited to once per second) without flushing staged work. Monitor replay pauses line selection while all primaries are in reconnect backoff. README documents the behavior; large integration and unit test coverage exercises holes, MGET, transactions, monitor, retries, and promotion.

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

@github-actions

github-actions Bot commented Oct 23, 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 routing changes, the queue-reset refactor and the new tests. The root cause is well explained, and the regressions are shown failing on the base and passing with the fix, which is the bar we want for a fix like this. A few comments below.

  • Scope. As the description says, this PR does more than fix Cluster: requests for a slot with no owner in a valid CLUSTER SLOTS reply are never sent; the thread spins and the run ignores --test-time/--requests #685. It also changes how primary reconnects behave on fully owned maps (same-endpoint queue retention) and adds CLUSTERDOWN-triggered refresh. The queue-retention policy changed three times inside this PR (53af982 → 8020ebb → 1174655), and the real 3-primary/3-replica disconnect test caught one of those versions regressing. Did you consider splitting retention into its own PR? It's the part most likely to affect users who never see a partial map, and on its own it would be easier to review and to revert. Not a blocker if you'd rather keep it together, but it would be good to hear why.

  • CLUSTERDOWN refresh rate. I know the README discloses the cost: -t 8 -c 50 can issue up to 400 CLUSTER SLOTS/s. Still, that load lands on a cluster that is already degraded, and CLUSTER SLOTS isn't free on large topologies, so the benchmark could make the failure it's measuring worse. Would it be hard to rate-limit per thread, or across the client group, instead of per client? If that's a bigger change than it looks, maybe a follow-up issue, but I'd rather not ship the per-client version without at least that discussion.

  • Concentrating error traffic. fallback_primary_conn_id() always picks the first connected primary, so every client sends all missing-owner traffic to the same node (the README says so too). I guess that's fine for correctness. I wonder if hashing the slot across the connected primaries would spread the CLUSTERDOWN load at little cost. Just a thought.

  • MGET cache build. In build_mget_slot_cache(), if fallback_primary_conn_id() returns UINT_MAX when the cache is built (e.g. every primary is permanently disconnected at that moment), the cid < num_conns check still skips the slot silently. That's the same key-omission this PR is fixing, just in a narrower window. Maybe I'm missing a guarantee that the cache is never rebuilt in that state. Can you confirm?

  • hold_pipeline hot path. The new monitor-replay gate runs on every hold_pipeline() call in monitor mode, including fully owned maps. It does a get_arbitrary_command() lookup and then loops over every shard group in fallback_primary_conn_id(). That's probably negligible, but this runs in a tight loop. Did you consider checking a cheaper "any primary in backoff" condition first?

  • Owned monitor routing. In create_monitor_request_cluster, the owned-slot branch no longer requires get_cluster_slots_state() == setup_done. I think that's intended, and test_owned_monitor_waits_for_primary_refresh covers it. Since it changes behavior on full maps too, it would help to call it out in the description next to the other full-map changes.

The core fix looks solid and the test coverage is thorough. Since this touches cluster routing, it may be worth a second look from whoever owns that area. I'd mainly like the scope and refresh-rate questions answered before this merges.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Addressed in b1d8478. CLUSTERDOWN now requests a bounded refresh even when the last map was full. The new no-disconnect fixture removes the slot on operation five and heals it only when SLOTS is requested: on the base there are 16 terminal failures and no refresh; the fix refreshes once, preserves all 20 operations, and recovers with either one terminal failure (retry disabled) or one extra successful replay (retry enabled).

The warning is now once per process, checked with two threads and three clients. The strict-secondary predicate is shared by both routing checks, and the comments explain deliberate first-primary selection and the warning-only transaction/monitor calls.

All 16 new integration tests and 16 unit programs pass. The 35 existing setup/topology compatibility controls also pass, as do the real two-primary Redis cases over plaintext and TLS. The MULTI fixture explicitly rejects a SLOTS command inside an open transaction; the refresh waits until EXEC. CI and the independent reviews remain pending.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

The monitor producer is not guaranteed to be a primary: a replica seed can generate work after discovering the primary. Falling back to conn_id would then send the write to that replica. The pending destination is safe with the existing lifecycle: shard_connection::fill_pipeline() completes AUTH/SLOTS before calling create_request(), which drains m_staged_monitor_commands first. On topology retirement, handle_cluster_slots() removes staged entries and compensates m_reqs_generated; a normal reconnect keeps the queue for draining. The existing global in-flight limit bounds staging while setup is pending.

Added a direct regression in b3b38dd: start from the replica seed and delay primary AUTH by 100ms, then replay 20 monitor writes to the missing slot. All 20 reach the primary, none reaches the replica, and all 20 terminal errors are counted. The original monitor-seed control, full-map recovery control, and strict-secondary MGET/arbitrary controls also pass (3 focused test functions, including the new variant).

I kept routing-policy validation separate from destination lookup because the lookup is also used while processing/replaying an already-owned request; it must not end the event loop or add generation-side diagnostics there. Both now share requires_replica(). The added healthy-path check is small but I have not measured its throughput impact and make no performance claim.

The once-per-second refresh per client is intentional even under full-coverage CLUSTERDOWN: each client has its own map and needs a bounded way to discover recovery. This does not introduce a process-wide polling coordinator. The prefix now uses a named constant with sizeof - 1, the README wrapping is fixed, and the monitor comment documents pending-setup staging. Real plaintext/TLS evidence is retained in the owner handoff; seven independent reviews and final-head CI remain pending.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

The per-client limit is intentional, and the README now states its scaling explicitly: 8 threads × 50 clients permits up to 400 refreshes/second during sustained CLUSTERDOWN, in addition to bootstrap discovery. Each client owns its own topology and connection/setup state; a shared thread timestamp alone would prevent some clients from repairing stale maps. Coalescing would also need to distribute and validate refreshed topology across those clients. Refreshing only with retries enabled would leave non-retrying workloads unable to discover removal/healing from a stale full map. The real-cluster tests establish correctness on the recorded two-primary fixtures, not acceptable overhead at 400 clients.

Strict secondary with error/queue deliberately fails when the generated read has no authoritative slot owner, including a transient hole from a refresh. Queue remains documented as error. Reusing the existing generate-and-skip no-route path here would consume that exact generated key; selecting an unrelated replica or a primary would violate the selected routing policy. Known-owner replica waiting is unchanged. Selecting the first eligible primary for permitted fallback is deliberate and now documented, including the possible concentration of error traffic.

Updated the two wall-time-dependent refresh bounds to allow bootstrap, the immediate refresh, and one refresh per elapsed second. The exact-two assertion remains for the pipeline-one healing case, which has only one CLUSTERDOWN trigger. The focused request/time/healing cases pass; independent TEST also demonstrated the old bound failing under delayed responses. cluster_client.cpp already includes explicitly.

Independent review has additionally found a two-primary missing-slot MGET liveness gap. That repair and its regression control are being handled before merge.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

The independent two-primary MGET blocker is fixed in c9ff438. A missing-slot MGET now stays on the primary assigned as its producer until the topology/cache rebuilds; it cannot switch underneath the cache when another primary finishes connecting. Strict-secondary validation still runs first. Known-owner routing is unchanged. This also keeps the send behind that producer's completed setup ladder.

The committed regression seeds primary B while advertised-first primary A has delayed AUTH. Before this fix the missing-slot MGET hit the eight-second watchdog; owned MGET and missing-slot ordinary GET controls passed. Now the request-count, timed and pipeline-eight MGET cases all preserve the exact keys and counts. All 18 integration functions, 16 units and 35 compatibility controls pass. Real two-primary Redis plaintext/TLS checks also pass, including 100 missing-slot MGET requests through the second seed, with exactly 100 counted errors.

For the latest monitor question: retirement compensation is one path, not a promise that every failed destination will be retired. If a connection cannot recover and reconnect is disabled, the existing connection error path ends its worker; the run is incomplete and fails. If a later topology retires a connection, its staged counts are compensated there. A normal reconnect preserves the staged queue. The producer cannot safely substitute its current connection because it may be a replica seed.

The refresh-rate and first-primary concentration trade-offs remain the explicit policy described in the previous reply and README. The tests establish correctness, not acceptable outage load at 400 clients. Distributing holes by hash adds a scheduling policy without an authoritative owner and does not address the MGET producer/setup invariant. The response-prefix comment now points to the same simple-error/RESP3 caveat as READONLY. The warning-only callers remain explicit; no additional helper is needed for this repair. Focused independent SEM/TEST/OUT rechecks and final-head CI are pending.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

The strict-secondary choice is intentional, including transient holes, as described in the earlier policy reply: #799 (comment). At that point generation has selected an exact key, but the map names neither its primary nor any authoritative replica. Reusing generate-and-skip not_available would lose that key; routing to some other replica or a primary violates strict secondary. Waiting without losing the key would require a new retained-request/recovery policy, including a deadline and behavior when the map never heals. This fix uses the selected error policy (and queue, which remains documented as error) and preserves existing waiting for known-owner replicas.

The same reply explains why a shared timestamp alone cannot replace per-client refresh: every client owns a separate topology/setup state. The documented scaling and concentration are accepted limitations of this narrow correction; the tests do not establish acceptable outage load at 400 clients.

The scripted tests do execute the actual cluster-mode router over authenticated TCP, including the two-primary setup transition, while owning their complete topology. They skip the outer cluster/TLS environment because that environment does not own these sockets. The real Redis plaintext/TLS proof now also covers the second-primary-seed MGET case, with exact request/error counts. Adding cluster-job topology mutation/restoration is useful follow-up coverage, but is not needed to make the committed reproduction exercise this routing code. Once-per-process warning suppression across --run-count is intentional. Focused independent routing rechecks remain the merge gate.

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

Copy link
Copy Markdown
Collaborator Author

Addressed against final owner head 53af982, following the review edit at 12:21:53:

  • The refresh budget remains per client, matching the existing per-client topology ownership. The documented -t 8 -c 50 ceiling is 400 refreshes/second plus bootstrap. A shared per-thread budget would coordinate independent clients and their recovery opportunities; that remains a follow-up, with no claim that the present outage polling load is optimal.
  • Yes, monitor selection happens before the key is known, so the preselection backoff gate also covers owned keys. More importantly, independent lifecycle testing found that a second setup failure still discarded already-selected lines. The final fix retains monitor payloads and ordinary routed key indices across redials to the same initialized address+port, with their generated counts unchanged. Fresh/different endpoints and topology retirement keep their existing reset policies. Two AUTH closures at pipeline 1/4 now preserve all ten distinct monitor values plus ten PINGs; ordinary keys remain exactly 1..20. Zero replay writes reach the replica. This addresses the repeated-failure case rather than relaxing the test counts.
  • Healthy owned-key checks use the slot-map lookup; the fallback scans apply to missing keys and the monitor wait. I considered caching, but a cached ID needs invalidation for connection/setup/reconnect and topology changes, which are the state transitions under repair here. This change uses current state directly and makes no measured throughput claim for the additional scans.
  • The normal local run passed all 21 committed fixture functions, 35 existing compatibility controls and 16 unit programs. Independent ASAN testing exposed the repeated-redial bug above; final-head ASAN, TSAN and coverage CI are still pending and are not claimed to have passed. The committed tests cover the retained workload sizes and pipelines, and a direct unit independently checks timer/refresh/queue state without scheduler sleeps. The actual fixture still owns plaintext sockets and skips the outer TLS/cluster environments as described in the PR.
  • README now explicitly says the missing-owner warning is once per process, including across --run-count runs.

The new queue unit fails when linked against ec99479, and a mutation removing refresh eligibility fails the live-seed-refresh assertion. Final independent rechecks and exact-head CI remain merge gates.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Following the 12:42:18 edit: I checked the same-endpoint demotion case with a private three-endpoint fixture. After two setup closures it promotes a different primary and advertises the old endpoint as a replica, then verifies that retained writes actually drain on the demoted endpoint and receive READONLY.

All four controls pass at 53af982: ordinary writes and monitor replay, each with retry disabled/enabled. Without retries, ordinary work has 8 terminal READONLY failures plus 12 successful writes, counted as 20 operations. With retries, the same 8 rejected attempts are resent to the new primary, all 20 exact keys complete, and the logical count remains 20. Monitor replay similarly has 5 terminal rejected SETs without retries, or all ten distinct SET values completed on the new primary with retries; its ten PINGs bring the logical total to 20 in both cases. A claimed retry remains outstanding and is processed once at its final response. The MOVED and topology-retirement paths retain their existing policies; these measurements specifically cover READONLY after demotion.

The refresh-rate choice and timing/CI limits remain as described in my preceding reply. A shared timestamp is small mechanically but also shares the recovery budget across independent client topologies; that behavior change is outside this repair. The monitor gate uses current connection state because any cached/pending-only flag needs updates across reconnect, setup and topology changes. I have not measured a throughput claim for that lookup. The README warning scope is now explicit; detailed queue/count semantics remain documented because they define what the benchmark reports after reconnect.

Final-head CI is not all green: the cluster replica-disconnect/wakeup test has failed, and I am investigating it against the previous head before any rerun. The PR remains blocked on that investigation, independent rechecks, and final-head CI.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

The replica-disconnect CI failure was a real regression, now corrected in 8020ebbfeeac5382cf1e6a2a38d957a7b4ae5501. Paired execution of the exact existing real three-primary/three-replica test passes on ec99479, stalls at 15,945/16,000 operations on 53af982, and completes all 16,000 with the correction (20 seconds including setup). Retaining counted requests on a permanently unavailable strict-secondary replica prevented completion.

Same-endpoint queue preservation is now limited to primaries, which are the missing-slot fallback destinations. Replica redials, including a primary demoted before redial, preserve the existing clear/compensate policy; no new primary fallback or unrelated-replica routing was added. README and the PR body state that this does not guarantee identity across replica redials. The demotion wire results in my previous reply remain evidence for 53af982, not a claim about the corrected replica-reset behavior. New direct units cover demotion, repeated replica redial, promotion, primary retention and exact generated-count compensation. Linking the new unit against the 53af982 production object fails its replica-reset assertion.

All 16 unit programs and all 21 missing-slot integration functions pass, including owned/unowned monitor replay with two AUTH closures and pipelines 1/4, exact ordinary keys and transaction progress. Formatting passes. New-head CI and focused independent review remain pending; I am not treating the failed run as flaky or claiming CI is green.

@fcostaoliveira fcostaoliveira changed the title Preserve workload progress and keys with partial cluster slot maps Keep cluster workloads progressing across partial maps and primary reconnects Oct 23, 2026
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Addressed the scope point in the title and description: this PR now explicitly covers partial maps and primary reconnects, and the Fix section states that primary queue retention and CLUSTERDOWN recovery also affect fully owned maps. Those follow-ups have separate commits and regressions.

On refresh fan-out: each client owns an independent slot map and its own connections, even when clients share an event base. A per-thread limiter could delay each client’s discovery, or would require distributing one reply safely to the other clients and reconciling their connection/setup state. This change retains the per-client bound and documents the aggregate 400/s example; I am not claiming it is a process-wide protection or that this is the optimal recovery polling policy. The monitor gate still scans groups; no throughput/overhead claim is made, and introducing a cached disconnected-primary count would add state transitions beyond this correction.

Independent review found a further role-transition error in 8020ebb, fixed in 11746554c02a4697de483d7095ea2100d89ff0e0: promotion could retain a former replica’s queued reads and bypass strict-secondary routing on drain. We now clear and compensate old replica work before changing its role, including live or pending-reconnect transitions. The committed paired fixture observes 2/8/32 invalid primary GETs before the fix at pipelines 4/16/64 and zero after, with 1,000 completed operations in every fixed case. Same-role primary reconnect identity remains covered. All 22 fixture functions and all 16 unit programs pass; deleting the promotion reset makes the new unit fail.

Current-source real-Redis coverage also includes the existing three-primary/three-replica permanent-disconnect regression, which completes all 16,000 operations after this correction. The manual partial-map plaintext/TLS evidence remains accurately attributed to c9ff438; the scripted promotion/partial-map fixtures do not substitute for native TLS or a committed real-Redis DELSLOTS test. A committed DELSLOTS control remains a coverage improvement, and final-head CI/rechecks are still required. The README retains the queue/promotion limitation so the user-facing identity guarantee is not overstated.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Following the 13:06:49 review edit:

  1. I am retaining the primary-redial repair here because removing it restores the demonstrated missing/replaced monitor values and ordinary keys while recovering the requests covered by Cluster: requests for a slot with no owner in a valid CLUSTER SLOTS reply are never sent; the thread spins and the run ignores --test-time/--requests #685. The separate commits and regressions identify that part, and the title, description and README explicitly disclose its effect on owned keys. The final replica and promotion exceptions have independent paired tests.

  2. Strict secondary with error fallback cannot select an authoritative replica for an unowned key; primary routing or choosing another key would violate the requested workload. Queue is currently reserved and treated as error. This PR therefore fails explicitly, including for a transient mid-run hole, rather than claiming continuous failover operation in that configuration. Synthesizing retryable no-route responses would require an additional identity, accounting and deadline contract. Known-owner replica waiting remains unchanged.

  3. The lookup returns at the first connected primary, so the healthy-first-primary case does not scan every shard. It can scan multiple groups when earlier primaries are unavailable. No large-cluster overhead measurement is claimed. A cached disconnected count would need correct invalidation across setup, reconnect and role transitions; I am keeping the directly tested state lookup in this correctness repair. Owned monitor replay waiting during primary backoff will also be stated in the final squash message.

  4. Exponential backoff could reduce sustained-outage polling while retaining per-client topology ownership. It would also change recovery latency and require cap/reset policy. This patch keeps the explicit one-refresh-per-second-per-client bound; the documented aggregate400/s example is a limitation, not evidence that outage load is harmless. I am not adding a new backoff policy in this fix.

  5. Exact final-head local ASan/LSan review passes six identity controls,25 focused subprocesses and queue/timer ownership checks, including promotion at pipelines4/16/64. Independent TEST also passes the existing real three-primary/three-replica16,000-operation control in21seconds. The fixed closure counts come from forced drops, not equality to requested sleep durations. Full remote ASan/TSan/UBSan workflows are still running; I am not claiming those gates have passed.

All final-head reviews and CI remain required before merge. The documented primary-only identity guarantee intentionally excludes replica redials and old replica work discarded on promotion.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

bugbot run

Please review current head c47fc40 after integrating master, including the topology-retention and bounded stderr logging changes. The automatic check skipped the unchanged PR patch; a fresh review will make the final integration gate explicit. Clean build17/17 units and26/26 focused RLTest functions pass. Full CI and independent rechecks are still pending.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Following the 17:35:19 review update:

  • A timestamp shared by a thread would throttle requests, but each client owns its own slot map and connection/role objects. Refreshing one client does not update its siblings. Sharing a cooldown alone therefore delays or can starve their recovery; distributing one response would require a coordinated topology publication and per-client application path. I have not measured outage load and am not claiming 400 polls/second is harmless. This PR retains the explicit per-client bound; a shared topology/backoff policy needs its own recovery and fairness tests.
  • The redial repair remains together with partial-map routing because otherwise the newly retained requests still lose or replace selected keys during primary setup/reconnect. Separate commits and paired regressions preserve review/bisection history. The effect on owned keys is explicit.
  • Strict-secondary/error deliberately fails on an ownerless key, including a transient hole. There is no authoritative replica destination; primary fallback or skipping the key violates that workload. The reserved queue mode still means error. Known-owner replica waiting is unchanged. A retryable ownerless queue would need explicit identity, deadline and accounting behavior.
  • The healthy monitor lookup returns at the first connected primary, rather than always scanning the entire map. A cached availability flag would require invalidation across the same setup/redial/role transitions under repair. No large-cluster hot-path performance result is claimed.
  • Confirmed the failure guard: the other fail_run caller is end_client_after_run(false), which already requests termination. The guard prevents more generation after failure; it does not stop a successful running client.
  • The README includes observable identity guarantees and their replica/promotion limits so users do not infer stronger replay guarantees. The detailed mechanics remain in code and the PR description.

After master integration, clean17/17 units and26/26 focused runtime functions pass; independent BUILD and SEM approve c47fc40. The remaining reviews and full CI are still mandatory.

@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

Following the 19:12:30 review update, the MGET fallback question now has a direct exact-head control.

UINT_MAX is reachable during terminal failure; it would be incorrect to claim that run_failed() must already be true. With a partial map advertising an invalid primary address and retiring the seed, GDB records cid=4294967295, run_failed=0 and a disconnected main connection at the cache assignment. Existing end_thread() has already requested event-loop termination. The process exits 1 with the explicit incomplete-thread/invalid-results error and Count=0. The no-reconnect and finite-two-attempt controls both exit 1 (1.007s and 3.010s), with zero workload commands. This is not a successful workload silently omitting keys. In viable rebuilds the fallback retains a connected, connecting or reconnect-pending primary, including the in-flight seed refresh. Exact-head trace, source reasoning and probes.

On the remaining points:

  • Queue retention and promotion handling remain together with partial-map routing because otherwise the newly retained requests still lose or replace their selected identities during redial. Their broader effect is explicit, and paired regression cases exercise the owned-key and replica transitions. This integration changes no production source.
  • Each client owns its topology and connection-role objects. A shared cooldown alone would suppress refreshes without applying another client's result, potentially starving recovery. Sharing topology publication needs coordinated application and fairness tests. The documented bound remains one refresh per second per client; I do not claim that its aggregate outage load is negligible.
  • The healthy monitor lookup returns at the first connected primary. Removing or caching the lookup needs correct invalidation across the same redial/setup/promotion transitions. No large-cluster hot-path performance result is claimed, and the duplicate fallback lookup remains a possible optimization.
  • The run_failed() producer guard prevents additional generation after an already-declared client failure, including non-routing failures. That is distinct from the thread-level termination signal observed above; successful clients are unaffected.
  • The README keeps observable request-identity, fallback and promotion limits so users do not infer stronger replay guarantees. Implementation detail can be shortened separately without changing this contract.

Current head8d4c7c2703ec3678b23ee81b9fd9890accf2dc4b has a fresh clean17-unit build,30 focused integration tests, and851 tests assigned exactly once across the sanitizer shards. Independent SEM, TEST and INTER rechecks approve it; the remaining lenses and full new-head CI are still required.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 8d4c7c2. Configure here.

Comment thread cluster_client.cpp Resolved
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Answers for head 42ede4a:

  • Owned monitor routing. Agreed, this changes behavior on full maps too. While a known owner primary is refreshing CLUSTER SLOTS or in reconnect backoff (but not disconnected), owned monitor lines are now staged on it, the same way ordinary routed keys already queue on their owner and drain once its setup completes. Before, the already-selected line went out on the producer, which can be a replica seed. With only the production hunk reverted, test_owned_monitor_waits_for_primary_refresh sends up to 19 of 20 SETs to the replica. The pipeline-4 leg fails on every run and the pipeline-1 leg in about two thirds of runs. With the change, all 20 ordered SETs reach the primary at both pipelines. Disconnected owners and the queue-cap fallback are unchanged. The description now covers this in the Fix section next to the other full-map changes, and I removed the wording saying other known-owner destinations are unchanged.
  • Scope. Retention stays in this PR. The fix depends on primary redials, and without retention the unowned keys this PR now keeps would still be lost or replaced during those redials. The PR is squash-merged, so the squash message will list each full-map behavior change: primary queue retention, CLUSTERDOWN-triggered refresh, and owned monitor staging during backoff/refresh.
  • CLUSTERDOWN refresh rate. The limit is one refresh per client per second because each client owns its own slot map and connections. A shared cooldown alone would suppress refreshes without updating the other clients' maps. Before this change, a stale full map never refreshed on CLUSTERDOWN at all. I haven't measured outage load at 400 clients and don't claim it's harmless. I'm happy to open a follow-up issue for shared or backoff topology polling once this lands.
  • Concentrating error traffic. I kept the first-connected-primary choice. There's no owner to hash to, the server's error is the authoritative answer, and the README documents it.
  • MGET cache build. No, there's no such guarantee. UINT_MAX is reachable during a cache rebuild while run_failed() is still false, after end_thread() has already asked the loop to stop. That run then exits 1 with zero workload commands and the incomplete-thread error, so a successful run never silently omits the slot.
  • hold_pipeline hot path. The gate only runs in monitor-random mode with an empty staged queue, and the lookup returns at the first connected primary, so a healthy map does a constant amount of work after the command lookup. I haven't measured it and make no throughput claim. A cached "any primary in backoff" flag would need invalidating across the same setup/redial/promotion transitions this PR fixes, so I'd rather keep the direct state check.

Full CI on 42ede4a is green (144 passed, 6 skipped).

@fcostaoliveira
fcostaoliveira merged commit 4018396 into master Oct 24, 2026
150 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 25, 2026
With --cluster-mode --rate-limiting, the up-front percentile warning
(#386) took its sample bound from the first committed topology only.
Since #799 a run can start on a partial slot map, and when the map heals
memtier opens more endpoint connections, each with its own rate limit.
On a 3-primary cluster with one primary's slots restored 1 s into a 6 s
run at 800 req/s, memtier warned that p99.99 "records at most about
9664" and "will not be resolved", then recorded 10187 samples and
resolved it.

The cluster client now publishes the largest rate-limited connection
fan-out committed so far, written once per topology commit under the
topology-summary mutex. The main thread's once-a-second check remembers
what it said about each percentile, for the run and the window, and when
the fan-out grows prints one header line and then either the warning
again with the raised bound or a "may now be resolved" note. A
--requests bound does not depend on connections and is not repeated. The
progress-line newline is printed only when there is a warning.

test_cluster_unowned_slots.py heals the fake cluster after memtier's
first warnings and checks the exact update lines, the window '*' marks,
and that a --requests warning is not repeated.

Fixes #825

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
… 2.2.2-alpha (#545)

**Depends on #822 and #832.** This branch merges both PR branches unchanged, so either can land first and the other merges cleanly:
- #822 (`fix/libevent22-tls-error-access`, at cba1fcc) brings the `shard_connection.cpp` TLS error guard and `tests/test_connection_error_types.py`. Please review those in #822.
- #832 (`fix/resp-bulk-length-overflow`, at 300da45) brings the RESP length/count bounds in `protocol.cpp`, the `check_length_limits()` unit test and the fuzzer's sanitizer-output checks. This PR's UBSan-aborting sanitized cell found that overflow. Please review those in #832.

Intended order: land #822 and #832 first, then merge master here (no rebase or force push), so this diff becomes CI, tooling and docs only. Refs #535.

#823 also adds a "Supported libevent versions" table and a #535 read-size note to DEVELOPMENT.md. Whichever of #823 and this PR lands second merges the two tables into one and keeps a single #535 paragraph.

## Problem
memtier's integration suites (including ASan/UBSan/TSan) run only on the distro's libevent 2.1.12. Nothing in CI builds the current security release 2.1.13-stable or the 2.2 series, and libevent itself is never instrumented. Because of that, the 2.2.2-alpha regression fixed in #822 (an out-of-bounds access inside libevent on every plaintext connection error in a TLS-enabled build) could only be found by hand. The earlier version of this workflow used `paths:` filters, so it could not be a required check (a skipped required check never reports), put versions in job names, and installed Redis from a different source than `ci.yml`.

## Root cause
libevent behaviour differs by series: 2.2.2-alpha asserts, or with `NDEBUG` reads and writes out of bounds, when `bufferevent_get_openssl_error()` is called on a plain bufferevent, and it returns no error for TLS bufferevents. 2.1 reads at most 4 KiB per socket read, 2.2 up to 16 KiB (#535). None of this is visible without building those libevent versions, instrumenting them, and checking which library memtier actually loads.

## Fix
- **`scripts/build-libevent.sh`**: one helper for Linux and macOS. It pins 2.1.12-stable, 2.1.13-stable and 2.2.2-alpha by release-asset sha256 (never `/archive/`) and libevent `master` by commit (`d82464a2`, canary only). It rejects a non-empty or non-directory prefix before creating it, builds with CMake (Release), and with `LIBEVENT_FLAVOUR=sanitize` also builds libevent with ASan+UBSan. `--source-id` feeds the CI cache key. The macOS jobs in `ci.yml` keep using it for 2.1.13 (clean prefix as in #674, debug mode off). The macOS OpenSSL 1.0.2 cell keeps master's autotools build of 2.1.12, unchanged. Because the existing `ci.yml` macOS jobs now go through the helper, a helper regression also breaks those jobs. `build-macos-libevent.sh` and the helper are in the harness pattern, so any change to them runs the full libevent grid.
- **`scripts/check-libevent-linkage.sh`** (Linux; on macOS it delegates to `check-macos-tls-links.sh`). It fails unless the `--version` `libevent=` field equals the expected string from the matrix (e.g. `2.2.2-alpha-dev`), the prefix's pkg-config files for every component are the same release, every libevent library loaded (directly or transitively, per `ldd`/`readelf`) comes from the prefix, the process loads exactly one libssl and one libcrypto (so `libevent_openssl` and memtier share one OpenSSL; checked on memtier's transitive `ldd` set, so a private OpenSSL found through RUNPATH is handled), and the `openssl=`/`prometheus=` fields are as intended.
- **`.github/workflows/libevent-compat.yml`** redesign:
  - No path filters. Triggers match `ci.yml` (`pull_request` and `push` on `master`, `main`, `2.*`), plus a nightly schedule, a weekly schedule and `workflow_dispatch`.
  - Stable job names `libevent-compat (<track>, <cell>)` with no versions in them. The track is `legacy` 2.1.12, `stable` 2.1.13, `next` 2.2.2-alpha or `canary` master.
  - Aggregate **`libevent-compat-gate`** (`if: always()`). It fails unless planning and every non-canary cell succeeded. This is the only check to mark required.
  - **Every PR/push**:
    - `stable` and `next` TLS full suites, standalone and cluster.
    - `next` plaintext full suites with **memtier and libevent both under ASan+UBSan**. This is the cell that catches the #822 regression.
    - `next` `--disable-tls` build (Prometheus on) with `make check`.
  - **Nightly**, and PRs that change this harness: adds 2.1.12 source builds (TLS and plaintext), the remaining plaintext and no-TLS cells, and macOS builds with OpenSSL 3 and 4.
  - **Weekly and on dispatch**: a libevent `master` canary with `continue-on-error`. It is not required and not part of the gate. A failing canary writes a warning and a step-summary line, and a small `canary-alert` job (`issues: write`, canary runs only) opens or updates one "libevent master canary is failing" issue.
  - Sanitized cells run with `ASAN_OPTIONS=detect_leaks=1:abort_on_error=1` and `UBSAN_OPTIONS=halt_on_error=1:abort_on_error=1:print_stacktrace=1`. Concurrency groups include the event name, so pushes never cancel scheduled or dispatched runs. The nightly skips Sunday, when the weekly run covers the same grid.
  - Built libevent is cached with `actions/cache`, keyed on version, sha256/commit, flavour, OpenSSL version, compiler version, and the hashes of the helper and the workflow.
  - Redis is installed from packages.redis.io, the same way as `ci.yml`.
  - Wall time: each test cell runs one topology, and the cluster suites are split into two file shards (`utils/select_test_shard.py`, coverage checked by `utils/check_test_shards.py`, as in the sanitizer workflows). On 658fed4 an unsharded cluster cell took 35–41 min, as long as `ci.yml`'s slowest cell (`OSS-CLUSTER API: TCP TLS`, 37 min); standalone cells take about 25 min.
- **`tests/test_reconnections.py`**: when memtier dies from a signal, the test prints its stderr, starting at the first sanitizer report or assertion. This makes an abort in `test_reconnect_cluster_mode_no_assertion` diagnosable from the CI log. On the previous head it failed with rc −6 in the sanitized alpha cell, and no stderr was printed.
- **`DEVELOPMENT.md`**: the tested libevent matrix, how to evaluate another libevent locally, the 2.1 (4 KiB) vs 2.2 (16 KiB) read size (Refs #535), and the TLS messages memtier prints on 2.2 after #822.

## Tests
- CI on 8e8b3a6: Libevent compatibility, all 28 jobs green (full grid, because this PR changes the harness), and all other workflows green. On 658fed4 it showed harness-side failures that are fixed: a test-time `PKG_CONFIG_PATH`, and absolute macOS install names for 2.2.
- The cell that was red before (`test_reconnect_cluster_mode_no_assertion`, rc −6 under ASan+UBSan on b3c67f1) passed on x86_64 on 658fed4 and 8e8b3a6. The earlier failure ran on a source 167 commits behind master, before several cluster-reconnect fixes landed (e.g. 019d658, #777, #797, #799). The test now prints memtier's stderr whenever memtier dies from a signal.
- Local (Ubuntu 24.04 container, OpenSSL 3.0.13):
  - The helper built 2.1.12, 2.1.13, 2.2.2-alpha, master and sanitized 2.2.2.
  - memtier built against each, plus `--disable-tls` and ASan+UBSan builds, and the linkage checker accepted every one.
  - The checker rejected each negative case: wrong expected version, prefix/runtime mismatch, a TLS expectation on a no-TLS build, a wrong Prometheus flag, and a build that loads the system libevent.
  - The helper rejected a non-empty prefix, a file used as prefix, an unknown version or flavour, and a missing argument.
- Before/after: unguarded `master` built against sanitized 2.2.2-alpha aborts on a refused plaintext connection with `AddressSanitizer: heap-buffer-overflow` in `bufferevent_get_ssl_error` (`bufferevent_ssl.c:1108`), called from `shard_connection.cpp`. This branch exits normally in the same setup.
- macOS (CI, nightly cells): with 2.2 the helper now sets absolute install names (`CMAKE_INSTALL_NAME_DIR`), because 2.2's CMake otherwise installs `@rpath/` dylibs, which `check-macos-tls-links.sh` rejects.
- `actionlint` (with shellcheck) is clean on the new workflow, `shellcheck` is clean on the scripts, and the C++ passes `clang-format-18 --dry-run --Werror`.

## Per-PR cost, sanitizers, and the required check
- **PR scope**: 10 Linux jobs. On 8e8b3a6 (full grid, 28 jobs, all green) the longest cell took 27 min (`next, plaintext-asan, standalone`) and the cluster shards 18–23 min. `ci.yml`'s slowest cell took about 37 min on the same push, so libevent-compat is not on the PR critical path.
- **Measured cost**: on 8e8b3a6 the 10 PR-scope jobs used about 203 runner-min (all existing workflows together use about 818 per PR run). Of that, `stable` (2.1.13) TLS is 3 jobs and about 68 runner-min.
- **Why `stable` runs per PR**: the goal is full coverage of the libevent users actually run. 2.1.13 is the current security release and ships in RHEL 9/10, Debian 13, Fedora, Alpine ≥ 3.21, Homebrew and MSYS2, while `ci.yml` runs integration suites only on Ubuntu's 2.1.12 and only builds and unit-tests 2.1.13. If CI budget ever requires it, the plan step makes moving it to nightly a one-line change.
- **ASan/LSan with an instrumented libevent**: `abort_on_error=1` stays on purpose. Without it, a leak exits with 23, and tests that only check `!= -6` pass over it. Full runs came back clean with no suppressions file: on 658fed4 the sanitized cluster cell passed 858/858, and on 8e8b3a6 all three sanitized cells passed. If an alpha-internal leak ever appears, the fix is a narrow LSan suppression with an upstream link, not a waiver.
- **Required check**: after merge, someone with admin rights must mark `libevent-compat-gate` (only that job) as required. Suggested timing: after three consecutive green nightlies, given that `next` is an alpha.
- **Canary pin**: the expected `2.2.2-alpha-dev` string is tied to the helper's `master_commit`. Both are commented to be bumped together.

## Affected versions
CI and tooling only. No memtier runtime change beyond what #822 (TLS error guard) and #832 (RESP length bounds) carry. The runtime failure that #822 fixes affects TLS-enabled builds running on libevent ≥ 2.2.2-alpha (2.1.x tolerates the call).


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes touch connection error handling, RESP parser bounds, and a large new required CI surface; misconfiguration of the gate or parser rejections could affect TLS diagnostics or malformed-server behavior.
> 
> **Overview**
> Adds **libevent compatibility CI** and build/link tooling so memtier is exercised against pinned **2.1.12**, **2.1.13**, and **2.2.2-alpha** (plus a non-blocking **master** canary). New `scripts/build-libevent.sh` and `check-libevent-linkage.sh` install verified libevent into a private prefix; macOS CI gains **cmake** and routes `build-macos-libevent.sh` through the shared helper. The **`libevent-compat.yml`** workflow runs a scoped PR matrix (TLS on stable/next, ASan+UBSan plaintext on 2.2) with nightly/weekly expansion, cluster sharding, caching, and a single required **`libevent-compat-gate`**.
> 
> **Runtime and test changes** in the same branch: **TLS connection errors** only call OpenSSL/libevent accessors on real TLS bufferevents, with certificate-verify fallback when libevent 2.2 reports no OpenSSL reason (`shard_connection.cpp` + new `test_connection_error_types.py`, wired into ASan/TSan/UBSan misc cells). **RESP parsing** rejects aggregate counts and bulk lengths that would overflow `int`/`long` bookkeeping (`protocol.cpp` + `check_length_limits()`). Fuzzer/reconnect tests broaden sanitizer failure detection and stderr logging on signal death. **DEVELOPMENT.md** documents the libevent matrix and local evaluation; **`.gitignore`** ignores local libevent build dirs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit cd86f27. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->



Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
)

## Problem

`--connection-stage-timeout=N` can abort after just over N − 1 seconds.

The supervisor stamps the run start and the first setup failure with `tv_sec` only, and compares whole seconds. The main loop polls it once per second (`sleep(1)`). Suppose the run starts at 10.99 s and a poll lands at 12.01 s: the supervisor sees 12 − 10 = 2 seconds after 1.02 s, so a 2 s timeout trips.

This makes `test_cluster_unowned_slots:test_unowned_keys_survive_repeated_redial` (from #799) flaky. It has a 2 s budget against about 1.1 s of injected server delays and backoffs. It failed in #545's `libevent-compat (legacy, plaintext, standalone)` cell:

```
Connection dropped, attempting reconnection 2/3 in 0.50 seconds...
memtier_benchmark: aborting after 2 seconds of connection-stage failures (last error: no response from server during setup).
  Wall time:        1.010s
```

Locally it failed 3 times in 180 runs: 2 of 70 on #545, 1 of 40 on #832, and 0 of 70 on master. Every failure was this abort after about one second. Neither #545 nor #832 touches this code; the failure depends on where in the second the run starts.

Deterministic reproduction (from review): start memtier at set points late in a wall-clock second, against a server that accepts and never replies, with `--connection-stage-timeout=2`. Master aborted early in 4 of 25 runs, after 1.016 s, still saying "2 seconds". With this PR none did; the fastest abort was 2.008 s.

## Fix

- Stamp the run start and the failure streak in wall-clock microseconds, and compare them with the timeout in microseconds.
- The comparison moves to `connection_stage_clock.h` (`connection_stage_timed_out()`), so it can be unit-tested.
- The abort message still reports whole seconds.
- With the once-per-second poll, an abort now lands between N and N + 1 seconds instead of between N − 1 and N.

## Tests

- **New unit test** `tests/unit/connection_stage_clock_test` (`make check`): a phase that started late in a second has not timed out 1.02 s later. It times out at exactly 2 s and reports whole elapsed seconds, has no start time before the first failure, and uses timestamps far from the epoch. A mutant that compares whole seconds fails it, and so does one that converts the timeout to microseconds in 32 bits (a 5000 s case).
- **Integration tests on libevent 2.1.12, ASan + UBSan.** I ran the 17 test files that use `--connection-stage-timeout` (connection setup rejection, cluster slots, unowned slots, reconnects, retries, CLI validation and others). Results are the same with and without the fix: 236 pass, and the one failure is the same pre-existing `test_memcache_meta_protocol:test_meta_unsupported_options_fail_before_connection` on both.


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a summary for commit e1a6c84. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
Fixes #834.

Since #799, a `-CLUSTERDOWN` reply makes each `cluster_client` refresh its topology with `CLUSTER SLOTS`, at most once per second. Each client keeps its own map, so `-t 8 -c 50` sent up to 400 refreshes per second for the whole outage.

This takes option 1 from the issue, per-client exponential backoff:
- While a client receives only `CLUSTERDOWN` replies, the gap between its refreshes doubles from 1 s to 8 s (refreshes at 0, 1, 3 and 7 s, then every 8 s). A sustained outage at `-t 8 -c 50` drops from 400 refreshes per second to 50.
- A successful reply to a keyed request resets the gap to 1 s. During CLUSTERDOWN Redis still answers keyless commands (PING, MULTI, WAIT), so their replies don't reset it, and neither do other errors (`TRYAGAIN`, `LOADING`, `MASTERDOWN`) or redirects. Without this, `--transaction` runs and keyless `--command` mixes would still poll once a second.
- The 1 s floor is kept, so polling is never faster than on master.
- The 8 s cap means a new map is seen at most 8 s after it's published, which is less than Redis's own failure detection (`cluster-node-timeout`, 15 s by default).

The decision lives in a small `clusterdown_refresh_backoff` struct in `retry_backoff.h`, next to the existing retry backoff. The README paragraph that stated the 400/s figure now states the schedule.

**Tests**
- `tests/unit/retry_backoff_test.cpp` gets a case for the schedule, the cap, the reset and the 1 s floor. Against master's fixed 1 s logic it fails 13 checks: a 60 s outage gives 61 refreshes instead of 10.
- The scripted-peer `CLUSTERDOWN` test in `tests/test_cluster_unowned_slots.py` gets a case that counts `CLUSTER SLOTS` during a sustained `CLUSTERDOWN`, for a plain workload, `--transaction`, and a SET+PING `--command` mix. Master's logic sends 14 against a bound of 8 to 10, and so does a reset on any successful reply for the two keyless-reply workloads. With the fix it passed 4/4 runs.

**Results** (Ubuntu 24.04 container, libevent 2.1.12):
- `make check` passes, plain and ASan+UBSan.
- `test_cluster_unowned_slots.py` passes 24/24, plain and sanitized.
- With `OSS_CLUSTER=1`, 7 cluster test files pass 70/72. The 2 failures (`test_transaction_connection_kills_do_not_hang`, `test_transaction_lost_multi_is_not_continued`) fail the same way on unmodified master in this container.

**Limitation (same as master):** if only some slots are down and the workload mixes keys, successful replies keep resetting the gap, so each client still refreshes about once a second. Removing that needs option 2 from the issue: one shared refresh per thread.


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes cluster-mode error handling and topology refresh timing during outages; behavior is well-tested but affects all CLUSTERDOWN paths in production benchmarks.
> 
> **Overview**
> **Replaces fixed 1 s `CLUSTER SLOTS` polling on `-CLUSTERDOWN` with per-client exponential backoff (1 → 8 s)** so large `-t`/`-c` runs no longer hammer the cluster during sustained outages (#834).
> 
> Each `cluster_client` now uses a `clusterdown_refresh_backoff` helper in `retry_backoff.h`: refresh gaps double after each `CLUSTERDOWN`-triggered topology poll until they cap at 8 s, while a **1 s floor** remains. A **successful reply to a keyed workload** resets the streak; keyless successes (`PING`, `MULTI`, monitor lines without keys, etc.) do not, via new `request_carries_key()` and `arbitrary_command::has_keys()`. README documents the revised refresh schedule.
> 
> **Tests** add unit coverage for the backoff schedule and integration cases that bound `CLUSTER SLOTS` calls under sustained `CLUSTERDOWN`, transactions, and monitor replay.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit eb42f5e. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

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: requests for a slot with no owner in a valid CLUSTER SLOTS reply are never sent; the thread spins and the run ignores --test-time/--requests

1 participant