Repository navigation
Report libevent/OpenSSL build vs runtime versions and harden libevent failures - #823
Conversation
… failures - Warn on stderr (after option parsing; --version stdout unchanged) when the runtime libevent major.minor or OpenSSL series differs from the build headers. Comparison in library_versions.h, unit-tested. - Crash report INFO adds libevent_build_version and openssl_runtime_version; JSON "run information" adds libevent/OpenSSL runtime and build versions (additive keys). - evthread_use_pthreads()/evthread_use_windows_threads() failure is fatal. - setup_event(): SSL_new()/bufferevent creation returning NULL fails the connect attempt instead of asserting. The SSL is not freed: libevent >= 2.1.9 frees it on failure with BEV_OPT_CLOSE_ON_FREE. - Prometheus exporter needs libevent_extra >= 2.1.4 (evhttp_request_set_on_complete_cb); document supported libevent versions (2.1.8 floor, 2.1.12 recommended, 2.1.13, 2.2.2-alpha). - cluster_transaction_test: avoid EVUTIL_INVALID_SOCKET (2.1.9+) so make check builds on libevent 2.1.8 (same change as #812). - Correct the READONLY bufferevent_write() comment (Refs #532). Refs #545, #532, #535 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🤖 Automated first-pass review — a human maintainer's review is still required before merge. Thanks for this. I went through the diff and the description, and it's well covered: the new JSON keys only add to
The core changes look solid to me. I'd just want the evthread release-note point and the two unverified tests settled before this merges. (would file this as a comment, not a formal block) |
evthread_use_pthreads() still runs before any event_base exists, but its failure is reported (exit 1) after option parsing, so --help and --version behave as before on a broken libevent_pthreads install. Name the libevent commit the TLS bufferevent failure path relies on, and say 2.1.8 is checked manually, not in CI. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the review. Fixed in 4ed9f92:
|
OpenSSL 3 only promises that a binary built with older headers runs on a newer library of the same major version. Report a runtime minor version older than the headers too (3.5 built, 3.0 run); patch levels and newer libraries stay quiet. Reflow the TLS bufferevent failure comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Answers to the updated review, at 23d22f7:
Nit: the comment has been reflowed. |
If no new bufferevent can be created, the protocol no longer points at the freed evbuffers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Answers to the latest review, at the new head:
|
…ufferevent The retry belongs to the previous attempt and must not run against the new bufferevent, or against none after a failed creation. Note the fd cost of the libevent <= 2.1.8 leak under repeated failure. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Answers at 665294d:
|
libevent_ssl_failure_keeps_socket() in library_versions.h replaces the inline 0x02010900 check and records what 2.1.8 actually does: an allocation failure leaves the socket open, a failure to arm the handshake events closes it through the partial bufferevent's destructor. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Answers at 915a10d:
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Answers at 94651ad:
|
…ENT.md Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Answers at 48261c2:
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Answers at b344fe9:
|
libevent_ssl_failure_socket_is_ours() says whether the caller owns the socket after the call, which on libevent <= 2.1.8 is not knowable. Note that cancelling the Unix connect retry in setup_event() is defensive. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Answers at fa146f5:
|
Also make the fake OpenSSL version text in the mismatch test match its number (15.99). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Answers at 81a3d1d:
|
|
Thanks. Answers to this round, with no code change:
|
- evthread failure: exit(1) like the other post-parse error exits, so LeakSanitizer (abort_on_error=1) no longer reports main()'s allocations; the test asserts no LeakSanitizer report. - Clear the protocol buffers in disconnect() and unconditionally in setup_event(), so a failed setup after disconnect() leaves none. - Drop the speculative Unix connect retry cancel from setup_event() and move the ownership explanation to libevent_ssl_failure_socket_is_ours(). - Shim records the socket a failed bufferevent call was given and reports at exit whether it was closed (by device/inode); tests assert it is closed (plain, TLS >= 2.1.9) and left open on a faked 2.1.8. - Tests check the JSON and crash report build vs runtime fields against faked runtime versions, and the crash INFO values against --version. - DEVELOPMENT.md: 2.1.12 runs the main CI suite. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Follow-up after an internal review, at 4e37512:
Validation, all passing: libevent 2.1.12 release build (standalone/cluster × plaintext/TLS, crash-handler tests, |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Answers at c9930c5 (the change is comment-only):
|
|
Thanks. No code change this round; answers below:
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ime version The master merge replaced #812's prerequisites sentence; restore its explanation next to the --disable-prometheus paragraph. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Pushed 80cd641 and a merge of master (9223861, picks up #806):
|
|
CI on 9223861: 144 pass, 1 fail. The failure is |
… 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]>
#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]>
…n Rocky Linux 8 (#855) ## Problem RHEL 8 ships libevent 2.1.8, the oldest release memtier is known to work with. CI never ran it. Running the standalone suite on Rocky Linux 8 (libevent 2.1.8, OpenSSL 1.1.1k, GCC 8, Redis 6.2) gave 12 failures. **10 in `test_unix_connect_backlog`, with SIGSEGV.** libevent 2.1.8 runs the bufferevent error callback from inside a failing `bufferevent_socket_connect()` (`freesock:` calls `bufferevent_run_eventcb_(bev, BEV_EVENT_ERROR, 0)`), before it returns -1. 2.1.9 stopped doing that (1dde74ef, "bufferevent_socket_connect{,_hostname}() missing event callback and use ret code"). memtier therefore handled the failure twice: 1. `handle_event()` logged `Connection error: Resource temporarily unavailable`, then reconnected or ended the thread, which freed the bufferevent. 2. `connect()` then handled the -1 itself. For a full Unix socket backlog (EAGAIN) that is `bufferevent_disable(m_bev, ...)` on the freed bufferevent: ``` memtier_benchmark crashed by signal: 11 /lib64/libevent-2.1.so.6(bufferevent_disable+0x14) shard_connection::connect(connect_info*) shard_connection.cpp:692 ``` The Unix backlog retry (`handle_unix_connect_retry()`) calls `bufferevent_socket_connect()` directly and had the same problem. **1 in `test_cli_validation_reconnect_backoff`.** The same double handling counted a failed reconnect twice. **`test_F16_ipv6`.** This one is environmental. evhttp resolves the bind address with `AI_ADDRCONFIG`, which rejects `::1` in a container with no non-loopback IPv6 address. The skip guard only tried `bind()`. ## Fix - `socket_connect()` wraps `bufferevent_socket_connect()` for both callers. While it runs, `handle_event()` only records the error, and the caller handles the failure once, as with libevent 2.1.9 and newer. Deferred callbacks (`BEV_OPT_DEFER_CALLBACKS`, e.g. an immediate refusal) run later from the loop and are unaffected. The Windows path, which goes through `bufferevent_connect_nonblocking()`, sets the same guard. - `test_F16_ipv6` now also skips when `getaddrinfo("::1", AI_PASSIVE | AI_ADDRCONFIG)` fails, which is the lookup evhttp makes. - New CI job **Test Rocky Linux 8 (libevent 2.1.8)**, plaintext and TLS. It runs a `rockylinux:8` container with the distro's libevent, OpenSSL and GCC, Redis 6.2 from AppStream, and Python 3.11. It checks `--version` reports `libevent=2.1.8-stable`, runs `make check`, then runs the standalone suite. ## Testing - **Rocky Linux 8, locally, with the same steps as the new CI job:** plaintext 869/869 and TLS 869/869 pass. Before the fix, plaintext had 12 failures. `test_unix_connect_backlog` also passed 3 out of 3 repeated runs. - **Ubuntu 24.04, libevent 2.1.12, ASan + UBSan:** `test_unix_connect_backlog.py`, `test_cli_validation_reconnect_backoff.py` and `test_reconnections.py` pass 51/51. - **Not covered:** the cluster suite on 2.1.8 is not part of the new job. - **Maintainer decision:** this job is the only check that catches the fix. Every other cell runs libevent 2.1.12 or newer, and `make check` passes without the fix. Consider making it required. Related: #823 documents 2.1.8 as the oldest known-working release ("CI does not build it yet"). This PR adds that CI job. Whichever of the two lands second updates that row. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes core connection setup and error handling on all platforms, though behavior is intended to match libevent 2.1.9+; the new Rocky Linux 8 CI is the main regression signal for the fix. > > **Overview** > Fixes **double-handling of synchronous connect failures on libevent 2.1.8** (RHEL 8), where a failing `bufferevent_socket_connect()` could invoke the error callback before returning `-1`, leading to reconnect/teardown and then use-after-free (e.g. Unix socket backlog / reconnect tests). > > **`shard_connection`** adds `socket_connect()` with `m_in_socket_connect` / `m_socket_connect_error`: during that call, `handle_event()` only records `BEV_EVENT_ERROR` instead of running reconnect logic; `connect()` and Unix backlog retry read the stashed errno. Connect paths route through this wrapper on non-Windows. > > **CI** adds a **Rocky Linux 8** job (distro libevent 2.1.8, TLS matrix) that builds, runs `make check`, and the standalone Python suite. > > **`test_F16_ipv6`** broadens the skip guard with `getaddrinfo("::1", …, AI_ADDRCONFIG)` so containers without routable IPv6 skip like evhttp would fail to bind. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 71ff40a. 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]>
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]>
Fixes the `Test Rocky Linux 8 (libevent 2.1.8, TLS=1)` job, which has failed on master since #855 landed (first failing run: 60ec3f0). `test_bufferevent_creation_failure_fails_connection` (from #823) always expected memtier to close the socket after `bufferevent_openssl_socket_new()` fails. On a real libevent 2.1.8 or older with TLS, memtier deliberately leaves that socket open, because libevent may already have closed it (`libevent_ssl_failure_socket_is_ours()`). The neighbouring `test_tls_bufferevent_failure_leaves_socket_on_libevent_2_1_8` checks exactly that with a faked version. #823 and #855 merged one after the other, so the real-2.1.8 TLS job never ran this test before landing. The test now reads the runtime libevent from `--version`. With TLS on libevent older than 2.1.9 it expects `left open on purpose` and the shim's `socket open` marker; otherwise it still expects `socket closed`. This is a test-only change, and memtier's behaviour is unchanged and correct. Results for `test_library_provenance.py`: - Rocky Linux 8 (libevent 2.1.8) with TLS: 7/7. - Ubuntu 24.04 (libevent 2.1.12), ASan + UBSan, plain and TLS: 7/7 each. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Test-only change; memtier runtime behavior is unchanged and only assertions are version-aware. > > **Overview** > Fixes CI on **Rocky Linux 8** (real libevent 2.1.8 with TLS) by aligning `test_bufferevent_creation_failure_fails_connection` with memtier’s existing socket-handling rules. > > That test used to always require the preload shim’s **`socket closed`** marker after a forced `bufferevent_*_socket_new()` failure. With **TLS** and **libevent older than 2.1.9**, memtier intentionally leaves the fd open and logs **`left open on purpose: libevent …`** because libevent may have already closed it. The test now parses the runtime libevent version from `--version` and branches: TLS + < 2.1.9 expects the open-socket path; all other cases still expect **`socket closed`**. No application code changes. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 8e30c4f. 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
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:
--versionlibevent=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-threadevent_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 inshard_connection::setup_event()hitassert(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 callsevhttp_request_set_on_complete_cb(), which first appeared in 2.1.4-alpha: it is missing fromrelease-2.1.3-alpha:include/event2/http.hand was added in upstream commit b083ca05. No document said which libevent versions are supported.bufferevent_write()said that call goes throughbufferevent_trigger_nolock_(). In libevent 2.1.12 and 2.2.2-alpha,bufferevent_write()isevbuffer_add(bufev->output, ...), the same path the protocol writers use (Refs Verify whether bufferevent_write is actually required for READONLY/CLIENT NO-TOUCH on discovered connections, or the original diagnosis was wrong #532).make checkdid not compile on libevent 2.1.8 (RHEL 8):tests/unit/cluster_transaction_test.cppusedEVUTIL_INVALID_SOCKET, which first appeared in 2.1.9. Use libevent cached time for deadline-clamped reconnects #812 (now on master) fixed that hunk, so it is no longer in this diff; master builds and passesmake checkon Rocky Linux 8 (libevent 2.1.8, OpenSSL 1.1.1k).Fix
Mismatch warnings (stderr only). After option parsing, memtier compares
LIBEVENT_VERSION_NUMBERwithevent_get_version_number(). If major.minor differ, it prints one warning to stderr. It does the same for OpenSSL, comparingOPENSSL_VERSION_NUMBERwithOpenSSL_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,--versionand--helpprint nothing extra, and--versionstdout is byte-identical. The comparison lives in the newlibrary_versions.h.Provenance. The crash report INFO section gains
libevent_build_version:andopenssl_runtime_version:. Existing keys are unchanged; note that the existingopenssl_version:is the build-time text.OpenSSL_version()is pre-resolved likeevent_get_version(). The JSONrun informationsection gains four new keys:libevent runtime version,libevent build version,OpenSSL runtime versionandOpenSSL 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 anyevent_baseexists; if it failed, memtier prints anerror:line and callsexit(1)right after option parsing, like the other post-parse error exits, so LeakSanitizer reports nothing.--helpand--versionbehave 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 returnsbool. On failure it logs anerror:line andconnect()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:BEV_OPT_CLOSE_ON_FREE, a failedbufferevent_openssl_socket_new()already frees theSSLin 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.BIO_NOCLOSE, and plainbufferevent_socket_new()does not close it either. memtier closes it.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.libevent_ssl_failure_socket_is_ours()inlibrary_versions.h, which is unit-tested.SSL_new()returning NULL is handled the same way; it was an assert before.setup_event()anddisconnect()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_extrapkg-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: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 (libevent 2.1.12 4 KiB read cap depresses pipelined 1 KiB GET results #535).
tests/run_local_gate.shnow checks for the 2.1.4 floor in DEVELOPMENT.md.Verify whether bufferevent_write is actually required for READONLY/CLIENT NO-TOUCH on discovered connections, or the original diagnosis was wrong #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(inmake 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 newtests/library_failure_injector.cand skip when not on Linux or when the binary is linked statically. Sanitizer runtimes are kept first inLD_PRELOAD, as in the crash-handler tests.test_json_run_information_library_versions: the new JSON keys are present,libevent runtime versionequals--version'slibevent=field,OpenSSL build versioncontainsopenssl=, 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.--versionstderr 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, theerror:line, no JSON written, and no LeakSanitizer report.--helpand--versionkeep their exit code and stdout under the same failure.test_bufferevent_creation_failure_fails_connection: a positive error exit (not a signal), theerror:line naming the constructor, and no sanitizer report. TLS runs exercisebufferevent_openssl_socket_new, plaintext runsbufferevent_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_connectionsnow also checks the new INFO lines, and thatlibevent_version:/openssl_version:equal--version'slibevent=/openssl=.Before/after: on master d8d4e9f, 4 of the 5 new tests fail:
Assertion 'm_bev != NULL' failed.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_8would hit the samem_bev != NULLassertion, andtest_crash_report_separates_build_and_runtime_versionswould find the new INFO fields missing. That makes 6 of the 7 tests intest_library_provenance.py, with the control passing.Local results (Docker, aarch64; CI covers x86_64):
test_prometheus:test_F16_ipv6, no IPv6 in the container; unrelated)--disable-tlsdetect_leaks=1), system libevent965cc5a8bb46ce4199a47e9b2c9e1cae3b137e8356ffdad6d94d3b9069b71dc2, which matches Debian'slibevent_2.1.8-stable-4.dsc. Built from source on glibc ≥ 2.36, 2.1.8 does not link (arc4random_addrandomis 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.--dry-run --Werroris 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 withLD_LIBRARY_PATHpointing at 2.1 fails to load beforemain(). The check therefore fires when the headers and the library come from different installations at build time: mixed-I/-Lprefixes, 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 viaCPPFLAGS=-I<2.2.2 prefix>/include, linked against the system 2.1.12 libraries. It builds and links,--versionis unchanged (libevent=2.1.12-stable), and a run printswarning: 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
--versionand existing JSON and crash-report keys are byte-identical. The only additions are the four JSON keys and the two crash INFO lines.Interactions
configure.acrequires 2.0.11. Theconfigure.achunks do not overlap: Use libevent cached time for deadline-clamped reconnects #812 touches the core/pthreads checks, this PR the Prometheus block.BEV_EVENT_ERRORhandler is untouched here, and this patch applies cleanly on top of Fix libevent TLS error reporting on 2.1 and 2.2 #822's head.Refs #545, #532, #535
🤖 Generated with Claude Code
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 informationkeys, 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/--versionunchanged).shard_connection::setup_event()returnsbooland replaces asserts onSSL_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.hunit tests, LD_PRELOADlibrary_failure_injector.c, andtest_library_provenance.pycover warnings, JSON, evthread fatality, and bufferevent failure paths; crash-handler integration checks new INFO fields.Reviewed by Cursor Bugbot for commit 9276de2. Bugbot is set up for automated code reviews on this repo. Configure here.