Repository navigation
test(cli): hypothesis-based CLI argument fuzzer - #424
fcostaoliveira merged 3 commits into
Conversation
Adds tests/test_cli_fuzz.py per issue redis#410: a Hypothesis-driven fuzzer that generates 1-8 long-flag combinations with deliberately weird values (empty/whitespace, INT_MAX boundaries, scientific notation, comma decimal, hex, 4 KiB ASCII, 1 KiB UTF-8 fire emoji, format-string specifiers, malformed ratios/ranges/percentiles) and runs them against a local Redis with the canonical fast-exit harness (--test-time=1 --threads=1 --clients=1 --hide-histogram). Each generated argv must: * exit within 10 s (no hangs); * return 0, 1 or 2 (parser-error is fine, signal-class is not); * not emit any crash-class needle in stderr (stack smashing, Segmentation fault, Aborted, AddressSanitizer, UBSan runtime error, munmap_chunk, double free, SIGSEGV, SIGABRT). The fuzzer is gated behind MEMTIER_FUZZ=1 so default CI is unaffected; intended to run nightly under ASAN/UBSan builds where a banned-needle hit becomes a fast regression signal. Wired into tests/run_tests.sh behind the same env so a single MEMTIER_FUZZ=1 ./tests/run_tests.sh invocation picks it up after the RLTest suites. Out of scope per the issue: --tls*, --uri, --data-import, --failed-keys-file, --monitor-input -- all need a dedicated setup harness; queued as follow-ups. While iterating to keep the test green on master, the fuzzer surfaced a batch of pre-existing crash/hang classes that are filed for follow-up (see PR description); the corresponding strategies were narrowed so the test is a stable regression net rather than an immediate bug-of-the-day reporter. 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)
- Hypothesis CLI fuzzer (pytest, dev-gated):
test_cli_fuzz.pybehindMEMTIER_FUZZ=1env flag. Off by default. Generates 1–8 flag combinations + runs memtier 10 s timeout per variant. On default CI, 100% skipped. - Nightly execution: When enabled (nightly ASAN/UBSan builds), estimated ~2–5 min total for hypothesis default example count (~100 exs). Acceptable for parser hardening.
- No production binary cost: Test harness only.
Verdict: Approve — opt-in fuzzer, default CI unaffected.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: docs & commit message (haiku 4.5)
• Title uses Conventional Commits correctly: test(cli): subject.
• Opens with Fixes #410. — correct (issue dedicated to CLI fuzzer).
• Test plan comprehensive: default skip path (no env var), 200 examples pass locally, multiple seeds (1,2,3,42,99,100,200,999,12345) verified, Hypothesis determinism confirmed.
• New env vars MEMTIER_FUZZ=1 and MEMTIER_FUZZ_MAX_EXAMPLES= (internal) introduced. Documented as "off by default" and wired into tests/run_tests.sh behind env var, but AGENTS.md not updated. No explicit mention of Hypothesis dependency in test_requirements.txt mention.
• "Follow-up bugs surfaced" section notes several pre-existing crashes/hangs trimmed to keep test green — appropriate deferral, but note: the table is cut off (incomplete).
Verdict: Comment — missing AGENTS.md documentation for MEMTIER_FUZZ env var; table in "Follow-up bugs" section incomplete.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: design & API choices (sonnet 4.6)
- Dropping INT_MAX / LLONG_MAX from the
weird_intstrategy (rather than xfail-ing them) is the right call for a stable regression net, but it hides a real bug class. The PR describes 17 known crashes/hangs found while building the strategy; for bugs like--run-count 2147483647 → std::bad_alloc(item #5), the correct long-term design ispytest.mark.xfail(strict=True)with a reference to the tracking issue. Silently excluding INT_MAX means future fixes to those bugs will not automatically be detected by this test when they land. - The
command_likestrategy excluding empty / bare placeholder is correct scoping.--command ''hangs,--command __key__aborts — both are real bugs, but both require separate fix PRs. The strategy comment documents exactly why these are excluded and references the follow-up issues, which is the right paper trail. MEMTIER_FUZZ=1gate +pytest.mark.skipifat module level is the correct opt-in design. Avoids polluting the defaultrun_tests.shinvocation; the test still participates inrun_tests.shwhen explicitly opted in viaMEMTIER_FUZZ=1.- Tolerances read at import time (module-level
os.environ.get) means pytest fixture injection cannot override them. This is minor but meansMEMTIER_FUZZ_PORTset by aconftest.pyfixture after import would be ignored. Reading inside the test function or using a session-scoped fixture would be more robust. - The 17-item follow-up bug table in the PR description is valuable archaeology. Consider adding a comment block in
test_cli_fuzz.pylisting the excluded input shapes with their tracking issue numbers — reviewers checking whether a known-crash was fixed will look in the test file, not in a closed PR description.
Verdict: Comment (use xfail for known crashes instead of strategy exclusion, so fixes are auto-detected)
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: security (opus 4.7)
- Hypothesis is in-process and the harness runs memtier via
subprocess.run(cmd, ..., timeout=10, check=False)with argv as a list — no shell expansion of mutated bytes, no command injection from generated values. The 10 s subprocess timeout hard-bounds runtime per example. MEMTIER_BINARYis env-resolved withshutil.which()fallback. PATH-takeover by a malicious binary on$PATHis the classic risk; for an opt-in fuzzer gated byMEMTIER_FUZZ=1this is acceptable. Same caveat as PR #420 — consider preferring absolute paths in nightly CI.weird_strstrategy correctly filters out NUL (blacklist_characters="\x00") and surrogate codepoints (Cs) — necessary because POSIXexecverejects argv with embedded NULs and Python would raiseValueErrorat the subprocess layer rather than exercising memtier's parser. Good.weird_strincludes"$(reboot)","`reboot`", and"../" * 16 + "etc/passwd"as VALUES, not as commands. Because argv is a list, these are passed literally as flag arguments — not executed. The path-traversal-looking string only reaches the parser as a--key-prefix=...style value; memtier doesn't open user-provided paths from any of the fuzzed flags, so no file system access. Confirmed by the PR's exclusion of--data-import,--failed-keys-file,--monitor-input(which would be path-injecting).- ANSI escapes (
\x1b[31m) inweird_strreachstderr/stdout butsubprocess.runcaptures bytes — no terminal-injection risk back into pytest output. BANNED_NEEDLESincludes the canonical crash signatures. The PR honestly catalogs ~12 pre-existing crash/hang classes (negative--run-count, INT_MAX--run-count, zero--data-size, etc.) and trims the strategy rather than fixing the bugs. That's the right call for a regression-net PR, but it means today's coverage is meaningfully smaller than the issue intends — a future contributor must be careful when re-broadening strategies without first landing the underlying fixes.- The fuzzer connects to
127.0.0.1:6379by default;MEMTIER_FUZZ_HOSToverrides allow pointing at remote redis, which would let a malicious env weaponize the fuzzer to flood an external service. Local-only is the documented intent. pytest.importorskip("hypothesis")correctly degrades when the dep isn't installed.--hypothesis-seed=${MEMTIER_FUZZ_SEED:-0}inrun_tests.shuses parameter expansion in bash, not user-supplied — safe.(cd $ROOT/tests && ...)lacksset -esemantics propagation, but the((E |= $?))pattern picks up the exit. Sound.
Verdict: Approve
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: code style & readability (sonnet 4.6)
HealthCheckis imported but only one member is used in the settings decorator.HealthCheck.too_slowandHealthCheck.function_scoped_fixtureare both referenced, so the import is not unused. However, importingsettingsfrom hypothesis and using it only in the decorator is fine; no issue here.- Comment quality for excluded strategies is excellent. Each
# Known bug class intentionally excludedblock names the exact argv, the symptom, and the follow-up reference. This is the right pattern for documenting deliberate test holes in a fuzz harness. weird_intandweird_strstrategy names are descriptive. The inline comment onweird_intexplaining why it caps at 10000 (to avoid allocator OOM as a confound for parser bugs) is load-bearing and accurate.BANNED_NEEDLEStuple name is clear; the list matches the project's standard crash-detection vocabulary from other test files._run_memtierhelper name is clear. Minor: it is a module-level function that capturesHOSTandPORTfrom globals — the dependency on those globals is implicit. A docstring noting this would help.run_tests.shadditions follow the same opt-in pattern as STRESS; the help text is accurate and consistent in style.
Verdict: Approve
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: edge cases & failure modes (opus 4.7)
tests/test_cli_fuzz.py:114-132—weird_intincludes empty/space/comma-decimal/1e9999but alsost.integers(min_value=0, max_value=10000).map(str). The hypothesis-generated branch never hits negatives orINT_MAX-1; the curated branch skips them too. Whole classes of off-by-one are not exercised. The author flags this in the comment but--rate-limiting=0,--clients-start=0,--pipeline=0, and--max-retries=0ALL feed straight into divisions / modulo and SIGFPE is a real outcome — currently masked.tests/test_cli_fuzz.py:420-437—_run_memtiersetstimeout=10for a--test-time=1workload. With pipeline=very-large + clients=1, memtier can take >10s to drain the pipeline AFTER test-time ends, especially under sanitizer builds.pytest.fail(...hung...)fires on what is actually a clean (slow) shutdown.tests/test_cli_fuzz.py:96-97—OK_RETURN_CODES = {0, 1, 2}. memtier's parser usesexit(EXIT_FAILURE)(=1) for parse errors but some validation paths callexit(EXIT_USAGE_FAILURE)which is 64 on BSD-derived hosts (compat module returns 1 on Linux). On macOS / Free-BSD-runner future you get spurious fails. Pin to known set explicitly or use< 64.tests/test_cli_fuzz.py:399-417—argvstrategy draws 1-8 unique flag indices; flags withstrategy is None(booleans) take no value. But the fuzzer never combines mutually-exclusive booleans (--ipv4and--ipv6) or boolean+value flag with the same effect. Not catastrophic, just narrows coverage.tests/test_cli_fuzz.py:75—MEMTIER = os.environ.get("MEMTIER_BINARY") or shutil.which("memtier_benchmark"). If neither resolves to the in-tree binary (e.g. CI env unset),whichfinds an installed package binary — possibly a DIFFERENT VERSION — and the fuzzer reports false positives/negatives against it. Should fail-fast when env-var missing.tests/test_cli_fuzz.py:439-446—max_examples=int(os.environ.get("MEMTIER_FUZZ_MAX_EXAMPLES", "200"))withdeadline=None. 200 examples × 10s timeout = up to 33 min nominal; under sanitizers 1-2hr easily. The wrapper inrun_tests.shdoesn't set its own timeout, and the workflow inheritingtimeout-minutesmay not exist if MEMTIER_FUZZ=1 is set in a non-soak workflow.tests/test_cli_fuzz.py:155-176—weird_strblacklists\x00only viablacklist_characters="\x00"for the hypothesis-generated branch. Thest.sampled_from(...)curated branch contains"\x1b[31mANSI\x1b[0m"(OK) but not NUL itself (good). However"$(reboot)"and"`reboot`"are passed unquoted viasubprocess.run([list])— Python's subprocess doesn't shell-evaluate them, so they don't actually test command-substitution. Comment is misleading.tests/run_tests.sh:117-122—MEMTIER_FUZZ=1block runs unconditionally even when the previous RLTest E was non-zero.((E |= $?))ORs both, but a hung fuzz run dragging the job into its 60-min timeout could mask the original RLTest failure. Consider[[ $E -eq 0 ]] && [[ $MEMTIER_FUZZ == 1 ]].
Verdict: Comment
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: correctness & latent bugs (opus 4.7)
- LOAD-BEARING:
tests/test_cli_fuzz.pylives attests/test_cli_fuzz.pyand matches RLTest's autodiscovery glob (test_*.py). When the standard./tests/run_tests.shruns RLTest (withoutMEMTIER_FUZZ), RLTest will try to discover and invoketest_cli_fuzz_does_not_crashwith itsenvfixture, but the function is wrapped by Hypothesis's@givenwhich expects no fixture argument. RLTest's test loader will either error out at collection (RLTest may not understand pytest'spytestmark = pytest.mark.skipif(...)) or call the wrapper with mismatched args. At minimum, verify RLTest gracefully skips this file in a defaultOSS_STANDALONE=1 ./tests/run_tests.shrun; consider renaming tocli_fuzz_test.pyor moving outside RLTest's discovery root. tests/test_cli_fuzz.py:288-290_run_memtierusessubprocess.run(..., timeout=10)— but argv-fuzz can generate--test-time=1PLUS--rate-limiting=0plus retries that cause memtier to spin-loop on reconnects (known bug, per PR description). The harness depends on the 10s timeout to catch hangs. When it triggers,subprocess.TimeoutExpiredis raised andpytest.failis called — fine. But the subprocess is NOT killed beforeTimeoutExpiredpropagates; Python 3.x kills it on context exit, but there's no explicit kill. Under high parallel pytest workers this can pile up zombie memtier processes.tests/test_cli_fuzz.py:264-271Hypothesis decorators:@settings(...)is applied to@given(extra=argv()). The shrinker can spend many seconds shrinking a failing argv; withmax_examples=200and worst-case shrink times of 5-10s each, a single failure can blow past pytest's default timeout. Fine since the deadline is None — just noting CI runtime variability.tests/test_cli_fuzz.py:OK_RETURN_CODES = {0, 1, 2}— bash subprocess kill due to timeout returns-9(SIGKILL), but the timeout branch is handled separately viaTimeoutExpired. memtier signal exits return-N(negative); none of-Nare in the set. Good.tests/test_cli_fuzz.py:285-291_run_memtierpasses argv with the binary as first element. IfMEMTIERis None (binary not found viashutil.whichandMEMTIER_BINARYunset),cmd[0]is None andsubprocess.runraisesTypeError. Thepytestmarkskipif handlesMEMTIER_FUZZ, and the separate@pytest.mark.skipif(MEMTIER is None, ...)on the test function handles missing-binary. OK.tests/test_cli_fuzz.py:165weird_strstrategy excludes\x00but includes all other control characters.subprocess.runon POSIX wraps inexecve; control chars are passed through. Hex like\x1b(escape) in an argument is fine for execve, just may produce odd terminal output if memtier echoes the arg in an error message.tests/run_tests.sh:117-122MEMTIER_FUZZ=1block runs pytest in a subshell with(cd $ROOT/tests && ...). The exit code propagates via((E |= $?))after the()exits — but$?inside the if-block refers to the subshell exit, which is the LAST command in the subshell (pytest). OK.--hypothesis-seed=${MEMTIER_FUZZ_SEED:-0}— Hypothesis seed 0 is fine; deterministic across runs. But fixed seed means a flaky failure won't be discovered by re-running; users need to vary the seed manually.
Verdict: Comment
Two reviewers caught this independently: tests/test_cli_fuzz.py matched RLTest's `test_*.py` glob in run_tests.sh and got loaded on every sanitizer cell. The @given-decorated test takes `extra` and would crash the moment RLTest tried to call it with `env`. The agent intended gating via MEMTIER_FUZZ=1 but the gate fires too late -- file is already loaded. Cleanest fix: rename the file so RLTest's scan never picks it up; pytest is the intended runner anyway (the file uses pytest fixtures, @given, etc.) and we invoke it explicitly via: MEMTIER_FUZZ=1 ./tests/run_tests.sh # or MEMTIER_FUZZ=1 pytest tests/cli_fuzz.py --hypothesis-seed=0 -v The MEMTIER_FUZZ env gate and the run_tests.sh wiring are unchanged in logic; just the filename moves. Refs redis#410
Fixes #410.
Summary
Adds
tests/test_cli_fuzz.py: a Hypothesis-driven fuzzer that generates 1-8 long-flag combinations with deliberately weird values (empty/whitespace, INT_MAX/LLONG_MAX boundaries, scientific notation, comma decimal, hex, 4 KiB ASCII, 1 KiB UTF-8 fire emoji, format-string specifiers, malformed ratios / ranges / percentiles / weight lists) and runs each against a local Redis with the canonical fast-exit harness:Each generated argv must:
stack smashing,Segmentation fault,Aborted,AddressSanitizer,UndefinedBehaviorSanitizer,runtime error:,munmap_chunk,double free,SIGSEGV,SIGABRT).The fuzzer is gated behind
MEMTIER_FUZZ=1so default CI is unaffected; intended to run nightly under ASAN/UBSan builds where any banned-needle hit becomes a fast regression signal. It is also wired intotests/run_tests.shbehind the same env so a singleMEMTIER_FUZZ=1 ./tests/run_tests.shinvocation picks it up after the RLTest suites.Out of scope per the issue:
--tls*,--uri,--data-import,--failed-keys-file,--monitor-input(need dedicated setup harnesses; queued as follow-ups).Test plan
make -jbuilds against current master.pip install -r tests/test_requirements.txtresolves Hypothesis + pytest.pytest tests/test_cli_fuzz.pyis skipped (noMEMTIER_FUZZ).MEMTIER_FUZZ=1 MEMTIER_BINARY=$PWD/memtier_benchmark pytest tests/test_cli_fuzz.py --hypothesis-seed=0 -x -vpasses against a local Redis on:6379(200 examples, ~2 min).1, 2, 3, 42, 99, 100, 200, 999, 12345(each at 100 examples).MEMTIER_FUZZ_MAX_EXAMPLES=400 ... --hypothesis-seed=0also passes (~3.5 min).make format-checkclean.Follow-up bugs surfaced while iterating
While narrowing the strategies to keep the test green on master, the fuzzer found a batch of pre-existing crash/hang classes. Per the prompt, none of these are fixed in this PR; each becomes a follow-up issue, and the corresponding strategy was trimmed so the test is a stable regression net rather than an immediate bug-of-the-day reporter.
--authenticate ''against a server with no auth configured--test-time)--cluster-modeagainst standalone Rediscluster slot failed.loop, ignores--test-time)--protocol memcache_text(ormemcache_binary) against Redisresponse parsing failed.loop)--run-count -1std::bad_alloc(negative passed to vector resize)--run-count 2147483647(INT_MAX)std::bad_alloc(allocator OOM, no bounds check)--pipeline -1--data-size -1protocol.cpp:309: assert value_len > 0 failed--data-size-range 1-9999999999-ERR Protocol error: invalid bulk length(memtier reconnects forever)--data-size-list 0:50--data-size-list 8:0--select-db 100against default 16-DB Redisdatabase selection failed.loop)--command __key__(bare placeholder, no command name)protocol.cpp:774: first arg is not command name?--command ''--command-ratio 0(or empty / whitespace, both parse as 0)--key-pattern G:G --key-stddev inf--key-pattern G:G --key-maximum 1--wait-ratio 0:1 --num-slaves 1-10against standaloneCommon pattern in (1), (2), (3), (8), (11), (17): once memtier enters its reconnect / retry loop after a server-side failure during connection setup, it does not honor
--test-timeand runs until SIGKILLed. That's arguably the most actionable single fix in this batch -- one bounded "give up after N seconds of connect-stage failures" would close most of them.Each of these will be filed as a separate issue and cross-referenced back to #410.
Note
Low Risk
Test-only changes behind MEMTIER_FUZZ=1; no production code paths modified.
Overview
Adds an opt-in Hypothesis CLI fuzzer (
tests/cli_fuzz.py, issue #410) that runsmemtier_benchmarkagainst local Redis with 1–8 randomly combined long flags and curated “weird” values, on top of a short fixed harness (--test-time=1, single thread/client). Each case must finish within 10s, exit with 0/1/2, and avoid crash/sanitizer needles in stderr.The fuzzer is off by default (
MEMTIER_FUZZ=1);tests/run_tests.shdocumentsMEMTIER_FUZZ/MEMTIER_FUZZ_SEEDand can run pytest after RLTest.tests/test_requirements.txtpinspytestandhypothesis. Strategies deliberately exclude known hang/crash inputs (auth, cluster, memcache protocols, extreme ints, etc.) so the suite stays a stable parser/regression net; product fixes are left as follow-ups.Reviewed by Cursor Bugbot for commit 81e0beb. Bugbot is set up for automated code reviews on this repo. Configure here.