Skip to content

Add libevent build helper and compatibility CI for 2.1.12, 2.1.13 and 2.2.2-alpha - #545

Merged
fcostaoliveira merged 54 commits into
masterfrom
test/libevent-222-opt-in
Oct 26, 2026
Merged

fcostaoliveira merged 54 commits into
masterfrom
test/libevent-222-opt-in

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Depends on #822 and #832. This branch merges both PR branches unchanged, so either can land first and the other merges cleanly:

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 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 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 Fix libevent TLS error reporting on 2.1 and 2.2 #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 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

  • 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, 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.
  • 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).

🤖 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.sh builds verified releases (sha256) or a pinned master commit into an empty private prefix, with optional ASan+UBSan on libevent itself. check-libevent-linkage.sh asserts runtime libevent=, pkg-config, ldd/OpenSSL coherency (macOS defers to existing TLS link checks). build-macos-libevent.sh now calls the shared helper (CMake) instead of an inline autotools tarball build; ci.yml macOS jobs install cmake for that path.

.github/workflows/libevent-compat.yml plans PR vs nightly vs weekly scopes, runs unit + sharded integration tests per cell, caches built libevent, exposes libevent-compat-gate as the single required check (canary is continue-on-error with issue alerting), and widens coverage on harness-touching PRs.

DEVELOPMENT.md documents the tested matrix, local evaluation steps, and 2.1 vs 2.2 read/TLS-error behavior. test_reconnections.py dumps memtier stderr on signal death so sanitizer aborts show up in logs. .gitignore ignores local libevent build prefixes.

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

@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🤖 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 shard_connection.cpp / protocol.cpp / unit-test parts belong to #822 and #832, and you've asked for them to be reviewed there, so I left them alone. The landing order (#822 and #832 first, then merge master here) also looks right to me. A few questions:

  • build-macos-libevent.sh now builds the existing ci.yml macOS jobs with CMake instead of autotools. That changes how already-required checks get their libevent, not just how the new workflow gets it. Is the CMake build of 2.1.13 equivalent to the old ./configure --disable-debug-mode build for our purposes? I mean things like OpenSSL detection and the dylib names check-macos-tls-links.sh expects. Green CI suggests yes; I'm asking so it's a deliberate choice and not a side effect of sharing the helper.
  • canary-alert gives the workflow issues: write so it can open, comment on and close issues on its own. I'm not sure we want a bot filing issues on the repo. A canary failure already writes a warning and a step-summary line, so the issue could be optional. What do you think?
  • The gate checks needs.compat.result == success, and canary cells use job-level continue-on-error. I may be wrong, but I'm not 100% sure what needs.compat.result reports for a matrix where only a continue-on-error cell failed. Have you seen a full+canary run with a red canary leave the gate green? DEVELOPMENT.md lists a green full+canary dispatch as a prerequisite for making the gate required, so it would be good to confirm.
  • On cost: ~200 runner-min per PR on top of ~818 is a noticeable increase. You've already explained why stable runs on every PR and that moving it to nightly is a one-line change, so I'm fine with that. Whoever manages the CI budget may want to weigh in before the gate becomes required.

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/continue-on-error behaviour is confirmed and someone has decided about the issue-filing job, this looks good from my side.

