Repository navigation
fix(cluster-slots): validate reply shape before indexing, log+skip malformed shards - #425
Conversation
…lformed shards cluster_client::handle_cluster_slots() walked the CLUSTER SLOTS reply with bare `mbulks_elements[N]` indexing and as_bulk() / as_mbulk_size() casts that assert(0) on type mismatch. A malformed reply from a hostile or buggy server crashed memtier with SIGSEGV (issue redis#417, surfaced by the RESP-fuzzer fixture `cluster_slots_malformed.bin` from PR redis#419). Validate before indexing: * top-level get_mbulk_value() must be non-null * each shard element must be is_mbulk_size() * shard must have >= 3 children (start, end, [host, port, ...]) * elements 0 and 1 (slot bounds) must be is_bulk() * element 2 (node tuple) must be is_mbulk_size() and have >= 2 children, both is_bulk() (host, port) Any malformed shard logs a benchmark_error_log and is skipped; the existing bootstrap connection stays in service. If the whole reply is non-array, log and return without touching topology. Fixes redis#417 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
|
Review: performance (haiku 4.5) verdict: O(1) per-shard validation, no hot-path impact ✓ • Validation scope: Runs once per CLUSTER SLOTS topology refresh (not per request or connection). The checks are type predicates (is_mbulk_size(), is_bulk()) and array-size comparisons, all O(1). Only walks the shard array once linearly in the existing loop. ✓ • Defensive indexing: Replaces unsafe bare • Error path: benchmark_error_log() on malformed shard is a single formatted write (happens rarely, off the request loop). No repeated stderr I/O in the hot path. ✓ • No new allocations: The shard loop now caches Summary: Pure hardening with zero algorithmic cost. The per-shard validation is compile-time conditional checking; negligible cost during bootstrap, zero cost once topology is loaded. No request-loop changes. |
|
Review: docs & commit message (haiku 4.5)
Verdict: Commits clean; follow-up PR should document RESP shape validation in reference docs (graceful skip behavior on malformed CLUSTER SLOTS). |
|
Review: design & API (sonnet 4.6) Verdict: The skip-malformed-shard strategy is the right default for a benchmarking tool but the operational visibility gap needs to be addressed before this lands.
|
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: security (opus 4.7)
- LOAD-BEARING: hostile-but-shape-valid replies still slip past.
mbulk_addr_el->valueismemcpy'd byte-for-byte intoaddrwith a trailing\0, but the rest of the code (strcmp(addr, m_connections[j]->get_address()),getaddrinfo(addr, ...)) treats it as a C-string. A node host of"127.0.0.1\x00evil.example.com"(value_len=29) will be deduped/compared only up to the embedded NUL — a malicious cluster master can alias a benign-looking host with a different real target, or skip dedup entirely for an otherwise-identical entry. Worth amemchr(value, '\0', value_len)reject in this PR's validation block. portis built viamemcpy(port, mbulk_port_el->value + 1, value_len)— the+ 1skips one byte of the RESP integer prefix and writesvalue_lenbytes into avalue_len + 1buffer. That reads one byte pastvalue(still inside the parser's allocation in practice, so not OOB on the heap, but the trailing\0lands on a non-zero byte andstrtoul/getaddrinfolater sees garbage). If a future RESP version emits a port as a non-integer bulk, the+ 1skip is wrong. The new validation only checksis_bulk(), not "starts with:" — consider assertingvalue_len > 0before the+ 1deref.- Validation correctness LGTM: top-level NULL check, per-shard
is_mbulk_size(), ≥3 children,is_bulk()on slot bounds,is_mbulk_size()+ ≥2is_bulk()children on the node tuple all matchas_mbulk_size()/as_bulk()'s assert-on-mismatch contract (protocol.h:71). The fuzzer fixturecluster_slots_malformed.binis correctly addressed. strtol(value + 1, NULL, 10)for slot bounds silently accepts non-numeric content (returns 0) and writes intoint min_slot/int max_slot. A reply withstart=-1orstart > max_slotwould corruptm_slot_to_shard[]indexing in the loop below (for j = min_slot; j <= max_slot). Bounds check (0 <= min_slot <= max_slot < REDIS_CLUSTER_SLOTS) belongs in this validator.- Skip-and-continue semantics are correct (the existing bootstrap connection stays in service) and
benchmark_error_logisprintf-style with literal format strings, so no format-string risk from server-controlled data. - DoS via repeated malformed replies: each malformed shard logs but doesn't rate-limit; a server that returns a 1M-shard array of malformed entries makes you log 1M lines. Low priority — only happens on the (rare) topology-refresh path.
Verdict: NEEDS WORK. The NUL-in-host issue is a real trust-boundary bug worth catching in this PR; slot-range and value+1 hardening are nice-to-have. The shape validation itself is solid.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: correctness & latent bugs (opus 4.7)
cluster_client.cpp:354-405empty-shard reply still wipes topology — if a misbehaving server returns a well-formed but emptyCLUSTER SLOTS(*0\r\n),get_mbulk_value()is non-NULL, the new shape check passes, the loop runs zero iterations, and the post-loop block at lines 408-420 sees every existing shard withclose_sc[i]==trueand tears down the whole topology. Pre-existing behavior, but this PR is the natural place to also guardmbulks_elements.size() > 0and log+keep current topology on empty reply, otherwise #417's "stay in service on malformed reply" promise doesn't hold for the empty-reply variant.cluster_client.cpp:368-370port memcpy underflow — for a hostile$0\r\n(zero-length) port bulk,mbulk_port_el->value == NULLandvalue_len == 0. The code doesmalloc(1)thenmemcpy(port, NULL + 1, 0). memcpy with n=0 from a NULL-derived pointer is UB by strict C even though no bytes move.value+1is a pre-existing skip-the-RESP-:-prefix hack that doesn't apply to bulk strings (only to inline integers); for an actual$lenhost/port bulk you're now silently dropping the first byte of the payload. Worth tightening in this PR since you're already validating shape here.cluster_client.cpp:358-359integer slot bounds —strtol(value + 1, ...)assumesvalue[0]is a RESP type byte (e.g.:). Slot bounds inCLUSTER SLOTSare returned as RESP integers (:), which match — butis_bulk()also passes for$bulkpayloads. A hostile server replying with$5\r\n12345\r\nfor the slot bound would surviveis_bulk()and then strtol would skip the'1'and parse"2345". No crash, but slot range silently corrupted. Consider validatingvalue[0] == ':'for the slot-bound elements, or routing through a typed helper.cluster_client.cpp:354no upper bound on shard count — a hostile server replying with*1000000followed by valid shards would cause a millioncreate_shard_connection/malloccalls andm_slot_to_shard[16384]writes (which is sized for 16384 slots, so out-of-range max_slot indexes UB the array). Pre-existing, but since this PR is hardening the function, a sanity cap (≤16384 shards) would close the rest of the attack surface from #417.cluster_client.cpp:362-365host malloc never freed on later validation failure — not actually triggered here because all the new validation runs before themalloc(addr). Just verified, OK.
Verdict: Comment
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: edge cases & failure modes (opus 4.7)
Verdict: REQUEST CHANGES (one real DoS-shaped gap on empty outer reply); rest are LGTM.
- Empty outer mbulk_value (zero shards) wipes topology.
get_mbulk_value()non-null butmbulks_elements.size() == 0falls through the validation and skips the for-loop entirely.close_scwas initialized all-true, so EVERY existing shard connection gets disconnected andm_slot_to_shardis never updated. A hostile or buggy server returning*0\r\nto CLUSTER SLOTS now silently tears down the live cluster topology mid-run — arguably worse than the crash this PR fixes, because the benchmark keeps running on a now-empty cluster. Recommend treatingmbulks_elements.empty()the same as a non-array: log + return without touchingclose_sc/m_connections. - Slot-bound bulk
value == NULLorvalue_len == 0still UB. Validation passesis_bulk()but doesn't verify the bulk has content. A$-1(null) reply for slot start/end producesvalue = NULL, thenstrtol(NULL + 1, ...)is undefined. A$0empty bulk producesvalueallocated butvalue_len == 0, sovalue + 1reads past the allocation. Add avalue != NULL && value_len > 0guard before thestrtol(value + 1, ...)calls. - Negative slot values land in
m_slot_to_shard[j]unchecked.strtolhappily accepts-1or99999from a bogus server. The subsequentfor (int j = min_slot; j <= max_slot; j++) m_slot_to_shard[j] = ...writes out-of-bounds for negativemin_slotormax_slot >= REDIS_CLUSTER_HSLOTS. Worth bounds-checking[0, 16383]while the shape validation is in this PR's scope (same fuzz fixture would reach it). is_bulk()is true for non-integer bulks too.strtol("hello" + 1, ...)returns 0 and reports no error. A malformed*3\r\n$5\r\nhello\r\n$5\r\nworld\r\n*2\r\n...\r\nreply would assign min_slot=0/max_slot=0 to every shard, collapsing the topology onto one shard. Consider validating thatstrtolconsumed the whole field (endptr check) before using the result.- Port
memcpy(... value + 1, value_len)is still off-by-one for $-bulk replies. Pre-existing, not introduced here, but the PR touches this exact line — easy to fix in the same patch. For a bulk$5\r\n12345\r\nthe value has no leading prefix, sovalue + 1skips the "1" and copies one byte past the buffer. (Works only because most servers send the port as an integer reply where the +1 skips the:.) Worth a follow-up note. - Node sub-array with zero
mbulks_elementsis handled correctly by< 2check — good. Likewise the top-level non-array early-return preserves the bootstrap connection.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: style & readability (sonnet 4.6)
Verdict: clean; one naming note.
-
benchmark_error_logmessages lack a severity prefix (cluster_client.cpp): all four new messages ("CLUSTER SLOTS: ...") go straight into the body with no "warning:" or "error:" prefix, while every otherbenchmark_error_logcall in the same file either uses "warning:" or is a factual diagnostic line. These are skip-not-abort situations, so "warning:" is the right prefix; omitting it makes them look like info-level noise vs the surrounding "warning: --transaction pin connection ..." lines. -
Comment explains what the guard does, not why the old code crashed (
cluster_client.cpp, top of the new validation block): "as_mbulk_size() and as_bulk() both call assert(0) on type mismatch" is accurate, but the deeper why — that malformed input from an untrusted server is realistic, not just hypothetical, per the fuzzer fixture — is in the PR description but not at the call site. A single sentence referencing the attack surface ("a misbehaving or proxy-mangling server can return a shorter array") would help a future maintainer understand why the guard must stay. -
Validation structure repeats the
is_mbulk_size()/is_bulk()pattern twice for shard and node: this is fine for two levels, but if a future protocol revision adds a third level the reader has no hint about the nesting depth. A brief structural comment ("// CLUSTER SLOTS reply: [[start, end, [host, port, ...]], ...]") above the loop would serve as the schema reference that explains both checks at once. -
Commit message headline truncated by GitHub (
fix(cluster-slots): validate reply shape before indexing, log+skip ma...): the body text is thorough, but the 72-char subject line was cut mid-word. Reword to fit: e.g. "fix(cluster-slots): validate reply shape, skip malformed shards (#417)". -
Nothing else to flag — new C++ uses the project's existing
strtol/malloc/memcpyidioms; no Python test in this PR.
…d zero-len bulks Review-pass follow-ups on redis#425 from the security + edge-cases + correctness lenses. * Empty mbulk reply (zero shards) now logs a warning and returns without touching m_connections. Previously this silently tore down every existing shard connection via the close_sc[] loop -- a malformed reply degraded the run to a no-shard hang instead of crashing it. * Slot bounds (min_slot / max_slot): parse via strtol with errno=0, then reject ERANGE, negatives, values > MAX_CLUSTER_HSLOT (16383), or min > max. Without this, m_slot_to_shard[16384] could be written out-of-bounds by a hostile server (heap corruption). * Host / port bulks: reject zero-length entries (memcpy(..., NULL+1, 0) is technically UB and produces an unusable empty connection key). * Host bulk also rejects embedded NULs (would alias other addrs via strcmp-based connection lookup). * Every skip-not-abort log line now uses the `warning:` prefix that matches the rest of the file (style reviewer). Refs redis#417
Cursor bugbot finding (medium): when every shard in the CLUSTER SLOTS reply failed validation and was skipped via continue, no close_sc[j] entry got set to false. The close-stale pass then disconnected every existing connection -- including the bootstrap -- silently turning a malformed reply into a no-shard hang. Track any_valid_shard across the loop; if false on completion, return early without entering the close-stale pass (same operational behaviour as the empty-reply short-circuit). Refs redis#417.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 721fc26. Configure here.
| } | ||
| errno = 0; | ||
| long parsed_min = strtol(min_el->value + 1, NULL, 10); | ||
| long parsed_max = strtol(max_el->value + 1, NULL, 10); |
There was a problem hiding this comment.
Insufficient value_len guard before strtol offset access
Low Severity
The new value_len == 0 check is intended to make the subsequent strtol(min_el->value + 1, ...) safe against hostile input, but it's insufficient. A hostile server sending a 1-byte binary bulk string ($1\r\nX\r\n) in the slot-bound position creates a bulk_el with value pointing to a 1-byte malloc'd buffer (no null terminator) and value_len == 1. This passes the == 0 check, but value + 1 then points past the allocation, causing strtol to read from unallocated heap memory. The guard needs to ensure enough accessible bytes exist after the +1 offset (e.g., value_len < 2).
Reviewed by Cursor Bugbot for commit 721fc26. Configure here.
PR redis#402 added PARALLELISM=2 to the sanitizer (ASAN/UBSan/TSAN) cluster cells because cluster bootstrap + serial RLTest pass routinely hit the workflow's 15-minute step ceiling. The regular Test workflow's OSS-CLUSTER cells were not updated at the time and have been a known master flake ever since (~3/8 master runs fail at the same 15-minute mark; deep-CI investigators on PRs redis#425 / redis#427 / redis#430 / redis#431 all confirmed the pattern). Add PARALLELISM=2 to the two affected cells: - OSS-CLUSTER API: TCP Plaintext - OSS-CLUSTER API: TCP TLS The 49/99-shard mega-cluster cells already use a single targeted test (TEST=test_rate_limited_completion_no_hang), so they're under budget without parallelism. Bundled with PR redis#430 because that PR was being blocked by exactly this flake on its final CI run.
…--key-pattern=G:G) (Refs #426 phase 3) (#430) * fix(opts): validate sampler configs (--data-size-list, --key-stddev, --key-pattern=G:G) Reject sampler configurations that can never produce a value at parse / construction time instead of hanging the worker loop or tripping the Gaussian assert: - --data-size-list entries with weight 0: the size sampler would skip them and (if every bucket is zero-weight) spin forever picking nothing. Issue #426 item 10. - --key-stddev must be finite and > 0: NaN compared false against the previous "<= 0" guard, and +/-inf produced a Gaussian rejection sampler that never satisfied its range constraint. Issue #426 item 15. - --key-pattern=G requires key-maximum - key-minimum >= 2: the Gaussian distribution asserts median > min && median < max, which is impossible on a 1-key range. SIGABRT before the fix. Issue #426 item 16. All three paths now emit a readable error and exit with code 2 (the parser-error convention used elsewhere in memtier_benchmark.cpp). Regression coverage in tests/test_cli_validation_sampler.py exercises each rejection plus a healthy G:G config to guard against false positives. Refs #426 Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(opts): relax G-range cutoff to max <= min, add median bounds check Review fix on #430 (correctness reviewer): the original `(max - min) < 2` cutoff rejected the perfectly valid 2-key Gaussian case (min=1, max=2). The sampler computes a default median of `(max - min)/2.0 + min + 0.5` which for that case is 1.5 -- strictly inside (1, 2), passes the `assert(median > min && median < max)`. The actual SIGABRT path was a user passing a `--key-median` that lands outside (min, max). Fix: * Reject only `max <= min` for --key-pattern=G (the truly-degenerate single-key case). * Additionally validate that any user-supplied `--key-median` lands strictly inside `(min, max)`. Default median=0 means "auto-compute" and is always safe. Refs #426 phase 3. * test(sampler): harden valid-G:G happy path against TLS connection-reset flake ASAN TLS cells under CI load dropped the first connection mid- handshake on the happy-path test (3 cells failed identically with 'Connection reset by peer / Maximum reconnection attempts (0) exceeded'). Make the workload a deterministic 10-request smoke and add --reconnect-on-error so the rc==0 assertion measures the parser path that the test exists to verify, not TLS flake. Refs #426 phase 3. * test(sampler): make valid-G:G happy path TLS-environment agnostic The previous hotfix (--reconnect-on-error + --max-reconnect-attempts=5) still relied on a successful TCP/TLS connection, but the test harness does not inject --tls/--cert flags here, so on TLS-only CI cells (ASAN/TSAN/UBSan TCP TLS, OSS TCP TLS v1.2/v1.3) the workload cannot connect at all and the rc==0 assertion always tripped. Restructure the assertion to match the test's documented purpose: verify only that the *parser* accepts the valid G:G config. The workload's runtime outcome is intentionally ignored. - Assert rc != 2 (parser did not reject). - Assert none of the Items 10/15/16 rejection diagnostics appear in stderr. - Bound the run with --connection-timeout=1 and --max-reconnect-attempts=1 so a TLS-only environment can't keep the subprocess alive past _run_memtier's 10s timeout. Refs #426 phase 3. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(opts): reject 2-key G:G range that SIGABRTs auto-computed median The d5b882c relaxation of the G-range cutoff from `(max - min) < 2` to `key_maximum <= key_minimum` was based on a wrong arithmetic claim in the accompanying comment: for (min=1, max=2) the auto-computed median in gaussian_distribution_range is median = (max - min) / 2.0 + min + 0.5 = 1/2.0 + 1 + 0.5 = 2.0 so the subsequent `assert(median > min && median < max)` fires (2.0 < 2 is false) and the process SIGABRTs -- exactly the regression Item 16 was supposed to prevent. Confirmed locally: with min=1, max=2 the previous build hit the crash-handler bug-report dump. Restore the original `(max - min) < 2` cutoff (and keep the unsigned- wrap-safe explicit `key_maximum < key_minimum` clause that d5b882c added), and rewrite the comment with the correct arithmetic so the choice of cutoff is auditable. The smallest accepted range is now (max - min) == 2 (e.g. min=1, max=3 -> auto-median = 2.5). This re-tightens the parser-reject path picked up by cursor[bot] on the previous commit; the negative test `test_key_pattern_g_one_key_range_rejected` continues to pass because the new diagnostic still contains the substring `key-pattern=G`. Refs #426 phase 3. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * ci: re-trigger workflows after master-flake noise The prior run hit the pre-existing master flakes `Test OSS-CLUSTER API: TCP {Plaintext,TLS}` (15-min step timeout) and the older workflow can't be partial-reran. Empty commit to force a fresh run. * ci: parallelize Test OSS-CLUSTER API cluster cells (mirror PR #402) PR #402 added PARALLELISM=2 to the sanitizer (ASAN/UBSan/TSAN) cluster cells because cluster bootstrap + serial RLTest pass routinely hit the workflow's 15-minute step ceiling. The regular Test workflow's OSS-CLUSTER cells were not updated at the time and have been a known master flake ever since (~3/8 master runs fail at the same 15-minute mark; deep-CI investigators on PRs #425 / #427 / #430 / #431 all confirmed the pattern). Add PARALLELISM=2 to the two affected cells: - OSS-CLUSTER API: TCP Plaintext - OSS-CLUSTER API: TCP TLS The 49/99-shard mega-cluster cells already use a single targeted test (TEST=test_rate_limited_completion_no_hang), so they're under budget without parallelism. Bundled with PR #430 because that PR was being blocked by exactly this flake on its final CI run. --------- Co-authored-by: Claude Sonnet 4.6 <[email protected]>
PR #425 added shape validation to handle_cluster_slots so a malformed CLUSTER SLOTS reply no longer SIGSEGVs via OOB indexing. The regression test was left env.skip()'d with a stale TODO(#417) note. Verified the fixture exercises the validated path and memtier no longer crashes; removing the skip restores CI coverage for the fix. Also threads a cluster_mode parameter through _run_fixture and _assert_no_crash so the test can launch memtier with --cluster-mode (required for the bootstrap CLUSTER SLOTS call to occur) while the mock server serves the adversarial fixture bytes as the CLUSTER reply. Refs: 2.4 review #14/#22 (Review 1 + Review 8 + Review 29). Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Comprehensive notes covering 153 commits since 2.3.1: - 3 security advisories (#405, #415, #425) - 5 major features (--realtime-latencies, --retry-on-error, --transaction, --command-miss-tracking, --connection-stage-timeout) - Cluster gains: monitor-input route-then-stage, MGET slot-aware - 12 breaking-fail-fast changes (B1-B12) — all reject inputs 2.3 silently accepted and then crashed/hung on - JSON additions (strictly additive) - Testing & CI investment summary - Perf parity confirmed (no regression vs 2.3.1) - Known divergences Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…rses Round-1 of the malformed-topology fix (commit 994e9ad) reset m_slot_to_shard_group and cleared m_shard_groups eagerly, before any shards were parsed. If every shard in the reply was subsequently skipped as malformed the existing state was already wiped, leaving all slots unmapped and m_shard_groups empty while existing TCP connections stayed up. Traffic saw no valid route until the next successful refresh. (Cursor bugbot HIGH, PR #456.) Fix: build the new topology into local std::vector buffers (new_slot_map initialised to UINT_MAX, new_groups empty) and only swap them into the member variables once any_valid_shard is true. On an all-malformed reply the member state is left untouched and a warning is logged. The stale-index aliasing invariant (PR #425, commit 994e9ad) is preserved: new_slot_map starts at UINT_MAX and is only written for slot ranges that belong to a valid shard, so absent slots stay at UINT_MAX after the swap -- identical guarantee to the old unconditional assign(), deferred. group.id is now sized from new_groups.size() (was m_shard_groups.size()) so group indices remain contiguous in the local buffer before the commit. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…456) * feat(command_meta): add is_read flag from READONLY command_flags 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]> * feat(shard_connection): add shard_role enum and m_role field 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]> * feat(shard_connection): add READONLY to the setup-state ladder for replicas 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]> * feat(cluster_client): introduce shard_group; rename m_slot_to_shard 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]> * feat(cluster_client): walk CLUSTER SLOTS replica tuples and populate 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]> * feat(read-pref) [A2] add read_pref_mode/fallback enums + benchmark_config 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]> * feat(read-pref) [A2] CLI flags, JSON config, help text, and parse-time 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]> * test(read-pref) [A2] CLI parse-time validation tests for --read-preference 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]> * feat(read-pref) [A3] add cluster replica helpers to tests/include.py 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]> * feat(read-pref) [A3] add read-preference test suite (4 files) 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]> * feat(read-pref) [A3] add OSS_CLUSTER_REPLICAS env-var to run_tests.sh 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]> * ci(read-pref) [A3] add OSS-CLUSTER+replicas matrix cell for read-preference 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]> * feat(read-pref): cluster routing core (select_target_conn + classify_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]> * feat(read-pref): mb.json observability (Endpoints + Read Routing) 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]> * test(read-pref): widen CLI-validation harness timeouts (A2 follow-up) 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]> * fix(read-pref): replica READONLY flush + bootstrap-window hold 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]> * fix(read-pref): cluster routing — slot-map reset, READONLY no-loop, hold-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]> * feat(read-pref): warn on --replica-clients + rp_primary; emit read_servers 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]> * fix(read-pref): sort Endpoints JSON array for deterministic ordering 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]> * test(read-pref): fix CI matrix TEST format; add failover; replicas-only 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]> * fix(cluster): MGET cross-connection backpressure honors --pipeline cap 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]> * fix(cluster): document slot-map UINT_MAX reset invariant + add assertion 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]> * fix(cluster): replica disconnect at dispatch defers, doesn't refresh 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]> * fix(hold-pipeline): yield on consecutive read-routing failures in mixed workloads Under strict --read-preference=secondary with no live replica, a mixed SET/GET workload (ratio.a > 0 && ratio.b > 0) busy-spins fill_pipeline: writes succeed (primary is live), but every GET routing attempt returns UINT_MAX from select_target_conn, causing create_request to return without advancing m_get_ratio_count. The fill_pipeline while-loop then retries the same GET on the next tick -- forever, burning CPU until replicas connect. The existing read-only bootstrap window (ratio.a == 0 gate) doesn't fire because ratio.a > 0 in a mixed workload. Fix: add m_strict_no_route_attempts counter on cluster_client. - get_key_for_conn increments the counter on each read routing failure (select_target_conn returning UINT_MAX) and resets it on any successful route. - hold_pipeline checks the counter against STRICT_NO_ROUTE_HOLD_THRESHOLD (64): if reached, performs the same live-replica scan used by the read-only bootstrap window; if no replica is live it returns true (yielding the event loop); if a replica is now live it clears the counter and falls through so traffic resumes immediately. The wake path is unchanged: the replica's READONLY completion callback calls schedule_fill() on all peer connections, which re-enters fill_pipeline -> hold_pipeline; the live-replica scan then passes, the counter clears, and reads drain to the newly-live replica. Closes cursor bugbot finding: cluster_client.cpp:948 strict-secondary spin in mixed workloads. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): replica routing requires READONLY ready before first read conn_is_live_for_routing only checked cluster_slots_state == setup_done, which meant a newly-discovered replica was immediately routable even while its READONLY handshake was still in flight. Sending a read in that window elicits -READONLY from the server. Add shard_connection::is_ready_for_reads() that returns true iff: - connection state == conn_connected - m_cluster_slots == setup_done - m_role == role_primary OR m_readonly_state == setup_done Rewrite conn_is_live_for_routing to delegate to is_ready_for_reads(). Also add get_readonly_state() accessor for completeness. Update both hold_pipeline liveness loops (read-only bootstrap gate and mixed-workload spin guard) to use is_ready_for_reads() so they don't count a READONLY-pending replica as routable either. Fixes: Cursor Bugbot finding HIGH cluster_client.cpp:393 Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): strict rp_secondary retry must not fall back to primary retry_after_redirect had an unconditional fallback: if (mapped == UINT_MAX) mapped = slot_primary_conn_id(hslot); When select_target_conn returns UINT_MAX because rp_secondary+!rpf_primary found no live replica, the old code silently promoted the retry onto the primary. This violated the "replicas only" contract — the same workload that would have returned not_available (rpf_error) or held in queue (rpf_queue) from the normal create path would instead be quietly served by the primary on the retry path. Fix: before the generic UINT_MAX fallback, detect the strict-secondary no-replica case (is_read && rp_secondary && fallback != rpf_primary) and return false immediately. The callers (handle_response MOVED/ASK paths) then call finalize_dropped_redirect, which honours --failed-keys-file and increments the error counter, consistent with rpf_error/rpf_queue semantics. Non-strict modes (rp_nearest, rp_secondary_preferred, rp_primary, and rp_secondary+rpf_primary) embed the primary fallback inside select_target_conn itself, so UINT_MAX in those modes means all nodes offline — the existing slot_primary_conn_id fallback is still correct. Also tighten the readiness guard in the mapped-connection check to use is_ready_for_reads() (connected + cluster_slots done + READONLY done for replicas) instead of the old two-field open-coded check. Fixes: Cursor Bugbot finding MED cluster_client.cpp:1688 Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): MGET deferral must not abandon batch on backpressure/no-route When create_mget_request() returns false due to cross-connection backpressure (destination at --pipeline capacity) or strict-secondary no-route (no live replica + rpf_error/queue), client::create_request was forcing m_get_ratio_count to ratio.b, silently abandoning the entire MGET batch instead of retrying it on the next fill_pipeline tick. Add a protected m_mget_defer flag to client that overrides set to true on defer paths and reset to false at the top of each call. create_request now only forces the counter forward when m_mget_defer is false (exhausted/no-slots paths), preserving the cursor for genuine defer cases. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): re-arm READONLY after live primary→replica role flip On CLUSTER SLOTS refresh, an already-connected endpoint newly listed as a replica only received set_role(role_replica); the READONLY setup ladder was not re-armed because m_readonly_state was setup_done from its primary lifetime. The connection was classified as a replica but the server never received READONLY, so all reads were rejected with -READONLY until the next reconnect. Add shard_connection::rearm_readonly(): resets m_readonly_state to setup_none and immediately fires the READONLY wire bytes via bufferevent_write (same path as the normal ladder) so fill_pipeline holds new user traffic until the ACK arrives. The method is a no-op when the connection is not yet in conn_connected state (connect() arms the ladder normally), when the role is not replica, or when m_readonly_state is already != setup_done (mid-handshake or idempotent second call). Call rearm_readonly() in handle_cluster_slots after set_role(role_replica) on the already-connected path. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): defer slot-map commit until at least one valid shard parses Round-1 of the malformed-topology fix (commit 994e9ad) reset m_slot_to_shard_group and cleared m_shard_groups eagerly, before any shards were parsed. If every shard in the reply was subsequently skipped as malformed the existing state was already wiped, leaving all slots unmapped and m_shard_groups empty while existing TCP connections stayed up. Traffic saw no valid route until the next successful refresh. (Cursor bugbot HIGH, PR #456.) Fix: build the new topology into local std::vector buffers (new_slot_map initialised to UINT_MAX, new_groups empty) and only swap them into the member variables once any_valid_shard is true. On an all-malformed reply the member state is left untouched and a warning is logged. The stale-index aliasing invariant (PR #425, commit 994e9ad) is preserved: new_slot_map starts at UINT_MAX and is only written for slot ranges that belong to a valid shard, so absent slots stay at UINT_MAX after the swap -- identical guarantee to the old unconditional assign(), deferred. group.id is now sized from new_groups.size() (was m_shard_groups.size()) so group indices remain contiguous in the local buffer before the commit. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(tests): skip read-preference tests early when no replicas are present All four test functions in test_read_preference_modes.py now call get_cluster_replica_connections() immediately after the isCluster() guard and invoke env.skip() if the list is empty. This prevents the tests from running on OSS-CLUSTER cells that were started without replicas (useSlaves=False) — the cells that were responsible for 26 CI failures because memtier was invoked on a topology that cannot satisfy the replica- routing assertions. Also removes the now-dead _skip_if_no_replicas() helper and the unused MEMTIER_BINARY import. test_read_preference_failover.py and test_read_preference_mget.py already had the correct guard order and are unchanged. test_read_preference_transaction.py tests parse-time errors and intentionally has no cluster/replica skip. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): route keyless read commands through read-preference policy Keyless arbitrary commands (keys_count == 0) such as DBSIZE or PING used with --command-is-read bypassed select_target_conn entirely and always sent on the current connection, which is always the primary. This violated the semantics of --read-preference=secondary/secondaryPreferred/nearest for those commands. Fix: when a keyless command is classified as a read (via is_read_command_index) and read_preference != rp_primary, resolve a target connection via select_target_conn(slot=0, is_read=true). Slot 0 is an arbitrary anchor — the slot is irrelevant for keyless commands; we only need it to resolve a shard_group so that select_target_conn can apply the configured routing policy. If topology is not ready (UINT_MAX return), the code falls back to conn_id preserving the previous behaviour. The routing observability counter (record_read_routing) is also updated so the read-routing stats correctly reflect the chosen endpoint role. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(tests): correct CI multi-file TEST and remove dead ENV_DEFAULTS run_tests.sh expanded TEST="f1 f2 f3 f4" as a single --test argument; RLTest's --test is action=append so only the first file ran. Split on spaces and emit one --test flag per file. ENV_DEFAULTS dict in test_read_preference_{modes,mget,failover}.py is not a real RLTest API. The actual defaults come from --use-slaves and --shards-count in run_tests.sh; the dicts were dead. Remove them. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): unstick nearest, generalize hold gates, recover READONLY-error Three load-bearing routing/setup fixes: * rp_nearest cold-start no longer pins everything to primary. Previously the warm-up fallback sent ALL traffic to the primary, primary became warm first, and replicas never received a sample -> never warm -> never picked. Now route to live-but-unwarmed replicas round-robin until every replica has >=10 samples, then fall through to the EWMA pick. * hold_pipeline bootstrap gate and strict-no-route spin guard were mode-locked to rp_secondary. Under rp_nearest / rp_secondary_preferred with all targets transiently down, fill_pipeline busy-spun. Both gates now apply whenever read_preference != rp_primary; the strict-fallback branch stays on rp_secondary. * READONLY error response from server left m_readonly_state stuck at setup_sent forever (is_ready_for_reads() == false, hold gate never releases). Disconnect on READONLY error so the reconnect ladder re-arms; wake peers so the bootstrap doesn't deadlock. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): backpressure, EWMA filter, observability polish * Strict-no-route spin counter no longer reset by successful writes. In mixed SET/GET workloads with replicas bootstrapping, every SET reset the 64-attempt yield, defeating the spin guard. Only successful READ routes reset the counter. * Arbitrary-MGET strict-secondary path now signals defer to the caller so the batch is retried rather than silently abandoned. Mirrors the built-in MGET m_mget_defer path. * hold_pipeline liveness checks aligned on is_ready_for_reads() for consistency with the rest of the routing code. * EWMA update filters non-read responses (AUTH/HELLO/CLUSTER SLOTS/ READONLY setup-ladder latencies) so they don't bias the first 10 samples on a replica. * Observability schema polish: dropped misleading endpoint Connection Errors field (never populated), renamed shard_id -> conn_id (it's a connection-vector index, not a stable shard id), extended Read Routing block to standalone --read-server mode, and aligned Endpoints array gating with Read Routing gating (read_preference != rp_primary). Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): READONLY error must trigger reconnect, not just disconnect The rt_readonly error arm in process_response() called disconnect() directly. That tears down the bufferevent but does not arm the reconnect backoff timer, so the replica sat in conn_disconnected indefinitely; m_readonly_state stayed pinned at setup_sent forever and the bootstrap hold gate in cluster_client::hold_pipeline never released until some unrelated event (e.g. a peer MOVED -> CLUSTER SLOTS refresh) brought the replica back. Under -NOREPLICATION-style READONLY errors the replica was effectively offline for the rest of the run. Call attempt_reconnect("READONLY error") instead: it internally calls disconnect() and then arms the backoff timer subject to --reconnect-on-error, --max-reconnect-attempts, and the MEMTIER_BACKOFF_CAP_SEC ceiling, so the setup ladder re-runs from scratch on the standard recovery cadence. Update the preceding comment block to reflect the new behavior so it stops claiming bare disconnect() re-arms the ladder. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): bump strict-no-route counter on MGET defer no-route The built-in MGET defer path (cluster_client::create_mget_request) took the strict-secondary no-route branch (select_target_conn returns UINT_MAX) and set m_mget_defer = true; return false without touching m_strict_no_route_attempts. Under mixed SET+MGET workloads the writes kept landing on the primary so fill_pipeline's pipeline-depth gate never fired, and the read-failure counter never ticked because the MGET path is the only read this arm sees -- net result was a busy spin in fill_pipeline until a replica came back up. Increment m_strict_no_route_attempts immediately before m_mget_defer on this branch so hold_pipeline's second gate (STRICT_NO_ROUTE_HOLD_- THRESHOLD) trips and parks the producer until a routable target reappears. Mirrors the keyless-arbitrary defer site at cluster_client.cpp:1393. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * chore(read-pref): comment + dead-code polish from reviewer pass Three small follow-ups noticed during review of the rp_nearest / rp_secondary code: a) cluster_client::select_target_conn (rp_nearest): the leading comment claimed the loop scans "primary + warm replicas". In practice update_latency_ewma only fires for rt_get/rt_arbitrary responses and those are always routed to a replica while at least one live replica exists, so the primary only ever shows up in the warm pool after the no-live-replica fallback has run. Tighten the wording to "warm replicas (and the primary if it has already accumulated samples)" and add a short note explaining why. b) cluster_client::select_target_conn: hoist `const size_t nreplicas = group.replicas.size();` to function scope above the mode switch. It was previously declared once inside the rp_nearest block and a second time inside the rp_secondary block; the duplicate declarations had identical RHS but lived in disjoint scopes which made the relationship invisible. c) shard_connection::process_response, rt_readonly success/error wake-peer loops: drop the `peer != NULL` guard. m_connections entries are pushed in the client constructor and never set to NULL thereafter; the check is dead code. Brings the two wake-peer loops to identical predicate form (`peer != this && peer->get_connection_state() == conn_connected`). No behavior change. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): rework READONLY error recovery to avoid worker kill + cap defeat The round-3 fix (attempt_reconnect on READONLY error) introduced two regressions found by independent reviewers: * m_reconnect_attempts was reset on every BEV_EVENT_CONNECTED, but the READONLY-error reconnect storm always completes TCP before -NOREPLICATION arrives. The counter never accumulated, so --max-reconnect-attempts=N never tripped - unbounded spin. Move the reset into the steady-state success branch so it only fires after the setup ladder completes end-to-end. * attempt_reconnect with --reconnect-on-error=off (default) calls event_base_loopbreak, killing the worker thread on first transient -NOREPLICATION. Behavior regression vs the round-2 bare disconnect(). Gate: only call attempt_reconnect when --reconnect-on-error is set; otherwise drop to bare disconnect() and wake peers so the next CLUSTER SLOTS refresh re-evaluates the failed replica. Also adds a NULL-check on event_new() in attempt_reconnect so a libevent allocation failure surfaces via a clean loopbreak instead of crashing on the subsequent event_add(). Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): MGET defer correctness - cursor drift and pipeline-cap spin * Slot cursor m_mget_conn_slot_cursor was pre-advanced before both defer guards (no-route, pipeline-cap). Deferred slots were silently skipped on retry - the cursor drifted with the tick rate, not the send rate. Move sc++ after both guards so defers retain the slot. * Pipeline-cap defer set m_mget_defer=true but did not bump m_strict_no_route_attempts. Pure-MGET workload + saturated replica spun fill_pipeline indefinitely: producer's own pipeline never grew, schedule_fill(dest) required libevent control which the spin blocked. Bump the counter here too so hold_pipeline can yield. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * docs(read-pref): revert inert standalone gate, fix wrong primary-EWMA comment * run_stats Read Routing gate reverted to cluster-only. The standalone clause (!cluster_mode && !read_servers.empty()) opened the JSON block but no data ever reached it - m_get_read_routing is fed only by cluster_client. Comment updated to match shipped behavior. * cluster_client comment on rp_nearest primary EWMA participation corrected: rt_arbitrary writes DO update primary EWMA, so under mixed arbitrary workloads the primary can warm and participate. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * test(read-pref): assert distribution for nearest and master pickup for failover Adds the missing regression assertions reviewers flagged: nearest must route at least one GET to a replica (otherwise the cold-seed loop regressed back to primary-pinned). Failover with secondaryPreferred must show master Ops > 0 (otherwise the fallback to primary was silently dropped). Adds two thin runtime tests: * keyless arbitrary read under rp_secondary (DBSIZE --command-is-read) * mixed SET+MGET strict-secondary spin-guard smoke Also guards the --transaction subprocess helper on env.isCluster() so the test does not bleed into standalone CI cells (parse-time-only assertions live in test_cli_validation_read_preference.py). Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * docs(read-pref): help text + README + parse-time-only disclosures * --read-preference=nearest: describe EWMA + cold-seed * --read-preference-fallback=queue: mark as reserved/treated-as-error * --replica-clients / --replicas-per-shard: disclose parse-time-only * --read-server: note read dispatch is currently cluster-only * README: add Read Preference section (modes, fallbacks, JSON schema) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): remove twin m_reconnect_attempts reset in timer path Round-5 commit 02d546a moved the reset out of BEV_EVENT_CONNECTED but missed the matching reset in handle_reconnect_timer_event's success branch (line 1505-1507). Under --reconnect-on-error with --max-reconnect- attempts=N and a permanently broken replica returning -NOREPLICATION on READONLY, the timer fires → connect() returns 0 at TCP handshake → the twin reset zeroes the counter → READONLY fails again → loop forever. The cap was still defeated. Remove the twin reset. The unified counter reset now lives only inside report_connection_stage_success, where it fires only after the full setup ladder completes and the first user-level response arrives. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): hold_pipeline yields on saturation even when any_route=true R4 reviewer found pure-MGET spin is throttled 64x but not eliminated. When the strict-no-route counter trips and any_route=true (saturated but live replica), the gate reset the counter and fell through. The producer's own pipeline never grew (pure MGET, no SETs), so fill_pipeline kept spinning. The libevent schedule_fill(dest) zero- timer queued at the defer site could not fire because the event loop never regained control. Yield unconditionally when the counter trips. Counter is reset by successful read routes (existing path) when traffic resumes. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): MGET success path resets strict-no-route counter MGET bypasses get_key_for_conn (which has its own counter reset at line 1148) so successful MGET sends never zeroed the counter. Intermittent defers on a healthy pure-MGET workload would slowly accumulate the counter until hold_pipeline tripped spuriously. Mirror the GET path: zero the counter after every successful send. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): disconnect() clears m_reconnecting; OFF path observability Three small lifecycle fixes: * disconnect() now clears m_reconnecting. If tear-down races with a pending reconnect timer, the flag would otherwise stay true and future attempt_reconnect calls would no-op silently. * --reconnect-on-error=off READONLY-error path now bumps the connection-error stat counter, mirroring the ON path. The OFF branch was the only stat-counter gap. * attempt_reconnect rolls back m_current_backoff_delay on event_new OOM in addition to m_reconnect_attempts, so a thread restart starts from a clean state. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): warn once per minute when all replicas lost on read-only run R3 reviewer noted that --reconnect-on-error=off + all-replicas-fail + ratio.a==0 hangs the benchmark indefinitely with no operator signal. Add a coarse rate-limited warning (one per 60s, CLOCK_MONOTONIC) when the bootstrap hold gate finds no live target so operators see the stall rather than silent hang. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * docs(read-pref): help/README/comment/test message cleanups * Replace 'see PR #456 limitations' in --help with README section reference. Don't bake PR numbers into shipped binaries. * Fix stale Endpoints array comment in run_stats.cpp (referenced the reverted standalone clause). * Tighten EWMA-update comment to acknowledge rt_arbitrary covers both reads and writes. * README Endpoints gate clarified as cluster_mode + non-primary pref. * Test error message no longer mentions --test-time=5 (workload is requests=200). * PR body test plan + cold-start wording updated via gh. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * test(read-pref): add primary-leak assertion + pure-MGET spin-guard reproducer * keyless-arbitrary-secondary now asserts primary received <= 4 DBSIZE calls (setup-ladder budget). Catches regressions where keyless reads leak to primary under rp_secondary. * New test_read_preference_mget_pure_pipeline_cap_spin_guard exercises --ratio=0:1 + multi-key-get + small pipeline to actually trigger the pipeline-cap defer path that bffeb91 + the round-6 hold_pipeline yield were meant to fix. Smoke-bounded by --test-time=5s. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): hold_pipeline self-clearing yield avoids deadlock Round-6 commit 4da75e8 made hold_pipeline yield unconditionally when the strict-no-route counter tripped, but the counter is shared per- cluster_client. Both producer and destination would hit the threshold and park indefinitely with no timer to wake them: producer broke out of fill_pipeline, destination's schedule_fill fired, dest hit hold's return-true, dest parked too. Counter could only reset via successful MGET send, reaching that required bypassing hold -- chicken and egg. Reset the counter to zero at the moment the yield fires. Next call finds counter==0 and falls through to create_mget_request; if the defer condition persists the counter rebuilds to 64 and yields again. Bounded spin (64 defers per yield) replaces the deadlock. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * test(read-pref): support requests=None so spin-guard test can actually run The new pure-MGET spin-guard test passes both --requests=200 (auto- injected) and --test-time=5, which memtier rejects as mutually exclusive. Result: the test never ran the path it was added for and silently failed at startup with exit code 2. Add a requests=None option to get_default_memtier_config that skips --requests emission. Update _run_mget_workload to forward the kwarg. The pure-MGET test now correctly uses --test-time only. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(ci): drop incompatible RLTEST_DEBUG from read-preference cluster cell The OSS-CLUSTER + replicas: read-preference matrix cell set both RLTEST_DEBUG=1 (forces --no-output-catch) and PARALLELISM=2. RLTest rejects this combination at startup and the cell has never run a single test since being added. Drop RLTEST_DEBUG so tests actually execute. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * test(harness): add subprocess timeout to Benchmark.run() so hangs fail fast A real spin regression in memtier would block the test harness on process.communicate() with no time bound. CI would then hang for 6 hours instead of producing a clean test failure. Add a timeout parameter (default 60s) so a hung benchmark surfaces as a failed assertion. Spin-guard tests pass timeout=20 for tighter detection. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * chore(read-pref): polish from round-6 reviewer pass * handle_reconnect_timer_event retry branch NULL-checks event_new * keyless-arb master_dbsizes asserts ==0 (no legitimate primary source) * Dead reset before loopbreak in exhaustion branch removed * "PR #456" self-references in cluster_client.cpp dropped * Rate-limited warning prefixed with thread id for log dedup Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): writes tolerate transient cluster_slots_state on primary 5 round-8 reviewers (R1, R2, R4, R6, R7) independently identified this: select_target_conn collapsed the master-era split between "writes to producer's own slot" (no liveness check) and "writes via slot map" (liveness check). The PR uniformly applied is_ready_for_reads, which requires cluster_slots_state == setup_done. When the primary briefly transitions to setup_none via set_cluster_slots() calls (role-aware disconnect, MOVED redirect, READONLY-no-loop guard, build-then-swap window), select_target_conn returns UINT_MAX. But client::get_key_for_conn has already advanced m_obj_gen->m_next_key -- the key index is consumed, no SET is issued. When the iterator wraps at m_key_max the client re-writes already-touched keys. Symptom: 500000 == 499824 (deterministic ~176 key loss per run, matching the ~9 skips x 20 clients math). Writes to the producer's primary only need the connection to be TCP-connected. The cluster_slots_state gate is meaningful only for reads (which need READONLY-acked replicas). Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): write-side spin guard prevents fill_pipeline busy-loop R6 + R7 round-8 finding: on all-malformed CLUSTER SLOTS reply (e.g., cluster_slots_malformed.bin fuzz fixture), m_shard_groups stays empty after the build-then-swap protection. Every SET routes through select_target_conn -> UINT_MAX -> not_available. Without a write-side spin guard, fill_pipeline busy-loops on m_pipeline->size() < pipeline forever, starving the event loop. --test-time timer never fires. Bump m_strict_no_route_attempts on write no-routes too. Yield in hold_pipeline when counter trips and the topology is empty or every shard group's primary is unroutable; reset on yield to preserve self-clearing semantics. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * test(harness): bump Benchmark.run() default timeout to 240s for ASAN/TLS R3 + R5 round-8 found: round-7 commit 2a98ebd set the default subprocess timeout to 60s. test_short_reconnect_interval issues 50,000 ops with --reconnect-interval=1 (full TLS handshake per op). Under ASAN+TLS: ~380-450 ops/sec -> needs 110-130s. The 60s default kills memtier mid-run, breaking ops-count and exit-code assertions across 3 CI cells (Single Endpoint TLS, OSS TLS v1.2, OSS TLS v1.3). Bump default to 240s. Spin-guard tests that explicitly pass timeout=20 stay tight. The default now covers ASAN+TLS+reconnect-heavy with margin while still failing fast on genuine hangs. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): bootstrap CLUSTER SLOTS failure must not advance setup_done R6 round-8 found: when CLUSTER SLOTS bootstrap reply is malformed, handle_cluster_slots's build-then-swap correctly preserves the prior state (empty on bootstrap), but shard_connection still transitions m_cluster_slots to setup_done unconditionally. The worker advances to steady-state routing with an empty topology -- every slot lookup returns UINT_MAX. Combined with the previous-commit write-side spin guard this is recoverable, but stalling here is the right behavior. Defer setup_done until at least one valid shard parses. handle_cluster_slots now returns bool (true on commit, false on rejection); shard_connection's rt_cluster_slots handler only advances setup_done on commit. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): cross-shard writes also tolerate transient cluster_slots_state R1 round-9 follow-up: commit 744339c fixed the producer==primary write path but the parallel gate at cluster_client.cpp:1304 (cross-shard write, target_conn_id != conn_id) still gated writes on the OTHER connection's cluster_slots_state == setup_done. Under transient topology churn (MOVED redirect, role flip, periodic refresh), this returned not_available after client::get_key_for_conn had already advanced m_obj_gen -- same silent key loss pattern as round-8. Mirror the round-9 fix here: gate the setup_done check on is_read. Writes to a TCP-connected primary always succeed; reads still need the full readiness check (READONLY ack on replicas). Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(read-pref): surface CLUSTER SLOTS rejection to supervisor R2 + R3 round-9 follow-up: the round-9 hang fix works for the fuzz fixture (cluster_slots_malformed.bin) because the mock half-closes after the malformed reply, triggering BEV_EVENT_EOF -> reconnect. If a real server kept the socket open, the worker would silently stall in fill_pipeline's setup branch until --connection-stage-timeout (default 30s) fired via the run-elapsed trip -- and with --connection-stage-timeout=0 it would hang indefinitely. Make recovery unconditional: report_connection_stage_failure on the committed==false branch so the supervisor's failure-streak detector arms regardless of peer EOF behavior. Matches how AUTH/HELLO/etc failures are already surfaced. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * chore(read-pref): strip round-N reviewer-history references from shipped code R7 round-9 flagged that round-N references (cluster_client.cpp, shard_connection.cpp, test_read_preference_mget.py) reappeared in shipped code after round-7 explicitly cleaned them out. PR-history labels make sense only with the review log; future readers will just see noise. Rewrite comments to describe what the code does, not which review round added it. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * chore(read-pref): complete round-N reviewer-history sweep Round-10 commit 7297ac1 scrubbed most round-N references but missed 4 sites flagged by R3 + R4 round-10 reviewers: * shard_connection.cpp:1031 — "Round-9 (R6)" prefix removed * cluster_client.cpp:621 — "Round-1 of this fix" history reframed * tests/test_read_preference_mget.py:181 — "Round-5 bug" label dropped * tests/mb.py:89 — "Round-7's 60s default" docstring rewritten Comments now describe code behavior, not which review round added it. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): mixed-workload MGET no longer silently skips on replica producers Cursor bugbot HIGH (client.cpp:673): when a replica connection is the producer in a mixed --ratio + --multi-key-get workload, its m_mget_conn_slots was empty (only primary-slot-owners got the slot keys cache populated), so create_mget_request returned false with m_mget_defer=false. The caller advanced m_get_ratio_count to the GET cap and silently skipped the MGET batch. Populate m_mget_conn_slots for replicas with the same slot set as their owning primary. create_mget_request already routes the actual MGET via select_target_conn(target_slot, true), so the replica producer's slot lookup succeeds, and dispatch still honors the --read-preference policy (no change in where the batch lands). Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): retry_after_redirect uses correct predicate for writes Cursor bugbot MED (cluster_client.cpp:1956): retry_after_redirect gated MOVED/ASK retries on is_ready_for_reads() which requires cluster_slots_state == setup_done on the target. For writes this is over-strict — writes only need TCP-connected because the primary owns the slot regardless of the slot-map ladder. Mirror the write-path tolerance from round-9 (744339c) and round-10 (a257fc2): split the readiness predicate by request type (is_read), checking get_connection_state() == conn_connected for writes and the full is_ready_for_reads() ladder for reads. Without this split, a primary mid-CLUSTER-SLOTS-refresh would reject a write retry and the retry would silently dribble back to the source connection. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): tighten port copy length in CLUSTER SLOTS parser Cursor bugbot MED (cluster_client.cpp:660): both the primary and replica port copies did memcpy(dst, value + 1, value_len). value points at the ':' bulk-header prefix and value_len is the strdup'd length including that prefix, so the digit run is value_len - 1 bytes. The old form copied value_len bytes and pulled one byte past the digits; it worked in practice only because strdup's trailing NUL backed up the +1 overrun. Tighten both copies to use value_len - 1 (port_digits_len / r_port_digits_len) so the source length matches the intent and static analyzers stop flagging the off-by-one. value_len == 0 is already rejected by the earlier empty-bulk guard, so no underflow risk. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): EWMA update filters rt_arbitrary writes Cursor bugbot MED (cluster_client.cpp:2011): rt_arbitrary covers both reads and writes from the --command path (the request type is stamped at creation, before read/write classification). Updating the per-endpoint EWMA on every arbitrary response biased nearest- mode selection toward endpoints that handled writes, defeating the nearest-replica intent in mixed arbitrary workloads. Route rt_arbitrary responses through classify_read() so only actual reads (rt_arbitrary with command-meta is_read_override / spec->is_read true) seed the EWMA; rt_get remains always-eligible. Setup-ladder responses (AUTH, HELLO, CLUSTER SLOTS, READONLY) and built-in writes (rt_set, rt_wait) are still excluded by the outer m_type gate. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * docs(read-pref): document monitor + keyless slot-0 deferred improvements Cursor bugbot MED x2: MONITOR routing under --read-preference and keyless arbitrary reads anchored on slot 0. Both are narrow design gaps requiring larger redesigns: 1. create_monitor_request_cluster routes monitor streams to slot- primary owners regardless of read_preference. MONITOR is intrinsically per-shard streaming and doesn't map cleanly to MongoDB-style read preferences. 2. The keyless arbitrary-read branch in create_arbitrary_request uses select_target_conn(0, true) — fine for a single-shard pin, but under rp_secondary every keyless read funnels into shard_group[0]'s replicas; other shards' live replicas are ignored. Spreading these requires round-robin across populated shard groups (or a select_replica_for_any_shard helper) and touches the shared rp_secondary / rp_nearest / preferred fallback ladder. Both sites carry an inline note pointing to follow-up issue #457. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * chore(read-pref): drop residual round-9/round-10 references in cluster_client Two round-N reviewer-history references survived the earlier sweeps (7297ac1, da4dd96) in the readiness-predicate comment block at cluster_client.cpp:2002. They referenced commits 744339c (round-9) and a257fc2 (round-10) by review-round label. Rewrite the comment to describe the behavior (write-path tolerance and cross-shard write retry path) without the round-N labels. The code behavior is unchanged. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): set primary role before reconnecting reused endpoint cursor-bugbot HIGH (PR #456 commit 575fdf3): on CLUSTER SLOTS refresh, the primary-discovery loop in handle_cluster_slots reuses an existing shard_connection when (addr, port) match an existing entry. If the reused endpoint was previously labeled role_replica and is now the slot primary, the reconnect path called connect_shard_connection() BEFORE set_role(role_primary). shard_connection::connect() reads m_role to decide whether to arm the READONLY ladder; armed against the stale replica label, it would send READONLY against a primary and leave the connection in a state where writes route to it as group.primary while the setup state still reflects replica ladder expectations. Fix: set_role(role_primary) before connect_shard_connection() in both the reused-and-disconnected branch and the new-connection branch. Mirrors the set_role-before-connect order already used for replicas in the same function. The unconditional set_role(role_primary) below (line ~770) is retained for the already-connected role-flip case where the previous label was role_replica and the connection stays up. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): READONLY retry accepts connected primary (no setup_done gate) cursor-bugbot MED (PR #456 commit dc72571): the -READONLY response retry path required the slot primary to be both conn_connected AND get_cluster_slots_state() == setup_done before accepting it as the retry target. Elsewhere in this PR, write routing and MOVED/ASK write retries treat conn_connected as sufficient because the primary owns the slot regardless of the cluster_slots ladder state. A primary mid-CLUSTER-SLOTS-refresh (cluster_slots_state transiently != setup_done) would therefore drop valid -READONLY retries as terminal errors instead of sending them to the primary that owns the slot. Drop the setup_done gate to align with select_target_conn's write-path tolerance and the retry_after_redirect predicate. The slot map itself is still consulted via slot_primary_conn_id(hslot); only the readiness check changes. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(cluster): restore master write-path invariant -- eliminate keyspace loss Round-13 closer: the 500000 == 499824 keyspace-loss failure across 8 CI cells (OSS-CLUSTER API plaintext+TLS x ASAN/TSAN/UBSan/Test) had a definitive root cause that rounds 9-12 missed. client::get_key_for_conn advances m_obj_gen->m_next_key[SET_ITER] BEFORE routing checks. Two paths silently dropped the consumed key: * select_target_conn write branch returned UINT_MAX when the primary was in conn_in_progress/conn_disconnected (transient TCP states during bootstrap or post-reconnect). Master's baseline did not have this gate -- writes to the producer's own slot were unconditional. The fast-path for writes now skips the conn_connected gate entirely: the producer is by definition conn_connected (else fill_pipeline wouldn't run), and cross-shard SETs queued on the target's pool drain safely when the target completes setup. * The cross-shard disconnect check in get_key_for_conn returned not_available without compensating m_obj_gen. Now triggers the topology refresh but falls through to queue the ke…


Fixes #417
cluster_client::handle_cluster_slots()walked theCLUSTER SLOTSreply with barembulks_elements[N]indexing andas_bulk()/as_mbulk_size()casts thatassert(0)on type mismatch. A malformed reply from a hostile or buggy server crashed memtier with SIGSEGV — captured by the RESP-fuzzer fixturetests/fixtures/resp_payloads/cluster_slots_malformed.binintroduced in PR #419 (which isenv.skip()'d with aTODO(#417)until this lands).Repro
i.e. an outer 1-element array containing an inner 1-element array whose only element is a simple-string. Old code did
shard->mbulks_elements[1]past the inner-array's only element → out-of-bounds read → SEGV.Fix
Validate before indexing:
get_mbulk_value()is non-nullis_mbulk_size()is_bulk()is_mbulk_size()and has ≥ 2is_bulk()children (host, port)Any malformed shard logs a
benchmark_error_logand is skipped — the existing bootstrap connection stays in service. If the whole reply is non-array, log and return without touching topology.Test plan
make format-checkclean.env.skip()+TODO(#417)fromtests/test_resp_response_fuzzer.py::test_cluster_slots_malformed. That test now exercises the validation path. (Follow-up PR.)🤖 Generated with Claude Code
Note
Medium Risk
Changes cluster topology parsing and connection lifecycle on refresh; validation reduces crash/OOB risk but alters behavior when servers return bad or empty slot maps.
Overview
Hardens
cluster_client::handle_cluster_slots()so memtier no longer crashes or corrupts memory on a badCLUSTER SLOTSRESP reply (fixes #417).Before walking shards, the handler now requires a non-empty top-level array and validates each shard’s shape (
[start, end, [host, port, …]]) withis_*checks instead of uncheckedas_bulk()/as_mbulk_size()(which couldassertor read past the end). Slot bounds are parsed withstrtol, checked forERANGE, and clamped to[0, MAX_CLUSTER_HSLOT]withmin <= maxsom_slot_to_shardcannot be written out of bounds. Host/port bulks must be non-empty; hosts with embedded NULs are rejected.Malformed shards are logged and skipped; wholly bad replies (non-array, empty topology, or every shard invalid) are ignored so existing connections—including bootstrap—stay up instead of tearing down all shards via
close_sc.Reviewed by Cursor Bugbot for commit 721fc26. Bugbot is set up for automated code reviews on this repo. Configure here.