Skip to content

Use the replying connection for missing cluster topology hosts - #777

Merged
fcostaoliveira merged 3 commits into
masterfrom
codex/fix684-sender-host-20261017
Oct 18, 2026
Merged

fcostaoliveira merged 3 commits into
masterfrom
codex/fix684-sender-host-20261017

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

A valid CLUSTER SLOTS reply can use an empty or NULL host to mean the endpoint that received the command. memtier rejected empty hosts and interpreted RESP3 NULL as _, so these clusters sent no workload and failed setup. Replica tuples have the same problem.

Root cause

Topology parsing had no sender context and required every host to be nonempty. Primary pre-scanning, primary connection creation, and replica registration each decoded hosts separately.

Fix

Pass the actual replying connection ID into topology parsing and copy its host before changing connections. Normalize empty/RESP2 NULL/RESP3 NULL endpoints consistently across all three parsing sites, retaining the tuple's advertised port. Keep literal _, unknown ?, embedded NULs, and malformed tuples distinct from missing hosts. Preserve primary/replica role protection and existing retry/topology handling.

Tests

  • CI prerequisite: corrected the existing CPU warning test (CPU warning test treats rounded JSON as an exact threshold decision #786) to account for three-decimal JSON rounding. Deterministic boundary checks and the real threshold test pass (2/2); nine injected guard controls pass, while the original exact-count guard and three weakened-guard mutants fail their intended controls. No CPU-accounting production code changed.

  • All 15 unit programs pass; formatting checks pass.

  • Seven focused endpoint tests pass. Five regression tests fail on the pre-fix 563f372 binary (whose cluster_client.cpp blob matches base cae16bf), while the malformed-host control passes before and after. The final hostname-seed test additionally verifies one AUTH across empty-to-explicit endpoint refresh.

  • RLTest: 40/40 pass across the endpoint, malformed/empty topology, and rejected connection-setup suites (before adding the seventh DNS-seed test, which also passes separately).

  • Real Redis 8.6 single-node cluster, plaintext and TLS, RESP2 and RESP3: empty, NULL, and explicit-host cases each complete exactly 10 server-observed SETs and JSON Sets.Count=10; ? cases fail within the 3-second setup deadline with zero SETs. Before the fix, empty/NULL cases send zero SETs and fail setup.

  • Non-seed primary and replica refresh tests use 127.0.0.2 and a different target port. Mutating the fallback to the seed host makes the target-count assertion fail. Removing normalization from the primary pre-scan makes the role-preservation test fail.

Endpoint policy follows the Redis CLUSTER SLOTS documentation. Seven independent reviews passed on the cluster-routing implementation. The final head adds only the prerequisite CPU test correction described above; focused review and new-head CI are pending.

Affected versions

Empty-host rejection is present in 2.4.0–2.5.2 and master, introduced by 39fc971 (#425). Replica validation arrived in 2.5.0 via #456. Earlier code copied the empty string without sender fallback; earlier working behavior is not established.

The CPU test rounding mismatch (#786) is present in source releases 2.5.0–2.5.2 and master, introduced with 4ebfa71 (#471). It is a test-suite false failure; this PR does not change production CPU accounting.

Fixes #684
Fixes #786

🤖 Generated with Claude Code


Note

Medium Risk
Changes cluster bootstrap and refresh routing for empty/NULL advertised hosts; incorrect fallback logic could mis-dial nodes or skip valid shards, though behavior is guarded by tests and explicit rejection of ambiguous hosts.

Overview
CLUSTER SLOTS topology parsing now follows Redis semantics for missing node hosts: empty bulk strings and RESP2/RESP3 NULL hosts are normalized to the replying connection’s address, while still using each tuple’s advertised port. Unknown or invalid hosts (?, embedded NULs, malformed tuples) are rejected instead of being treated as missing.

handle_cluster_slots takes conn_id so the parser can snapshot the sender host before mutating connections; primary pre-scan, primary dial, and replica registration all share a new cluster_slots_host helper.

Integration tests cover empty/null primary and replica hosts, mid-run refresh from a non-seed sender, role preservation when aliases normalize to the same endpoint, and hostname seed reuse across host forms. The cluster mock harness gains bind-address flexibility and MOVED replies that use the target’s real address.

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

@github-actions

github-actions Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

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

Thanks for this. The fix itself looks right to me. Taking the sender host from the replying connection's get_address() before any topology changes, and keeping the tuple's own port, matches the CLUSTER SLOTS semantics. Moving all three parse sites onto one cluster_slots_host() helper is a good cleanup. The new test_cluster_slots_endpoints.py also covers the cases I'd worry about: the non-seed sender on 127.0.0.2, the replica refresh path, and the role-preservation alias. Two small things:

  • With ? now rejected on purpose, the old separate warnings ("empty host/port", "host contains NUL") are folded into one generic "invalid host/port". A user running with cluster-preferred-endpoint-type hostname and no hostname configured will get ? back. "invalid host/port" doesn't say much about why. I wonder if it's worth keeping the reason in the message (e.g. "unknown endpoint '?'" vs "empty port" vs "host contains NUL"). It's a cheap change and would save someone some debugging. Not blocking.
  • Just checking: was the test_cpu_stats.py rounding change meant to ship in this PR? It looks unrelated to Cluster mode rejects a CLUSTER SLOTS entry with an empty host (node that doesn't know its own IP) instead of using the connection's endpoint #684. I'm guessing it flaked on this branch's CI. If it's a standalone fix, a separate PR would keep the history easier to read and make it easier to cherry-pick onto a release branch. That's your call.

Nitpicking: the comment on cluster_slots_host() says empty endpoints "may" use the same fallback. Maybe point to the Redis doc wording there, so the next reader knows why empty and NULL get the same treatment.

The core change looks good to me. A second look from whoever owns cluster routing would still be good, since this touches bootstrap and refresh dialing.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

The validation is complete and the PR body now has the measured results: 15 unit programs, 40 existing/focused RLTest cases, all seven final endpoint tests, and real Redis plaintext/TLS RESP2/RESP3 controls pass. Both targeted mutations fail their intended tests.

On the address question: bootstrap client::connect() converts the resolved sockaddr to a numeric address before calling set_address_port(). The new hostname-seed test starts with --server=localhost --ipv4, gets an empty self-endpoint, then refreshes to explicit 127.0.0.1; it completes the exact JSON count with only one AUTH, so the same connection is reused. Discovered nodes retain their advertised host string, as before; canonicalizing arbitrary DNS-name/IP aliases throughout topology identity would be a separate change. The fallback uses the actual replying connection's stored endpoint, not the configured seed.

The 127.0.0.2 tests now skip only when that address family/address cannot be bound; other socket errors still fail. The invalid sender-ID path is defensive (the caller passes its own ID) and uses the existing rejected-topology retry path, covered by the malformed-reply tests. I kept the helper small and the combined invalid-host warning for now; more detailed reason-specific diagnostics are a reasonable separate improvement.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Following the edited review: the empty-host ASK case is not harmless. Independent paired controls on base cae16bf and this head show explicit-host ASK reaches the target with 20 ASKING/20 successful SET and no failed keys; empty-host ASK sends 60 attempts back to the source, zero target commands and 20 failed-key rows at max-retries2. Filed #780 separately: this redirect helper is unchanged by this PR. MOVED shares the parser but was not separately runtime-reproduced in that report.

Cluster mode with a Unix socket is already rejected by verify_cluster_option before connecting; the independent CLI control exits2. The null TCP sender case therefore is not a supported cluster CLI path.

The hostname-seed behavior is intentional: client::connect stores the numeric connected address before set_address_port. The DNS-seed regression verifies one AUTH across empty-to-explicit refresh; discovered hostname aliases keep their previous behavior. The generic invalid-host diagnostic is less specific, but still identifies the shard/replica and does not echo malformed bytes; that diagnostic refinement remains a nonblocking nit.

Independent SEM, BUILD, OUT, LIFE and INTER reviews have passed. TEST/MAINT and final CI remain gates.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

The ASAN TCP plaintext failure on 7f1ca3b is an existing CPU-test precision mismatch: the runtime compares an unrounded double, while JSON rounds per-thread cores_used to three decimals. A valid raw value such as 1.0001 warns at 100% but serializes as 1.000, so the old exact-count assertion rejects it. Filed #786 with the source-version history (2.5.0–2.5.2/master).

The test-only follow-up eb36131 now bounds the warning count by the ±0.0005-core interval implied by JSON formatting. Definitely below/above-threshold results still require silence/warnings, and duplicate warnings still fail. The real private-Redis threshold test and deterministic boundary test pass. Nine injected checks of the actual assertion pass; restoring the old exact comparison or removing either bound fails the intended controls. Production CPU accounting and the reviewed topology implementation are unchanged.

All seven independent reviews of the topology fix are complete. Focused review of this test delta and CI on the new head remain gates. The earlier replies still cover the routing questions and the separate empty-ASK issue #780.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Yes, the CPU test correction is an intentional prerequisite after this branch’s otherwise completed CI failed that existing assertion. It is isolated in its own commit eb36131 and tracked by #786, so it can be reviewed or cherry-picked independently. The raw-double/three-decimal boundary is reproduced deterministically; the original guard fails and the interval guard preserves definite warning/silence checks. No production CPU code changed. Focused independent TEST/MAINT review and the new-head CI are still required.

The unknown-host diagnostic and comment wording are nonblocking refinements. For this fix I kept the existing shard/replica context and generic rejection without echoing malformed bytes. The PR links the Redis CLUSTER SLOTS endpoint documentation; empty and NULL use the actual sender, while ? remains unknown and rejected. All seven independent reviews of the routing change have completed.

@fcostaoliveira
fcostaoliveira merged commit f60bead into master Oct 18, 2026
132 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
… 2.2.2-alpha (#545)

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

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

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

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

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

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

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

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

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


<!-- CURSOR_SUMMARY -->
---

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



Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant