Skip to content

Restore parser value policy after cluster topology refreshes - #797

Merged
fcostaoliveira merged 2 commits into
masterfrom
codex/fix653-refresh-retention-20261023
Oct 23, 2026
Merged

fcostaoliveira merged 2 commits into
masterfrom
codex/fix653-refresh-retention-20261023

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 23, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

After a connection drops during CLUSTER SLOTS, a non-main shard reconnects with parser value retention still enabled. Later bulk/array responses incur allocations and payload copies that the workload does not use.

Root cause

Topology discovery temporarily enables keep_value, but disconnect resets parser state without restoring that policy. Completion also resets the policy to a hard false, losing a caller's pre-existing true setting.

Fix

Save the parser policy when CLUSTER SLOTS is sent and restore it on success, rejection or disconnect. Restoration is idempotent when the topology callback itself disconnects the connection. Incremental SCAN and verification retain their original value policy. No CLI or output schema changes.

Tests

  • New unit test drives real loopback connections, setup commands and parser callbacks: 14 cases, each with two refresh cycles. Covers drops before/during a reply, empty/error/rejected/accepted replies, disconnect inside the topology callback, repeated disconnect, non-main reconnect, and both prior policies. Checks actual 64 KiB bulk/array materialization. Fails on base 4bade81, passes with the fix.
  • All 17 make check programs and formatting pass locally. Five existing scripted cluster refresh/error/overlap controls and four authenticated Redis SCAN/verification controls also pass.
  • Paired parser instrumentation on base 4bade81 and the fix: after either refresh-drop scenario, 64 bulk replies plus 32 two-element arrays cause 128 payload allocations / 8,388,608 copied bytes before, 0 / 0 after. The disabled-policy control remains 0 / 0. This measures allocation/copy work, not throughput or client CPU; no end-to-end performance improvement is claimed.
  • The baseline unit harness uses test-only access to the existing policy member; baseline production sources and objects are unchanged. The allocation probe drives deterministic setup/parser transitions and does not claim a live Redis failover benchmark.

Affected versions

Introduced by 891df95ccfef156dc54fb9b40bcad32dff583070 (#67). git tag --contains identifies 1.2.16 through 2.5.2, plus unreleased master. Release coverage is derived from history; runtime comparisons here use master 4bade818c3642e1771a34e2faddb3fcc9b96c956. #667 already corrected the empty/error reply's hard-false cleanup but did not restore the original policy or cover interrupted refreshes.

Fixes #653

🤖 Generated with Claude Code


Note

Medium Risk
Touches cluster connection setup and parser policy on disconnect/reconnect paths; behavior change is localized but affects all cluster-mode Redis connections during topology refresh.

Overview
Fixes parser value retention (keep_value) leaking across CLUSTER SLOTS topology refreshes. Sending the slot map still turns retention on temporarily, but the connection now saves the prior policy and restores it when the refresh finishes (success or rejection), fails (empty/error reply), or the socket disconnects—including when the topology callback disconnects mid-reply. That replaces always forcing keep_value off after a parsed reply, so verification and incremental SCAN callers that already had retention enabled keep their setting.

Adds abstract_protocol::get_keep_value(), override state on shard_connection, and restore_cluster_slots_value_policy() (idempotent on repeated disconnect). New unit test cluster_slots_retention_test drives real loopback setup, multiple refresh outcomes, and checks 64 KiB bulk/array materialization—not just the policy bit.

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

@github-actions

Copy link
Copy Markdown

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

Thanks for this. The production change is small, and I think the save/restore is right. I checked whether the override can be armed twice, which would overwrite the saved value with true. It can't: send_conn_setup_commands only sends CLUSTER SLOTS from setup_none, set_cluster_slots() leaves setup_sent alone, and the retry path restores before cluster_slots_retry_cb re-arms. The two callers that set keep_value(true) on their own (SCAN incremental in the client ctor, and verify_client) both do it at construction time, before any refresh can be in flight, so the saved value will be theirs.

The regression test matches the bar set in #364: it fails on base, passes with the fix, and drives real parser materialization rather than only checking the policy bit.

Nitpicking: in cluster_slots_retention_test.cpp, path is a bare 0..6 int with meanings like path == 4 → reject and path == 6 → disconnect in callback. A small enum, or named constants, would make the case list readable without reverse-engineering the ternaries on line 380.

Looks good to me otherwise.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks for checking the setup-state and caller-policy paths. The final test follow-up also covers disconnect before any refresh and a caller changing its retention policy after the override has been released. It checks actual bulk/array materialization; deleting the inactive guard or failing to clear the active flag now fails the committed test. The production change is unchanged.

I agree named cases would make the local fixture easier to scan. I have kept that as a nonblocking readability nit here: the seven scenarios are documented at the case loop, and the explicit policy/output assertions exercise each path. No CLI or output-schema change is introduced, and the allocation measurements are not presented as throughput measurements.

@fcostaoliveira
fcostaoliveira merged commit cd43101 into master Oct 23, 2026
136 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

Development

Successfully merging this pull request may close these issues.

Cluster: a connection that drops while its CLUSTER SLOTS refresh is in flight keeps set_keep_value(true) after reconnecting (copies every reply value)

1 participant