Repository navigation
Keep cluster workloads progressing across partial maps and primary reconnects - #799
Conversation
|
🤖 Automated first-pass review — a human maintainer's review is still required before merge. Thanks for this. I went through the routing changes, the queue-reset refactor and the new tests. The root cause is well explained, and the regressions are shown failing on the base and passing with the fix, which is the bar we want for a fix like this. A few comments below.
The core fix looks solid and the test coverage is thorough. Since this touches cluster routing, it may be worth a second look from whoever owns that area. I'd mainly like the scope and refresh-rate questions answered before this merges. |
|
Addressed in b1d8478. CLUSTERDOWN now requests a bounded refresh even when the last map was full. The new no-disconnect fixture removes the slot on operation five and heals it only when SLOTS is requested: on the base there are 16 terminal failures and no refresh; the fix refreshes once, preserves all 20 operations, and recovers with either one terminal failure (retry disabled) or one extra successful replay (retry enabled). The warning is now once per process, checked with two threads and three clients. The strict-secondary predicate is shared by both routing checks, and the comments explain deliberate first-primary selection and the warning-only transaction/monitor calls. All 16 new integration tests and 16 unit programs pass. The 35 existing setup/topology compatibility controls also pass, as do the real two-primary Redis cases over plaintext and TLS. The MULTI fixture explicitly rejects a SLOTS command inside an open transaction; the refresh waits until EXEC. CI and the independent reviews remain pending. |
|
The monitor producer is not guaranteed to be a primary: a replica seed can generate work after discovering the primary. Falling back to Added a direct regression in b3b38dd: start from the replica seed and delay primary AUTH by 100ms, then replay 20 monitor writes to the missing slot. All 20 reach the primary, none reaches the replica, and all 20 terminal errors are counted. The original monitor-seed control, full-map recovery control, and strict-secondary MGET/arbitrary controls also pass (3 focused test functions, including the new variant). I kept routing-policy validation separate from destination lookup because the lookup is also used while processing/replaying an already-owned request; it must not end the event loop or add generation-side diagnostics there. Both now share The once-per-second refresh per client is intentional even under full-coverage CLUSTERDOWN: each client has its own map and needs a bounded way to discover recovery. This does not introduce a process-wide polling coordinator. The prefix now uses a named constant with |
|
The per-client limit is intentional, and the README now states its scaling explicitly: 8 threads × 50 clients permits up to 400 refreshes/second during sustained CLUSTERDOWN, in addition to bootstrap discovery. Each client owns its own topology and connection/setup state; a shared thread timestamp alone would prevent some clients from repairing stale maps. Coalescing would also need to distribute and validate refreshed topology across those clients. Refreshing only with retries enabled would leave non-retrying workloads unable to discover removal/healing from a stale full map. The real-cluster tests establish correctness on the recorded two-primary fixtures, not acceptable overhead at 400 clients. Strict secondary with error/queue deliberately fails when the generated read has no authoritative slot owner, including a transient hole from a refresh. Queue remains documented as error. Reusing the existing generate-and-skip no-route path here would consume that exact generated key; selecting an unrelated replica or a primary would violate the selected routing policy. Known-owner replica waiting is unchanged. Selecting the first eligible primary for permitted fallback is deliberate and now documented, including the possible concentration of error traffic. Updated the two wall-time-dependent refresh bounds to allow bootstrap, the immediate refresh, and one refresh per elapsed second. The exact-two assertion remains for the pipeline-one healing case, which has only one CLUSTERDOWN trigger. The focused request/time/healing cases pass; independent TEST also demonstrated the old bound failing under delayed responses. cluster_client.cpp already includes explicitly. Independent review has additionally found a two-primary missing-slot MGET liveness gap. That repair and its regression control are being handled before merge. |
|
The independent two-primary MGET blocker is fixed in c9ff438. A missing-slot MGET now stays on the primary assigned as its producer until the topology/cache rebuilds; it cannot switch underneath the cache when another primary finishes connecting. Strict-secondary validation still runs first. Known-owner routing is unchanged. This also keeps the send behind that producer's completed setup ladder. The committed regression seeds primary B while advertised-first primary A has delayed AUTH. Before this fix the missing-slot MGET hit the eight-second watchdog; owned MGET and missing-slot ordinary GET controls passed. Now the request-count, timed and pipeline-eight MGET cases all preserve the exact keys and counts. All 18 integration functions, 16 units and 35 compatibility controls pass. Real two-primary Redis plaintext/TLS checks also pass, including 100 missing-slot MGET requests through the second seed, with exactly 100 counted errors. For the latest monitor question: retirement compensation is one path, not a promise that every failed destination will be retired. If a connection cannot recover and reconnect is disabled, the existing connection error path ends its worker; the run is incomplete and fails. If a later topology retires a connection, its staged counts are compensated there. A normal reconnect preserves the staged queue. The producer cannot safely substitute its current connection because it may be a replica seed. The refresh-rate and first-primary concentration trade-offs remain the explicit policy described in the previous reply and README. The tests establish correctness, not acceptable outage load at 400 clients. Distributing holes by hash adds a scheduling policy without an authoritative owner and does not address the MGET producer/setup invariant. The response-prefix comment now points to the same simple-error/RESP3 caveat as READONLY. The warning-only callers remain explicit; no additional helper is needed for this repair. Focused independent SEM/TEST/OUT rechecks and final-head CI are pending. |
|
The strict-secondary choice is intentional, including transient holes, as described in the earlier policy reply: #799 (comment). At that point generation has selected an exact key, but the map names neither its primary nor any authoritative replica. Reusing generate-and-skip The same reply explains why a shared timestamp alone cannot replace per-client refresh: every client owns a separate topology/setup state. The documented scaling and concentration are accepted limitations of this narrow correction; the tests do not establish acceptable outage load at 400 clients. The scripted tests do execute the actual cluster-mode router over authenticated TCP, including the two-primary setup transition, while owning their complete topology. They skip the outer cluster/TLS environment because that environment does not own these sockets. The real Redis plaintext/TLS proof now also covers the second-primary-seed MGET case, with exact request/error counts. Adding cluster-job topology mutation/restoration is useful follow-up coverage, but is not needed to make the committed reproduction exercise this routing code. Once-per-process warning suppression across |
|
Addressed against final owner head 53af982, following the review edit at 12:21:53:
The new queue unit fails when linked against ec99479, and a mutation removing refresh eligibility fails the live-seed-refresh assertion. Final independent rechecks and exact-head CI remain merge gates. |
|
Following the 12:42:18 edit: I checked the same-endpoint demotion case with a private three-endpoint fixture. After two setup closures it promotes a different primary and advertises the old endpoint as a replica, then verifies that retained writes actually drain on the demoted endpoint and receive READONLY. All four controls pass at 53af982: ordinary writes and monitor replay, each with retry disabled/enabled. Without retries, ordinary work has 8 terminal READONLY failures plus 12 successful writes, counted as 20 operations. With retries, the same 8 rejected attempts are resent to the new primary, all 20 exact keys complete, and the logical count remains 20. Monitor replay similarly has 5 terminal rejected SETs without retries, or all ten distinct SET values completed on the new primary with retries; its ten PINGs bring the logical total to 20 in both cases. A claimed retry remains outstanding and is processed once at its final response. The MOVED and topology-retirement paths retain their existing policies; these measurements specifically cover READONLY after demotion. The refresh-rate choice and timing/CI limits remain as described in my preceding reply. A shared timestamp is small mechanically but also shares the recovery budget across independent client topologies; that behavior change is outside this repair. The monitor gate uses current connection state because any cached/pending-only flag needs updates across reconnect, setup and topology changes. I have not measured a throughput claim for that lookup. The README warning scope is now explicit; detailed queue/count semantics remain documented because they define what the benchmark reports after reconnect. Final-head CI is not all green: the cluster replica-disconnect/wakeup test has failed, and I am investigating it against the previous head before any rerun. The PR remains blocked on that investigation, independent rechecks, and final-head CI. |
|
The replica-disconnect CI failure was a real regression, now corrected in Same-endpoint queue preservation is now limited to primaries, which are the missing-slot fallback destinations. Replica redials, including a primary demoted before redial, preserve the existing clear/compensate policy; no new primary fallback or unrelated-replica routing was added. README and the PR body state that this does not guarantee identity across replica redials. The demotion wire results in my previous reply remain evidence for All 16 unit programs and all 21 missing-slot integration functions pass, including owned/unowned monitor replay with two AUTH closures and pipelines 1/4, exact ordinary keys and transaction progress. Formatting passes. New-head CI and focused independent review remain pending; I am not treating the failed run as flaky or claiming CI is green. |
|
Addressed the scope point in the title and description: this PR now explicitly covers partial maps and primary reconnects, and the Fix section states that primary queue retention and CLUSTERDOWN recovery also affect fully owned maps. Those follow-ups have separate commits and regressions. On refresh fan-out: each client owns an independent slot map and its own connections, even when clients share an event base. A per-thread limiter could delay each client’s discovery, or would require distributing one reply safely to the other clients and reconciling their connection/setup state. This change retains the per-client bound and documents the aggregate 400/s example; I am not claiming it is a process-wide protection or that this is the optimal recovery polling policy. The monitor gate still scans groups; no throughput/overhead claim is made, and introducing a cached disconnected-primary count would add state transitions beyond this correction. Independent review found a further role-transition error in Current-source real-Redis coverage also includes the existing three-primary/three-replica permanent-disconnect regression, which completes all 16,000 operations after this correction. The manual partial-map plaintext/TLS evidence remains accurately attributed to |
|
Following the 13:06:49 review edit:
All final-head reviews and CI remain required before merge. The documented primary-only identity guarantee intentionally excludes replica redials and old replica work discarded on promotion. |
…d-slot-progress-20261023
|
bugbot run Please review current head c47fc40 after integrating master, including the topology-retention and bounded stderr logging changes. The automatic check skipped the unchanged PR patch; a fresh review will make the final integration gate explicit. Clean build17/17 units and26/26 focused RLTest functions pass. Full CI and independent rechecks are still pending. |
|
Following the 17:35:19 review update:
After master integration, clean17/17 units and26/26 focused runtime functions pass; independent BUILD and SEM approve c47fc40. The remaining reviews and full CI are still mandatory. |
…d-slot-progress-20261023
|
Following the 19:12:30 review update, the MGET fallback question now has a direct exact-head control.
On the remaining points:
Current head8d4c7c2703ec3678b23ee81b9fd9890accf2dc4b has a fresh clean17-unit build,30 focused integration tests, and851 tests assigned exactly once across the sanitizer shards. Independent SEM, TEST and INTER rechecks approve it; the remaining lenses and full new-head CI are still required. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 8d4c7c2. Configure here.
|
Thanks. Answers for head
Full CI on |
With --cluster-mode --rate-limiting, the up-front percentile warning (#386) took its sample bound from the first committed topology only. Since #799 a run can start on a partial slot map, and when the map heals memtier opens more endpoint connections, each with its own rate limit. On a 3-primary cluster with one primary's slots restored 1 s into a 6 s run at 800 req/s, memtier warned that p99.99 "records at most about 9664" and "will not be resolved", then recorded 10187 samples and resolved it. The cluster client now publishes the largest rate-limited connection fan-out committed so far, written once per topology commit under the topology-summary mutex. The main thread's once-a-second check remembers what it said about each percentile, for the run and the window, and when the fan-out grows prints one header line and then either the warning again with the raised bound or a "may now be resolved" note. A --requests bound does not depend on connections and is not repeated. The progress-line newline is printed only when there is a warning. test_cluster_unowned_slots.py heals the fake cluster after memtier's first warnings and checks the exact update lines, the window '*' marks, and that a --requests warning is not repeated. Fixes #825 Co-Authored-By: Claude Opus 5.5 <[email protected]>
… 2.2.2-alpha (#545) **Depends on #822 and #832.** This branch merges both PR branches unchanged, so either can land first and the other merges cleanly: - #822 (`fix/libevent22-tls-error-access`, at cba1fcc) brings the `shard_connection.cpp` TLS error guard and `tests/test_connection_error_types.py`. Please review those in #822. - #832 (`fix/resp-bulk-length-overflow`, at 300da45) brings the RESP length/count bounds in `protocol.cpp`, the `check_length_limits()` unit test and the fuzzer's sanitizer-output checks. This PR's UBSan-aborting sanitized cell found that overflow. Please review those in #832. Intended order: land #822 and #832 first, then merge master here (no rebase or force push), so this diff becomes CI, tooling and docs only. Refs #535. #823 also adds a "Supported libevent versions" table and a #535 read-size note to DEVELOPMENT.md. Whichever of #823 and this PR lands second merges the two tables into one and keeps a single #535 paragraph. ## Problem memtier's integration suites (including ASan/UBSan/TSan) run only on the distro's libevent 2.1.12. Nothing in CI builds the current security release 2.1.13-stable or the 2.2 series, and libevent itself is never instrumented. Because of that, the 2.2.2-alpha regression fixed in #822 (an out-of-bounds access inside libevent on every plaintext connection error in a TLS-enabled build) could only be found by hand. The earlier version of this workflow used `paths:` filters, so it could not be a required check (a skipped required check never reports), put versions in job names, and installed Redis from a different source than `ci.yml`. ## Root cause libevent behaviour differs by series: 2.2.2-alpha asserts, or with `NDEBUG` reads and writes out of bounds, when `bufferevent_get_openssl_error()` is called on a plain bufferevent, and it returns no error for TLS bufferevents. 2.1 reads at most 4 KiB per socket read, 2.2 up to 16 KiB (#535). None of this is visible without building those libevent versions, instrumenting them, and checking which library memtier actually loads. ## Fix - **`scripts/build-libevent.sh`**: one helper for Linux and macOS. It pins 2.1.12-stable, 2.1.13-stable and 2.2.2-alpha by release-asset sha256 (never `/archive/`) and libevent `master` by commit (`d82464a2`, canary only). It rejects a non-empty or non-directory prefix before creating it, builds with CMake (Release), and with `LIBEVENT_FLAVOUR=sanitize` also builds libevent with ASan+UBSan. `--source-id` feeds the CI cache key. The macOS jobs in `ci.yml` keep using it for 2.1.13 (clean prefix as in #674, debug mode off). The macOS OpenSSL 1.0.2 cell keeps master's autotools build of 2.1.12, unchanged. Because the existing `ci.yml` macOS jobs now go through the helper, a helper regression also breaks those jobs. `build-macos-libevent.sh` and the helper are in the harness pattern, so any change to them runs the full libevent grid. - **`scripts/check-libevent-linkage.sh`** (Linux; on macOS it delegates to `check-macos-tls-links.sh`). It fails unless the `--version` `libevent=` field equals the expected string from the matrix (e.g. `2.2.2-alpha-dev`), the prefix's pkg-config files for every component are the same release, every libevent library loaded (directly or transitively, per `ldd`/`readelf`) comes from the prefix, the process loads exactly one libssl and one libcrypto (so `libevent_openssl` and memtier share one OpenSSL; checked on memtier's transitive `ldd` set, so a private OpenSSL found through RUNPATH is handled), and the `openssl=`/`prometheus=` fields are as intended. - **`.github/workflows/libevent-compat.yml`** redesign: - No path filters. Triggers match `ci.yml` (`pull_request` and `push` on `master`, `main`, `2.*`), plus a nightly schedule, a weekly schedule and `workflow_dispatch`. - Stable job names `libevent-compat (<track>, <cell>)` with no versions in them. The track is `legacy` 2.1.12, `stable` 2.1.13, `next` 2.2.2-alpha or `canary` master. - Aggregate **`libevent-compat-gate`** (`if: always()`). It fails unless planning and every non-canary cell succeeded. This is the only check to mark required. - **Every PR/push**: - `stable` and `next` TLS full suites, standalone and cluster. - `next` plaintext full suites with **memtier and libevent both under ASan+UBSan**. This is the cell that catches the #822 regression. - `next` `--disable-tls` build (Prometheus on) with `make check`. - **Nightly**, and PRs that change this harness: adds 2.1.12 source builds (TLS and plaintext), the remaining plaintext and no-TLS cells, and macOS builds with OpenSSL 3 and 4. - **Weekly and on dispatch**: a libevent `master` canary with `continue-on-error`. It is not required and not part of the gate. A failing canary writes a warning and a step-summary line, and a small `canary-alert` job (`issues: write`, canary runs only) opens or updates one "libevent master canary is failing" issue. - Sanitized cells run with `ASAN_OPTIONS=detect_leaks=1:abort_on_error=1` and `UBSAN_OPTIONS=halt_on_error=1:abort_on_error=1:print_stacktrace=1`. Concurrency groups include the event name, so pushes never cancel scheduled or dispatched runs. The nightly skips Sunday, when the weekly run covers the same grid. - Built libevent is cached with `actions/cache`, keyed on version, sha256/commit, flavour, OpenSSL version, compiler version, and the hashes of the helper and the workflow. - Redis is installed from packages.redis.io, the same way as `ci.yml`. - Wall time: each test cell runs one topology, and the cluster suites are split into two file shards (`utils/select_test_shard.py`, coverage checked by `utils/check_test_shards.py`, as in the sanitizer workflows). On 658fed4 an unsharded cluster cell took 35–41 min, as long as `ci.yml`'s slowest cell (`OSS-CLUSTER API: TCP TLS`, 37 min); standalone cells take about 25 min. - **`tests/test_reconnections.py`**: when memtier dies from a signal, the test prints its stderr, starting at the first sanitizer report or assertion. This makes an abort in `test_reconnect_cluster_mode_no_assertion` diagnosable from the CI log. On the previous head it failed with rc −6 in the sanitized alpha cell, and no stderr was printed. - **`DEVELOPMENT.md`**: the tested libevent matrix, how to evaluate another libevent locally, the 2.1 (4 KiB) vs 2.2 (16 KiB) read size (Refs #535), and the TLS messages memtier prints on 2.2 after #822. ## Tests - CI on 8e8b3a6: Libevent compatibility, all 28 jobs green (full grid, because this PR changes the harness), and all other workflows green. On 658fed4 it showed harness-side failures that are fixed: a test-time `PKG_CONFIG_PATH`, and absolute macOS install names for 2.2. - The cell that was red before (`test_reconnect_cluster_mode_no_assertion`, rc −6 under ASan+UBSan on b3c67f1) passed on x86_64 on 658fed4 and 8e8b3a6. The earlier failure ran on a source 167 commits behind master, before several cluster-reconnect fixes landed (e.g. 019d658, #777, #797, #799). The test now prints memtier's stderr whenever memtier dies from a signal. - Local (Ubuntu 24.04 container, OpenSSL 3.0.13): - The helper built 2.1.12, 2.1.13, 2.2.2-alpha, master and sanitized 2.2.2. - memtier built against each, plus `--disable-tls` and ASan+UBSan builds, and the linkage checker accepted every one. - The checker rejected each negative case: wrong expected version, prefix/runtime mismatch, a TLS expectation on a no-TLS build, a wrong Prometheus flag, and a build that loads the system libevent. - The helper rejected a non-empty prefix, a file used as prefix, an unknown version or flavour, and a missing argument. - Before/after: unguarded `master` built against sanitized 2.2.2-alpha aborts on a refused plaintext connection with `AddressSanitizer: heap-buffer-overflow` in `bufferevent_get_ssl_error` (`bufferevent_ssl.c:1108`), called from `shard_connection.cpp`. This branch exits normally in the same setup. - macOS (CI, nightly cells): with 2.2 the helper now sets absolute install names (`CMAKE_INSTALL_NAME_DIR`), because 2.2's CMake otherwise installs `@rpath/` dylibs, which `check-macos-tls-links.sh` rejects. - `actionlint` (with shellcheck) is clean on the new workflow, `shellcheck` is clean on the scripts, and the C++ passes `clang-format-18 --dry-run --Werror`. ## Per-PR cost, sanitizers, and the required check - **PR scope**: 10 Linux jobs. On 8e8b3a6 (full grid, 28 jobs, all green) the longest cell took 27 min (`next, plaintext-asan, standalone`) and the cluster shards 18–23 min. `ci.yml`'s slowest cell took about 37 min on the same push, so libevent-compat is not on the PR critical path. - **Measured cost**: on 8e8b3a6 the 10 PR-scope jobs used about 203 runner-min (all existing workflows together use about 818 per PR run). Of that, `stable` (2.1.13) TLS is 3 jobs and about 68 runner-min. - **Why `stable` runs per PR**: the goal is full coverage of the libevent users actually run. 2.1.13 is the current security release and ships in RHEL 9/10, Debian 13, Fedora, Alpine ≥ 3.21, Homebrew and MSYS2, while `ci.yml` runs integration suites only on Ubuntu's 2.1.12 and only builds and unit-tests 2.1.13. If CI budget ever requires it, the plan step makes moving it to nightly a one-line change. - **ASan/LSan with an instrumented libevent**: `abort_on_error=1` stays on purpose. Without it, a leak exits with 23, and tests that only check `!= -6` pass over it. Full runs came back clean with no suppressions file: on 658fed4 the sanitized cluster cell passed 858/858, and on 8e8b3a6 all three sanitized cells passed. If an alpha-internal leak ever appears, the fix is a narrow LSan suppression with an upstream link, not a waiver. - **Required check**: after merge, someone with admin rights must mark `libevent-compat-gate` (only that job) as required. Suggested timing: after three consecutive green nightlies, given that `next` is an alpha. - **Canary pin**: the expected `2.2.2-alpha-dev` string is tied to the helper's `master_commit`. Both are commented to be bumped together. ## Affected versions CI and tooling only. No memtier runtime change beyond what #822 (TLS error guard) and #832 (RESP length bounds) carry. The runtime failure that #822 fixes affects TLS-enabled builds running on libevent ≥ 2.2.2-alpha (2.1.x tolerates the call). <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes touch connection error handling, RESP parser bounds, and a large new required CI surface; misconfiguration of the gate or parser rejections could affect TLS diagnostics or malformed-server behavior. > > **Overview** > Adds **libevent compatibility CI** and build/link tooling so memtier is exercised against pinned **2.1.12**, **2.1.13**, and **2.2.2-alpha** (plus a non-blocking **master** canary). New `scripts/build-libevent.sh` and `check-libevent-linkage.sh` install verified libevent into a private prefix; macOS CI gains **cmake** and routes `build-macos-libevent.sh` through the shared helper. The **`libevent-compat.yml`** workflow runs a scoped PR matrix (TLS on stable/next, ASan+UBSan plaintext on 2.2) with nightly/weekly expansion, cluster sharding, caching, and a single required **`libevent-compat-gate`**. > > **Runtime and test changes** in the same branch: **TLS connection errors** only call OpenSSL/libevent accessors on real TLS bufferevents, with certificate-verify fallback when libevent 2.2 reports no OpenSSL reason (`shard_connection.cpp` + new `test_connection_error_types.py`, wired into ASan/TSan/UBSan misc cells). **RESP parsing** rejects aggregate counts and bulk lengths that would overflow `int`/`long` bookkeeping (`protocol.cpp` + `check_length_limits()`). Fuzzer/reconnect tests broaden sanitizer failure detection and stderr logging on signal death. **DEVELOPMENT.md** documents the libevent matrix and local evaluation; **`.gitignore`** ignores local libevent build dirs. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit cd86f27. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> Co-Authored-By: Claude Opus 5.5 <[email protected]>
) ## Problem `--connection-stage-timeout=N` can abort after just over N − 1 seconds. The supervisor stamps the run start and the first setup failure with `tv_sec` only, and compares whole seconds. The main loop polls it once per second (`sleep(1)`). Suppose the run starts at 10.99 s and a poll lands at 12.01 s: the supervisor sees 12 − 10 = 2 seconds after 1.02 s, so a 2 s timeout trips. This makes `test_cluster_unowned_slots:test_unowned_keys_survive_repeated_redial` (from #799) flaky. It has a 2 s budget against about 1.1 s of injected server delays and backoffs. It failed in #545's `libevent-compat (legacy, plaintext, standalone)` cell: ``` Connection dropped, attempting reconnection 2/3 in 0.50 seconds... memtier_benchmark: aborting after 2 seconds of connection-stage failures (last error: no response from server during setup). Wall time: 1.010s ``` Locally it failed 3 times in 180 runs: 2 of 70 on #545, 1 of 40 on #832, and 0 of 70 on master. Every failure was this abort after about one second. Neither #545 nor #832 touches this code; the failure depends on where in the second the run starts. Deterministic reproduction (from review): start memtier at set points late in a wall-clock second, against a server that accepts and never replies, with `--connection-stage-timeout=2`. Master aborted early in 4 of 25 runs, after 1.016 s, still saying "2 seconds". With this PR none did; the fastest abort was 2.008 s. ## Fix - Stamp the run start and the failure streak in wall-clock microseconds, and compare them with the timeout in microseconds. - The comparison moves to `connection_stage_clock.h` (`connection_stage_timed_out()`), so it can be unit-tested. - The abort message still reports whole seconds. - With the once-per-second poll, an abort now lands between N and N + 1 seconds instead of between N − 1 and N. ## Tests - **New unit test** `tests/unit/connection_stage_clock_test` (`make check`): a phase that started late in a second has not timed out 1.02 s later. It times out at exactly 2 s and reports whole elapsed seconds, has no start time before the first failure, and uses timestamps far from the epoch. A mutant that compares whole seconds fails it, and so does one that converts the timeout to microseconds in 32 bits (a 5000 s case). - **Integration tests on libevent 2.1.12, ASan + UBSan.** I ran the 17 test files that use `--connection-stage-timeout` (connection setup rejection, cluster slots, unowned slots, reconnects, retries, CLI validation and others). Results are the same with and without the fix: 236 pass, and the one failure is the same pre-existing `test_memcache_meta_protocol:test_meta_unsupported_options_fail_before_connection` on both. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a summary for commit e1a6c84. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fixes #834. Since #799, a `-CLUSTERDOWN` reply makes each `cluster_client` refresh its topology with `CLUSTER SLOTS`, at most once per second. Each client keeps its own map, so `-t 8 -c 50` sent up to 400 refreshes per second for the whole outage. This takes option 1 from the issue, per-client exponential backoff: - While a client receives only `CLUSTERDOWN` replies, the gap between its refreshes doubles from 1 s to 8 s (refreshes at 0, 1, 3 and 7 s, then every 8 s). A sustained outage at `-t 8 -c 50` drops from 400 refreshes per second to 50. - A successful reply to a keyed request resets the gap to 1 s. During CLUSTERDOWN Redis still answers keyless commands (PING, MULTI, WAIT), so their replies don't reset it, and neither do other errors (`TRYAGAIN`, `LOADING`, `MASTERDOWN`) or redirects. Without this, `--transaction` runs and keyless `--command` mixes would still poll once a second. - The 1 s floor is kept, so polling is never faster than on master. - The 8 s cap means a new map is seen at most 8 s after it's published, which is less than Redis's own failure detection (`cluster-node-timeout`, 15 s by default). The decision lives in a small `clusterdown_refresh_backoff` struct in `retry_backoff.h`, next to the existing retry backoff. The README paragraph that stated the 400/s figure now states the schedule. **Tests** - `tests/unit/retry_backoff_test.cpp` gets a case for the schedule, the cap, the reset and the 1 s floor. Against master's fixed 1 s logic it fails 13 checks: a 60 s outage gives 61 refreshes instead of 10. - The scripted-peer `CLUSTERDOWN` test in `tests/test_cluster_unowned_slots.py` gets a case that counts `CLUSTER SLOTS` during a sustained `CLUSTERDOWN`, for a plain workload, `--transaction`, and a SET+PING `--command` mix. Master's logic sends 14 against a bound of 8 to 10, and so does a reset on any successful reply for the two keyless-reply workloads. With the fix it passed 4/4 runs. **Results** (Ubuntu 24.04 container, libevent 2.1.12): - `make check` passes, plain and ASan+UBSan. - `test_cluster_unowned_slots.py` passes 24/24, plain and sanitized. - With `OSS_CLUSTER=1`, 7 cluster test files pass 70/72. The 2 failures (`test_transaction_connection_kills_do_not_hang`, `test_transaction_lost_multi_is_not_continued`) fail the same way on unmodified master in this container. **Limitation (same as master):** if only some slots are down and the workload mixes keys, successful replies keep resetting the gap, so each client still refreshes about once a second. Removing that needs option 2 from the issue: one shared refresh per thread. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes cluster-mode error handling and topology refresh timing during outages; behavior is well-tested but affects all CLUSTERDOWN paths in production benchmarks. > > **Overview** > **Replaces fixed 1 s `CLUSTER SLOTS` polling on `-CLUSTERDOWN` with per-client exponential backoff (1 → 8 s)** so large `-t`/`-c` runs no longer hammer the cluster during sustained outages (#834). > > Each `cluster_client` now uses a `clusterdown_refresh_backoff` helper in `retry_backoff.h`: refresh gaps double after each `CLUSTERDOWN`-triggered topology poll until they cap at 8 s, while a **1 s floor** remains. A **successful reply to a keyed workload** resets the streak; keyless successes (`PING`, `MULTI`, monitor lines without keys, etc.) do not, via new `request_carries_key()` and `arbitrary_command::has_keys()`. README documents the revised refresh schedule. > > **Tests** add unit coverage for the backoff schedule and integration cases that bound `CLUSTER SLOTS` calls under sustained `CLUSTERDOWN`, transactions, and monitor replay. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit eb42f5e. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> Co-Authored-By: Claude Opus 5.5 <[email protected]>

Problem
A valid partial
CLUSTER SLOTSmap can leave a generated key without an owner. A request-count or timed workload targeting that hole spins without sending requests. Mixed owned/unowned keys silently skip the unowned keys and repeat others instead.Root cause
The slot map uses
UINT_MAXfor an absent owner, but generation has already advanced the key cursor before routing returnsnot_available. No request is sent or counted, so the producer's pipeline limit and response-driven clock cannot stop it. The MGET producer cache separately omits unowned slots.Fix
This also changes general primary reconnect and CLUSTERDOWN recovery behavior for fully owned maps, not only partial maps. Same-endpoint primary queue retention and the response-triggered topology refresh are described below and have separate follow-up commits and regressions.
Keep accepting partial maps. Send missing-owner writes and reads that permit primary routing to a known primary, retaining the exact key and allowing Redis to provide the routing response. MGET keeps those slots in its producer cache and uses that ready primary until the next topology/cache rebuild, preserving the producer and generated keys while other primaries finish setup. Transactions and monitor replay retain their existing primary routing. A replica seed is never used as the missing-owner write destination.
For strict
secondaryreads witherroror reservedqueuefallback, fail the run explicitly without sending to an unrelated replica or a primary. Use the normal event-loop failure/cleanup path. Missing-owner requests also fail explicitly if every primary is permanently disconnected. A primary still connecting, awaiting an armed reconnect, or awaiting the reconnect's SLOTS refresh remains eligible. Transactions park with their exact staged key while waiting.Monitor replay waits before selecting a line while all primaries are in reconnect backoff. Already-selected monitor lines and ordinary routed keys stay queued, with unchanged generated-request counts, across redials to the same initialized primary address and port, including repeated setup failures. Replica redials (including demotion), fresh/different endpoints and topology retirement keep their existing reset and compensation policy. Before a replica becomes primary, its old queued work is cleared and compensated too, including live or pending-reconnect role transitions, so strict-secondary reads cannot bypass routing on the promoted endpoint. Request identity is not guaranteed across replica redials or promotion; this preserves established strict-secondary progress on other shards when a replica remains unavailable. Primary queue preservation applies to owned and unowned work alike.
Owned monitor routing (also changes fully owned maps). An owned monitor line is now staged on its known primary whenever that primary is not disconnected, including while it is in reconnect backoff or refreshing CLUSTER SLOTS. Before, a primary whose SLOTS state was not
setup_donewas skipped and the already-selected line was sent on the producer connection, which can be a replica seed. This is the same rule ordinary routed keys already follow: the command queues on its owner and drains after the owner's setup ladder completes. Disconnected owners and the staged-queue cap keep their existing fallback.CLUSTERDOWNresponses request a topology refresh at most once per second per client without discarding staged work, including when a formerly full map becomes stale without a disconnect. Each client owns its topology:-t 8 -c 50permits up to 400 refreshes/second during sustained errors, in addition to bootstrap. A process-wide poll coordinator or recovery backoff is outside this fix. The missing-owner warning prints once per process, including across--run-countruns. The existing setup ladder waits until EXEC/DISCARD when MULTI is open. Ordinary workload-error accounting and configured retries apply.Tests
42ede4a):test_owned_monitor_waits_for_primary_refreshuses a replica seed, a CLUSTERDOWN reply from the primary and a delayed SLOTS refresh, alternating owned and unowned keys. It requires zero replica SETs, all 20 ordered values on the primary and 40 completed operations. With only the production hunk reverted, up to 19 of 20 SETs reach the replica; the pipeline-4 leg fails on every run and the pipeline-1 leg in about two thirds of runs (it depends on whether the next owned line is created before the refresh starts), so pipeline 4 is the deterministic leg.On base
43ca07691b842cdd427c7006dbf4a85dce18f3ad, the all-unowned request and timed cases hit a six-second watchdog at approximately 100% of one CPU with zero data commands. A 1,000-request sequential workload over a half-covered key range sent only 501 distinct keys. The new request-count, exact-key-sequence, MGET, and full-map removal/recovery regressions fail on that base; the owned-key control passes.With the fix:
c9ff438passed an owned Redis 8.6 two-primary cluster over both plaintext and TLS full-map and missing-slot controls: 100 SET requests and 100 MGET requests through the second primary seed each produce 100 counted CLUSTERDOWN failures; a two-second timed workload finishes; a 1,000-key sequential workload produces 999 stored keys plus exactly one failed key, preserving all 1,000 requests.c9ff438(eight-second watchdog) and a monitor line discarded across reconnect. Fixed transaction recovery completes all 24 operations with eight exact-key SETs. Fixed monitor recovery sends all ten distinct replay values plus ten PINGs, with zero writes to the replica; owned-slot replay has the same recovery control. Terminal/no-reconnect cases fail promptly instead of staging work on a permanently dead primary. The fixture delays both READONLY and the reconnect's SLOTS response to cover the timer-to-refresh transition.ec99479: after two AUTH socket closures, pipeline 1 sent nine monitor SETs with rotated values, and pipeline 4 sent seven instead of ten while replacing the rest with PINGs. Ordinary routed writes similarly skipped early keys. The final fix preserves all ten distinct monitor values plus ten PINGs, and ordinary exact keys 1..20, for owned and unowned slots after one/two setup failures. The committed controls retain pipeline 1/4 and delay the reconnect SLOTS reply. A queue-ownership unit checks fresh, same and different endpoints plus unchanged/compensated counts; another distinguishes a live seed's pending refresh from a disconnected seed. Linking againstec99479fails queue preservation; removing refresh eligibility fails the new refresh unit.ec99479, fails on53af982at 15,945/16,000 operations after the 60-second watchdog, and passes again with primary-only queue retention (all 16,000 operations, 20 seconds including harness setup). Same-endpoint replica retention had stranded counted reads on a permanently unavailable strict-secondary target. New unit controls check primary retention, replica reset, demotion, promotion, and unchanged/compensated counts; linking the new unit with the53af982production object fails the replica-reset assertion.8020ebb: with strict secondary/error, a replica closed on its first GET and was promoted by SLOTS; retained queues sent 2/8/32 reads to the new primary at pipelines 4/16/64. The committed regression fails on that head and passes after clearing the old replica queues before changing role: zero primary reads and 1,000 completed operations in each case. New units check promotion compensation before role change and preservation only for work staged after promotion; removing the promotion reset fails that unit. The exact real replica-disconnect control still completes 16,000 operations (25 seconds including harness).c9ff438fails its wait assertion.make format-check, Ruff F, andgit diff --checkpass.After normally integrating master through #810, head
c47fc40passes a clean build, all 17 unit programs, formatting, and 26 actual RLTest functions (22 missing-slot routing, 3 bounded stderr logging, and weighted aggregate latency), in 103 seconds on authenticated private Redis. The four PR implementation/test files remain byte-identical to reviewed1174655; master supplies the logging prerequisite and merged statistics/topology fixes. Initial local incremental validation used stale objects with dummy dependency files; a clean rebuild and an independent single-stale-object control confirmed and resolved that local build artifact.These are correctness and termination measurements, not a throughput comparison. The new head needs all seven focused rechecks and its own full CI. Earlier ASan/TSan timeouts are not waived; issue #482 remains open pending this CI result.
Affected versions
The missing-owner sentinel behavior was introduced by
ee757e7152a537f91861f29d272a36eabf20c3c0(#456), first released in 2.5.0; 2.5.0–2.5.2 and current master are affected. The request-count/identity regression is established against the preceding routing behavior; older timed-run liveness problems are not claimed to originate in that commit.Fixes #685
🤖 Generated with Claude Code
Note
High Risk
Changes core cluster routing, reconnect queue accounting, and failure modes across GET/MGET, transactions, monitor replay, and read-preference policies.
Overview
Cluster mode no longer stalls or drops keys when
CLUSTER SLOTSis partial or goes stale. Unowned slots route writes and primary-eligible reads to a fallback primary while keeping the generated key; strictsecondarywitherror/queuefallback fails the run instead of misrouting. MGET keeps hole slots on their producer primary until the next topology rebuild.Reconnect and queue policy is refined: same-endpoint primary redials retain staged keys, monitor lines, and request counts; replica redials, endpoint changes, and replica→primary promotion still clear unsent queues with generated-count compensation so strict-secondary reads cannot drain on a new primary.
-CLUSTERDOWNtriggers a per-client topology refresh (rate-limited to once per second) without flushing staged work. Monitor replay pauses line selection while all primaries are in reconnect backoff. README documents the behavior; large integration and unit test coverage exercises holes, MGET, transactions, monitor, retries, and promotion.Reviewed by Cursor Bugbot for commit 42ede4a. Bugbot is set up for automated code reviews on this repo. Configure here.