Skip to content

Reject RESP lengths and counts the parser cannot represent - #832

Merged
fcostaoliveira merged 8 commits into
masterfrom
fix/resp-bulk-length-overflow
Oct 26, 2026
Merged

fcostaoliveira merged 8 commits into
masterfrom
fix/resp-bulk-length-overflow

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

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

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

🤖 Generated with Claude Code


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.

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

A bulk length of LONG_MAX or LONG_MAX - 1 (strtol clamps an out-of-range
length to LONG_MAX) made m_bulk_len + 2 overflow long in rs_read_bulk.
A RESP3 map or attribute count above INT_MAX / 2 overflowed int when
doubled. Under per-element miss tracking, nested counts adding up past
INT_MAX overflowed m_nested_remaining. Counts above INT_MAX were also
silently truncated when stored in int.

Reject a bulk length above LONG_MAX - 2. Also reject an aggregate whose
elements, together with the ones still outstanding, exceed INT_MAX.
Both go through the existing parse_response() == -1 error path. Valid
lengths and counts parse as before.

The RESP fuzzer missed this because UBSan with halt_on_error=1 and no
abort_on_error exits 1 and prints only "runtime error:". Treat that
string, and LeakSanitizer reports, as crash needles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review. A human maintainer still needs to review this before merge.

Thanks for this. I went through the bounds and they look right to me. outstanding is taken before the nested decrement and count is added after it, so m_total_bulks_count stays at or below INT_MAX. The tracked_nested condition uses the same !m_push && line[0] != '|' gate as the tracking block below it, so the m_nested_remaining - 1 adjustment applies exactly when the += count - 1 branch can run. Parsing the bulk length into a local, so a rejected line leaves m_bulk_len alone, is a nice touch. The unit cases cover both sides of each boundary, and you showed they fail on master, which is the bar this kind of parser fix should meet.

One question, not blocking and probably a follow-up rather than something for this PR: with miss tracking on, a top-level *2147483647 is still accepted and goes straight into elem_hits_reserve(count). That is a std::vector<uint8_t>::reserve of about 2 GB, sized by whatever count the server declares, before any elements arrive. It isn't UB and it isn't new, but it's the same class of "trust the server's declared count" issue. I wonder if it's worth capping the reserve, e.g. std::min(count, some_small_hint), and letting push_back grow the vector, now that you're in this code anyway.

Thanks also for the runtime error: needle in the fuzzer. A UBSan exit with code 1 slipping past the harness is exactly the kind of gap that hides bugs like this one.

The core fix looks solid to me.

@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 22c6282. Configure here.

Comment thread tests/unit/redis_protocol_test.cpp Resolved
fcostaoliveira and others added 2 commits October 24, 2026 12:42
…G_MAX

long is 32-bit on Windows, so strtol clamped counts above INT_MAX to
LONG_MAX == INT_MAX. That let them pass the new bound, and the unit test
hardcoded 64-bit LONG_MAX boundaries (MSYS2 UCRT64 make check failed).
Parse aggregate counts as long long, and build the bulk length
boundaries from LONG_MAX at run time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

fcostaoliveira commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thanks for the review (version updated 2026-10-24T11:43:15Z).

  • README row 5: updated in 300da45. *4294967295 is now described as a count above INT_MAX that is rejected by the outstanding-elements bound, instead of as an unsigned wrap.
  • Partial mbulk tree on the -1 path: the connection is not torn down. process_response() logs "error: response parsing failed." and reports a connection-stage failure. The parser stays in rs_read_line. Both new rejections return before any state changes: m_total_bulks_count, m_current_mbulk, the tree, the status and tracking are all untouched. So the rejected element's slot stays outstanding and the tree stays consistent with the counter. Nothing walks m_last_response until a later reply completes (parse_response() == 1). This is the same contract as the existing "unsupported response" return. Tearing the connection down on any parse error would be a broader behaviour change, so I've left it out of this PR.
  • ASan: the local sanitizer runs use --enable-sanitizers --enable-ubsan, i.e. ASan+UBSan with ASAN_OPTIONS=detect_leaks=1:abort_on_error=1. make check and all 12 test_resp_response_fuzzer.py tests pass there with the new LeakSanitizer / runtime error: needles. Update: all asan.yml jobs on 300da45 have now passed.

fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
… branch

