Skip to content

test(cli): hypothesis-based CLI argument fuzzer - #424

Merged
fcostaoliveira merged 3 commits into
redis:masterfrom
filipecosta90:test/issue-410-cli-hypothesis-fuzz
Jun 1, 2026
Merged

fcostaoliveira merged 3 commits into
redis:masterfrom
filipecosta90:test/issue-410-cli-hypothesis-fuzz

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 30, 2026 •

Copy link
Copy Markdown
Collaborator

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:

memtier_benchmark --server=... --port=... --test-time=1 --threads=1 --clients=1 --hide-histogram <generated flags>

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, UndefinedBehaviorSanitizer, 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 any banned-needle hit becomes a fast regression signal. It is also 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 (need dedicated setup harnesses; queued as follow-ups).

Test plan

  • make -j builds against current master.
  • pip install -r tests/test_requirements.txt resolves Hypothesis + pytest.
  • Default pytest tests/test_cli_fuzz.py is skipped (no MEMTIER_FUZZ).
  • MEMTIER_FUZZ=1 MEMTIER_BINARY=$PWD/memtier_benchmark pytest tests/test_cli_fuzz.py --hypothesis-seed=0 -x -v passes against a local Redis on :6379 (200 examples, ~2 min).
  • Same with seeds 1, 2, 3, 42, 99, 100, 200, 999, 12345 (each at 100 examples).
  • MEMTIER_FUZZ_MAX_EXAMPLES=400 ... --hypothesis-seed=0 also passes (~3.5 min).
  • make format-check clean.
  • Nightly: run under ASAN/UBSan builds (separate workflow change).

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.

# argv (minimal repro) symptom
1 --authenticate '' against a server with no auth configured hangs (reconnect loop, ignores --test-time)
2 --cluster-mode against standalone Redis hangs (cluster slot failed. loop, ignores --test-time)
3 --protocol memcache_text (or memcache_binary) against Redis hangs (response parsing failed. loop)
4 --run-count -1 SIGABRT, std::bad_alloc (negative passed to vector resize)
5 --run-count 2147483647 (INT_MAX) SIGABRT, std::bad_alloc (allocator OOM, no bounds check)
6 --pipeline -1 hangs (negative size, underflow loop)
7 --data-size -1 SIGABRT, protocol.cpp:309: assert value_len > 0 failed
8 --data-size-range 1-9999999999 hangs after -ERR Protocol error: invalid bulk length (memtier reconnects forever)
9 --data-size-list 0:50 SIGABRT, value_len=0 assert
10 --data-size-list 8:0 hangs (zero weight, sampler picks nothing)
11 --select-db 100 against default 16-DB Redis hangs (database selection failed. loop)
12 --command __key__ (bare placeholder, no command name) SIGABRT, protocol.cpp:774: first arg is not command name?
13 --command '' hangs
14 --command-ratio 0 (or empty / whitespace, both parse as 0) hangs
15 --key-pattern G:G --key-stddev inf hangs (sampler never produces a key)
16 --key-pattern G:G --key-maximum 1 SIGABRT (Gaussian path on a 1-key range)
17 --wait-ratio 0:1 --num-slaves 1-10 against standalone hangs (WAIT never satisfied, no timeout exit)