@fcostaoliveira
fcostaoliveira marked this pull request as ready for review September 21, 2026 14:53
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Addressed in b3985ac:

  • The existing macOS wrapper now uses the shared helper, so the 2.1.13 pin/checksum has one definition. The separate OpenSSL 1.0.2 job retains its existing 2.1.12/autotools build; migrating that legacy combination is outside this change. Both affected macOS jobs now install CMake explicitly. A CMake 4.0.3 build also caught and verified the required policy-minimum compatibility setting for stable libevent.
  • Compatibility CI now runs on build-related path changes, weekly, and via workflow_dispatch. It does not run on unrelated source/documentation PRs. Existing distribution-library CI remains unchanged.
  • Removed the enumerated TEST list and string substitutions. Each compatibility job now runs the complete standalone and cluster suites. The no-TLS configuration keeps the default Prometheus support enabled; the four TLS/Prometheus compile combinations were separately checked locally.
  • The helper prefers sha256sum on Linux and falls back to shasum for macOS.

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.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

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.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Addressed the stable-selection safeguard in 709dab0: the existing macOS wrapper explicitly sets LIBEVENT_VERSION=2.1.13-stable, while the generic helper retains the alpha opt-in. Verified both unset and exported-alpha caller environments.

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.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks; these are intentional scope choices:

  • The macOS-wrapper path trigger is conservative: that wrapper is a consumer of the same helper and pinned default, so changes to how it selects/configures the dependency run the shared-helper compatibility matrix too. The actual wrapper is exercised by the existing macOS CI jobs. All four macOS jobs passed on the final 709dab0 head, including OpenSSL 1.1 and OpenSSL 3.0. Keeping this extra build-related trigger is a deliberate coverage/cost tradeoff; ordinary C++/documentation changes do not trigger this matrix.
  • Stable 2.1.13 is the control for the isolated-prefix/shared-helper path. Distribution CI uses the distribution's libevent, not necessarily this release or the same build/linkage path. It also protects the pinned dependency now used by the existing custom macOS builds. The scheduled/manual coverage remains useful independently of whether alpha eventually becomes suitable as a default; this PR makes no such default-upgrade decision.
  • Requiring an empty install prefix intentionally prevents mixing stale installed headers/libraries after a failed or changed build. A failure before install leaves an empty reusable prefix; a partial install requires a fresh prefix. The message and documentation recommend an empty/fresh prefix. I prefer not to suggest an unconditional recursive deletion command against a caller-supplied directory. Fresh GitHub runner prefixes are unaffected.
  • This workflow guards compatibility and actual loader selection. It does not claim to guard throughput or every libevent backend's read limit. A public-API max-read value alone would be a misleading regression assertion: 2.1 already advertises a 16 KiB bufferevent limit while its inner evbuffer clamps actual reads. A Linux syscall-level check can observe the distinction, as the separate diagnostic does, but scheduling/availability and non-FIONREAD backends need different expectations. Keeping that experiment separate avoids encoding a performance claim into a functional compatibility job.
  • When adding another supported version, maintainers must update the helper checksum case and CI matrix/runtime-version expectations together. The existing inline comment explains the alpha runtime suffix; the workflow's exact-version assertion deliberately fails if upstream changes that convention.

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.