The sanitized next cell's UBSan abort found the bulk-length overflow;
carry the fix so the cell can go green before either PR lands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Re the review updated 2026-10-24T11:54:05Z, about a nested map near the bound: I checked this locally in an ASan+UBSan build (abort_on_error=1) against 300da45 with these extra cases. All three pass and UBSan reports nothing:

  • *2\r\n%1073741823\r\n returns 0 (waits). Outstanding is 1, so the limit is (INT_MAX - 1) / 2 = 1073741823, and the total becomes exactly INT_MAX.
  • *2\r\n%1073741824\r\n returns -1.
  • *3\r\n%1073741823\r\n returns -1. Outstanding is 2, so the limit is 1073741822.

The bot marked this as optional, and #545 currently carries this branch merged in, so I haven't pushed these cases. I can add them if a maintainer wants them in-tree.

fcostaoliveira and others added 2 commits October 24, 2026 14:48
A nested RESP3 attribute takes a slot of its parent but is not tracked
for per-element misses. That leaves m_nested_remaining larger than the
outstanding element count, so *1 *2 |0 *2147483647 with miss tracking
on still overflowed m_nested_remaining. When a tracked nested element
is being recorded, include m_nested_remaining - 1 in the bound as well.

Also parse the bulk length into a local, so a rejected length leaves
m_bulk_len unchanged. Add unit cases for maps nested under outstanding
elements and for the nested-attribute case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

