Repository navigation
feat: --read-preference (cluster + standalone read-endpoint routing) - #456
Merged
Merged
Conversation
Extract the READONLY flag from the redis/redis JSON command corpus alongside the existing MOVABLEKEYS extraction, and surface it as a new bool is_read field on CommandSpec. Prep work for routing read-only commands to replicas under --read-preference; no behavior change today (no consumer reads the field yet). Re-runs gen_command_meta.py to refresh command_meta_data.h. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Introduce a shard_role enum (role_primary, role_replica) plus a connection- scoped m_role field and is_replica()/get_role()/set_role() accessors on shard_connection. Defaults to role_primary so existing primaries-only callers see no behavior change. Connection-scoped (not setup-state-scoped) so the role survives reconnects; this is what lets the upcoming READONLY setup stage re-fire on every reconnect for replica connections. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…plicas Wire a new rt_readonly request type and an m_readonly_state setup-state slot that fires between HELLO and CLUSTER SLOTS for replica connections in cluster mode. The stage is re-armed on every connect() so READONLY re-issues across reconnects (the flag is connection-scoped on the server side). Primaries and standalone-mode replicas skip the stage entirely (initialized to setup_done). Adds write_command_readonly() to abstract_protocol with a real RESP-1 implementation in redis_protocol and assert(0) stubs in both memcache protocols (the READONLY ladder is gated to is_redis_protocol() callers). No connection becomes a replica yet -- m_role is still always role_primary -- so this commit is a no-op in the current call graph. The follow-up handle_cluster_slots change is what starts flipping connections to role_replica. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Add a shard_group struct (id, primary, replicas, per-thread replica_rr_cursor) and a vector<shard_group> m_shard_groups owned by cluster_client. Replace the flat unsigned m_slot_to_shard[16384] array with std::vector<unsigned int> m_slot_to_shard_group that points each slot at its owning shard_group index. Add a slot_primary_conn_id() helper that resolves a slot through the new indirection to the primary's conn_id; route every existing m_slot_to_shard reader (get_key_for_conn, transaction-pin lookahead, create_monitor_request_ cluster, retry_after_redirect, build_mget_slot_cache, handle_cluster_slots itself) through it. UINT_MAX is returned during the bootstrap window before CLUSTER SLOTS lands; each caller treats it the same way it treated the prior zero-initialized table. Replicas vector stays empty in handle_cluster_slots; a follow-up commit adds the [3..N] walk that fills it. Primaries-only routing behavior is preserved. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…shard_group
Extend handle_cluster_slots to iterate mbulks_elements[3..N] after the primary
node tuple at [2], applying the same (host, port, ...) parse and the same
dedupe-by-(addr,port) lookup used for primaries. For each replica entry:
- reuse an existing shard_connection if one already matches (preserves
connections across topology refreshes; close_sc[] flags it as live)
- otherwise create a fresh one via create_shard_connection() and connect
it with connect_shard_connection(); the shard_group gets the resulting
shard_connection*
Set m_role = role_replica BEFORE connect() so the new READONLY setup stage
fires alongside AUTH/HELLO during the connection's initial handshake. Existing
replicas have their role refreshed (idempotent) so a primary that just lost
its slots and was reclassified as a replica is relabeled even when no
reconnect happens in this pass.
Replicas are NOT routed to yet; select_target_conn() and the routing changes
are deferred to the integration agent. The shard_group.replicas list is the
data plumbing those callers will read from.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…nfig fields Add new enums (read_pref_mode, read_pref_fallback) and a lightweight read_server_spec struct to memtier_benchmark.h. Extend benchmark_config with read_preference, read_preference_fallback, read_servers, replica_clients, and replicas_per_shard. Add is_read_override (int, -1/0/1 tri-state replacing std::optional<bool>) to arbitrary_command in config_types.h/.cpp and initialize it to -1 in the constructor so existing callers are unaffected. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…e validation Add six new long options to config_parse_args(): --read-preference=MODE (primary|secondary|secondaryPreferred|nearest) --read-server=HOST:PORT repeatable; IPv6 brackets supported --command-is-read per-command read override modifier --replica-clients=N --replicas-per-shard=K --read-preference-fallback=MODE (error|queue|primary) Post-parse validation: - --transaction + --read-preference != primary → hard error - --read-preference set without --cluster-mode and no --read-server → warning Extend config_print_to_json() with read_preference, read_preference_fallback, replica_clients, and replicas_per_shard keys under the configuration block. Extend usage() with a "Read Preference Options" section and --command-is-read help text in the Arbitrary command section. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…rence flags Add test_cli_validation_read_preference.py covering: - unknown --read-preference mode rejected - all four valid modes accepted at parse time - --read-preference without --cluster-mode or --read-server emits warning - --transaction + --read-preference!=primary is a hard error - --read-server bad HOST:PORT formats rejected - --read-server valid HOST:PORT accepted; suppresses 'no effect' warning - unknown --read-preference-fallback value rejected; valid values accepted - --command-is-read without preceding --command rejected Tests invoke the binary via subprocess; no live Redis required. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Add three helper functions for read-preference tests: - get_cluster_replica_connections(): introspect CLUSTER NODES to return redis.Redis connections for every replica in the cluster. - reset_commandstats(): CONFIG RESETSTAT on a list of connections. - get_get_call_count(): read cmdstat_get.calls from INFO COMMANDSTATS. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Four new RLTest test files covering the --read-preference flag: - test_read_preference_modes.py: primary/secondary/secondaryPreferred/ nearest routing assertions via cmdstat_get on masters vs replicas. - test_read_preference_failover.py: secondaryPreferred falls back to master when one replica is stopped. - test_read_preference_mget.py: --multi-key-get routes MGET to replicas when --read-preference=secondary. - test_read_preference_transaction.py: --transaction + non-primary read-preference rejected at parse time; primary accepted (positive path). Tests will fail until the feature is implemented in the C++ layer. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
When OSS_CLUSTER_REPLICAS=1, run_tests.sh passes --use-slaves and --shards-count $SHARDS to RLTest so replica nodes are started alongside each master. Documents the new variable in the help block. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…erence Add a new test-ubuntu matrix entry that runs the read-preference test suite with OSS_CLUSTER_REPLICAS=1 (3 shards, 1 replica each, no TLS, parallelism=2). Tests read_preference_modes, _mget, and _transaction. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…read)
Layers the load-bearing routing logic on top of the A1 foundation:
* select_target_conn(slot, is_read) - resolves a slot to the conn_id that
should serve the request under --read-preference. Writes always go to
primary; reads route per mode (primary / secondary / secondaryPreferred /
nearest). Strict secondary returns UINT_MAX when no replica is live so
the caller can apply --read-preference-fallback.
* classify_read(request*) and is_read_command_index(idx) - shared
read/write classifier respecting arbitrary_command::is_read_override,
CommandSpec::is_read, and the safe-default-write fallback for unknown
commands.
* Routing hooks:
- cluster_client::get_key_for_conn switches from slot_primary_conn_id
to select_target_conn, picking up reads on replicas under
--read-preference and falling back through the same available_for_*
machinery already used for cross-shard work dispatch.
- cluster_client::create_mget_request routes MGET to the selected
replica via send_mget_command on the routed conn.
- cluster_client::create_get_request override exists solely to bump
the per-command read-routing counter when the send lands locally.
- retry_after_redirect routes via select_target_conn so the read-class
re-route after MOVED honors --read-preference (writes still pin to
the slot primary).
* -READONLY handling: server told us the replica won't accept the
command. Force re-route to slot primary (bypassing read_preference)
and retry once. We do NOT trigger a CLUSTER SLOTS refresh - READONLY
is a per-request signal, not a topology event.
* EWMA latency tracking on shard_connection (LATENCY_EWMA_ALPHA=0.1,
min 10 samples before counting as "warm"). Updated in
cluster_client::handle_response on successful responses. Cold endpoints
treated as +inf by `nearest`-mode selection so they don't get
over-picked during warm-up.
* Per-endpoint observability: m_routed_ops bumped in push_req for every
user-level request; per-arbitrary-command and built-in GET routing
counters split Ops-from-Primary vs Ops-from-Replica.
Build clean (no new warnings). Existing CLI smoke tests still pass:
--read-preference=secondary parses, --transaction guard fires.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Capture --read-preference routing state at run end so it survives into
the structured JSON output:
* endpoint_snapshot + read_routing_summary types on run_stats: per-conn
snapshot (addr, role, shard_id, routed_ops, EWMA latency, samples)
plus aggregated Ops-from-Primary / Ops-from-Replica counters keyed by
arbitrary-command index (and a built-in GET slot).
* run_benchmark() snapshots all shard_connections after threads.join()
but before worker teardown -- by that point routing counters and EWMA
state are stable and the shard_connection objects are still alive.
Per-(addr, role) coalescing keeps the JSON O(distinct endpoints), not
O(threads x connections).
* run_stats::print_json emits two new sub-objects when cluster_mode AND
read_preference != primary:
- "Read Routing": Ops from Primary / Ops from Replica / Primary
Fraction for built-in GET.
- "Arbitrary Read Routing": same shape, one entry per --command
classified as a read.
Plus an unconditional "Endpoints" array in cluster mode (always
useful, even under rp_primary, as an audit trail of which conns saw
traffic).
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The A2 prep PR landed parse-time validation tests that invoke memtier against a dead port (--p 1) with --test-time=1, expecting it to exit quickly. The bound was 5s subprocess timeout, but memtier's post-test cleanup phase (connection-error reporting + per-thread stats render) runs after --test-time elapses and pushes total wall time past 5s on modern systems. Bump subprocess timeout to 15s and add --max-reconnect-attempts=1 + --connection-stage-timeout=2 to bound the connect/setup loops so the process exits in well under that. Restores green CI for the 4 tests that were flaking on A2 alone. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Two bugs surfaced once the routing layer started exercising the replica connections introduced by A1: 1. Replica READONLY bytes never reached the wire. The A1 setup ladder appends the READONLY frame via protocol::write_command_readonly, which writes through evbuffer_add() on the bufferevent's output evbuffer directly. For a connection whose FD was attached to its bufferevent via the bufferevent_socket_new + bufferevent_socket_connect path (the A1 replica-discovery flow), the evbuffer notify callback does NOT re-arm EPOLLOUT on the FIRST user-level send. The bytes sit in the output buffer forever and the connect-callback's send_conn_setup_commands has no chance to flush them. As a result the replica never receives +OK to its READONLY, is_conn_setup_done() returns false forever, pending_resp stays at 1, all_connections_idle returns false, and the test never finishes. Fix: use bufferevent_write() for the READONLY frame so libevent's bufferevent_trigger_nolock_ runs and EPOLLOUT is registered. Primaries don't hit this because their setup ladder is a no-op (all setup states default to setup_done). 2. fill_pipeline spin under rp_secondary when no replica is live yet. On bootstrap, the primary tries to generate a GET, select_target_conn returns UINT_MAX (no live replica yet), get_key_for_conn returns not_available, create_get_request returns false, m_reqs_generated is not incremented. fill_pipeline's while condition is unchanged (pipeline empty < target depth), so it loops forever. The event loop never gets a chance to fire BEV_EVENT_CONNECTED for the in-progress replicas. Result: total stall. Fix: hold_pipeline now detects "read-only workload + non-primary read-preference + no live replica" and returns true so the producer yields the event loop. The READONLY response handler then calls schedule_fill on peers, unblocking the bootstrap. connections_manager.h grows a get_connections() virtual so the READONLY response handler can wake peers without depending on the concrete client / cluster_client type. Verified end-to-end on a local 3-shard cluster with 1 replica/shard: - --read-preference=secondary now completes and routes 100% of GETs to replicas (mb.json: Ops from Replica=100, Primary Fraction=0). - --read-preference=nearest completes; during the cold-start window all reads stay on primary as designed. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
🛡️ Jit Security Scan Results✅ No security findings were detected in this PR
Security scan by Jit
|
…old-pipeline tightening Three correctness fixes in cluster_client.cpp from PR #456 review: 1. m_slot_to_shard_group[] is now reset to UINT_MAX before every CLUSTER SLOTS rebuild (handle_cluster_slots) and at construction. Previously, the slot map kept stale group indices for slots that disappeared from the new reply; after m_shard_groups.clear() those indices could alias to a different new group -> silent mis-routing until MOVED recovered. Every existing reader (slot_primary_conn_id, select_target_conn, get_key_for_conn -> *_for_conn helpers, retry_after_redirect, create_monitor_request_cluster, create_mget_request) already treats out-of-range gidx as "not available" and bails. 2. -READONLY retry path no longer falls back to the rejecting replica when no live primary is known. The previous fallback (primary_target = conn_id) re-queued the request onto the same replica that just returned -READONLY, guaranteeing rejection until --retry-max-attempts. New behavior: schedule a CLUSTER SLOTS refresh on the rejecting connection and finalize the request as a terminal error; future traffic re-routes correctly on the next pipeline tick. 3. hold_pipeline()'s read-preference gate now fires only for the strict mode (rp_secondary with fallback != rpf_primary). Previously it stalled rp_secondary_preferred / rp_nearest / rp_secondary+rpf_primary when no replica was live, even though those modes are explicitly defined to fall back to the primary. Non-strict reads now drain to primary instead of stalling. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…rvers in mb.json Two low-impact CLI/config follow-ups from PR #456 review: 1. Add a parse-time warning when --replica-clients is set together with --read-preference=primary. The extra replica clients are silently ignored because every read still goes to the primary; mirrors the existing "--read-preference has no effect" warning for the standalone- without-read-server case. 2. Emit `read_servers` in the configuration block of mb.json as a comma-separated "host:port,host:port,..." string. Was missing while replica_clients / read_preference / read_preference_fallback were already there; matches the surrounding key=value style (data_size_list, wait-ratio, etc.). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
m_endpoint_snapshots is built by absorbing per-thread snapshots in absorb_endpoint(), so its emission order tracks the thread-local merge order and varies run-to-run. stable_sort by (addr, role) before print_json gives stable mb.json output and makes diffs reviewable. addr already encodes host:port via shard_connection::set_address() so a separate port comparator is unnecessary. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ly assertion
CI matrix cell used file:function pairs ('test_read_preference_modes:
test_read_preference_modes') but no function by that name exists -- the
actual functions are test_read_preference_primary / _secondary /
_secondary_preferred / _nearest. RLTest silently no-matched and the
read-preference suite was skipped in CI. Fixes:
- Switch TEST to file paths only ('test_read_preference_modes.py ...'),
which is the format tests/run_tests.sh expects to forward verbatim to
'--test'. Add test_read_preference_failover.py to the cell (previously
omitted; the failover scenario is the highest-signal regression test).
- Replace the post-SHUTDOWN-NOSAVE time.sleep(1) in
test_read_preference_failover.py with a 5s-capped polling loop that
breaks as soon as a replica stops responding to PING. Avoids a
hard-coded delay that under-shoots on slow CI and over-shoots on fast
machines.
- Add the master_gets == 0 assertion to
test_read_preference_secondary_preferred. The strict variant
(rp_secondary) already enforces this; the preferred variant should too
whenever live replicas are available -- without the assertion, a
silent regression that diverts secondaryPreferred reads to masters
would not be caught.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Collaborator
Author
Reviewer follow-ups addressed (commits 994e9ad..f8a25d2)Bundled 4 follow-up commits on
|
When --read-preference routes MGET to a different connection than the producer (replica round-robin, nearest-mode, secondary-preferred fallback), fill_pipeline's `m_pipeline->size() < pipeline` gate only caps the producer (conn_id). The destination's actual in-flight depth is invisible at the create_mget_request site, so the producer kept issuing MGETs without observing the destination's depth -- a replica under skewed routing could be driven well past --pipeline, ballooning the latency tail and overshooting the rate target. Mirror the monitor-input route-then-stage backpressure pattern (in_flight clamp at hold_pipeline, staged-queue cap at create_monitor_request_cluster) by checking m_connections[routed]->get_pending_resp() >= --pipeline before sending when routed != conn_id. If the destination is at cap, schedule_fill() the destination (its own fill_pipeline will drain and re-check on the next response) and return false; the existing caller path (client::create_request) advances the GET ratio counter so the outer loop rebalances without busy-spinning. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Cursor bugbot re-flagged the slot-map reset on f8a25d2 as incomplete, claiming slots absent from a new CLUSTER SLOTS reply could still hold stale group indices. Re-verified against the current code: - handle_cluster_slots() unconditionally assigns m_slot_to_shard_group[0..MAX_CLUSTER_HSLOT] = UINT_MAX BEFORE m_shard_groups.clear() and BEFORE the per-shard loop (line 574, introduced by 994e9ad). - The per-shard loop only WRITES the slot map for slots explicitly listed in the new reply (line 774's `for j in [min_slot, max_slot]`). - Slots absent from the new reply therefore stay at the UINT_MAX sentinel set by the assign(). - All six reader sites (slot_primary_conn_id, select_target_conn, get_key_for_conn, retry_after_redirect, create_monitor_request_cluster, create_mget_request) treat `gidx >= m_shard_groups.size()` as "not available" and bail. The finding is stale. To prevent regression, this commit pins the invariant in code: 1. An explicit "INVARIANT" comment block calling out the requirement that the assign() must be unconditional and BEFORE the per-shard loop -- a future refactor moving it inside the loop or guarding it would silently reintroduce the stale-index aliasing bug 994e9ad fixed. 2. A runtime assert() on m_slot_to_shard_group.size() == MAX+1 immediately before the assign(). The vector is sized once at construction and never resized after, so this can only fire if a future refactor breaks the size invariant. No behavior change; documentation + guard only. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…slots
In get_key_for_conn, select_target_conn picks a live target connection
(conn_is_live_for_routing filters disconnected nodes at selection
time). A TOCTOU window between selection and the dispatch-time check
at line 1037 can still see the target disconnected if the bufferevent
fires BEV_EVENT_EOF in between. The previous behavior unconditionally
triggered a CLUSTER SLOTS refresh in that case.
That recovery is correct for a primary outage (the slot's
authoritative owner is gone, no other node can serve the request
without a fresh topology), but wrong for a replica outage. A replica
going down is a local routing gap, not a topology change: the slot
still has a live primary, and the round-robin / nearest / preferred
selection path on the next tick already knows how to skip a dead
replica and pick a live one (or fall back to the primary per
--read-preference-fallback). Under skewed workloads or a transiently-
flapping replica, the unconditional refresh would churn CLUSTER SLOTS
on every produce tick where the dispatch-time check trips, swamping
the bootstrap connection with no upside.
Split the recovery by target role:
- !is_replica() (primary or default): keep the existing CLUSTER
SLOTS refresh on the producer connection.
- is_replica() : skip the refresh; just return
not_available. The next
regular topology poll heals
naturally.
shard_role defaults to role_primary at construction, so !is_replica()
matches the prior behavior for any connection whose role was never
flipped (bootstrap conns, write-only configs).
Bugbot finding (cluster_client.cpp:1029).
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This was referenced Oct 14, 2026
Merged
This was referenced Oct 23, 2026
fcostaoliveira
added a commit
that referenced
this pull request
Oct 25, 2026
master stopped leaking the pending setup request with e935f80 (#475); 41371a5, which already has the #456 refactor, still leaks it. Name the fix that a 2.4 backport would need. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 25, 2026
fcostaoliveira
added a commit
that referenced
this pull request
Oct 25, 2026
) On a cluster with replicas, memtier retries a -READONLY reply to the slot's primary (ee757e7, #456), but no test proved that. The only check was a placeholder in test_read_preference_failover.py that always skipped, with a stale TODO(#100). test_cluster_readonly_retry.py covers it with scripted peers on ephemeral ports, under --protocol=resp2 and resp3: a replica A answers SETs with -READONLY while B owns the key's slot. Every SET A got is then rejected, and each one is accepted exactly once by B, including SETs sent late, after the retry. Two decoy primaries, C (the seed) and D (last in the map), own no key's slot and must get no SET, so a resend to any other connection fails the test. When a cluster cell expects replicas (--use-slaves, i.e. OSS_CLUSTER_REPLICAS=1) but CLUSTER NODES lists none or can't be read, get_cluster_replica_connections() now raises instead of returning [] and letting the read-preference tests skip green. It raises rather than asserting because RLTest drops a failed assert when the test then skips. Cells without replicas still skip. The README "Testing with replicas" section and the helper docstrings describe the RLTest fork's real cluster replicas. Fixes #462 Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira
added a commit
that referenced
this pull request
Oct 26, 2026
…883) Closes #450. #450's leak (a `--connection-stage-timeout` abort during cluster setup, under LeakSanitizer) no longer reproduces on master. It was fixed by e935f80 (#475), whose `shard_connection` destructor change frees requests still queued on a connection. The leaked object was the in-flight AUTH request from `send_conn_setup_commands()`. The `cluster_client` itself was always deleted. Evidence (ASan + UBSan build, `ASAN_OPTIONS=detect_leaks=1:abort_on_error=1`, no-auth Redis 7.0.15, Ubuntu 24.04 container): - The issue's exact reproducer exits 2 with no LSan report in 5/5 runs on master 29f63de. - 1142696, from when the issue was filed, exits 134 in 3/3 runs with `Direct leak of 96 byte(s)` allocated in `shard_connection::send_conn_setup_commands`. - Bisect: 41371a5 still leaks, and e935f80 is the first clean commit. - Clean on master, 3 runs each: - 4 threads × 4 clients - `--pipeline=16` - a real 1-node cluster - a password-protected cluster with a wrong password - a password-protected cluster with no password - `--protocol=resp3` The only leftover was in `tests/cli_fuzz.py`, which discarded the `--authenticate '' --cluster-mode` argv shape, citing #450. This PR removes that skip and the now-unused `assume` import, so the nightly CLI fuzz (which runs master with `detect_leaks=1`) covers that combination again. It also corrects the `cli-fuzz-nightly.yml` comment that credited the master fix to the #456 refactor: 41371a5 already contains #456 and still leaks, so a 2.4 backport would need #475. No product code changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Overview
This PR introduces
--read-preference-aware read routing to memtier_benchmark's cluster mode, with familiar primary / secondary / secondaryPreferred / nearest modes. Reads can now be steered to replicas via four modes, while writes always go to the slot-owning primary. Per-endpoint observability (Ops, EWMA latency, role) is added tomb.jsonso the routing decision is auditable.Modes supported
primary(default)secondarysecondaryPreferrednearestWrites (SET, WAIT, MULTI/EXEC, EVAL/EVALSHA, …) always go to the slot primary regardless of the mode.
CLI flags
mb.json schema additions
Two new sub-objects, emitted only in cluster mode:
Per-arbitrary-command routing breakdown is emitted under
"Arbitrary Read Routing"when--command-style workloads are used.Load-bearing routing logic
cluster_client::select_target_conn(slot, is_read)— single source of truth for per-slot routing. Writes collapse to the slot primary. Reads dispatch per--read-preference. ReturnsUINT_MAXon no-route (bootstrap window or strictsecondarywith no live replica); callers handle gracefully vianot_available+ a hold inhold_pipelineso the event loop has a chance to bring replicas online.cluster_client::classify_read(request*)andis_read_command_index(idx)— shared read/write classifier respectingarbitrary_command::is_read_override,CommandSpec::is_read, and the safe-default-write fallback for unknown commands.get_key_for_conn,create_mget_request,create_get_request(override), andretry_after_redirectall consultselect_target_connso the routing decision applies to the steady-state hot path, MGET fan-out, MOVED retries, and the per-command observability counters consistently.-READONLYresponse: server tells us the request was misclassified as a read on a replica. Force-route to the slot primary regardless of--read-preferenceand retry once; noCLUSTER SLOTSrefresh (READONLY is per-request, not a topology event).m_latency_ewma_usonshard_connection, α=0.1, min 10 samples before "warm". Cold endpoints treated as +∞ bynearestso they don't get over-picked during warm-up; while no replica is warm, cold-seed round-robin distributes reads across live replicas until each accumulatesLATENCY_EWMA_MIN_SAMPLES, falling back to the primary only when no live replica is available.Limitations (deferred)
CLUSTER SLOTSin cluster mode. Standalone replicas can only be supplied via--read-server HOST:PORTfor now.primaryPreferreddeferred. Mirror ofsecondaryPreferred; not part of this PR.--read-preference-fallback=queuedeferred. Todayqueueis accepted at parse time but the routing-sideUINT_MAXpath treatsqueuethe same aserror(returnsnot_available; the next tick retries). True queue semantics (per-conn waiting list) is follow-up work.--replica-clients/--replicas-per-shardwiring is parse-time only — the routing layer doesn't yet vary connection counts by role.Test plan
autoreconf -ivf && ./configure && make -j— no new warnings vs master.--read-preference=secondary --versionparses;--transaction --read-preference=secondaryerrors with mention of both flags.test_cli_validation_read_preference.py(9 tests) — all green on OSS_STANDALONE.test_read_preference_transaction.py(4 tests, all auto-skipped on standalone — cluster-mode only).--read-preference=primary: 100% Ops on primaries; "Read Routing" omitted (gated on non-primary).--read-preference=secondary: 100% Ops on replicas; "Read Routing" reports Ops from Primary=0, Replica=100.--read-preference=nearest: cold-seed round-robins reads across live replicas until each accumulatesLATENCY_EWMA_MIN_SAMPLES, then the EWMA pick takes over. The primary participates only after the no-live-replica fallback (or under arbitrary-write workloads viart_arbitrary).--read-preference=secondarystandalone-without---read-serveremits the "has no effect" warning and exits 0.OSS_CLUSTER_REPLICAS=1cell (A3) runs the 4 read-preference test files, including a dedicated RESP3 cell.🤖 Generated with Claude Code
Note
High Risk
Large changes to cluster request routing, topology refresh, and pipeline accounting on the hot path; regressions could mis-route reads/writes, hang benchmarks, or leak keys under mixed workloads.
Overview
Adds cluster-mode read routing via
--read-preference(primary, secondary, secondaryPreferred, nearest) and related CLI, with writes still pinned to slot primaries.Routing core: Replaces per-slot primary-only mapping with
shard_group(primary + replicas fromCLUSTER SLOTS).select_target_conn()is the single routing decision for GET/MGET, arbitrary reads (CommandSpec::is_read/--command-is-read), MOVED/ASK retries, and keyless reads. Replica connections get a READONLY setup ladder;-READONLYforces retry to the primary.nearestuses per-connection EWMA latency with cold-replica round-robin seeding.Pipeline / accounting fixes:
hold_pipelinegains replica warmup gates, cross-shard in-flight backpressure, and spin-yield guards;m_mget_deferdistinguishes MGET defer vs slot exhaustion; clearing cross-shard key pools compensatesm_reqs_generatedto avoid hangs.handle_cluster_slotsuses build-then-swap topology commit, parses replica tuples, and returns bool for setup completion.Observability: JSON gains Read Routing / Endpoints blocks when cluster mode and non-primary preference (per the PR description).
CI / docs: Five new CI matrix cells for read-preference tests; ASAN/TSAN/UBSAN matrices split long TLS jobs by
TESTand addpaths-ignore; README documents modes, limitations, and RLTest replica caveats.Reviewed by Cursor Bugbot for commit 64c4d23. Bugbot is set up for automated code reviews on this repo. Configure here.