Repository navigation
test(protocol): adversarial RESP-server fuzzer for client-side parsing - #419
fcostaoliveira merged 5 commits into
Conversation
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]>
fcostaoliveira
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Review: security (opus 4.7)
- Mock-redis fixture is local-only by construction:
--hostdefaults to127.0.0.1and the harness intest_resp_response_fuzzer.pyalways 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 betweengetsockname()and the mock server'sbind(). Mitigated bySO_REUSEADDRand the fact that this is test-only. Not exploitable, just flaky.- Fixture files in
tests/fixtures/resp_payloads/*.binare checked in (binary,.gitattributesmarks them so). No fixture is executable. Reading them withopen(args.fixture, "rb")is safe;--fixtureaccepts 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_BINARYwhich is an in-tree path resolved bytests/include.py. No untrusted binary execution. subprocess.Popenfor both mock and memtier passes argv as a list (notshell=True), so even iffixture_namesomehow contained shell metacharacters it could not inject. Good._handle()usesconn.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_verbaccepts arbitrary RESP-ish bytes and slices via.index(b"\r\n"). Worst case: ValueError caught andverbisNone. No memory unsafety in Python.PER_FIXTURE_TIMEOUT_S = 15plusSIGTERMthenSIGKILLcleanup is correct — memtier cannot leak from a hung test.mock_proc.terminate()infinallyis also correct.cluster_slots_malformedtest is skipped withTODO(#417); the fixture itself documents a known SIGSEGV. This is honest disclosure (a known unfixed crash is acknowledged) rather than masking — but consider gating withenv.expect_crashso 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
left a comment
There was a problem hiding this comment.
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_slotsSIGSEGV that would be invisible to a unit-level parser harness). #421'sredis_protocol_fuzztargets only the parser TU and can explore the coverage space at ~10⁶ iterations/s. The overlap onparse_responsebytes is intentional redundancy, not waste. - Twelve deterministic
.binfixtures checked intotests/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-clusterflag on the mock server is an API surface worth documenting at the call site in the test. The flag controls whetherCLUSTERis inHANDSHAKE_DEFAULT— a subtlety that will confuse anyone adding a future fixture without reading the mock server source. - Skipping
cluster_slots_malformedwithTODO(#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
left a comment
There was a problem hiding this comment.
Review: edge cases & failure modes (opus 4.7)
tests/test_resp_response_fuzzer.py:10473-10478—_free_portdoes bind→close→hand the port to a separatePopen. Between close andmock_procbind another process can grab it; the subsequent_wait_for_portthen 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_portpolls every 50ms up to 5s. On a sanitizer-slowed runner the mock server can take >5s to import + bind; you then returnFalseand the test returns silently(False, None, False, None, "mock server failed to bind")which_assert_no_crashdoes 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_procPopen usesstdout=out, stderr=err, opened withopen(stdout_path, "w"). Thewithblock closes the files when memtier still holds the fd. On a hang, theTimeoutExpiredpath SIGTERMs memtier but the file handles in the parent are already closed; subsequent reads viaopen(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 doesmock_proc.terminate(); wait(timeout=2)thenkill. Ifmem_proc.kill()already happened and memtier left a connection half-open, the mock's per-connection thread is still inrecv(timeout=5.0)(line 121 of the mock).mock_proc.terminateSIGTERMs but the worker threads are daemon and the main thread blocks ins.accept(); cleanup is racy.tests/fixtures/mock_redis_resp_fuzzer.py:118-160—_handleparses 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=2may finish without ever seeing the fixture. False negatives.tests/fixtures/mock_redis_resp_fuzzer.py:106-115—_parse_verbdoesint(blob[1:crlf])with no bounds check on result. If memtier sent*-1\r\nthe function returns the$parse path which thenindex-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_malformedisenv.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_unsupportedfirst 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
left a comment
There was a problem hiding this comment.
Review: code style & readability (sonnet 4.6)
mock_redis_resp_fuzzer.pymodule docstring is thorough and accurate. TheHANDSHAKE_DEFAULTset is well-named, and the comment explaining whyclusteris absent from it is exactly the kind of "why not" comment that prevents future confusion._parse_verbhandles incomplete buffers gracefully and the comment says so. Good._benign_replyis readable but its docstring is absent — a one-liner explaining the fallback+OK\r\nlogic (AUTH/SELECT/CLIENT/PING all accept the same reply) would help a new contributor understand why no switch is needed._assert_no_crashduplicates structure from every caller. Eachtest_*function is a one-liner that calls_assert_no_crashwhich calls_run_fixture; the indirection is fine and intentional, but_skip_if_unsupportedreturns a bool and the caller mustifon it. A decorator or pytest skip-fixture would be more idiomatic pytest, though RLTest compatibility may constrain that.TODO(#417)intest_cluster_slots_malformedis 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
left a comment
There was a problem hiding this comment.
Review: correctness & latent bugs (opus 4.7)
tests/fixtures/mock_redis_resp_fuzzer.py:_handleonly verb-sniffs the FIRST RESP request inrolling, replies, then setsrolling = 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:138after serving the fuzz payload the server callsshutdown(SHUT_WR)but the original socket hassettimeout(5.0). If memtier doesn't close its read side, the server thread sits inrecv()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-156mem_proc = subprocess.Popen(...)is opened insidewith tempfile.TemporaryDirectory()but themock_proc.terminate()cleanup in the outerfinallyblock runs AFTER the TemporaryDirectory exits. Ifmem_procwrites a core dump totdat 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-198env.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.binis 10000 ×*1\r\nfollowed 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_NEEDLESincludes"assertion failed"(lowercase) but glibc's__assert_failemitsAssertion ... failed. Case-sensitive match will miss it. Minor.tests/fixtures/mock_redis_resp_fuzzer.py:114conn.sendall(payload)ignores partial-send / EPIPE; OSError catch is aroundshutdown, 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_malformedtest isenv.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
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 5458b01. Configure here.
| "AddressSanitizer", | ||
| "UndefinedBehaviorSanitizer", | ||
| "stack smashing detected", | ||
| "assertion failed", |
There was a problem hiding this comment.
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)
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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_fixturepath (the existing_run_fixturepasses--cluster-modenowhere). Consider leaving a# TODO(#417): when fixed, pass cluster_mode=True to _run_fixturecomment that makes the exact missing wiring obvious, rather than just "remove this skip and call_assert_no_crash".pytest.mark.xfailwould be cleaner thanenv.skip()for a known-crashing fixture. Anxfailrecords that the test ran and failed in the expected way, turning into a greenxpassautomatically 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_verbhas 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\nback-to-back),rollingaccumulates both and_parse_verbreturns the first verb. Aftersendall(_benign_reply(...))the buffer is reset tob""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--pipelinetest could silently skip the fuzz payload. A one-line comment ("assumes commands arrive individually, not pipelined") would capture this.--passthrough-clusterflag duplicates the HANDSHAKE_DEFAULT logic in a fragile way. Addingclusterto 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 isadd one --flag per verb, which doesn't scale. A--passthrough-verb=CLUSTER,CONFIGmulti-value flag would be extensible without API churn.- 12 fixtures committed as
.bin, includingmbulk_deep_nest.binat ~10 001 lines. The deep-nest fixture is human-readable ASCII but has a.binextension 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
left a comment
There was a problem hiding this comment.
Review v2: security (opus 4.7)
- (load-bearing)
.binfixtures: no path-injection risk. The harness constructsfixture_path = os.path.join(FIXTURES_DIR, fixture_name)andfixture_nameis a hard-coded literal in eachtest_*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)plusopen(args.fixture, "rb")is what executes — no glob, no exec. Clean. - (load-bearing) mock server bind:
127.0.0.1by default, both server and client.mock_redis_resp_fuzzer.pydefaults--host="127.0.0.1"and the harness's_free_portdoesbind(("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--hostargument is still user-settable on the CLI, so anyone scripting against this fixture directly could bind to0.0.0.0. Not a regression risk — it's a test fixture, not a daemon.) SO_REUSEADDR+_free_portrace window. Between_free_portreleasing the port and the mock server'sbind, another process can grab the port.SO_REUSEADDRdoes NOT prevent this on Linux for the second binder if the first is still in TIME_WAIT or fully released. Harness has_wait_for_portto 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.bindeclares$1000000000followed by 4 bytes then EOF. On the client sideprotocol.cppreads the length and waits form_bulk_len + 2bytes. 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=2retest under tight RLIMIT_AS to confirm.mbulk_deep_nest.binis 40 KB of*1\r\nruns (10000 nests). Under the audited parser this exercises the destructor recursion onm_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_malformedis gated byenv.skip()with aTODO(#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
left a comment
There was a problem hiding this comment.
Review v2: style & readability (sonnet 4.6)
-
.binfixtures lack\r\nline terminators — RESP is CRLF-only (load-bearing). The diff showsbulk_huge_length.binas$1000000000\nABCD(LF only), but the README documents it as$1000000000\r\nABCD. The.gitattributesbinarymarker 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\nnot\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 viaxxd. -
TODO(#417)skip intest_cluster_slots_malformedis correctly filed and commented — nothing new to add here. -
_skip_if_unsupportedpattern (standaloneif _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. Usingenv.skip()directly, thenreturnon the next line, would be idiomatic and avoid the boolean-propagation indirection. -
mock_redis_resp_fuzzer.pymodule docstring is excellent — explains what, why, and the pass criterion. No changes needed. -
_assert_no_crashskip-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 coverageand drop the attribution.
Verdict: the \r\n/\n discrepancy in the .bin fixtures is potentially load-bearing and should be verified before merge.
fcostaoliveira
left a comment
There was a problem hiding this comment.
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::_handleonly verb-sniffs the first request inrolling, replies, and zeroesrolling = 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 sendingHELLO\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 3which 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_fuzzis tracked in_handleand discarded; if memtier exits during HELLO/AUTH (e.g. fixture corrupts the handshake reply because someone enables--passthrough-cluster=falsefor a CLUSTER-targeted fixture against--cluster-mode), the test passes green with zero coverage. Recommend exportingserved_fuzzto a sentinel file the harness can stat andenv.skip()'ing if the fixture was never delivered (same shape as the cursor bugbot fix you already applied formock server failed to bind). -
_parse_verb(mock_redis_resp_fuzzer.py:79): the inline-command branch returnsbuf.split(b" ", 1)[0]— but the line could end with\r\nand 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 (-chealth checks). Trim\r\nbefore splitting. -
test_cluster_slots_malformedisenv.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_xfailand 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.binis*1\r\nx10000 ++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+OKmatches that request, and the second+OKis the only unsolicited one. The fixture name implies both are unsolicited; in practice only one is. Either drop one+OKfrom 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
left a comment
There was a problem hiding this comment.
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_fixtureskip path is clean, BUTenv.skip()inside_assert_no_crashdoesn't unwind the helper's local state. When_wait_for_porttimes out,_run_fixturereturns withmock_procstill tracked in thefinallyblock — thefinallyrunsmock_proc.terminate(); mock_proc.wait(timeout=2)which is fine. Then_assert_no_crashcallsenv.skip()and returns; assertion machinery sees no calls and reports SKIP. Propagation OK. But themock_log.name(NamedTemporaryFile(delete=False)) leaks into/tmpon every skip — confirmed by reading the diff at the Popen site. Usetempfile.TemporaryDirectory()oros.unlink(mock_log.name)in afinally._wait_for_portis race-free against the mock'slisten()(TCP handshake won't succeed until the kernel has the listener queued), but does NOT detect a mock that crashed AFTER listen. Mock'sserve()callss.bindthens.listen(64)then enters the accept loop. If the fixture file is unreadable,main()exits BEFORE binding →_wait_for_porttimes out (5s wasted, clean skip). But if the mockaccept()s then dies in_handle(e.g. fixture is 0 bytes and the handler hits an unguarded path), memtier connects,_wait_for_portreturns True, but the mock is now dead. Addmock_proc.poll()between connect attempts: a non-None returncode means the mock died — return early with skip.- MOCK SERVER BUG:
_handledrops pipelined requests after the handshake. After replying to the handshake verb,rolling = b""discards the remainder ofrecv(65536). memtier_benchmark issues HELLO + COMMAND + CLIENT + workload pipelined in a single TCP segment in some configurations (notably with--cluster-modeand 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\nframing and only consuming the bytes for the handled verb, leaving the rest ofrollingintact 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 = 15vs--test-time=2— butmem_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 viawith open(stderr_path, "w") as err, not PIPE, so this is actually safe. Verified. Disregard if I misread.test_cluster_slots_malformedisenv.skip()with a TODO pointing at #417 — fine, but please add apytest.mark.xfail-equivalent (RLTest'senv.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.)
…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]>


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-redisserver. 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-clusterflag lets non-clusterfixtures be run against
--cluster-modememtier without theirCLUSTER SLOTSconsuming the fuzz reply.tests/fixtures/resp_payloads/*.bin-- the 12 deterministic bytesequences listed in the issue. The accompanying
README.mdmapseach fixture to the targeted parser branch (line numbers in
protocol.cpp/cluster_client.cpp).tests/test_resp_response_fuzzer.py-- RLTest harness, one testfunction 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 failsthe 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
TEST=test_resp_response_fuzzer.py ./tests/run_tests.sh(RLTestreports
Total Tests Run: 12, Total Tests Failed: 0).cluster_slots_malformed.bin) currently triggersa SIGSEGV in
cluster_client::handle_cluster_slotswhenmemtier is launched with
--cluster-mode. That cluster-mode testis gated by
env.skip()with aTODO(#417)comment so CI staysgreen; once the fix lands, the skip should be removed.
make format-checkclean.with
--test-time=2per fixture); no port leaks or strandedpython subprocesses.
Follow-ups filed
(root-caused per issue Add adversarial RESP-server fuzzer for client-side protocol parsing #409 audit point 4; repro fixture and harness
are this PR).
Notes / judgment calls
RUN_RESP_FUZZ=1opt-in env flag (mentioned in theissue's CI section) because the harness now runs in ~65 s total and
is just a regression net. Happy to gate it if reviewers prefer.
handshake only when
--passthrough-clusteris set, so thecluster_slots_malformedpayload actually reaches the cluster-slotsparser when the test is eventually unskipped.
mbulk_deep_nest.bin) is 40 KB of*1\r\nruns; theother 11 are <100 B each.
🤖 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.binper workload command and half-closes. Twelve byte fixtures undertests/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..gitattributesmarks those.binfiles as binary so line endings are not normalized.test_resp_response_fuzzer.pyruns 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_malformedis explicitlyenv.skip()until #417 fixes a cluster-mode SIGSEGV inhandle_cluster_slots.Reviewed by Cursor Bugbot for commit 1b39115. Bugbot is set up for automated code reviews on this repo. Configure here.