Repository navigation
perf(miss-tracking): alloc-free per-position tracking for ArrayPerElementNulls (HMGET) [RED-200840] - #472
Merged
fcostaoliveira merged 1 commit intoJun 16, 2026
Conversation
…mentNulls The arbitrary-command miss-tracking for ArrayPerElementNulls replies (HMGET/MGET/ZMSCORE/GEOPOS/...) forced set_keep_value(true), materializing the entire reply tree -- a malloc+memcpy per element plus an mbulk/bulk_el node per element -- purely to attribute hits/misses per position. For small values the per-element node allocation, not the value copy, dominates, so this cost ~37% throughput / ~80% client CPU per op on HMGET (RED-200840, lab-confirmed). Replace the materialized walk with a per-top-level-element hit bitmap recorded directly by the parser (set_track_elem_misses): one uint8_t per element into m_last_response.m_elem_hits, no value copy, no node tree. Hit/miss is known at parse time: - bulk leaf: hit iff $N with N>0 (null $-1 and empty $0 are misses); - single-type leaf: hit unless RESP3 null '_'; - nested sub-array element: hit iff non-empty (*0/*-1 are misses). Nesting is handled with a single counter (m_nested_remaining) that tracks outstanding leaf slots in the current top-level element's subtree, so only direct children of the top-level array are recorded -- no frame stack, any depth. The client reads the bitmap instead of walking get_mbulk_value(); a non-array reply (top_array_len<0) still yields one miss bucket, exactly as the old get_mbulk_value()==NULL guard did. Verified deterministically (key-maximum=1) that per-position hit/miss is identical to the materialized walk for HMGET, MGET, and nested GEOPOS, under both RESP2 and RESP3. Co-Authored-By: Claude Opus 4.8 <[email protected]>
🛡️ Jit Security Scan Results✅ No security findings were detected in this PR
Security scan by Jit
|
fcostaoliveira
added a commit
that referenced
this pull request
Jun 16, 2026
…mentNulls (#472) The arbitrary-command miss-tracking for ArrayPerElementNulls replies (HMGET/MGET/ZMSCORE/GEOPOS/...) forced set_keep_value(true), materializing the entire reply tree -- a malloc+memcpy per element plus an mbulk/bulk_el node per element -- purely to attribute hits/misses per position. For small values the per-element node allocation, not the value copy, dominates, so this cost ~37% throughput / ~80% client CPU per op on HMGET (RED-200840, lab-confirmed). Replace the materialized walk with a per-top-level-element hit bitmap recorded directly by the parser (set_track_elem_misses): one uint8_t per element into m_last_response.m_elem_hits, no value copy, no node tree. Hit/miss is known at parse time: - bulk leaf: hit iff $N with N>0 (null $-1 and empty $0 are misses); - single-type leaf: hit unless RESP3 null '_'; - nested sub-array element: hit iff non-empty (*0/*-1 are misses). Nesting is handled with a single counter (m_nested_remaining) that tracks outstanding leaf slots in the current top-level element's subtree, so only direct children of the top-level array are recorded -- no frame stack, any depth. The client reads the bitmap instead of walking get_mbulk_value(); a non-array reply (top_array_len<0) still yields one miss bucket, exactly as the old get_mbulk_value()==NULL guard did. Verified deterministically (key-maximum=1) that per-position hit/miss is identical to the materialized walk for HMGET, MGET, and nested GEOPOS, under both RESP2 and RESP3. Co-authored-by: Claude Opus 4.8 <[email protected]>
fcostaoliveira
added a commit
that referenced
this pull request
Jun 16, 2026
…prometheus-exporter Resolves tests/test_requirements.txt by keeping both new deps (prometheus_client for the exporter suites + psutil for master's CPU cross-validation). Source files (run_stats, client, memtier_benchmark) auto-merged; verified: both build flavors compile, make check + format-check green, statsd wire test 4/4 (one-producer refactor intact), live /metrics scrape 200. Co-Authored-By: Claude Fable 5 <[email protected]>
This was referenced Jun 16, 2026
This was referenced Oct 24, 2026
Closed
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Follow-up to #469 (now merged). Fixes the HMGET half of the RED-200840 regression. (Supersedes #470, which GitHub auto-closed when #469's branch was deleted; rebased onto master so the diff is now HMGET-only.)
ArrayPerElementNullsreplies (HMGET / MGET / ZMSCORE / GEOPOS / ...) forcedset_keep_value(true), materializing the whole reply tree — amalloc+memcpyper element plus anmbulk/bulk_elnode per element — purely to attribute hits/misses per position. For small values the per-element node allocation dominates, so #469 (EmptyCollection/HGETALL only) left HMGET regressed.This replaces the materialized walk with a per-top-level-element hit bitmap recorded directly by the parser (
set_track_elem_misses): oneuint8_tper element intoprotocol_response::m_elem_hits— no value copy, no node tree. Hit/miss is known at parse time:$N, N>0 (null$-1and empty$0are misses);_;*0/*-1are misses).Nesting uses a single counter (
m_nested_remaining) tracking outstanding leaf slots in the current top-level element's subtree, so only direct children of the top array are recorded — no frame stack, any depth.Lab results (Granite Rapids, single-core client, pipeline=64, 40-field hashes, N=5 interleaved)
Correctness
Verified deterministically (
--key-maximum=1, fixed keys) that per-position hit/miss is identical to the old materialized walk for HMGET (mixed present/absent fields), MGET (multi-key spec), and nested GEOPOS — under both RESP2 and RESP3 (_null path). The existingtests/test_arbitrary_command_misses.pysuite covers these shapes.🤖 Generated with Claude Code
Co-Authored-By: Claude Opus 4.8 [email protected]
Note
Medium Risk
Touches RESP parsing and miss-accounting on the benchmark hot path; behavior is intended to match the prior walk but nested-array and RESP3 edge cases are subtle.
Overview
ArrayPerElementNulls miss tracking (HMGET, MGET, ZMSCORE, GEOPOS, …) no longer turns on
set_keep_value(true)to build a full reply tree. Clients that need per-position misses now enableset_track_elem_misses(true), and the Redis parser records oneuint8_tper top-level reply element inprotocol_response::m_elem_hitswhile streaming the RESP frame.client::handle_responseforReplyShape::ArrayPerElementNullsaggregates hits/misses fromget_elem_hits()(andget_top_array_len()for non-array replies) instead of walkingget_mbulk_value(). Semantics match the old materialized walk: bulk hits when length > 0, RESP3_is a miss, nested sub-arrays count as a hit when non-empty.Nested replies use
m_nested_remaininginredis_protocolso only direct children of the top array are recorded, without allocating mbulk/bulk nodes on the hot path.Reviewed by Cursor Bugbot for commit 20298d7. Bugbot is set up for automated code reviews on this repo. Configure here.