Common 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-time and 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 runs memtier_benchmark against 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.sh documents MEMTIER_FUZZ / MEMTIER_FUZZ_SEED and can run pytest after RLTest. tests/test_requirements.txt pins pytest and hypothesis. 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.

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 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)

  • Hypothesis CLI fuzzer (pytest, dev-gated): test_cli_fuzz.py behind MEMTIER_FUZZ=1 env 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 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(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 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)

  • Dropping INT_MAX / LLONG_MAX from the weird_int strategy (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 is pytest.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_like strategy 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=1 gate + pytest.mark.skipif at module level is the correct opt-in design. Avoids polluting the default run_tests.sh invocation; the test still participates in run_tests.sh when explicitly opted in via MEMTIER_FUZZ=1.
  • Tolerances read at import time (module-level os.environ.get) means pytest fixture injection cannot override them. This is minor but means MEMTIER_FUZZ_PORT set by a conftest.py fixture 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.py listing 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 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)

  • 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_BINARY is env-resolved with shutil.which() fallback. PATH-takeover by a malicious binary on $PATH is the classic risk; for an opt-in fuzzer gated by MEMTIER_FUZZ=1 this is acceptable. Same caveat as PR #420 — consider preferring absolute paths in nightly CI.
  • weird_str strategy correctly filters out NUL (blacklist_characters="\x00") and surrogate codepoints (Cs) — necessary because POSIX execve rejects argv with embedded NULs and Python would raise ValueError at the subprocess layer rather than exercising memtier's parser. Good.
  • weird_str includes "$(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) in weird_str reach stderr/stdout but subprocess.run captures bytes — no terminal-injection risk back into pytest output.
  • BANNED_NEEDLES includes 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:6379 by default; MEMTIER_FUZZ_HOST overrides 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} in run_tests.sh uses parameter expansion in bash, not user-supplied — safe.
  • (cd $ROOT/tests && ...) lacks set -e semantics propagation, but the ((E |= $?)) pattern picks up the exit. Sound.

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: code style & readability (sonnet 4.6)

  • HealthCheck is imported but only one member is used in the settings decorator. HealthCheck.too_slow and HealthCheck.function_scoped_fixture are both referenced, so the import is not unused. However, importing settings from 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 excluded block 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_int and weird_str strategy names are descriptive. The inline comment on weird_int explaining why it caps at 10000 (to avoid allocator OOM as a confound for parser bugs) is load-bearing and accurate.
  • BANNED_NEEDLES tuple name is clear; the list matches the project's standard crash-detection vocabulary from other test files.
  • _run_memtier helper name is clear. Minor: it is a module-level function that captures HOST and PORT from globals — the dependency on those globals is implicit. A docstring noting this would help.
  • run_tests.sh additions follow the same opt-in pattern as STRESS; the help text is accurate and consistent in style.

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_cli_fuzz.py:114-132 — weird_int includes empty/space/comma-decimal/1e9999 but also st.integers(min_value=0, max_value=10000).map(str). The hypothesis-generated branch never hits negatives or INT_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=0 ALL feed straight into divisions / modulo and SIGFPE is a real outcome — currently masked.
  • tests/test_cli_fuzz.py:420-437 — _run_memtier sets timeout=10 for a --test-time=1 workload. 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 uses exit(EXIT_FAILURE) (=1) for parse errors but some validation paths call exit(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 — argv strategy draws 1-8 unique flag indices; flags with strategy is None (booleans) take no value. But the fuzzer never combines mutually-exclusive booleans (--ipv4 and --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), which finds 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")) with deadline=None. 200 examples × 10s timeout = up to 33 min nominal; under sanitizers 1-2hr easily. The wrapper in run_tests.sh doesn't set its own timeout, and the workflow inheriting timeout-minutes may not exist if MEMTIER_FUZZ=1 is set in a non-soak workflow.
  • tests/test_cli_fuzz.py:155-176 — weird_str blacklists \x00 only via blacklist_characters="\x00" for the hypothesis-generated branch. The st.sampled_from(...) curated branch contains "\x1b[31mANSI\x1b[0m" (OK) but not NUL itself (good). However "$(reboot)" and "`reboot`" are passed unquoted via subprocess.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=1 block 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 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)

  • LOAD-BEARING: tests/test_cli_fuzz.py lives at tests/test_cli_fuzz.py and matches RLTest's autodiscovery glob (test_*.py). When the standard ./tests/run_tests.sh runs RLTest (without MEMTIER_FUZZ), RLTest will try to discover and invoke test_cli_fuzz_does_not_crash with its env fixture, but the function is wrapped by Hypothesis's @given which expects no fixture argument. RLTest's test loader will either error out at collection (RLTest may not understand pytest's pytestmark = pytest.mark.skipif(...)) or call the wrapper with mismatched args. At minimum, verify RLTest gracefully skips this file in a default OSS_STANDALONE=1 ./tests/run_tests.sh run; consider renaming to cli_fuzz_test.py or moving outside RLTest's discovery root.
  • tests/test_cli_fuzz.py:288-290 _run_memtier uses subprocess.run(..., timeout=10) — but argv-fuzz can generate --test-time=1 PLUS --rate-limiting=0 plus 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.TimeoutExpired is raised and pytest.fail is called — fine. But the subprocess is NOT killed before TimeoutExpired propagates; 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-271 Hypothesis decorators: @settings(...) is applied to @given(extra=argv()). The shrinker can spend many seconds shrinking a failing argv; with max_examples=200 and 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 via TimeoutExpired. memtier signal exits return -N (negative); none of -N are in the set. Good.
  • tests/test_cli_fuzz.py:285-291 _run_memtier passes argv with the binary as first element. If MEMTIER is None (binary not found via shutil.which and MEMTIER_BINARY unset), cmd[0] is None and subprocess.run raises TypeError. The pytestmark skipif handles MEMTIER_FUZZ, and the separate @pytest.mark.skipif(MEMTIER is None, ...) on the test function handles missing-binary. OK.
  • tests/test_cli_fuzz.py:165 weird_str strategy excludes \x00 but includes all other control characters. subprocess.run on POSIX wraps in execve; 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-122 MEMTIER_FUZZ=1 block 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
@fcostaoliveira
fcostaoliveira merged commit feea51d into redis:master Jun 1, 2026
65 checks passed
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
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 hypothesis-based CLI fuzz tests for memtier_benchmark flags

1 participant