fcostaoliveira commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Re the review updated 2026-10-24T13:49:29Z:

  • m_total_bulks_count wording: fixed in 3b65721. The comment above the bound now says the doubling and m_nested_remaining are int arithmetic, and that the bound keeps the unsigned int m_total_bulks_count within int range. The README row for mbulk_count_overflow.bin says the same.
  • elem_hits_reserve(count) with a top-level *2147483647 under miss tracking: agreed, this is a real problem. It is not overflow or UB, though: it is a large up-front allocation driven by a header line, and it predates this PR (perf(miss-tracking): alloc-free per-position tracking for ArrayPerElementNulls (HMGET) [RED-200840] #472). I'd rather keep this PR to the overflow fixes and handle that separately. A capped or lazy reserve would be a performance-sensitive change to the perf(miss-tracking): alloc-free per-position tracking for ArrayPerElementNulls (HMGET) [RED-200840] #472 path and deserves its own review. I've noted it for follow-up.
  • tracked_nested bound: thanks for tracing it. dfc7899 adds the at-bound case (*1 *2 |0 *2147483646 waits) and the above-bound case (... *2147483647 is rejected). On 300da45 the above-bound case tripped UBSan (protocol.cpp:760:48: signed integer overflow: 2 + 2147483646). It also fails on master.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Re the review updated 2026-10-24T14:02:40Z:

fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Re the review updated 2026-10-24T14:41:28Z: thanks. On the elem_hits_reserve(count) question: yes, I think it's worth a separate issue. Capping the reserve (for example min(count, small) and letting the vector grow) is a reasonable direction, but it touches the #472 hot path, so it should be reviewed and benchmarked on its own. I'm leaving it out of this PR and have flagged it for a follow-up issue. On a92655a the only red job is again the unrelated TSan crash-tail failure (test_crash_handler_integration, -14 watchdog), tracked by #412 and #828.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

CI note for a92655a. The only failure is TSAN OSS-CLUSTER API: TCP TLS (misc) → test_crash_handler_integration:test_crash_handler_time_zone_lock_held, with exit -14 from the watchdog and no BUG REPORT END. This is the known TSan crash-report failure: it also fails on master (1c4c897, run 40071862306) and on other PRs (#812, #828). Its root cause is analysed in #828 (TSan symbolizing a suppressed report while the main thread receives the test's SIGSEGV), and it is tracked by #412. This PR does not touch the crash handler. I'm re-running the failed job on that evidence. A different failure would be investigated rather than re-run.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. Pushed 15ef8ad, which moves the strtoll-vs-strtol / Windows long note next to the strtoll call. The bound's comment now only explains why the bound exists.

  • More fuzzer fixtures. I tried %1073741824\r\n as a fixture, but it doesn't catch a regression end to end. With master's protocol.cpp under ASan+UBSan, the fuzzer harness passes that fixture too (12/13 passed; only bulk_int_overflow failed). A top-level map count doesn't reach the int arithmetic that overflows. That needs the nested-aggregate and miss-tracking paths, and the harness doesn't enable miss tracking (it runs SETs in default mode, no --command MGET). The nested-attribute case is the same, so I left both to the unit test. check_length_limits() fails on master's parser for each of them, and fixtures that pass either way would only add runtime.
  • Release notes. I added a "Release notes" section to the description. *2147483648, previously truncated to a null array, and bulk lengths above LONG_MAX - 2 are now protocol errors.

#545 picks up 15ef8ad in its next master/#832 merge.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Thanks. The elem_hits_reserve(count) reserve of about 2 GB for *2147483647 with miss tracking is filed as #837. It's the same "trust the declared count" class, and as you say it isn't UB or new, so I kept it out of this fix. #837 suggests the same approach as you: cap the reserve at a small hint and let push_back grow the vector.

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

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

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

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

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

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

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

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

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

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


<!-- CURSOR_SUMMARY -->
---

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



Co-Authored-By: Claude Opus 5.5 <[email protected]>
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
#832's bound comment and unit-test comment said a nested attribute takes
a parent slot; with this PR an attribute is drained in its own scope and
takes none. Keep #832's bound and say so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
Fixes #458.

`redis_protocol::parse_response()` treated a RESP3 attribute (`|N`) like an ordinary aggregate. Its key/value pairs became part of the reply. With `set_keep_value(true)` that crashes. The three forms in the issue comments all reproduce on master under ASan + UBSan:
- `|0\r\n*1\r\n+a\r\n`: the attribute becomes the root of the kept tree, and the next aggregate calls `add_new_element()` on a NULL cursor (`protocol.cpp:764`).
- An attribute inside an attribute hits `assert(!m_attribute)`.
- An attribute on an array element, `*2\r\n|1\r\n+k\r\n+v\r\n+a\r\n*1\r\n+b\r\n`: it takes one of the parent's slots, so the reply ends early, and the following aggregate dereferences NULL.

Without keep_value, the attribute's elements were counted as hits and as ArrayPerElementNulls elements, which is the miscount the issue describes. An error inside an attribute also marked the whole reply as an error; it no longer does.

**Fix (`protocol.cpp` only).** An attribute is now drained in its own scope, the same way a nested push (`>`) already is. It takes no slot from its parent, and anything inside it (another attribute, or a push) is drained with it. When it ends, parsing continues as if it weren't there; at top level, the reply goes on. Nothing from an attribute is ever added to the reply tree, so there is nothing to free.

**Tests.** A new `check_attribute_frames()` in `tests/unit/redis_protocol_test.cpp` covers:
- the three crash forms
- an attribute before `*0` (still empty for EmptyCollection, with and without keep_value)
- an attribute inside a map
- an attribute on an array element (gives [miss, hit] for ArrayPerElementNulls)
- attribute bulks not counted as hits

Against master's `protocol.cpp`, each crash form aborts under ASan (null member call, or the assertion) and the counting cases give wrong results. With the fix every case passes.

**Results** (Ubuntu 24.04 container, ASan + UBSan):
- `make check` passes, and clang-format is clean.
- `test_resp_response_fuzzer.py`, `test_read_preference_resp3.py`, `test_arbitrary_command_misses.py` and `test_collection_scan.py` pass 47/47.

**#832** (also in `protocol.cpp` / `redis_protocol_test.cpp`) merges cleanly with this, and the merged tree's sanitized unit test passes, including #832's nested-attribute bound checks. Once both land, a comment in #832 saying a nested attribute "takes a parent slot" will be out of date.

## Release notes (proposed)

> Fixes crashes and miscounts when a RESP3 server sends attribute frames (`|`): attribute contents are no longer counted in Hits/Misses or per-element miss tracking, and no longer reach the kept reply (#458).


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core RESP3 reply parsing and completion logic; incorrect draining could mis-frame replies or miscount hits, though behavior is narrowly scoped to attribute frames with extensive unit tests.
> 
> **Overview**
> Fixes **#458** by treating RESP3 **attribute** frames (`|N`) like out-of-band drain scopes (same pattern as nested push `>`), instead of merging their key/value pairs into the command reply.
> 
> **`protocol.cpp`:** On `|`, the parser enters nested drain mode (`m_push` / `m_push_nested`), skips consuming a parent aggregate slot, and does not record attributes as the top-level reply body, kept mbulk tree, hits, or per-element miss tracking. When the attribute ends, parsing resumes on the following element; errors inside an attribute no longer mark the whole reply as failed. **`m_push_outer_attribute`** is removed in favor of this unified nested-scope handling.
> 
> **Tests:** New **`check_attribute_frames()`** covers prior crash shapes (top-level and nested attributes with `keep_value`), maps, empty arrays, push/attribute interaction, and ArrayPerElementNulls alignment.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit a173343. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->


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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RESP parser: oversized bulk length or aggregate count causes signed integer overflow (UB)

1 participant