@fcostaoliveira fcostaoliveira changed the title Add opt-in libevent 2.2.2-alpha builds and compatibility CI Support opt-in libevent 2.2.2-alpha and guard TLS error access Sep 21, 2026
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Additional dependency-instrumented validation found a real compatibility defect and changed the scope. Fixed in 05a8415:

  • A TLS-enabled memtier called bufferevent_get_openssl_error for plaintext BEV_EVENT_ERROR too. Stable safely returned zero, but alpha's SSL-only accessor accesses outside the plain bufferevent allocation. Instrumenting only memtier did not expose this; instrumenting libevent did.
  • The call is now guarded by the same openssl_ctx condition used when constructing the bufferevent. Added bounded plaintext connection-refusal and TLS handshake-failure tests, with reconnect and sanitizer assertions.
  • The existing alpha plaintext CI cell now instruments both memtier and libevent with ASan/UBSan. It remains a TLS-capable binary, so both new regression paths run there. No additional matrix jobs were added. Connection implementation and regression-test paths now trigger the matrix.
  • Documented the separate alpha limitation: its accessor currently returns no queued OpenSSL reasons for genuine TLS bufferevents. The guard prevents the plaintext invalid access; it does not pretend to repair that upstream diagnostic behavior.

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.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Addressing the latest review:

  1. Yes, the regression fails on the preserved master-source binary with instrumented alpha, and passes after the guard. The before-fix ASan stack is heap-buffer-overflow → bufferevent_get_ssl_error (bufferevent_ssl.c:1108) → bufferevent_get_openssl_error (bufferevent_openssl.c:543) → shard_connection::handle_event (shard_connection.cpp:1475). The test fails first on the signal exit, and the diagnostic is also present. The direct driver explicitly requires this expected baseline failure. Added the evidence to the description. Stable's defensive upcast makes this specific to alpha; forcing an artificial stable failure would misrepresent the regression. The single instrumented cell is intentional and still runs the full suites plus both new transport regressions.
  2. Agreed this is an alpha diagnostics regression, including the risk that fallback errno text is not an SSL protocol reason. The guard does not introduce that TLS behavior: on a genuine TLS connection it leaves the accessor loop/fallback unchanged. This opt-in build documents the upstream limitation rather than adding a version-specific workaround or claiming alpha is production-ready. ERR_get_error() is not an appropriate substitute because libevent already drains that queue.
  3. Intentional: the BEV_EVENT_ERROR callback operates on the current live bufferevent, installed by setup_event; it is not delivered for a null m_bev. The constructor's TLS-context predicate is the relevant type guard. A second defensive null check is unnecessary here.
  4. Keeping abort_on_error is intentional. Any sanitizer finding, including a leak on a failure path, should fail this validation. Turning abort off changes the failure exit form, not whether a leak should be accepted. The tests reject both signal death and sanitizer diagnostics, and both instrumented local suites passed with these exact options.
  5. The trigger is intentionally scoped to this shared dependency build and the connection implementation/regressions under test. The weekly/manual matrix covers other libevent consumers; existing distribution CI still runs for their ordinary source changes. This is the coverage/cost compromise described in earlier review, not a claim that every libevent API caller triggers this workflow.
  6. Widening the test window from 2 to 5 seconds gives margin over the fixture's one-second read timeout and initial reconnect delay while retaining the stronger two-actual-connections assertion. The subprocess remains bounded at 15 seconds. Switching the capability probe to the existing --version openssl field also removes the help-format dependency.

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.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Settling the remaining scope choices for this PR:

  • Keeping all six cells for the listed PR paths. The actual compatibility failure was alpha-specific and invisible to the stable control and memtier-only sanitizers, so moving alpha to a weekly-only check would remove the pre-merge regression guarantee we just added. The matrix remains scoped rather than running for every source change. This is a deliberate acceptance of the added CI cost to validate the optional dependency path. The comment directly above SANITIZE already records why dependency instrumentation is necessary; the description and regression test explain the plaintext/TLS-enabled shape. There are three stable cells (plaintext, TLS, TLS-disabled), with the same three alpha configurations.
  • Negative Python subprocess return codes indicate signal termination. The >= 0 assertion specifically rejects those; the following assertions independently require connection-error/reconnect evidence and reject sanitizer diagnostics. Expected ordinary benchmark failure exit codes are allowed because these fixtures deliberately cannot serve a workload.
  • The PKG_CONFIG_PATH selection remains useful: CMake's FindOpenSSL invokes pkg_check_modules(_OPENSSL ... openssl) and uses the resulting hints. OPENSSL_ROOT_DIR is also explicit; both point at the same selected OpenSSL to avoid ambient Homebrew/pkg-config discovery selecting a different one.
  • The nonempty-prefix rejection applies to an existing nonempty directory. A newly created directory is empty and passes that guard; it cannot be the directory just created by mkdir that triggers the rejection absent concurrent external modification. Empty prefixes left by pre-install failures remain reusable; partially installed prefixes deliberately require a fresh destination.

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]>
fcostaoliveira and others added 4 commits October 24, 2026 07:27
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]>
@fcostaoliveira fcostaoliveira changed the title Support opt-in libevent 2.2.2-alpha and guard TLS error access Add libevent build helper and compatibility CI for 2.1.12, 2.1.13 and 2.2.2-alpha Oct 24, 2026
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]>
fcostaoliveira pushed a commit that referenced this pull request Oct 24, 2026
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]>
fcostaoliveira and others added 2 commits October 24, 2026 08:23
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]>
fcostaoliveira and others added 3 commits October 24, 2026 23:50
…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]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Pushed 3a20b86, and merged master and #832 (a7fe64f) back in. #832's protocol.cpp, unit test, fuzzer test and fixtures README are byte-identical to the #832 branch. The diff against master is again only CI, tooling and docs plus the #822/#832 hunks.

  • Sanitized TLS on next. Added a nightly-only next, tls-asan, standalone cell. It runs Fix libevent TLS error reporting on 2.1 and 2.2 #822's TLS fallback (bufferevent_openssl_get_ssl() + SSL_get_verify_result()) against an ASan+UBSan libevent, and it adds no per-PR cost. Since this push changes the workflow, this PR's own run uses the full grid and runs that cell now.
  • CI budget. Agreed, that sign-off belongs to whoever owns the CI budget, before libevent-compat-gate is made required. It stays in the description as an open maintainer decision.
  • Harness paths. utils/select_test_shard.py and utils/check_test_shards.py now trigger the full grid as well.

