Skip to content

test(protocol): adversarial RESP-server fuzzer for client-side parsing - #419

Merged
fcostaoliveira merged 5 commits into
redis:masterfrom
filipecosta90:test/issue-409-resp-response-fuzzer
Jun 1, 2026
Merged

fcostaoliveira merged 5 commits into
redis:masterfrom
filipecosta90:test/issue-409-resp-response-fuzzer

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 30, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #409

Summary

Adds a defensive test fixture exercising the client-side RESP-response
parser branches that the audit in #409 flagged as unaudited (bulk-length
overflow, RESP3 push / verbatim / map edge cases, malformed CLUSTER SLOTS,
unsolicited replies, truncated frames).

Three pieces:

  • tests/fixtures/mock_redis_resp_fuzzer.py -- ~200 LoC mock-redis
    server. Lets the HELLO / AUTH / SELECT handshake pass with benign
    replies, then serves the adversarial payload to the first workload
    command and half-closes. A --passthrough-cluster flag lets non-cluster
    fixtures be run against --cluster-mode memtier without their
    CLUSTER SLOTS consuming the fuzz reply.
  • tests/fixtures/resp_payloads/*.bin -- the 12 deterministic byte
    sequences listed in the issue. The accompanying README.md maps
    each fixture to the targeted parser branch (line numbers in
    protocol.cpp / cluster_client.cpp).
  • tests/test_resp_response_fuzzer.py -- RLTest harness, one test
    function per fixture. Asserts no fatal signal, no crash-needle in
    stderr (Aborted, Segmentation fault, AddressSanitizer,
    UndefinedBehaviorSanitizer, stack smashing detected,
    assertion failed), and a 15 s wall-clock budget so a hang fails
    the test instead of stalling CI.

No C++ changes -- this is a test-only PR. The pass criterion mirrors the
input-side hardening from #405: 'report and exit cleanly, never crash.'

Test plan

  • All 11 non-cluster fixtures PASS on current master under
    TEST=test_resp_response_fuzzer.py ./tests/run_tests.sh (RLTest
    reports Total Tests Run: 12, Total Tests Failed: 0).
  • The 12th fixture (cluster_slots_malformed.bin) currently triggers
    a SIGSEGV in cluster_client::handle_cluster_slots when
    memtier is launched with --cluster-mode. That cluster-mode test
    is gated by env.skip() with a TODO(#417) comment so CI stays
    green; once the fix lands, the skip should be removed.
  • make format-check clean.
  • Mock server cleanly tears down across the 12-test run (~65 s total
    with --test-time=2 per fixture); no port leaks or stranded
    python subprocesses.

Follow-ups filed

Notes / judgment calls

🤖 Generated with Claude Code


Note

Low Risk
No production code changes—only test fixtures, gitattributes, and CI harness; cluster malformed-slots test is skipped pending #417.

Overview
Adds defensive CI regression coverage for the memtier client-side RESP response parser (issue #409), mirroring the “no crash, no hang” contract from PR #405 on the input side.

A new Python mock-redis (mock_redis_resp_fuzzer.py) completes the usual handshake with benign replies, then serves one checked-in adversarial .bin per workload command and half-closes. Twelve byte fixtures under tests/fixtures/resp_payloads/ target specific parser branches (bulk length overflow, deep nesting, RESP3 edge cases, truncated frames, etc.), with a README mapping each file to the intended code path. .gitattributes marks those .bin files as binary so line endings are not normalized.

test_resp_response_fuzzer.py runs memtier (~2s per case, 15s cap) against the mock for each fixture and fails on fatal signals, known crash strings in stderr, or hangs. RLTest cluster mode is skipped for the whole module to avoid expensive cluster bootstrap; test_cluster_slots_malformed is explicitly env.skip() until #417 fixes a cluster-mode SIGSEGV in handle_cluster_slots.

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

Adds a defensive test fixture exercising client-side RESP-response
parser branches that the audit in redis#409 flagged as unaudited (bulk-length
overflow, RESP3 push/verbatim/map edge cases, malformed CLUSTER SLOTS,
unsolicited replies, truncated frames).

The fixture consists of:

* `tests/fixtures/mock_redis_resp_fuzzer.py` -- a small (~200 LoC)
  mock-redis server that lets the HELLO/AUTH/SELECT handshake pass
  with benign replies and then serves a single adversarial RESP fixture
  to the first workload command and half-closes the connection.
* `tests/fixtures/resp_payloads/*.bin` -- 12 in-tree deterministic
  byte sequences, one per targeted parser branch. The README maps each
  fixture to the specific protocol.cpp / cluster_client.cpp line being
  exercised.
* `tests/test_resp_response_fuzzer.py` -- RLTest harness that runs
  memtier briefly against the mock for each fixture and asserts no
  fatal signal, no crash needle in stderr (`Aborted`,
  `Segmentation fault`, `AddressSanitizer`, ...), and no hang inside
  a 15s per-fixture budget.

All 11 in-tree fixtures PASS on current master. The
`cluster_slots_malformed` cluster-mode exercise *crashes* memtier with
SIGSEGV in `cluster_client::handle_cluster_slots`; that fixture is
skipped with a TODO referencing follow-up redis#417 so CI stays green.

Framing: this is defensive client hardening, not an attack tool.
Fixtures live in-tree, are reviewed during normal code review, and the
pass criterion is "report and exit cleanly, never crash" -- the same
contract the input-side parsers already have after redis#405.

Fixes redis#409

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread tests/test_resp_response_fuzzer.py Resolved

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: performance (haiku 4.5)

  • Test fixture only: mock_redis_resp_fuzzer.py + 10 KB of .bin payloads. No production code changes, no binary impact.
  • Fixture execution cost: Each test spawns the Python mock-server (milliseconds) and runs memtier against it. Adds ~30–60 s per test run. One-time hardening investment, not steady-state.
  • Malformed-reply parsing untested pre-PR: This closes a gap in our audit coverage. No regression.

Verdict: Approve — test harness only, no production impact.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: docs & commit message (haiku 4.5)

• Title uses Conventional Commits correctly: test(protocol): subject.
• Opens with Fixes #409 — correct (issue #409 covers this as the sole item, not split across PRs).
• Test plan section present and comprehensive: 12 fixtures asserted PASS, no fatal signals.
• PR body correctly claims "test-only PR" (no C++ changes), passes criterion "report and exit cleanly, never crash" mirrors #405 hardening.
• No new env vars or features requiring AGENTS.md updates — purely test instrumentation.

Verdict: Approve

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: security (opus 4.7)

  • Mock-redis fixture is local-only by construction: --host defaults to 127.0.0.1 and the harness in test_resp_response_fuzzer.py always passes "127.0.0.1". Bind address is never user-attacker-controlled. Good security boundary.
  • _free_port() is the classic bind-zero-then-close race; on a busy host another process can claim the port between getsockname() and the mock server's bind(). Mitigated by SO_REUSEADDR and the fact that this is test-only. Not exploitable, just flaky.
  • Fixture files in tests/fixtures/resp_payloads/*.bin are checked in (binary, .gitattributes marks them so). No fixture is executable. Reading them with open(args.fixture, "rb") is safe; --fixture accepts any path so a malicious test author could pass /etc/shadow, but that's not a meaningful threat in a test repo. No corpus exfiltration risk because the fuzzer writes nothing — it only reads and serves to a loopback memtier.
  • The harness runs MEMTIER_BINARY which is an in-tree path resolved by tests/include.py. No untrusted binary execution.
  • subprocess.Popen for both mock and memtier passes argv as a list (not shell=True), so even if fixture_name somehow contained shell metacharacters it could not inject. Good.
  • _handle() uses conn.settimeout(5.0) and reads with a 64 KiB buffer; a malicious client (but we control the client) could DoS the mock by sending bytes but not draining. Not in scope for a test fixture.
  • _parse_verb accepts arbitrary RESP-ish bytes and slices via .index(b"\r\n"). Worst case: ValueError caught and verb is None. No memory unsafety in Python.
  • PER_FIXTURE_TIMEOUT_S = 15 plus SIGTERM then SIGKILL cleanup is correct — memtier cannot leak from a hung test. mock_proc.terminate() in finally is also correct.
  • cluster_slots_malformed test is skipped with TODO(#417); the fixture itself documents a known SIGSEGV. This is honest disclosure (a known unfixed crash is acknowledged) rather than masking — but consider gating with env.expect_crash so CI re-fails if the upstream fix lands and the skip becomes stale.
  • 10001-line mbulk_deep_nest.bin (10 KB) is fine for the repo; libFuzzer-style grown corpora are excluded by .gitignore (good — no accumulating-corpus exfiltration risk).

Verdict: Approve

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: design & API choices (sonnet 4.6)

  • The mock-server approach (PR #419) and the in-process libFuzzer harness (PR #421) are complementary, not duplicates. #419 exercises the full memtier client lifecycle (handshake → workload → disconnect) and catches integration-level bugs (e.g., the handle_cluster_slots SIGSEGV that would be invisible to a unit-level parser harness). #421's redis_protocol_fuzz targets only the parser TU and can explore the coverage space at ~10⁶ iterations/s. The overlap on parse_response bytes is intentional redundancy, not waste.
  • Twelve deterministic .bin fixtures checked into tests/fixtures/resp_payloads/ is the right shape for a regression net: reproducible, diffable, CI-cacheable. The README mapping each file to a parser branch is exactly the documentation future maintainers will need.
  • The --passthrough-cluster flag on the mock server is an API surface worth documenting at the call site in the test. The flag controls whether CLUSTER is in HANDSHAKE_DEFAULT — a subtlety that will confuse anyone adding a future fixture without reading the mock server source.
  • Skipping cluster_slots_malformed with TODO(#417) is correct design for a regression-net test: the skip keeps CI green while the SIGSEGV (#417) is open, and the skip comment is a self-removing TODO that will be obvious once the fix lands. This is preferable to xfail, which can silently pass for the wrong reason.
  • The 15 s wall-clock budget per fixture provides a hang-detection floor, but it means the 12-test suite takes ~3 min in the worst case (all hang). Documenting the expected pass time (~65 s) in the workflow or README helps set expectations.

Verdict: Approve

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: edge cases & failure modes (opus 4.7)

  • tests/test_resp_response_fuzzer.py:10473-10478 — _free_port does bind→close→hand the port to a separate Popen. Between close and mock_proc bind another process can grab it; the subsequent _wait_for_port then connects to the wrong listener and the test "succeeds" against a stranger. Use a parent-held socket passed via SO_REUSEPORT or retry on EADDRINUSE.
  • tests/test_resp_response_fuzzer.py:10484-10490 — _wait_for_port polls every 50ms up to 5s. On a sanitizer-slowed runner the mock server can take >5s to import + bind; you then return False and the test returns silently (False, None, False, None, "mock server failed to bind") which _assert_no_crash does NOT check — the fuzz fixture is reported as PASSED when in fact the mock never came up.
  • tests/test_resp_response_fuzzer.py:10560 — mem_proc Popen uses stdout=out, stderr=err, opened with open(stdout_path, "w"). The with block closes the files when memtier still holds the fd. On a hang, the TimeoutExpired path SIGTERMs memtier but the file handles in the parent are already closed; subsequent reads via open(stderr_path, "r") work, but you've discarded any data memtier wrote between SIGTERM and SIGKILL.
  • tests/test_resp_response_fuzzer.py:10585-10593 — finally-block does mock_proc.terminate(); wait(timeout=2) then kill. If mem_proc.kill() already happened and memtier left a connection half-open, the mock's per-connection thread is still in recv(timeout=5.0) (line 121 of the mock). mock_proc.terminate SIGTERMs but the worker threads are daemon and the main thread blocks in s.accept(); cleanup is racy.
  • tests/fixtures/mock_redis_resp_fuzzer.py:118-160 — _handle parses ONE verb from the rolling buffer then either replies-and-continues OR serves-the-payload-and-shuts-write. After a handshake reply, rolling = b"" — but if the client pipelined the handshake with the workload (memtier does pipeline by default), the workload bytes are lost. Net effect: the fuzz payload may not be served on the first connection; memtier reconnects and gets it the second time, which means --test-time=2 may finish without ever seeing the fixture. False negatives.
  • tests/fixtures/mock_redis_resp_fuzzer.py:106-115 — _parse_verb does int(blob[1:crlf]) with no bounds check on result. If memtier sent *-1\r\n the function returns the $ parse path which then index-throws on missing bytes — caught at line 113 ValueError → returns None → handshake stalls. Minor but adds to flakiness.
  • tests/test_resp_response_fuzzer.py:10722-10740 — test_cluster_slots_malformed is env.skip()-d unconditionally referencing issue #417. The fixture file is checked in, the mock will serve it, but the test never runs. Fine for now, but the skip body still calls _skip_if_unsupported first which can succeed-skip; net effect is two skips.
  • tests/test_resp_response_fuzzer.py:10448 — PER_FIXTURE_TIMEOUT_S = 15. Under TSAN (PR #418's matrix) memtier startup alone can take 5-8s on a cold runner. The hang-detector fires before the actual workload runs and the fixture is marked "hung".

Verdict: Comment

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: code style & readability (sonnet 4.6)

  • mock_redis_resp_fuzzer.py module docstring is thorough and accurate. The HANDSHAKE_DEFAULT set is well-named, and the comment explaining why cluster is absent from it is exactly the kind of "why not" comment that prevents future confusion.
  • _parse_verb handles incomplete buffers gracefully and the comment says so. Good.
  • _benign_reply is readable but its docstring is absent — a one-liner explaining the fallback +OK\r\n logic (AUTH/SELECT/CLIENT/PING all accept the same reply) would help a new contributor understand why no switch is needed.
  • _assert_no_crash duplicates structure from every caller. Each test_* function is a one-liner that calls _assert_no_crash which calls _run_fixture; the indirection is fine and intentional, but _skip_if_unsupported returns a bool and the caller must if on it. A decorator or pytest skip-fixture would be more idiomatic pytest, though RLTest compatibility may constrain that.
  • TODO(#417) in test_cluster_slots_malformed is the right pattern to link a deferred skip to its issue. Clean.
  • Commit message is a single-commit Conventional Commit with accurate scope.

Verdict: Approve

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: correctness & latent bugs (opus 4.7)

  • tests/fixtures/mock_redis_resp_fuzzer.py:_handle only verb-sniffs the FIRST RESP request in rolling, replies, then sets rolling = b"" discarding any pipelined remainder. memtier with default behavior sends HELLO then immediately starts the workload; if both arrive in one TCP segment, the workload command is dropped and the test never exercises the fuzz reply — the test would "pass" without actually serving the fixture. Worth verifying via the verbose log that "verb=set/get" actually appears.
  • tests/fixtures/mock_redis_resp_fuzzer.py:138 after serving the fuzz payload the server calls shutdown(SHUT_WR) but the original socket has settimeout(5.0). If memtier doesn't close its read side, the server thread sits in recv() until the 5s timeout, then closes — meaning the per-test 15s budget can swallow ~5s per connection of mock-server cleanup, multiplied by reconnect attempts.
  • tests/test_resp_response_fuzzer.py:152-156 mem_proc = subprocess.Popen(...) is opened inside with tempfile.TemporaryDirectory() but the mock_proc.terminate() cleanup in the outer finally block runs AFTER the TemporaryDirectory exits. If mem_proc writes a core dump to td at termination, it's already deleted before mock cleanup begins. Not a correctness bug, but the harness loses crash artifacts.
  • tests/test_resp_response_fuzzer.py:189-198 env.assertIsNone(needle_hit, ...) — when needle_hit is, e.g., "Aborted", the message uses {!r} which prints "'Aborted'" — but the assert fires regardless. Functionally fine.
  • mbulk_deep_nest.bin is 10000 × *1\r\n followed by a terminator. Per the PR description this is meant to exercise the recursive destructor path; with PR #415's iterative fix applied the test passes. With PR #415 NOT applied, this fixture would crash memtier in a way that the test counts as a real bug (it asserts no crash). So this test is timing-coupled to #415's merge — if #419 lands first, the test fails on master. Worth noting in merge ordering.
  • tests/test_resp_response_fuzzer.py:CRASH_NEEDLES includes "assertion failed" (lowercase) but glibc's __assert_fail emits Assertion ... failed. Case-sensitive match will miss it. Minor.
  • tests/fixtures/mock_redis_resp_fuzzer.py:114 conn.sendall(payload) ignores partial-send / EPIPE; OSError catch is around shutdown, not the sendall. If the client closes during send, the worker raises and the connection leaks in the daemon thread (process exits eventually, but logs noise).
  • The cluster_slots_malformed test is env.skip()'d but the fixture is still on disk. A future contributor unaware of #417 may unskip and watch CI fall over. Fine — TODO comment is explicit.

Verdict: Comment

Cursor bugbot finding (high severity): when `_wait_for_port` timed out
because the mock-redis server failed to bind, `_run_fixture` returned
(False, None, False, None, "mock server failed to bind") -- all the
"crashed / needle_hit / hung" fields stayed at their initial sentinel
values, so every assertion in `_assert_no_crash` passed and the test
silently reported green with zero fuzz coverage.

Detect the sentinel stderr string and call env.skip() instead. This
matches the intent the comment in _run_fixture spells out ("if the
mock did not come up, that is a test-infra bug, not a memtier bug --
skip cleanly").

Refs redis#409

@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 and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 5458b01. Configure here.

"AddressSanitizer",
"UndefinedBehaviorSanitizer",
"stack smashing detected",
"assertion failed",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Crash needle "assertion failed" never matches any platform

Medium Severity

The "assertion failed" needle in CRASH_NEEDLES is dead code — it can never match on any platform. On glibc/Linux, assert(0) outputs Assertion '0' failed. (capital "A", expression between the words). On macOS, it outputs assertion "0" failed: (expression between the words). Since the check uses substring matching (needle in stderr_text), the contiguous string "assertion failed" never appears in either format. The codebase has assert(0) calls in protocol.cpp and cluster_client.cpp that these fixtures specifically target, so the needle gap is relevant. The SIGABRT signal check provides a backup, but the needle-based detection — which is the only check that works when the crash message appears in stderr without a signal (e.g., a caught abort or subprocess wrapper) — is ineffective.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 5458b01. Configure here.

… budget

The mock-server fuzz harness does not need RLTest's redis at all -- it
talks to a python-managed mock on 127.0.0.1. On cluster cells RLTest
still bootstraps a fresh 3-shard TLS cluster per test (one per RESP
fixture * 12 fixtures ~ 6 minutes of pure setup), pushing the regular
`Test OSS-CLUSTER API: TCP TLS` cell over its 15-minute job timeout.
The fuzzer's contract is mode-independent, so cluster coverage adds
nothing.

skipOnCluster in _skip_if_unsupported instead of touching each
test_* function individually.

Refs redis#409

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: performance (haiku 4.5)

Timeout safety margin quantified:

  • Mock server half-closes after serving malformed payload → memtier parser must handle and exit. Test budgets 15 sec wall-clock per fixture (12 fixtures = ~180 sec total, well under CI 10-minute smoke budget).
  • Hang detection: subprocess timeout triggers after 15s → emits FAIL + repro file path, no cascade hang.
  • Fixture #4 (40 KB deeply nested arrays) + mutators exercise allocator churn, but per-iteration overhead is sub-second.

Parser path coverage vs. timeout:

  • All 11 non-cluster fixtures pass in ~2 sec each (benign handshake + malformed workload reply + disconnect).
  • Cluster-gated fixture (SIGSEGV in handle_cluster_slots, xfailed) is skipped, not causing timeout drift.
  • Critical issue: does NOT eliminate timeout for sure — the test is gated by a 15-second hard wall. A pathological input (e.g., the malformed *1\r\n*1\r\n... nesting if mutated further) could cause a hang past 15s if the parser loops infinitely. This PR catches crashes and exits cleanly; infinite loops require a separate loop-detection mechanism (e.g., iteration counter in parser).

Verdict: 15-second per-fixture timeout barely fits the happy path (~2 sec nominal, margin 13×). Better than unbounded, but true timeout elimination requires parser-level iteration guards. Marginally safe for current known cases; would benefit from loop-limit instrumentation before production use.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: docs & commit message (haiku 4.5)

  • Hotfixes explicitly reference Cursor bugbot: Third commit ("skip cleanly when mock server fails") explicitly says "Cursor bugbot finding (high severity)"; fourth commit ("skip on cluster") explicitly mentions the cluster setup timeout problem and the solution. Both are clearly attributed.
  • Refs #409 and follow-up #417 correct: PR body states "Fixes #409", hotfixes reference their own issues (#409). The cluster_slots_malformed SIGSEGV is properly deferred to #417.
  • skipOnCluster hotfix present and correct: Fourth commit adds the cluster-skip gate, clearly stated "Refs #409". No undisclosed assumptions about PR #405 merge ordering — the PR body does not assert merge-ordering constraints; #405's VLA fix is independent of #419's response-side parser tests.
  • No missing issue refs: all three hotfixes properly link back (no orphan commits).

Verdict: hotfixes well-documented and cursor attribution explicit; merge-ordering claim not made.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: design & API (sonnet 4.6)

  • cluster_slots_malformed.bin + env.skip() is the right trade-off, but the skip is underpowered. The current implementation keeps the fixture in-tree (correct — it is the regression payload), keeps the test function (correct — it documents the bug), but the skip is unconditional: even after #417 lands, a developer removing the skip will not get a passing test without also wiring in a cluster-mode _run_fixture path (the existing _run_fixture passes --cluster-mode nowhere). Consider leaving a # TODO(#417): when fixed, pass cluster_mode=True to _run_fixture comment that makes the exact missing wiring obvious, rather than just "remove this skip and call _assert_no_crash".
  • pytest.mark.xfail would be cleaner than env.skip() for a known-crashing fixture. An xfail records that the test ran and failed in the expected way, turning into a green xpass automatically once the fix lands — no manual skip removal required. env.skip() is RLTest idiom but the test file runs under both RLTest and pytest; @pytest.mark.xfail(strict=True, reason="cluster_client crash #417") on the function would give CI a stricter signal without coupling the gate to a human remembering to re-enable it.
  • _parse_verb has a silent failure mode on long pipelined handshakes. If memtier sends several commands before the mock replies (e.g. HELLO\r\n + CLIENT SETNAME\r\n back-to-back), rolling accumulates both and _parse_verb returns the first verb. After sendall(_benign_reply(...)) the buffer is reset to b"" but the second command is lost. The fixture's 1-connection-per-command usage works around this today, but the design assumption isn't documented and a future --pipeline test could silently skip the fuzz payload. A one-line comment ("assumes commands arrive individually, not pipelined") would capture this.
  • --passthrough-cluster flag duplicates the HANDSHAKE_DEFAULT logic in a fragile way. Adding cluster to the handshake set via a flag is correct, but if a future fixture needs to pass through a different verb (e.g. CONFIG) the pattern is add one --flag per verb, which doesn't scale. A --passthrough-verb=CLUSTER,CONFIG multi-value flag would be extensible without API churn.
  • 12 fixtures committed as .bin, including mbulk_deep_nest.bin at ~10 001 lines. The deep-nest fixture is human-readable ASCII but has a .bin extension and is marked binary in .gitattributes. That is correct for safety, but the README's "to regenerate, see the generator script described in PR #409" is a dangling reference — #409 is an issue, not a PR, and no generator script appears in this diff. Pointing to a concrete file path or inline recipe would make the fixture reproducible for reviewers who want to verify the byte content.

Verdict: the overall design (mock server + deterministic binary fixtures + RLTest harness) is clean and well-scoped. The cluster_slots_malformed skip strategy works but xfail would give a stronger signal. The _parse_verb pipeline assumption and the dangling generator reference are minor but worth fixing before the fixture set grows.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: security (opus 4.7)

  • (load-bearing) .bin fixtures: no path-injection risk. The harness constructs fixture_path = os.path.join(FIXTURES_DIR, fixture_name) and fixture_name is a hard-coded literal in each test_* function ("bulk_huge_length.bin", etc.). No user input flows into the path, and the mock server passes the resolved path as --fixture <path> in argv list form (no shell). os.path.isfile(args.fixture) plus open(args.fixture, "rb") is what executes — no glob, no exec. Clean.
  • (load-bearing) mock server bind: 127.0.0.1 by default, both server and client. mock_redis_resp_fuzzer.py defaults --host="127.0.0.1" and the harness's _free_port does bind(("127.0.0.1", 0)), then memtier connects to "127.0.0.1". Confirmed loopback-only. The harness never passes --host, so the default holds. Good. (Minor: the --host argument is still user-settable on the CLI, so anyone scripting against this fixture directly could bind to 0.0.0.0. Not a regression risk — it's a test fixture, not a daemon.)
  • SO_REUSEADDR + _free_port race window. Between _free_port releasing the port and the mock server's bind, another process can grab the port. SO_REUSEADDR does NOT prevent this on Linux for the second binder if the first is still in TIME_WAIT or fully released. Harness has _wait_for_port to detect the bind failure but treats it as "test-infra skip" — could swallow a genuine port-stealing collision in noisy CI. Minor.
  • bulk_huge_length.bin declares $1000000000 followed by 4 bytes then EOF. On the client side protocol.cpp reads the length and waits for m_bulk_len + 2 bytes. If the parser allocates a libevent watermark buffer of 1 GB before realizing EOF, the test could OOM the runner before tripping the crash needle. The mock half-closes after sending the bytes so the client should EOF first — but worth a --test-time=2 retest under tight RLIMIT_AS to confirm.
  • mbulk_deep_nest.bin is 40 KB of *1\r\n runs (10000 nests). Under the audited parser this exercises the destructor recursion on m_last_response. If the destructor is recursive (not iterative) this can stack-overflow the test runner and look like a memtier crash. PR #415 made mbulk teardown iterative — confirm this fixture runs against post-#415 code, not pre-.
  • cluster_slots_malformed is gated by env.skip() with a TODO(#417). Correct call given the known SIGSEGV. Suggestion: instead of skipping, the test could assert that memtier prints a specific error and exits with a non-zero status, then xfail the assertion until #417 lands — that way the skip can't be accidentally forgotten when the bug is fixed.

Verdict: ship. The path-injection and bind-host concerns are both clean.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: style & readability (sonnet 4.6)

  1. .bin fixtures lack \r\n line terminators — RESP is CRLF-only (load-bearing). The diff shows bulk_huge_length.bin as $1000000000\nABCD (LF only), but the README documents it as $1000000000\r\nABCD. The .gitattributes binary marker stops git from normalising line endings at checkout, but it does not add \r\n; the bytes stored are what was committed. If the files were created with a text editor on Linux they will contain \n not \r\n. The libev RESP tokenizer reads until \r\n; a bare-LF fixture will never match and the parser will either wait forever or emit a parse error — both outcomes mean the fixture does not actually exercise the targeted code path. The fixture generator script (referenced in README but not committed) should be checked or the bytes confirmed via xxd.

  2. TODO(#417) skip in test_cluster_slots_malformed is correctly filed and commented — nothing new to add here.

  3. _skip_if_unsupported pattern (standalone if _skip_if_unsupported(env): return) diverges from the existing codebase idiom (env.skipOnCluster() / env.skip() at the top of the function with no return). The existing tests never use a helper-plus-return guard. Using env.skip() directly, then return on the next line, would be idiomatic and avoid the boolean-propagation indirection.

  4. mock_redis_resp_fuzzer.py module docstring is excellent — explains what, why, and the pass criterion. No changes needed.

  5. _assert_no_crash skip-on-bind-failure comment cites "cursor bugbot finding" — external tool references in comments are noise after the first few weeks. Prefer # avoids a silent green run with zero coverage and drop the attribution.

Verdict: the \r\n/\n discrepancy in the .bin fixtures is potentially load-bearing and should be verified before merge.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: correctness & latent bugs (opus 4.7)

Tip: 1b39115. Test fixtures + python mock server + RLTest harness. Pure test-only, but the mock and harness can be wrong in ways that hide real crashes:

  • mock_redis_resp_fuzzer.py::_handle only verb-sniffs the first request in rolling, replies, and zeroes rolling = b"" for handshake commands. The connection's stream parser is not real: any handshake command that arrives pipelined behind a prior buffered request (e.g. memtier sending HELLO\r\n\r\nAUTH... because of an earlier short-read) has its trailing bytes silently dropped. In practice memtier sends handshake commands one-at-a-time waiting for replies, so this is fine today — but a future memtier change that pipelines handshake (or adds --resp 3 which negotiates differently) will start producing flaky tests that look like RESP3 push frames hanging the parser. Add a comment to that effect, or do proper buffer consumption.

  • The fuzzer harness asserts only "no crash needle / no fatal signal / no hang", but does not assert the mock server actually served the fixture. served_fuzz is tracked in _handle and discarded; if memtier exits during HELLO/AUTH (e.g. fixture corrupts the handshake reply because someone enables --passthrough-cluster=false for a CLUSTER-targeted fixture against --cluster-mode), the test passes green with zero coverage. Recommend exporting served_fuzz to a sentinel file the harness can stat and env.skip()'ing if the fixture was never delivered (same shape as the cursor bugbot fix you already applied for mock server failed to bind).

  • _parse_verb (mock_redis_resp_fuzzer.py:79): the inline-command branch returns buf.split(b" ", 1)[0] — but the line could end with \r\n and the verb would be "PING\r" (since you split before stripping the CRLF). Then .lower() → "ping\r" ∉ HANDSHAKE_DEFAULT, falls into the fuzz branch, and memtier sees an adversarial reply to a PING. PING is allowed to arrive after HELLO/AUTH in some configurations (-c health checks). Trim \r\n before splitting.

  • test_cluster_slots_malformed is env.skip()'d unconditionally with a TODO pointing at #417. But the fixture file is checked in and listed in the README. Reviewers reading this PR will think the test is doing work; the harness reports it as PASS. Either suffix the test name with _xfail and add @pytest.mark.xfail/equivalent RLTest skip-with-reason, or strip the test function entirely and re-add when #417 lands. Currently the green-PASS hides the regression.

  • mbulk_deep_nest.bin is *1\r\n x10000 + +OK\r\n. On master this should now exercise the iterative mbulk teardown landed in #415. But the fixture is followed by an immediate half-close (mock server's default). The PR description in #409 noted "100K levels" as the original target; 10K is comfortably above the recursive-teardown stack limit but well below the ulimit a clean post-#415 build would tolerate. As a regression guard for "did the iterative teardown get reverted?" 10K is too few — bump to 100K so the test fails if anyone re-introduces recursion. As-is, a regression to recursive teardown would pass on a stack with default ulimit (8 MiB / ~48 bytes/frame = ~170K depth tolerance).

  • tests/fixtures/resp_payloads/unsolicited_reply.bin (+OK\r\n+OK\r\n) is served only after handshake completes, so memtier has already sent one SET; the first +OK matches that request, and the second +OK is the only unsolicited one. The fixture name implies both are unsolicited; in practice only one is. Either drop one +OK from the fixture or change the mock to serve the fixture before memtier sends a request (impossible with current handshake-first design without a flag). Cosmetic but the README's "force the unsolicited-reply path" claim doesn't quite match what the test actually exercises.

Verdict: Comment

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: edge cases & failure modes (opus 4.7)

Verdict: APPROVE with one real-bug finding (mock-server pipelining drops requests, fakes "hang") and a few hardening notes.

  • _run_fixture skip path is clean, BUT env.skip() inside _assert_no_crash doesn't unwind the helper's local state. When _wait_for_port times out, _run_fixture returns with mock_proc still tracked in the finally block — the finally runs mock_proc.terminate(); mock_proc.wait(timeout=2) which is fine. Then _assert_no_crash calls env.skip() and returns; assertion machinery sees no calls and reports SKIP. Propagation OK. But the mock_log.name (NamedTemporaryFile(delete=False)) leaks into /tmp on every skip — confirmed by reading the diff at the Popen site. Use tempfile.TemporaryDirectory() or os.unlink(mock_log.name) in a finally.
  • _wait_for_port is race-free against the mock's listen() (TCP handshake won't succeed until the kernel has the listener queued), but does NOT detect a mock that crashed AFTER listen. Mock's serve() calls s.bind then s.listen(64) then enters the accept loop. If the fixture file is unreadable, main() exits BEFORE binding → _wait_for_port times out (5s wasted, clean skip). But if the mock accept()s then dies in _handle (e.g. fixture is 0 bytes and the handler hits an unguarded path), memtier connects, _wait_for_port returns True, but the mock is now dead. Add mock_proc.poll() between connect attempts: a non-None returncode means the mock died — return early with skip.
  • MOCK SERVER BUG: _handle drops pipelined requests after the handshake. After replying to the handshake verb, rolling = b"" discards the remainder of recv(65536). memtier_benchmark issues HELLO + COMMAND + CLIENT + workload pipelined in a single TCP segment in some configurations (notably with --cluster-mode and modern OpenSSL). The workload command never sees a reply, memtier waits forever → harness flags it as a HANG (false positive). Fix by parsing request length from the inbound *N\r\n$M\r\n...\r\n framing and only consuming the bytes for the handled verb, leaving the rest of rolling intact for the next loop iteration.
  • _free_port() bind-then-release IS racy. Comment acknowledges it. SO_REUSEADDR on the mock means the bind succeeds even if another process grabbed the same port in between — but now the mock and the other process are both listening, and connections race. On CI runners with many concurrent test workers this fires. Either pass the listening socket FD across to the mock (avoid the race) or retry with N different ports.
  • PER_FIXTURE_TIMEOUT_S = 15 vs --test-time=2 — but mem_proc.wait(timeout=15) is BEFORE reading stderr. If memtier double-frees and ASan prints a 50 KiB report to stderr that blocks on a full pipe (pipe capacity is 64K on Linux but ASan reports near that ceiling), memtier hangs on the write while the harness waits for exit — both stall until the 15s timeout. Current code opens stderr to a file via with open(stderr_path, "w") as err, not PIPE, so this is actually safe. Verified. Disregard if I misread.
  • test_cluster_slots_malformed is env.skip() with a TODO pointing at #417 — fine, but please add a pytest.mark.xfail-equivalent (RLTest's env.expectFailure(...) or a clearly-named separate "expected_to_crash" suite) so that when #417 fixes the crash, this test starts passing and isn't silently still skipped. Today removal of the skip requires manually finding this TODO.

(Files: tests/fixtures/mock_redis_resp_fuzzer.py + tests/test_resp_response_fuzzer.py.)

@fcostaoliveira
fcostaoliveira merged commit d9c049e into redis:master Jun 1, 2026
68 checks passed
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
fcostaoliveira added a commit that referenced this pull request Jun 1, 2026
…lformed shards (#425)

* fix(cluster-slots): validate reply shape before indexing, log+skip malformed shards

cluster_client::handle_cluster_slots() walked the CLUSTER SLOTS reply
with bare `mbulks_elements[N]` indexing and as_bulk() / as_mbulk_size()
casts that assert(0) on type mismatch. A malformed reply from a
hostile or buggy server crashed memtier with SIGSEGV (issue #417,
surfaced by the RESP-fuzzer fixture `cluster_slots_malformed.bin` from
PR #419).

Validate before indexing:
  * top-level get_mbulk_value() must be non-null
  * each shard element must be is_mbulk_size()
  * shard must have >= 3 children (start, end, [host, port, ...])
  * elements 0 and 1 (slot bounds) must be is_bulk()
  * element 2 (node tuple) must be is_mbulk_size() and have >= 2
    children, both is_bulk() (host, port)

Any malformed shard logs a benchmark_error_log and is skipped; the
existing bootstrap connection stays in service. If the whole reply is
non-array, log and return without touching topology.

Fixes #417

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(cluster-slots): reject empty topology, validate slot bounds, guard zero-len bulks

Review-pass follow-ups on #425 from the security + edge-cases + correctness lenses.

  * Empty mbulk reply (zero shards) now logs a warning and returns
    without touching m_connections. Previously this silently tore down
    every existing shard connection via the close_sc[] loop -- a
    malformed reply degraded the run to a no-shard hang instead of
    crashing it.
  * Slot bounds (min_slot / max_slot): parse via strtol with errno=0,
    then reject ERANGE, negatives, values > MAX_CLUSTER_HSLOT (16383),
    or min > max. Without this, m_slot_to_shard[16384] could be written
    out-of-bounds by a hostile server (heap corruption).
  * Host / port bulks: reject zero-length entries (memcpy(..., NULL+1, 0)
    is technically UB and produces an unusable empty connection key).
  * Host bulk also rejects embedded NULs (would alias other addrs via
    strcmp-based connection lookup).
  * Every skip-not-abort log line now uses the `warning:` prefix that
    matches the rest of the file (style reviewer).

Refs #417

* fix(cluster-slots): don't tear down connections if all shards malformed

Cursor bugbot finding (medium): when every shard in the CLUSTER SLOTS
reply failed validation and was skipped via continue, no close_sc[j]
entry got set to false. The close-stale pass then disconnected every
existing connection -- including the bootstrap -- silently turning a
malformed reply into a no-shard hang.

Track any_valid_shard across the loop; if false on completion, return
early without entering the close-stale pass (same operational
behaviour as the empty-reply short-circuit). Refs #417.

---------

Co-authored-by: Claude Sonnet 4.6 <[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.

Add adversarial RESP-server fuzzer for client-side protocol parsing

1 participant