Repository navigation
Add libevent build helper and compatibility CI for 2.1.12, 2.1.13 and 2.2.2-alpha - #545
Conversation
|
🤖 Automated first-pass review. A human maintainer still needs to review this before merge. Thanks for this. I've read the workflow and the two scripts. The
The harness itself looks careful to me: pinned sha256s, an empty-prefix guard, linkage checks with negative cases exercised, and stable job names. Once the gate/ |
|
Addressed in b3985ac:
On the read limit: no new memtier API call is needed. In 2.2.2, bufferevent_ratelim_init_ initializes max_single_read from MAX_SINGLE_READ_DEFAULT (16384) and immediately passes it to evbuffer_set_max_read on the input buffer. The 2.1.x inner evbuffer clamp is what prevents its nominal 16 KiB bufferevent limit from taking effect. The source review and Linux syscall preflight confirm 16 KiB plaintext reads with the alpha library. Platforms without FIONREAD have a separate fallback, so this is not an all-platform performance claim. One additional measurement detail: alpha uses read() for a single iovec, while stable uses readv(). The diagnostic now accounts for both and verifies every response byte. The timed comparison will report whole-release changes; it will not attribute the entire difference to the read cap alone. Local cluster runs and the timed comparison are still in progress, and the expanded CI is running on the new head. |
|
The two affected macOS jobs passed on b3985ac, including executable startup and the existing linkage checks: Libevent's APPLE target configuration explicitly sets INSTALL_NAME_DIR to the installation prefix's lib directory, so the generic CMake @rpath default does not apply here. No additional loader workaround is needed. Added tests/run_tests.sh, tests/test_requirements.txt, and tests/gen-test-certs.sh to both path filters in 0e4c622. The PR description now explicitly distinguishes the full integration suites in CI from the focused local ASan/UBSan runs. All four local default-build integration configurations (standalone/cluster × plaintext/TLS) have passed; minimal-build runs and the timed comparison are still progressing. CI is running again on the latest head; I canceled superseded in-progress runs to avoid duplicating their work. |
|
Addressed the stable-selection safeguard in 709dab0: the existing macOS wrapper explicitly sets The affected macOS jobs also passed on 0e4c622: OpenSSL 1.1 and OpenSSL 3.0. Libevent explicitly sets an absolute Apple INSTALL_NAME_DIR. This evidence is now in the PR description as well. All six local integration configurations and both focused sanitizer runs passed: 594 passed, 234 skipped, zero failures in total. Upstream alpha CTest passed 84/84. CI is rerunning for the final one-line safeguard. |
|
Thanks; these are intentional scope choices:
The completed diagnostic accounts for exactly 10,330,005 response bytes in each of four traces. At P16, stable made 2,526 positive socket reads (max 4,096 bytes) and alpha made 913 (max 16,384 bytes); P1 used 10,001 calls for both. Alpha uses read() for a single iovec, so both read and readv were counted. An independent reviewer reparsed the raw traces and all 24 untraced performance samples. Rising shared-host load makes the numerical throughput deltas inconclusive; the read-size/path observation itself is verified. The result supports an opt-in evaluation path, not a promised speedup or default dependency upgrade. |
|
Additional dependency-instrumented validation found a real compatibility defect and changed the scope. Fixed in 05a8415:
After the fix, instrumented plaintext and TLS suites each passed 40 tests, with one expected skip and no sanitizer findings. All six local build configurations rebuilt and passed unit tests. Both independent reviewers approved the fix/tests/workflow. Final-head CI is running; merge remains gated on its result. |
|
Addressing the latest review:
Restoring the unrelated trailing blank line. The OpenSSL@3 documentation selection stays because it aligns the optional macOS build recipe with the selected CI OpenSSL. The small test/documentation follow-up passed all six local regression configurations (10 passes, two TLS-disabled skips), and the original binary again produced the expected ASan failure. It is pushed; production code is unchanged from 05a8415. Independent review approved the timing and capability-probe changes. |
|
Settling the remaining scope choices for this PR:
No further code change is needed for these decisions. Both independent implementation reviewers approve the current outcome. Waiting for all final-head checks before merge. |
A TLS-enabled build called bufferevent_get_openssl_error() on every connection error, including plaintext connections. libevent 2.2.2-alpha only asserts the bufferevent type there (upstream 2f27523e): a debug build aborts and a release build reads and writes past the plain socket bufferevent. Query it only when the connection was created with the OpenSSL context, the same predicate setup_event() uses. The same libevent release drains the OpenSSL queue into the bufferevent but its accessor returns nothing for a TLS bufferevent, so TLS failures were silent. When no reason is returned, report a failed certificate verification from the SSL object, and otherwise say that libevent >= 2.2 reported no OpenSSL reason. libevent 2.1 still returns the queued reasons, so its output is unchanged. Add regressions for a refused plaintext connection, a rejected handshake and an untrusted server certificate. Refs #545 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve ci.yml (master's macOS lines plus cmake for the helper; libtool stays removed, see #762), DEVELOPMENT.md (master's macOS sections, keep the libevent section) and scripts/build-macos-libevent.sh (clean the prefix as in #674, then build through scripts/build-libevent.sh with debug mode disabled). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Take #822's shard_connection.cpp and tests/test_connection_error_types.py verbatim so whichever PR lands first, the other merges cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
scripts/build-libevent.sh now pins 2.1.12-stable, 2.1.13-stable and 2.2.2-alpha by release-asset sha256 and libevent master by commit, rejects a non-empty prefix before creating it, and can build libevent with ASan+UBSan (LIBEVENT_FLAVOUR=sanitize). --source-id feeds the cache key. scripts/check-libevent-linkage.sh proves what a Linux build runs with: the --version libevent field equals the expected string, the prefix's pkg-config files are the same release, every libevent library loaded (directly or transitively) comes from the prefix, libevent_openssl and memtier share one libssl, and the openssl=/prometheus= fields are as intended. macOS delegates to check-macos-tls-links.sh. libevent-compat.yml drops its path filters, which made it unusable as a required check, and uses ci.yml's triggers plus a nightly and weekly schedule. A plan job picks the cells: every PR runs 2.1.13 and 2.2.2 TLS standalone/cluster suites, 2.2.2 plaintext suites with memtier and libevent both under ASan+UBSan (the cell that catches the #822 regression), and a 2.2.2 --disable-tls build with make check. Nightly, and PRs that change this harness, add 2.1.12, the remaining plaintext and no-TLS cells and macOS with OpenSSL 3 and 4. A weekly canary builds libevent master and may fail. Job names carry the track, not the version; libevent-compat-gate is the one check to require. Built libevent is cached by version, checksum, flavour, OpenSSL, compiler and helper hash. Redis comes from packages.redis.io as in ci.yml. tests/test_reconnections.py prints memtier's stderr (from the first sanitizer report) whenever memtier dies from a signal, so an abort in the cluster reconnect test is diagnosable from the CI log. DEVELOPMENT.md documents the tested matrix, local evaluation, the 4 KiB (2.1) vs 16 KiB (2.2) read size (Refs #535) and the TLS error messages memtier prints on 2.2. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-ups to the libevent 2.2 guard: - libevent also queues the SSL_get_error() code of the failed call, e.g. SSL_ERROR_SYSCALL. It is not an OpenSSL error code, has no reason string, and was printed as "TLS connection error: (null)" (passing NULL to %s). On a refused TLS connection it also suppressed "Connection refused". Skip these codes; the socket error and the queued OpenSSL errors report the failure. Fall back to ERR_error_string_n() for a reason-less code. - Print "reported no OpenSSL reason" only when there is no socket error either, so refused, reset and closed TLS connections are reported as the socket errors they are. This also removes the libevent version check. - Read the socket error before logging anything. - Test --tls-skip-verify failures, refused TLS connections, and run the file in the sanitizer TLS cells. Refs #545 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-ups to the libevent 2.2 guard: - libevent also queues the SSL_get_error() code of the failed call, e.g. SSL_ERROR_SYSCALL. It is not an OpenSSL error code, has no reason string, and was printed as "TLS connection error: (null)" (passing NULL to %s). On a refused TLS connection it also suppressed "Connection refused". Skip these codes; the socket error and the queued OpenSSL errors report the failure. Fall back to ERR_error_string_n() for a reason-less code. - Print "reported no OpenSSL reason" only when there is no socket error either, so refused, reset and closed TLS connections are reported as the socket errors they are. This also removes the libevent version check. - Read the socket error before logging anything. - Test --tls-skip-verify failures, refused TLS connections, and run the file in the sanitizer TLS cells. Refs #545 Co-Authored-By: Claude Opus 5.5 <[email protected]>
libevent 2.2's CMake leaves INSTALL_NAME_DIR unset, so its dylibs are @rpath/ names that check-macos-tls-links.sh rightly rejects: dyld may then load a libevent from any rpath entry. 2.1 sets the absolute prefix itself; set it for every version. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-222-opt-in Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he full grid - #822's TLS fallback depends most on libevent 2.2 internals; run it against an ASan+UBSan libevent in a nightly 'next, tls-asan, standalone' cell. - The cluster cells depend on utils/select_test_shard.py and utils/check_test_shards.py, so a PR changing them runs the full grid. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Pushed 3a20b86, and merged master and #832 (a7fe64f) back in. #832's
|
…ire the gate - 2.2's TLS do_read() keeps calling SSL_read() until 16 KiB or the socket is drained, unlike 2.1's one record per event. - List the nightly sanitized TLS cell, and write down the intended timing for making libevent-compat-gate required. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Pushed 659efb7:
Also fixed after an independent review: 2.2's TLS On 3a20b86, |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks.
|
…-222-opt-in Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 48b91bb. Configure here.
|
Thanks.
|
The integration cells ran a bare pip install of tests/test_requirements.txt. RLTest is pinned to a git commit and pip's --retries does not cover git, so a transient clone failure failed the cell. Use utils/install_test_requirements.sh, as ci.yml and the sanitizer workflows do, and treat it as part of the harness so a change to it runs the full grid. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. On the gate question, I tested it rather than guessing. Gate vs. canary. I ran a probe workflow on my fork with this file's exact structure: a matrix job with
So a broken canary shows as a red canary job (plus the step-summary warning and the Per-PR cost and Diff after #822 and #832 land. Will do. Right now the sanitizer |
Master now routes CI apt installs through utils/apt_install.sh (#868), which drops the runner's packages.microsoft.com source and retries update and install. The compat cells were left on bare apt-get, so a 403 from that source would fail them before building. Use the helper for the build dependencies and Redis, and add it to the harness regex. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Taking the new points first. macOS CMake build: deliberate.
Evidence from
Gate vs. canary. I tested this with probes on my fork in the previous reply, which this edit may not have seen:
The real
|
## Problem
With libevent **2.2.2-alpha** (released 2026-07-01, the current 2.2 release), a TLS-enabled memtier:
1. **Corrupts memory on a plaintext connection error.** Any `BEV_EVENT_ERROR`, for example a refused connection, calls `bufferevent_get_openssl_error()` on the plain socket bufferevent. With an instrumented libevent:
```
ERROR: AddressSanitizer: heap-buffer-overflow ... READ of size 1
#0 bufferevent_get_ssl_error bufferevent_ssl.c:1108
#1 shard_connection::handle_event(short) shard_connection.cpp:2073
0x... is located 68 bytes after 616-byte region ... allocated by bufferevent_socket_new
```
A libevent built without `NDEBUG` aborts in `EVUTIL_ASSERT` instead.
2. **Fails TLS connections silently.** A rejected handshake or an untrusted server certificate prints only `Connection error, attempting reconnection…`, with no reason.
With libevent **2.1** (what distributions ship), the same error loop prints `TLS connection error: (null)`. It passes NULL to `%s`, which glibc renders and other C libraries need not. On a refused `--tls` connection that line replaces `Connection error: Connection refused`.
## Root cause
- Upstream [2f27523e](libevent/libevent@2f27523e) ("bufferevent_ssl: do not return NULL from upcast") made `bufferevent_ssl_upcast()` only assert the type, and `bufferevent_get_ssl_error()` gained an inverted check (`if (BEV_IS_SSL(bev)) return err;`). The check is still on libevent master d82464a2.
- For a plain bufferevent, the accessor reads and decrements past the object.
- For a TLS bufferevent, it always returns 0. libevent has already drained the thread's OpenSSL queue into its own per-connection array, so `ERR_get_error()` cannot recover the reasons either.
- memtier called the accessor unconditionally in TLS builds, ever since TLS support (53353b8).
- libevent queues the `SSL_get_error()` result of the failed call (`SSL_ERROR_SYSCALL`, `SSL_ERROR_SSL`) next to the real OpenSSL error codes (`conn_closed()` in 2.1 and 2.2). memtier printed those as OpenSSL errors; they have no reason string, which is the `(null)`.
## Fix
- Query the accessor only when `m_config->openssl_ctx` is set. That is the same condition `setup_event()` uses before creating the OpenSSL bufferevent.
- Skip the queued `SSL_get_error()` codes (`ERR_GET_LIB() == 0`). If a real code has no reason string, use `ERR_error_string_n()`.
- When a TLS connection reports no OpenSSL reason:
- If the certificate check ran (that is, without `--tls-skip-verify`) and failed, report `certificate verify failed: <X509 reason>` from `SSL_get_verify_result()`.
- Otherwise, if there is no socket error either, print `TLS connection error: no OpenSSL reason reported (libevent <version>)`.
- Otherwise, print the existing `Connection error: <socket error>`.
- Read the socket error before logging anything; the Windows deferred-refusal path sets it.
Output on libevent 2.1:
| Case | Before | After |
|---|---|---|
| Real OpenSSL reasons (handshake failure, certificate rejected) | the reasons, plus a trailing `TLS connection error: (null)` | the same reasons, no `(null)` line |
| Refused or reset `--tls` connection | `TLS connection error: (null)` | `Connection error: Connection refused` (or reset, broken pipe…) |
| Peer closes during the handshake (no socket error) | `TLS connection error: (null)` | the OpenSSL reason if any (e.g. `unexpected eof while reading`), else `no OpenSSL reason reported` |
| Plaintext connections | unchanged | unchanged |
## Tests
New `tests/test_connection_error_types.py`. The first and third cases are based on #545.
| Test | Asserts |
|---|---|
| `test_plaintext_connection_refused` | A TLS-enabled binary handles a refused plain connection, with no TLS error and no sanitizer report |
| `test_tls_connection_refused` | A refused `--tls` connection reports `Connection error: Connection refused`: no `(null)` and no `no OpenSSL reason reported` line |
| `test_tls_handshake_failure` | An HTTP reply to the ClientHello is reported as `TLS connection error:` and reconnected |
| `test_tls_certificate_verify_failure` | The suite's CA-signed certificate without `--cacert` is reported as `certificate verify failed` |
| `test_tls_skip_verify_failure_not_blamed_on_certificate` | With `--tls-skip-verify`, a handshake rejected for a missing client certificate is not blamed on the certificate |
The file is also added to the TLS "misc" lists in the ASan, UBSan and TSan workflows.
Ubuntu 24.04, OpenSSL 3.0.13, `TLS=1` standalone:
| libevent | master d8d4e9f | this PR |
|---|---|---|
| 2.1.12 (distro) | `test_tls_connection_refused` fails (`(null)`, no `Connection refused`) | 5/5 pass |
| 2.2.2-alpha Release | handshake, certificate and skip-verify tests fail (no reason printed) | 5/5 pass |
| 2.2.2-alpha, libevent and memtier ASan+UBSan | **heap-buffer-overflow** above | 5/5 pass, no sanitizer output |
- On 2.1.12 TLS: `test_sigpipe_tls_rst.py`, `test_tls_logging.py`, `test_reconnections.py` and this file give 40/40.
- `make check` passes on 2.1.12 and 2.2.2. `clang-format` 18 passes. The new file passed 25 consecutive runs on each of 2.1.12 and 2.2.2.
- The libevent 2.2 cells that exercise this in CI come with the compatibility work in #545.
## Affected versions
- Introduced in 53353b8 ("Initial TLS support", 2019-08-16), present from 1.3.0 through 2.5.2 and on master.
- The memory error and the silent TLS failures need libevent ≥ 2.2.2-alpha (upstream 2f27523e; 2.2.1-alpha still returned NULL).
- The `(null)` line and the missing `Connection refused` affect every libevent version before 2.2.2 (2.1.x, 2.2.1-alpha).
Refs #545, #535
<!-- CURSOR_SUMMARY -->
---
> [!NOTE]
> **Medium Risk**
> Changes core reconnect/error logging on every failed connection in TLS builds; behavior is well-covered by new integration tests and sanitizer CI, but mistakes could misclassify errors or skip reporting.
>
> **Overview**
> Fixes **connection error reporting** on `BEV_EVENT_ERROR` so TLS builds no longer call libevent’s OpenSSL error APIs on plain socket bufferevents (avoids ASan heap overflows / asserts on libevent 2.2.2) and produce clearer logs across libevent 2.1 and 2.2.
>
> In `shard_connection.cpp`, the handler now snapshots the socket errno first, only drains OpenSSL errors when `openssl_ctx` is set (real TLS connections), skips queued `SSL_get_error` pseudo-codes, falls back to `SSL_get_verify_result()` for certificate failures when libevent returns no reason, and prefers `Connection error: …` for transport failures such as connection refused.
>
> Adds **`tests/test_connection_error_types.py`** (plaintext refused, TLS refused, bad handshake, cert verify, `--tls-skip-verify` behavior) and wires it into the ASan/TSan/UBSan TLS “misc” matrix jobs. **`test_reconnections.py`** docstring is updated to match the new TLS vs socket error logging.
>
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit cba1fcc. 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 `redis_protocol::parse_response()` does signed arithmetic on lengths and counts that come from the server. An oversized value makes that arithmetic overflow, which is undefined behaviour (#831): - `$9223372036854775807` (and `$99999999999999999999`, which `strtol` clamps to `LONG_MAX`): `m_bulk_len + 2` overflows `long` in `rs_read_bulk` (`protocol.cpp:864`). The same happens for RESP3 `!` and `=`. - RESP3 `%1073741824` / `|1073741824`: `count *= 2` overflows `int` (`protocol.cpp:723`). - With per-element miss tracking, nested counts such as `*2\r\n*2147483646\r\n*3\r\n` overflow `m_nested_remaining` (`protocol.cpp:747`). So does a nested RESP3 attribute followed by a large count, e.g. `*1\r\n*2\r\n|0\r\n*2147483647\r\n`: the `|` takes a parent slot without being tracked. - Not UB, but wrong: a count above `INT_MAX` is truncated when stored in `int`, so `*2147483648` is read as a null array. The existing fixture `bulk_int_overflow.bin` reaches the first case. `test_bulk_int_overflow` still passed under `ubsan.yml` because `halt_on_error=1` without `abort_on_error` makes UBSan exit 1 after printing only `runtime error:`. The harness checks only for negative exit codes and a set of stderr needles that did not include that string. #545's libevent CI aborts on UBSan and failed on it with `exit_code=-6`. ## Root cause - 84c922a (#134) changed `m_bulk_len` from `unsigned int` to a `long` read with `strtol`. Nothing bounds it, so `m_bulk_len + 2` can overflow. - 1d5ac99 (#182) added the map/attribute doubling on an unbounded `int`. - 61a261b (#472) added the `int` nested-element bookkeeping. ## Fix - Bulk/blob: the length is parsed into a local first. If it is above `LONG_MAX - 2`, the parser returns the existing protocol error (`-1`, "error: response parsing failed.") without changing any parser state, and `line` is freed. Where `long` is 32 bits (LLP64, e.g. MSYS2/Windows), lengths above 2^31 - 3 are now rejected; before, they overflowed (UB) or waited forever. - Aggregates: the count is parsed with `strtoll`, because `long` is 32 bits on Windows. Negative values are clamped as before. The parser then rejects the aggregate if its elements (doubled for `%`/`|`), plus the elements still outstanding, would exceed `INT_MAX`. A nested aggregate counts as one outstanding slot of its parent. When miss tracking is recording a nested element, the bound also uses `m_nested_remaining - 1`, because a nested attribute can leave `m_nested_remaining` larger than the outstanding count. This keeps `m_total_bulks_count`, `m_nested_remaining` and the doubling within `int`. - Valid lengths and counts behave exactly as before. That includes `$-1`, `$0`, other negative lengths, `*-1`, and counts up to `INT_MAX`. - `tests/test_resp_response_fuzzer.py`: add `runtime error:` and `LeakSanitizer` to the crash needles. UBSan is now caught whatever `abort_on_error` is set to. The fixture README is updated to match. ## Tests - New `check_length_limits()` in `tests/unit/redis_protocol_test.cpp`. It covers the boundaries (LONG_MAX, LONG_MAX-1 and out-of-range bulk lengths are rejected, LONG_MAX-2 waits for data; INT_MAX vs INT_MAX+1 arrays; INT_MAX/2 vs INT_MAX/2+1 maps and attributes; maps nested under outstanding elements; nested outstanding at INT_MAX vs above it; the nested-attribute tracking case at and above the bound). It also checks that ordinary bulk, empty, null, map and nested replies still parse. - Before (master `protocol.cpp` with the new tests), Ubuntu 24.04 / GCC 13 / system libevent: - normal build: `redis_protocol_test` reports 14 `FAIL` lines. - UBSan build: `runtime error` at `protocol.cpp:864:80` (`9223372036854775807 + 2`), `:723:27` (`1073741824 * 2`) and `:747:48` (`2147483646 + 2`). - `test_resp_response_fuzzer.py` with the CI `UBSAN_OPTIONS`: `test_bulk_int_overflow` FAIL, `needle 'runtime error:' exit_code=1`. With `abort_on_error=1`: FAIL, `exit_code=-6`. - After: - `make check`: 18/18 in both the normal and the ASan+UBSan (`detect_leaks=1`, `abort_on_error=1`) builds. - `test_resp_response_fuzzer.py`: 12/12 in the normal build, in ASan+UBSan with the CI UBSan options, and in ASan+UBSan with `abort_on_error=1` (`ASAN_OPTIONS=detect_leaks=1:abort_on_error=1` throughout). - The bulk boundaries in the unit test are built from `LONG_MAX` at run time, so the test also holds where `long` is 32 bits (MSYS2 UCRT64). - `clang-format` 18 `--dry-run --Werror` is clean. **Unrelated CI failure:** `TSAN OSS-CLUSTER API: TCP TLS (misc)` fails on 3b65721 and on the current head a92655a in `test_crash_handler_integration:test_crash_handler_time_zone_lock_held` (watchdog exit -14, missing BUG REPORT END). This is the known TSan crash-tail failure, tracked by #412 and targeted by #828. This PR does not touch the crash handler. ## Release notes Behaviour change: an aggregate count above what the parser can represent (e.g. `*2147483648`, which used to be truncated and read as a null array) and a bulk length above `LONG_MAX - 2` are now protocol errors (`response parsing failed`). No real server sends these. ## Affected versions - Bulk length overflow: 84c922a, every tag from 1.4.0 through 2.5.2 (not 1.3.0). - Map/attribute doubling: 1d5ac99, 1.4.0 through 2.5.2. - Nested miss-tracking overflow: 61a261b, 2.5.0 through 2.5.2. Fixes #831 <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes core RESP parsing on every connection; malformed oversized frames now error out instead of UB, but legitimate traffic within prior limits is unchanged. > > **Overview** > Hardens the Redis RESP parser in `parse_response` so malicious or oversized wire values cannot trigger integer overflow (UB) or silent truncation. > > **Bulk/blob lengths** (`$`, `!`, `=`) are validated before updating parser state: if `strtol` yields a length above `LONG_MAX - 2`, parsing fails with `-1` instead of overflowing `m_bulk_len + 2` in the bulk-read path. > > **Aggregate counts** (`*`, `%`, `|`, etc.) are read with `strtoll` (for 32-bit `long` on Windows), negative counts are still treated as zero, and counts are rejected when declared elements (×2 for maps/attributes) plus outstanding/nested miss-tracking slots would exceed `INT_MAX`. Valid replies behave as before. > > **Tests/docs:** adds `check_length_limits()` unit coverage for boundary cases; extends the RESP fuzz harness crash needles (`runtime error:`, `LeakSanitizer`) and updates fixture README expectations. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit a7fe64f. 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]>
#545 added the CI coverage table (Libevent versions) and this PR the support-status table (Supported libevent versions); point each at the other. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… failures (#823) ## Problem Part of the libevent support work (Refs #545). memtier did not check or record which libevent and OpenSSL it was built against and which it runs with, and a few libevent failures were not handled: - A binary built with one libevent's headers can load another series' library, for example headers from one prefix and the library from another, or a vendored header. Nothing reported this. The `--version` `libevent=` field shows the runtime library; `openssl=` shows the build headers. The JSON output had no library versions at all. - `evthread_use_pthreads()` / `evthread_use_windows_threads()` failing only printed a warning. Cross-thread `event_base_loopbreak()` (Ctrl+C, `--connection-stage-timeout`) depends on it, so the run could hang later. - `bufferevent_openssl_socket_new()` / `bufferevent_socket_new()` returning NULL in `shard_connection::setup_event()` hit `assert(m_bev != NULL)`, and the process aborted with SIGABRT. - `configure.ac`, DEVELOPMENT.md and README said the Prometheus exporter needs libevent 2.1.1. The exporter calls `evhttp_request_set_on_complete_cb()`, which first appeared in **2.1.4-alpha**: it is missing from `release-2.1.3-alpha:include/event2/http.h` and was added in upstream commit b083ca05. No document said which libevent versions are supported. - The comment above the READONLY `bufferevent_write()` said that call goes through `bufferevent_trigger_nolock_()`. In libevent 2.1.12 and 2.2.2-alpha, `bufferevent_write()` is `evbuffer_add(bufev->output, ...)`, the same path the protocol writers use (Refs #532). - `make check` did not compile on libevent 2.1.8 (RHEL 8): `tests/unit/cluster_transaction_test.cpp` used `EVUTIL_INVALID_SOCKET`, which first appeared in 2.1.9. #812 (now on master) fixed that hunk, so it is no longer in this diff; master builds and passes `make check` on Rocky Linux 8 (libevent 2.1.8, OpenSSL 1.1.1k). ## Fix - **Mismatch warnings (stderr only).** After option parsing, memtier compares `LIBEVENT_VERSION_NUMBER` with `event_get_version_number()`. If major.minor differ, it prints one warning to stderr. It does the same for OpenSSL, comparing `OPENSSL_VERSION_NUMBER` with `OpenSSL_version_num()` (`SSLeay()` on OpenSSL 1.0.2): before 3.0 it compares major.minor (1.0 vs 1.1); from 3.0 on it reports another major version or a library minor version older than the headers (3.5 built, 3.0 run), because OpenSSL 3 only promises that older headers run on a newer library. Patch levels and newer libraries are not reported, so the el9 RPM case (2.1.13 build, 2.1.12 runtime) stays quiet. Because the check runs after option parsing, `--version` and `--help` print nothing extra, and `--version` stdout is byte-identical. The comparison lives in the new `library_versions.h`. - **Provenance.** The crash report INFO section gains `libevent_build_version:` and `openssl_runtime_version:`. Existing keys are unchanged; note that the existing `openssl_version:` is the build-time text. `OpenSSL_version()` is pre-resolved like `event_get_version()`. The JSON `run information` section gains four new keys: `libevent runtime version`, `libevent build version`, `OpenSSL runtime version` and `OpenSSL build version`. The two OpenSSL keys appear only when TLS is compiled in. No existing key is renamed. - **evthread failure** is now fatal for a run. `evthread_use_pthreads()` still runs first, before any `event_base` exists; if it failed, memtier prints an `error:` line and calls `exit(1)` right after option parsing, like the other post-parse error exits, so LeakSanitizer reports nothing. `--help` and `--version` behave as before. This is a behaviour change for release notes: a run on such an install used to continue with a warning. - **bufferevent/SSL creation failure.** `setup_event()` now returns `bool`. On failure it logs an `error:` line and `connect()` returns -1, which is the existing path for a socket setup failure: standalone aborts the run in prepare, and cluster mode retries the connection and ends the run as failed. Ownership was checked in the libevent source: - With `BEV_OPT_CLOSE_ON_FREE`, a failed `bufferevent_openssl_socket_new()` already frees the `SSL` in libevent ≥ 2.1.9 (e86ccfe5, first released in 2.1.9-beta) and in 2.2.2-alpha. memtier therefore does **not** free it; doing so would be a double free. - The socket is not closed by libevent, because the SSL's socket BIO is `BIO_NOCLOSE`, and plain `bufferevent_socket_new()` does not close it either. memtier closes it. - On libevent ≤ 2.1.8 it depends on where libevent failed. An allocation failure leaves the socket open and leaks the SSL. A failure to arm the handshake events frees the partial bufferevent with the SSL attached, and its destructor closes both. memtier can't tell these apart, so it leaves the socket open, rather than risk closing a descriptor number that another thread has just been given, and logs `error: socket N left open on purpose: libevent <version> may already have closed it.` That is one socket (and possibly one SSL) per failed attempt, and only under libevent allocation failure. - The rule lives in `libevent_ssl_failure_socket_is_ours()` in `library_versions.h`, which is unit-tested. - `SSL_new()` returning NULL is handled the same way; it was an assert before. - `setup_event()` and `disconnect()` now clear the protocol's buffer pointers once the bufferevent is freed. Before, they kept pointing at the freed evbuffers until the next successful connect. - **Docs and configure.** The `libevent_extra` pkg-config check, the configure error message, DEVELOPMENT.md and README now say 2.1.4. The real gate, the link test, was already effectively 2.1.4, so no build that works today stops working. The core libevent minimum in configure is **unchanged**. DEVELOPMENT.md gains a "Supported libevent versions" table: - 2.1.8: oldest release known to work (RHEL 8), checked manually, not built in CI - 2.1.12: recommended minimum, runs the main CI suite - 2.1.13: current stable with security fixes - 2.2.2-alpha: experimental It also documents the mismatch warning, the new JSON keys, and the 2.1 vs 2.2 read size difference that makes results from the two series not directly comparable (#535). `tests/run_local_gate.sh` now checks for the 2.1.4 floor in DEVELOPMENT.md. - **#532 comment**: the comment is corrected. This is a comment-only change; the code path is untouched. ## Tests - New unit test `tests/unit/library_versions_test.cpp` (in `make check`) covers the series comparison. Cases: libevent patch levels and series; OpenSSL 3.x patch differences, a newer and an older minor, 3 vs 4, 1.0 vs 1.1 vs 3; LibreSSL. - New RLTest file `tests/test_library_provenance.py`. The LD_PRELOAD tests use the new `tests/library_failure_injector.c` and skip when not on Linux or when the binary is linked statically. Sanitizer runtimes are kept first in `LD_PRELOAD`, as in the crash-handler tests. - `test_json_run_information_library_versions`: the new JSON keys are present, `libevent runtime version` equals `--version`'s `libevent=` field, `OpenSSL build version` contains `openssl=`, the existing keys are still there, and a matched install prints no warning. - `test_libevent_series_mismatch_warns_on_stderr`: with a fake runtime libevent (2.99) and, in TLS builds, a fake OpenSSL, memtier prints exactly one warning per library on stderr and none on stdout. The JSON reports the runtime version. `--version` stderr stays empty. - `test_libevent_patch_difference_does_not_warn`: a 2.1.x patch difference prints no warning. - `test_evthread_failure_is_fatal`: exit 1, the `error:` line, no JSON written, and no LeakSanitizer report. `--help` and `--version` keep their exit code and stdout under the same failure. - `test_bufferevent_creation_failure_fails_connection`: a positive error exit (not a signal), the `error:` line naming the constructor, and no sanitizer report. TLS runs exercise `bufferevent_openssl_socket_new`, plaintext runs `bufferevent_socket_new`. The shim records the socket it was given and checks at exit that memtier closed it, using the descriptor's device/inode so that a reused number isn't mistaken for it. - `test_tls_bufferevent_failure_leaves_socket_on_libevent_2_1_8`: with a faked 2.1.8 runtime, the socket is left open and the log line appears. - `test_crash_report_separates_build_and_runtime_versions`: with faked runtime versions, the crash report's runtime fields show the fake and its build fields don't. The mismatch test checks the same for the JSON keys. - `test_crash_handler_with_active_connections` now also checks the new INFO lines, and that `libevent_version:`/`openssl_version:` equal `--version`'s `libevent=`/`openssl=`. - **Before/after**: on master d8d4e9f, 4 of the 5 new tests fail: - bufferevent: SIGABRT on `Assertion 'm_bev != NULL' failed`. - evthread: exit 0 with a warning. - JSON: the keys are missing. - mismatch: no warning. The patch-difference negative control passes on both. Two more tests were added later; reading the code says both also fail on master, but they haven't been run there. `test_tls_bufferevent_failure_leaves_socket_on_libevent_2_1_8` would hit the same `m_bev != NULL` assertion, and `test_crash_report_separates_build_and_runtime_versions` would find the new INFO fields missing. That makes 6 of the 7 tests in `test_library_provenance.py`, with the control passing. - Local results (Docker, aarch64; CI covers x86_64): | Variant | Build | make check | New tests + crash-handler tests | |---|---|---|---| | Ubuntu 24.04, system libevent 2.1.12, OpenSSL 3.0.13 | ✓ | 19/19 | standalone plaintext + TLS pass. Full TLS standalone suite: 727 pass / 109 skip / 1 fail (`test_prometheus:test_F16_ipv6`, no IPv6 in the container; unrelated) | | libevent 2.2.2-alpha (source) | ✓ | 19/19 | standalone plaintext + TLS, cluster TLS pass | | `--disable-tls` | ✓ | 19/19 | pass | | libevent 2.1.8 (source, OpenSSL 3.0.13) | ✓ | 19/19 | standalone plaintext + TLS, cluster TLS pass | | rockylinux:8, distro libevent 2.1.8-11.el8_10, OpenSSL 1.1.1k, GCC 8.5 | ✓ (TLS + Prometheus) | 19/19 (fails to compile without the test fix) | n/a | | ASan+UBSan (`detect_leaks=1`), system libevent | ✓ | | standalone plaintext + TLS, cluster TLS pass | - The libevent 2.1.8 tarball is the GitHub release asset, sha256 `965cc5a8bb46ce4199a47e9b2c9e1cae3b137e8356ffdad6d94d3b9069b71dc2`, which matches Debian's `libevent_2.1.8-stable-4.dsc`. Built from source on glibc ≥ 2.36, 2.1.8 does not link (`arc4random_addrandom` is undefined). That is a libevent 2.1.8 vs new glibc problem, not a memtier one, and RHEL 8 (glibc 2.28) is not affected; the local harness works around it with a no-op define. - clang-format 18 `--dry-run --Werror` is clean on all changed C++ files. ### When the mismatch check can fire Distribution packages tie the library file name to the series (`libevent-2.1.so.7`, `libevent-2.2.so.1`, `libssl.so.3`), so a binary built against 2.2 headers and run with `LD_LIBRARY_PATH` pointing at 2.1 fails to load before `main()`. The check therefore fires when the headers and the library come from different installations at build time: mixed `-I`/`-L` prefixes, a Homebrew plus source-built libevent, vendored headers, or a loader that resolves another series under the same name. The runtime path is covered by the preload shim. A real mix was also built locally: 2.2.2-alpha headers via `CPPFLAGS=-I<2.2.2 prefix>/include`, linked against the system 2.1.12 libraries. It builds and links, `--version` is unchanged (`libevent=2.1.12-stable`), and a run prints `warning: memtier_benchmark was built with libevent 2.2.2-alpha-dev headers but is running with libevent 2.1.12-stable; rebuild it against the libevent it runs with.` ## Affected versions - The assert on bufferevent creation failure and the evthread warning-only handling are in every current release. Hitting them in practice needs allocation failure or a broken libevent install. - The incorrect 2.1.1 minimum dates from the Prometheus exporter's introduction. Users with 2.1.1–2.1.3 already got a configure error from the link test; only the message and docs were wrong. - No change for a matched install: stdout, `--version` and existing JSON and crash-report keys are byte-identical. The only additions are the four JSON keys and the two crash INFO lines. ## Interactions - **#812** (merged) edited the DEVELOPMENT.md prerequisites line, raising the core minimum to 2.0.11. The merge keeps this PR's line, and the "Supported libevent versions" section now says why `configure.ac` requires 2.0.11. The `configure.ac` hunks do not overlap: #812 touches the core/pthreads checks, this PR the Prometheus block. - **#545** also adds a libevent table to DEVELOPMENT.md ("Libevent versions", with CI coverage) and its own #535 read-size note. Whichever of #545/#823 lands second merges the two tables into one, keeping this PR's support status next to #545's CI coverage, and keeps a single #535 paragraph. - **#822** (libevent 2.2 TLS error access): no overlap. The `BEV_EVENT_ERROR` handler is untouched here, and this patch applies cleanly on top of #822's head. Refs #545, #532, #535 <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Touches TLS connection setup, fatal evthread initialization, and version-mismatch detection on every run; behavior changes for broken libevent installs and mismatched header/library pairs, but matched installs stay warning-free. > > **Overview** > Adds **build vs runtime provenance** for libevent and OpenSSL: startup stderr warnings when major series (or OpenSSL 3.x minor) mismatch, four new JSON `run information` keys, and crash-report INFO lines separating loaded libraries from compile-time headers. > > **Hardens libevent integration:** `evthread_use_pthreads()` failure is **fatal** after option parsing (`--help`/`--version` unchanged). `shard_connection::setup_event()` returns `bool` and replaces asserts on `SSL_new` / bufferevent creation with logged errors and connect failure; TLS socket cleanup follows **runtime** libevent version (leave socket open on ≤2.1.8 when unsafe to close). Protocol buffers are cleared when the bufferevent is freed. > > **Docs/configure:** Prometheus exporter minimum is documented and enforced as **libevent 2.1.4** (`evhttp_request_set_on_complete_cb`). DEVELOPMENT.md adds a supported-libevent table and related CI notes. > > **Tests:** `library_versions.h` unit tests, LD_PRELOAD `library_failure_injector.c`, and `test_library_provenance.py` cover warnings, JSON, evthread fatality, and bufferevent failure paths; crash-handler integration checks new INFO fields. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9276de2. 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]>
Keep both sides in shard_connection: #855's socket_connect members and NULL check, then this PR's read tracking. DEVELOPMENT.md (from #545 and #823) now says memtier reads past 2.1's 4 KiB cap on plaintext. Co-Authored-By: Claude Opus 5.5 <[email protected]>
## Problem libevent before 2.2 reads at most 4 KiB (`EVBUFFER_MAX_READ`) from a socket per read event. libevent 2.2 reads up to 16 KiB. When pipelined replies exceed 4 KiB, memtier built against 2.1 reads and parses them 4 KiB at a time, with one event-loop pass for each chunk. The same memtier source therefore reports different throughput depending on the libevent series it was built with (#535). No libevent 2.1 API raises the cap. ## Fix This only applies to plaintext connections on libevent before 2.2. When libevent's read added exactly 4 KiB, memtier reads on, up to 16 KiB in all, before parsing: - **Read size.** It reads what `FIONREAD` reports as already queued, so the read never blocks. A pending EOF or socket error stays for libevent's next read to report as before. - **Frozen input.** libevent keeps the end of the input buffer frozen outside its own read (`bufferevent_readcb`), so memtier unfreezes and refreezes it around this read the same way. - **Detecting a capped read.** An evbuffer callback records how much each read added. Nothing touches the connection after `process_response()`, which can delete it (a cluster reconnect frees the non-main connections). The code lives in `libevent_read_cap.h`, so a unit test can drive it. Unchanged: TLS bufferevents (they already read about a whole record per event), libevent 2.2, and Windows. Windows builds still have the 4 KiB cap: the Winsock version (`ioctlsocket()`, IOCP bufferevents) is neither written nor tested. The 16 KiB total matches libevent 2.2 on purpose. A variant that read 4 + 16 KiB was faster still (+60% over master on 2.1.12), but it would have made 2.1 builds read differently from 2.2. Reading more per event on both series is a separate decision. ## Evidence Docker loopback, aarch64, 8 vCPU. Redis 7.0.15 pinned to CPU 0, memtier on CPUs 1–7. GETs only, 100,000 keys, 1 KiB values, 100% hits, 4 threads × 40 clients, 20 s per run, alternating A B B A. Totals rows. | pipeline 16 | ops/s | avg latency | |---|---:|---:| | master, libevent 2.1.12 | 1.54–1.64M (median ≈1.59M) | ≈1.65 ms | | this PR, libevent 2.1.12 | 1.91–1.94M (one 1.64M outlier) | ≈1.33 ms | | master, libevent 2.2.2-alpha (reference) | 1.88–1.90M (one 1.65M outlier) | ≈1.35 ms | - **Pipeline 1:** unchanged. Both builds run at ≈480–505K ops/s, and no read reaches 4 KiB. - **Syscalls, `strace -c`:** 10,000 GETs on one connection at pipeline 16 took 2,522 `readv` + 2,524 `ioctl` on master. With this PR the best run took 625 `readv` + 625 `recvfrom` + 1,252 `ioctl`. Across repeated runs `readv` varied from 647 to 1,242, so total reads fell by 30–50%. - **Worst case for the extra check:** every reply exactly 4096 bytes (`-d 4087` GETs, pipeline 1), so every read event makes the extra `ioctl` and finds nothing queued. 4 threads x 40 clients, six 20 s runs per build: median 454.6k ops/s on master, 454.2k with this PR, which is within noise. For 10,000 such GETs, `ioctl` calls go from 10,002 to 20,002. libevent already makes one FIONREAD call before every `readv`. - **Byte loss:** KB/s scales with ops/s in every run. These are local loopback numbers, not the AWS methodology. Their purpose is to show that this PR brings 2.1 builds level with 2.2. ## Tests - **New unit test.** `tests/unit/libevent_read_cap_test` drives a real socket bufferevent over a socketpair. Whenever more is queued, one read event takes 16 KiB on every libevent series. It also covers short reads, an uncapped 4 KiB read, the input staying frozen, and an EOF after the data that is still reported. It passes on Linux with 2.1.12 (ASan + UBSan), 2.1.13 and 2.2.2-alpha, on Rocky Linux 8 with 2.1.8, and on macOS with 2.1.13. The socketpair buffers are raised to 64 KiB because macOS defaults to 8 KiB. If the input is left frozen, which switches the fix off, it fails with 4096 instead of 16384. - **New integration test.** `tests/test_pipelined_large_replies.py` imports 64 distinct 3000-byte values and checks them back with `--verify-only` at pipeline 16, so replies cross the 4 KiB boundary. It passes on master and on this PR. A mutant that commits one byte too few hangs the parser, and the test fails it. - **Full suite, sanitized (ASan + UBSan, `abort_on_error=1`), libevent 2.1.12:** 772 pass, 1 fail. The failure is `test_json_early_exit`, an LSan leak on an option-validation exit that also fails on master (#850). - **libevent 2.1.8 (RHEL 8):** same freeze handling and the same 4 KiB cap in its `bufferevent_sock.c`/`buffer.c`. ## Needs a maintainer decision This changes measured results. - **Failed runs.** When a server closes mid-burst, memtier now handles every reply that already arrived before it notices the close, as 2.2 builds do. Master handles 4–8 replies, then fails writing. So a failed run's reply count and log line can change, e.g. `connection dropped.` instead of `Connection error: Broken pipe`. - **Benchmarks.** Benchmarks with deep pipelines and replies larger than 4 KiB will be faster on libevent 2.1 builds than with earlier memtier releases on the same libevent. Results from 2.1 builds then match 2.2 builds. Docs follow-up: #545 (DEVELOPMENT.md "Socket read size") and #823 ("2.1 reads at most 4 KiB per socket read") describe the uncompensated cap. Whichever of them lands after this PR needs a line saying memtier now reads past it on plaintext connections (not on Windows); if this PR lands last, I'll add it here. ## Release notes (proposed) > On libevent 2.1 builds (not Windows), memtier now reads up to 16 KiB per socket read event on plaintext connections, as libevent 2.2 does. Deep-pipeline throughput with replies larger than 4 KiB is therefore no longer comparable with earlier memtier releases on the same libevent. It now matches libevent 2.2 builds. The server is unchanged. Fixes #535 <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes the hot-path read callback and direct socket reads on plaintext connections for libevent < 2.2, which affects parsing, disconnect timing, and published benchmark numbers without touching TLS or Windows. > > **Overview** > **Aligns plaintext socket read batching with libevent 2.2 on libevent 2.1 builds** (fixes #535). libevent before 2.2 only pulls 4 KiB per read event; pipelined replies larger than that were parsed in smaller chunks and throughput diverged from 2.2. > > Adds **`libevent_read_cap.h`**: on non-Windows, when runtime libevent is < 2.2, plaintext socket bufferevents register an evbuffer callback to detect a full 4 KiB read, then **`recv` up to 12 KiB more** from already-queued bytes (`FIONREAD`), respecting frozen input buffers and leaving EOF/errors for libevent. **TLS and Windows are unchanged.** > > **`shard_connection`** wires this in `cluster_client_read_handler` and when creating plaintext `bufferevent_socket_new` connections. > > **Tests:** new unit test `libevent_read_cap_test` (16 KiB per read event, short reads, EOF) and integration test `test_pipelined_large_replies.py` (`--verify-only`, pipeline 16, ~3 KiB values). > > **Note for reviewers:** deep-pipeline benchmarks with replies > 4 KiB on libevent 2.1 will report higher throughput than older memtier on the same libevent; failed-run behavior when the server closes mid-burst may also differ slightly from master. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 906bedc. 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]>
Picks up 14 master commits, including the connect-failure changes in #855 (libevent 2.1.8's error callback from a failing connect), #823 (hardened libevent failures), #822 (TLS error reporting) and the libevent compatibility CI from #545. No conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>

Depends on #822 and #832. This branch merges both PR branches unchanged, so either can land first and the other merges cleanly:
fix/libevent22-tls-error-access, at cba1fcc) brings theshard_connection.cppTLS error guard andtests/test_connection_error_types.py. Please review those in Fix libevent TLS error reporting on 2.1 and 2.2 #822.fix/resp-bulk-length-overflow, at 300da45) brings the RESP length/count bounds inprotocol.cpp, thecheck_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 Reject RESP lengths and counts the parser cannot represent #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 thanci.yml.Root cause
libevent behaviour differs by series: 2.2.2-alpha asserts, or with
NDEBUGreads and writes out of bounds, whenbufferevent_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 libeventmasterby commit (d82464a2, canary only). It rejects a non-empty or non-directory prefix before creating it, builds with CMake (Release), and withLIBEVENT_FLAVOUR=sanitizealso builds libevent with ASan+UBSan.--source-idfeeds the CI cache key. The macOS jobs inci.ymlkeep using it for 2.1.13 (clean prefix as in socket_options_test segfaults in build-macos (3): Homebrew libevent now links OpenSSL 4, memtier links openssl@3 #674, debug mode off). The macOS OpenSSL 1.0.2 cell keeps master's autotools build of 2.1.12, unchanged. Because the existingci.ymlmacOS jobs now go through the helper, a helper regression also breaks those jobs.build-macos-libevent.shand 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 tocheck-macos-tls-links.sh). It fails unless the--versionlibevent=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, perldd/readelf) comes from the prefix, the process loads exactly one libssl and one libcrypto (solibevent_openssland memtier share one OpenSSL; checked on memtier's transitivelddset, so a private OpenSSL found through RUNPATH is handled), and theopenssl=/prometheus=fields are as intended..github/workflows/libevent-compat.ymlredesign:ci.yml(pull_requestandpushonmaster,main,2.*), plus a nightly schedule, a weekly schedule andworkflow_dispatch.libevent-compat (<track>, <cell>)with no versions in them. The track islegacy2.1.12,stable2.1.13,next2.2.2-alpha orcanarymaster.libevent-compat-gate(if: always()). It fails unless planning and every non-canary cell succeeded. This is the only check to mark required.stableandnextTLS full suites, standalone and cluster.nextplaintext full suites with memtier and libevent both under ASan+UBSan. This is the cell that catches the Fix libevent TLS error reporting on 2.1 and 2.2 #822 regression.next--disable-tlsbuild (Prometheus on) withmake check.mastercanary withcontinue-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 smallcanary-alertjob (issues: write, canary runs only) opens or updates one "libevent master canary is failing" issue.ASAN_OPTIONS=detect_leaks=1:abort_on_error=1andUBSAN_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.actions/cache, keyed on version, sha256/commit, flavour, OpenSSL version, compiler version, and the hashes of the helper and the workflow.ci.yml.utils/select_test_shard.py, coverage checked byutils/check_test_shards.py, as in the sanitizer workflows). On 658fed4 an unsharded cluster cell took 35–41 min, as long asci.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 intest_reconnect_cluster_mode_no_assertiondiagnosable 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 libevent 2.1.12 4 KiB read cap depresses pipelined 1 KiB GET results #535), and the TLS messages memtier prints on 2.2 after Fix libevent TLS error reporting on 2.1 and 2.2 #822.Tests
PKG_CONFIG_PATH, and absolute macOS install names for 2.2.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, Use the replying connection for missing cluster topology hosts #777, Restore parser value policy after cluster topology refreshes #797, Keep cluster workloads progressing across partial maps and primary reconnects #799). The test now prints memtier's stderr whenever memtier dies from a signal.--disable-tlsand ASan+UBSan builds, and the linkage checker accepted every one.masterbuilt against sanitized 2.2.2-alpha aborts on a refused plaintext connection withAddressSanitizer: heap-buffer-overflowinbufferevent_get_ssl_error(bufferevent_ssl.c:1108), called fromshard_connection.cpp. This branch exits normally in the same setup.CMAKE_INSTALL_NAME_DIR), because 2.2's CMake otherwise installs@rpath/dylibs, whichcheck-macos-tls-links.shrejects.actionlint(with shellcheck) is clean on the new workflow,shellcheckis clean on the scripts, and the C++ passesclang-format-18 --dry-run --Werror.Per-PR cost, sanitizers, and the required check
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.stable(2.1.13) TLS is 3 jobs and about 68 runner-min.stableruns 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, whileci.ymlruns 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.abort_on_error=1stays on purpose. Without it, a leak exits with 23, and tests that only check!= -6pass 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.libevent-compat-gate(only that job) as required. Suggested timing: after three consecutive green nightlies, given thatnextis an alpha.2.2.2-alpha-devstring is tied to the helper'smaster_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).
🤖 Generated with Claude Code
Note
Low Risk
Changes are CI, shell helpers, and test logging; no production C++ behavior in this diff beyond what dependent PRs carry separately.
Overview
Adds libevent compatibility CI and supporting scripts so memtier is exercised against pinned 2.1.12, 2.1.13, 2.2.2-alpha, and a weekly master canary—not only distro 2.1.12 from main CI.
scripts/build-libevent.shbuilds verified releases (sha256) or a pinnedmastercommit into an empty private prefix, with optional ASan+UBSan on libevent itself.check-libevent-linkage.shasserts runtimelibevent=, pkg-config,ldd/OpenSSL coherency (macOS defers to existing TLS link checks).build-macos-libevent.shnow calls the shared helper (CMake) instead of an inline autotools tarball build;ci.ymlmacOS jobs install cmake for that path..github/workflows/libevent-compat.ymlplans PR vs nightly vs weekly scopes, runs unit + sharded integration tests per cell, caches built libevent, exposeslibevent-compat-gateas the single required check (canary iscontinue-on-errorwith issue alerting), and widens coverage on harness-touching PRs.DEVELOPMENT.mddocuments the tested matrix, local evaluation steps, and 2.1 vs 2.2 read/TLS-error behavior.test_reconnections.pydumps memtier stderr on signal death so sanitizer aborts show up in logs..gitignoreignores local libevent build prefixes.Reviewed by Cursor Bugbot for commit 9d366b3. Bugbot is set up for automated code reviews on this repo. Configure here.