…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]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Pushed 659efb7:

  • When the gate becomes required. DEVELOPMENT.md now says it next to the "only libevent-compat-gate needs to be required" line: make it required only after three consecutive green nightly runs and one green full+canary dispatch.
  • One topology per PR. That call belongs to whoever watches the CI budget. It remains an open maintainer decision in the description.
  • macOS OpenSSL 1.1 on the CMake helper. It's green on this PR's current runs: build-macos-openssl-1-1 passed on 3a20b86, as did build-macos (3.0), (3) and (4), the Homebrew libevent job, and the autotools OpenSSL 1.0.2 job.
  • Cache key hashing the workflow. Yes, that's deliberate: build options come from the workflow, so any edit rebuilds the libevents once. On a cache miss that adds a few minutes per cell, only on PRs that touch the harness.

Also fixed after an independent review: 2.2's TLS do_read() keeps calling SSL_read() until 16 KiB or the socket is drained. It can therefore take several records per event, unlike 2.1's one, and DEVELOPMENT.md now says that. The new sanitized TLS cell is listed in the coverage table. On 3a20b86 it passed 874/874.

On 3a20b86, libevent-compat (legacy, plaintext, standalone) failed in test_unowned_keys_survive_repeated_redial, from #799. memtier hit that test's 2-second --connection-stage-timeout: the test injects 0.2 s and 0.4 s server delays and two 0.5 s backoffs. The same test passed in the stable, next and sanitized standalone cells of that run, and ci.yml's cells on the same libevent 2.1.12. I'm checking how often it fails on master; details follow.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks.

  • stable per PR. I'd keep it, because ci.yml's 2.1.13 jobs only build. Alpine, Debian trixie/sid, MSYS2 and el9/el10 compile and some run make check, but none of them runs the integration suites against 2.1.13. Moving it to nightly is the one-line change in plan. As you say, that decision belongs to whoever owns the CI budget, and it stays listed as open in the description.
  • Gate vs. canary. I haven't seen it either. PR runs never include the canary, and workflow_dispatch only works once the workflow is on the default branch. The gate checks needs.compat.result == success. Whether a matrix job whose only failures are continue-on-error cells reports success there is exactly what the first full+canary dispatch has to show. DEVELOPMENT.md already says to make the gate required only after one green full+canary dispatch. If that run shows a canary failure turning the gate red, the fix is to drop the canary from compat into its own job that the gate doesn't depend on, and I'll do that then.
  • macOS helper switch. Intentional: one helper builds the same pinned 2.1.13 the same way for both workflows. The ci.yml macOS jobs, including OpenSSL 1.1 and 3.0 on the CMake build, are green on this PR, and check-macos-tls-links.sh still checks the linkage.
  • Cache key. Yes, that's deliberate (see my previous reply).

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ 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.

Comment thread .github/workflows/libevent-compat.yml Resolved
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks.

  • Canary vs. gate. Agreed, it hasn't been seen yet, and no PR run includes the canary. The first full+canary dispatch after merge has to show it. DEVELOPMENT.md makes that dispatch a precondition for marking the gate required. If the canary turns the gate red, the canary moves to its own job outside needs.
  • What the gate covers. Gating only on stable and the sanitized next plaintext cell is a reasonable option. I'd keep the next TLS cells in, because they are what catch the other half of Fix libevent TLS error reporting on 2.1 and 2.2 #822: 2.2 returning no OpenSSL reason on TLS bufferevents. That choice, and the per-PR minutes, are for the maintainers to make before the gate is required, and both are listed as open in the description.
  • macOS. A second look from whoever maintains the macOS/OpenSSL matrix (socket_options_test segfaults in build-macos (3): Homebrew libevent now links OpenSSL 4, memtier links openssl@3 #674, Drop the unused LT_INIT and the libtool build dependency #762) is welcome. All six macOS jobs are green on this PR's runs.
  • nullglob. Right, it can't happen after a successful install, which the earlier step checks. I'll fix it the next time the script changes, rather than spend a full-grid CI run on it now.

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]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

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 continue-on-error: ${{ matrix.canary }} and fail-fast: false, and a gate with if: always() reading needs.<job>.result.

  • Run 40172132895, only the canary leg fails: the canary job is failure, needs.<job>.result is success, the gate passes, and the run concludes success.
  • Run 40172036273, a second matrix in the same run where the non-canary leg fails: needs.<job>.result is failure, so the gate fails.

So a broken canary shows as a red canary job (plus the step-summary warning and the canary-alert issue) but never turns libevent-compat-gate red, and a failing required cell does. I still plan one real full+canary dispatch before making the gate required, as the description says. But the failing-canary case no longer depends on that dispatch happening to fail.

Per-PR cost and canary-alert issues. Agreed, both are maintainer calls. They're listed under "Needs a maintainer decision" in the description, together with when to make the gate required. Moving stable TLS to nightly is a one-line change in plan, and dropping the issue automation means deleting the canary-alert job. The step-summary warning stays either way.

Diff after #822 and #832 land. Will do. Right now the sanitizer TEST: list edits (adding test_connection_error_types.py in asan.yml, tsan.yml and ubsan.yml) come from #822, merged in here, as do shard_connection.cpp, protocol.cpp and the test files. Once those PRs land I'll merge master back in and confirm the diff is only workflows, scripts, .gitignore and docs before this merges.

fcostaoliveira and others added 2 commits October 25, 2026 07:18
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]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Taking the new points first.

macOS CMake build: deliberate. build-macos-libevent.sh now calls the shared helper so that the existing macOS jobs and the compat cells build libevent the same way. These things are unchanged from the old ./configure build:

  • the same 2.1.13 release tarball and sha256 (the helper pins the same checksum)
  • the same OpenSSL (-DOPENSSL_ROOT_DIR="$ssl_prefix", plus PKG_CONFIG_PATH as before)
  • debug mode off (-DEVENT__DISABLE_DEBUG_MODE=ON, the CMake spelling of --disable-debug-mode)
  • samples and regress tests off

Evidence from build-macos-openssl-1-1 on cd86f27 (run 40172285422):

  • CMake reports Found OpenSSL: /opt/homebrew/opt/[email protected]/lib/libcrypto.dylib (found version "1.1.1w").
  • It installs libevent_openssl-2.1.7.dylib, the same file name autotools produces, under the private prefix.
  • memtier then reports libevent=2.1.13-stable openssl=OpenSSL 1.1.1w.

check-macos-tls-links.sh matches any libevent_openssl*.dylib rather than one exact name. It checks that memtier and libevent_openssl load from that prefix and link the same OpenSSL, and all three macOS jobs pass it.

Gate vs. canary. I tested this with probes on my fork in the previous reply, which this edit may not have seen:

  • Run 40172132895 has the same continue-on-error: ${{ matrix.canary }} matrix and the same if: always() gate. When only the canary leg fails, the canary job is red, but needs.<job>.result is success, the gate passes, and the run concludes success.
  • Run 40172036273: when a non-canary leg fails, the result is failure and the gate fails.

The real full+canary dispatch is still planned before the gate becomes required.

canary-alert issues and per-PR cost. Both are maintainer calls, listed under "Needs a maintainer decision". If maintainers prefer no bot-filed issues, deleting the canary-alert job leaves the warning and the step-summary line.

fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
## 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]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
## 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]>
@fcostaoliveira
fcostaoliveira merged commit 6d7594a into master Oct 26, 2026
56 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
#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]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
… 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]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
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]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
## 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 &lt; 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 &lt; 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 &gt; 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]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
)

## 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]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant