Skip to content

test(monitor-input): black-box fuzz corpus + Python driver for parser hardening - #422

Merged
fcostaoliveira merged 6 commits into
redis:masterfrom
filipecosta90:test/issue-408-monitor-input-corpus-fuzzer
Jun 1, 2026
Merged

fcostaoliveira merged 6 commits into
redis:masterfrom
filipecosta90:test/issue-408-monitor-input-corpus-fuzzer

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 30, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #408

Follow-up to PR #405 / issue #404 (VLA stack-overflow in arbitrary_command::split_command_to_args). The existing tests/test_monitor_input.py covers five canonical lines and one 16 MiB ASCII regression — not enough to prevent the next parser-level CVE in load_from_file / split_command_to_args / extract_command_type.

What's added

  • tests/fuzz/monitor_input_corpus/ — 18 seed files exercising the parser's edge cases: empty, header-only, minimal, mixed-case, redacted-AUTH (real Enterprise capture artefact), hex-escape, embedded-NUL, embedded-quote, single-quote, unterminated-quote, trailing-garbage (the goto err at config_types.cpp:585), CRLF-mixed, UTF-8 BOM, no-trailing-newline, full commands.json matrix, partial truncation, binary gzip blob, pathological quote storm.
  • tests/fuzz/fuzz_monitor_input.py — ~250 LoC mutating fuzzer driver. Per iteration: pick a seed, apply a random chain of mutators (bitflip / chop / dup / inject_nul / grow up to 8 MiB / crlf-jitter / quote-storm), write to tmpfile, run memtier_benchmark --monitor-input=<f> --command="__monitor_line@__" --requests=10 against a local redis. Flag SIGSEGV, glibc stack smashing detected, AddressSanitizer report, or 30s timeout. Non-zero exit is fine — the contract is "report and exit, never crash."

Findings on current master

Smoke run of 200 iterations across the 18 seeds (default ulimit -s 12500) surfaced 7 crash-class findings (~3.5 % rate). All SIGSEGV mid-fill_pipeline, consistent with the VLA path PR #405 fixes plus the follow-ups in the sibling issues (#406 protocol.cpp:949 sscanf, #409 cluster_slots crash captured separately as #417). Reproducer files are emitted alongside the fuzzer logs (/tmp/fuzz_monitor_*/repro_*.bin).

Why CI wiring is not in this PR

The fuzzer surfaces real bugs that need separate fixes. Adding nightly cron + on-PR smoke now would turn CI red on master before #405 / #406 / #407 / #409 merge. Once those land, follow-up PR will:

  • Smoke on every PR: FUZZ_ITER=50 in the existing flow-tests job (~2 min).
  • Nightly cron: FUZZ_ITER=20000 against an ASAN build, reproducer files uploaded as artefacts.

For now, contributors can run the driver locally:

MEMTIER=$(pwd)/memtier_benchmark FUZZ_ITER=200 \
  python3 tests/fuzz/fuzz_monitor_input.py

Test plan

🤖 Generated with Claude Code


Note

Medium Risk
New CI can fail on known parser/memory bugs until related fixes land; fuzzing targets input parsing and runs ASAN+UBSan builds against Redis.

Overview
Adds a black-box fuzz harness for --monitor-input / load_from_file and split_command_to_args: a seed corpus under tests/fuzz/monitor_input_corpus/ and tests/fuzz/fuzz_monitor_input.py, which mutates seeds and runs memtier_benchmark against local Redis, treating only crashes, sanitizer output, and timeouts as failures.

CI and docs: .github/workflows/monitor-fuzz.yml builds with ASAN+UBSan, runs the driver on nightly cron and workflow_dispatch, and on PRs labeled run-fuzz (smaller FUZZ_ITER). Failures upload /tmp/fuzz_monitor_* reproducers. DEVELOPMENT.md documents the label and local invocation.

The driver caps grow mutations (default 256 KiB), optionally enables huge synthetic seeds via FUZZ_INCLUDE_HUGE, uses --test-time=2, and checks crash signals before allowlisting known nonfatal assertions.

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

… hardening

Issue redis#408 follow-up to PR redis#405 / issue redis#404 (VLA stack-overflow in
arbitrary_command::split_command_to_args). The existing
tests/test_monitor_input.py covers five canonical lines and one 16 MiB
ASCII regression; not enough to prevent the next parser-level CVE in
load_from_file / split_command_to_args / extract_command_type.

This commit adds a black-box fuzz harness:

  tests/fuzz/monitor_input_corpus/  -- 18 seed files exercising
    empty / header-only / minimal / mixed-case / redacted-AUTH /
    hex-escape / embedded-NUL / embedded-quote / single-quote /
    unterminated-quote / trailing-garbage / CRLF-mixed / UTF-8 BOM /
    no-trailing-newline / all-commands.json / partial-truncation /
    binary-gzip-blob / pathological-quote-storm

  tests/fuzz/fuzz_monitor_input.py  -- ~250 LoC mutating fuzzer driver.
    Per iteration: pick a seed, apply a random chain of mutators
    (bitflip / chop / dup / inject_nul / grow up to 8 MiB / crlf-jitter /
    quote-storm), write to tmpfile, run
        memtier_benchmark --monitor-input=<f> --command="__monitor_line@__"
                          --requests=10
    against a local redis, and flag any SIGSEGV, glibc "stack smashing
    detected", AddressSanitizer report, or 30s timeout. Non-zero exit
    is fine -- the contract is "report and exit, never crash".

Findings on current master (200 iterations across the 18 seeds, default
ulimit -s 12500):
  * 7 crash-class findings (~3.5%) -- all SIGSEGV mid-fill_pipeline,
    consistent with the VLA path PR redis#405 fixes plus follow-ups in the
    sibling issues (redis#406 / redis#407 / redis#409 cluster_slots crash). Reproducer
    files are emitted alongside the fuzzer logs.

CI wiring is intentionally NOT added to this PR. The fuzzer surfaces
real bugs that need separate fixes; wiring nightly cron + on-PR smoke
follows once redis#405 / redis#406 / redis#407 / redis#409 land. See PR description for the
phased plan.

Refs redis#408

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread tests/fuzz/fuzz_monitor_input.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)

  • Mutating fuzzer driver (local-dev): fuzz_monitor_input.py spawns memtier ~50 times per seed × 18 seeds with random mutations. Each run ~1–5 s; total ~5 min per fuzzer execution. Development tool only, not wired into default CI.
  • No production code: Corpus seeds + Python driver. Zero binary impact.
  • Corpus overhead: 18 KB of seed files. Negligible.

Verdict: Approve — dev fuzzer, 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(monitor-input): subject.
• Opens with Fixes #408 — correct (issue dedicated to monitor input black-box fuzz coverage).
• Test plan honest: 200 iterations on master reproduce expected VLA crashes (reproducers emitted to /tmp/fuzz_monitor_*/repro_*.bin), smoke passes on clean run, defers reproducer triage to follow-up.
• New env var FUZZ_ITER= introduced and shown in example command but not documented in AGENTS.md or tests/run_tests.sh. Usage example shows MEMTIER=$(pwd)/memtier_benchmark FUZZ_ITER=200 python3 tests/fuzz/fuzz_monitor_input.py, suggesting integration is ad-hoc, not auto-wired into standard test flow.
• CI wiring intentionally deferred per "Why CI wiring is not in this PR" — reasonable to avoid CI red before #405/#406/#409 merge.

Verdict: Comment — missing AGENTS.md documentation for FUZZ_ITER env var and integration notes.

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

  • Driver invokes memtier via subprocess.run(cmd, ...) with argv as a list — no shell expansion of mutated bytes, even if a corpus mutator embeds shell metacharacters. Safe.
  • MEMTIER = Path(os.environ.get("MEMTIER", str(DEFAULT_MEMTIER))) is environment-controlled but the script is a local developer harness, not invoked from untrusted contexts. MEMTIER.exists() is checked before execve. Acceptable.
  • tempfile.NamedTemporaryFile(prefix="mfuzz_", suffix=".txt", delete=False) is mkstemp-equivalent — safe; secure tempfile creation. The repro file is intentionally retained on crash (good — needed for triage) and os.unlink(mpath) is called on clean exit (no disk-fill DoS).
  • Crash repros are stored at /tmp/mfuzz_*.txt — process-owner-readable only by default. On a shared CI runner where umask defaults to 0022 these would be other-readable; not a corpus exfiltration risk for byte sequences the test author already wrote.
  • REDIS_HOST / REDIS_PORT default to 127.0.0.1:6379 — local-only by construction. A user who overrides REDIS_HOST=public.redis could weaponize the fuzzer to flood a remote target, but that's an explicit env-var override, not an attack surface.
  • The fuzzer cap 32 MiB (mutate() truncates) plus --test-time=2 per run bound the wall-clock and memory per iteration. FUZZ_TIMEOUT=60 default per-run cleans up via Python's subprocess timeout — subprocess.run with timeout correctly SIGKILLs the child on expiry.
  • KNOWN_NONFATAL_ASSERTIONS masks a run_stats::print_type_column assertion that's flagged as non-memory-safety. This is honest filtering, but it does suppress a real assertion crash that could overshadow new ones; consider also asserting the masked needle's count stays constant rather than blanket-suppressing.
  • INCLUDE_HUGE_SYNTHETIC is opt-in (FUZZ_INCLUDE_HUGE=1) — the 17 MiB single-line and 1 M tiny-line seeds are NOT committed; they're built at runtime in memory. No repo bloat or persistent corpus.
  • ASAN_OPTIONS / UBSAN_OPTIONS use setdefault so existing env values are preserved — good practice; an attacker would need to already control env, which is out of threat model.
  • CRASH_SIGNALS = {-11, -6, -7, -8, -4} correctly maps SEGV/ABRT/BUS/FPE/ILL. No coverage of SIGSYS / seccomp-class crashes, but those aren't in scope for a parser fuzzer.

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)

  • Black-box driver + in-process libFuzzer (#421) on the same monitor_input parser is justified, not redundant. The black-box driver exercises the full CLI surface (binary invocation, file path handling, argv parsing), catches hangs and signal exits at process granularity, and is runnable by anyone with python3 and a Redis instance. The in-process harness in #421 covers only load_from_file internals at high iteration speed. Both lenses are useful.
  • Corpus directories diverge: this PR uses tests/fuzz/monitor_input_corpus/ while #421 uses tests/fuzz/corpus/monitor/. After both merge, seeds are siloed between the two harnesses. libFuzzer can absorb new seeds from an external corpus via -merge=1; the Python driver reads CORPUS_DIR at init. The two should share one canonical directory, or there should be a documented one-way sync (e.g., corpus/monitor/ feeds both). The current split will cause them to diverge in coverage over time.
  • GROW_MAX defaulting to 256 KiB (not the 8 MiB spec) pending #405 is an explicit design choice well-documented in the source. The FUZZ_INCLUDE_HUGE opt-in flag for the >16 MiB synthetic seeds is the right deferral pattern. Both constants should be bumped in the follow-up that wires CI.
  • No CI wiring is a coherent stance while the upstream fixes are in flight, but it means the harness has no CI regression coverage of its own. The promise to add FUZZ_ITER=50 smoke in a follow-up should be tracked as a TODO comment in fuzz_monitor_input.py, not only in the PR description.
  • The driver lives in tests/fuzz/ while it reads from tests/fuzz/monitor_input_corpus/. If a contributor moves or renames the corpus directory, the hardcoded CORPUS_DIR = HERE / "monitor_input_corpus" silently finds nothing and the driver runs zero iterations against actual seeds. A startup assertion (assert CORPUS_DIR.exists()) would surface this immediately.

Verdict: Comment (unify corpus directories with #421; add startup assertion on CORPUS_DIR existence)

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

  • CRASH_SIGNALS uses raw signal numbers ({-11, -6, -7, -8, -4}). Adding a comment mapping each to its name (-11: SIGSEGV, -6: SIGABRT, -7: SIGBUS, -8: SIGFPE, -4: SIGILL) would make the set self-documenting without requiring readers to cross-reference signal.h.
  • KNOWN_NONFATAL_ASSERTIONS tuple name is clear and the comment explaining why these are excluded is excellent — it names the exact assertion text, the function it lives in, and the follow-up issue. This is a model "why not" comment.
  • Mutator functions (bitflip, chop, dup, inject_nul, grow, crlf, quote_storm) have consistent signatures and are easy to scan. No docstrings needed at this length; the names are self-explanatory.
  • generate_synthetic_seeds docstring explains the FUZZ_INCLUDE_HUGE=1 gate and its dependency on PR #405; this is important context that would otherwise be invisible.
  • GROW_MAX env-override comment is good ("on master (pre-PR #405) lines above ~1 MiB reliably trip…") — it explains both the current default and why to raise it post-fix.
  • Commit message is Conventional Commits compliant 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: edge cases & failure modes (opus 4.7)

  • tests/fuzz/fuzz_monitor_input.py:160-228 — run_one writes via tempfile.NamedTemporaryFile(..., delete=False) then os.unlink(mpath) only on success. On a crash you keep the repro (intended) BUT on the except BaseException path at line 227 the file is also kept; on a KeyboardInterrupt during a 50-iteration sweep you leak one mfuzz_*.txt per active iteration with no rate-limit. CI runners with small /tmp choke.
  • tests/fuzz/fuzz_monitor_input.py:69 — CRASH_SIGNALS = {-11, -6, -7, -8, -4} covers SEGV/ABRT/BUS/FPE/ILL. Missing: -9 (SIGKILL — OOM-killer when the harness eats 32 MiB × N iterations) is treated as PASS. A real OOM-driven kill on the loader's getline is now invisible.
  • tests/fuzz/fuzz_monitor_input.py:170-180 — cmd always points at a real redis (REDIS_HOST/PORT). Many fuzzed inputs produce SET/GET commands that race against a shared redis. Two parallel fuzz workers stomp each other's key namespace and you can get spurious -MOVED responses that look like memtier bugs. Pin a --key-prefix={uuid}_ or use 127.0.0.1:0 shim.
  • tests/fuzz/fuzz_monitor_input.py:182-184 — ASAN_OPTIONS=abort_on_error=0:exitcode=42:halt_on_error=1 plus UBSAN_OPTIONS=...:exitcode=42. Both share exitcode=42. A clean memtier that exits with EXIT_FAILURE=1 for a parse error is fine, but if a future memtier introduces exit(42) for an unrelated reason the harness misattributes it as a sanitizer hit.
  • tests/fuzz/fuzz_monitor_input.py:144-157 — generate_synthetic_seeds builds an in-memory b'\xab' * (17*1024*1024) and b'...' * 1_000_000. The million-line seed is ~50 MB of Python bytes held in RAM while mutate() then copies/chops/grows it 50 times per iteration (default FUZZ_ITER). Peak Python RSS ~ 500 MB - 1 GB on the synthetic-seed pass. CI runners with 7 GB are fine, but laptops aren't.
  • tests/fuzz/fuzz_monitor_input.py:104-108 — inject_nul calls arr.insert(random.randrange(len(arr)+1), 0) — for a 32 MiB input this does an O(N) shift per insert × up to 8 inserts = 256 MiB of memcpy per mutation. The 60s harness wall-clock can spend most of the budget here, starving actual fuzz iterations.
  • tests/fuzz/fuzz_monitor_input.py:139-141 — out[:32 * 1024 * 1024] caps post-mutation size BUT the synthetic 17 MiB seed grows under grow() past 32 MiB on the first mutator pass; the cap then truncates mid-bulk and you've manufactured an unterminated-quote input. Probably the intent (it's a fuzzer), but it means the "huge single line" seed never actually reaches the loader at >17 MiB.
  • tests/fuzz/fuzz_monitor_input.py:194-202 — TimeoutExpired path writes e.stderr decoded to stderr — but e.stderr is only populated when capture_output=True and the subprocess wrote before the timeout. For a true hang you get None and the harness operator has no clue what happened.

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)

  • tests/fuzz/fuzz_monitor_input.py:CRASH_SIGNALS is {-11, -6, -7, -8, -4} mapping to SEGV, ABRT, BUS, FPE, ILL — but glibc's *** stack smashing detected *** calls __stack_chk_fail() which raise(SIGABRT) and exits with -6, which IS in the set. However the comment says "ABRT (stack-smash uses abort)" suggesting awareness; OK. Note -8 is SIGFPE (divide by zero etc.), -7 is SIGBUS. All present.
  • tests/fuzz/fuzz_monitor_input.py:99-104 bitflip does i = random.randrange(len(arr)) — if arr is empty the early-return at line 99 covers it. OK.
  • tests/fuzz/fuzz_monitor_input.py:115 inject_nul calls arr.insert(random.randrange(len(arr) + 1), 0) repeatedly — random.randrange(len(arr) + 1) even when len(arr)==0 returns 0, so insert at position 0 works. Each iteration grows the array by 1, so subsequent randranges are larger. OK.
  • tests/fuzz/fuzz_monitor_input.py:165-167 run_one BaseException handler keeps the repro file but does NOT close/cleanup the tempfile path on KeyboardInterrupt; the path is leaked as intended (for inspection). OK.
  • tests/fuzz/fuzz_monitor_input.py:153-156 non-crash path: os.unlink(mpath) runs only if no crash pattern is matched AND not a signal exit. If subprocess returns 0 with no crash pattern, fine. But if subprocess returns 1 (parse error, the explicit "contract is OK"), os.unlink runs at line 174 — wait, looking again: clean run returns 0 and unlinks at line 174. Parse error (rc=1) without crash pattern: falls through the signal check (1 not in CRASH_SIGNALS), passes the pattern loop, hits line 174 unlink. OK.
  • tests/fuzz/fuzz_monitor_input.py:171-174 if any of the crash conditions trigger, the function returns False without unlinking — keeping the repro file. Good. But the file path is leaked to caller via the stderr message only; if the fuzzer runs 200 iterations and 7 fail, those 7 tempfiles persist in /tmp. Acceptable.
  • tests/fuzz/fuzz_monitor_input.py:185-190 ASAN_OPTIONS sets halt_on_error=1 AND abort_on_error=0 AND exitcode=42. With halt_on_error=1 and abort_on_error=0, ASan calls _exit(42) on first error — but with halt_on_error=0 it would continue after errors. The intent (don't SIGABRT, just exit) is clear. UBSan's halt_on_error=1 also sets _exit(42). The pattern is consistent.
  • tests/fuzz/fuzz_monitor_input.py:217-222 generate_synthetic_seeds() constructs a 1M-line b"..." * 1_000_000 string in Python memory — that's ~33 MB. Then million * FUZZ_ITER iterations each get a mutated copy. With FUZZ_INCLUDE_HUGE=1 and FUZZ_ITER=50, peak Python memory crosses 1.5 GB. The harness will likely OOM-kill itself on a 2 GB runner before the test memtier even starts. Worth documenting as "set FUZZ_INCLUDE_HUGE only on a >4 GB box."
  • tests/fuzz/fuzz_monitor_input.py:131 mutate() caps output at 32 MiB but the grow mutator can grow up to GROW_MAX bytes ON TOP of the seed. With multiple grows chained (random 1-4 mutators), final size could blow past 32 MiB before the cap. Cap is enforced at the end so fine, but signal: if you DON'T want grown sizes >256 KiB on master (per the comment), the chained-grow case can still produce larger inputs.

Verdict: Comment

…list

Cursor Bugbot finding (medium severity): the verdict logic in
fuzz_monitor_input.py:198 returned True (clean) and deleted the repro
the moment any KNOWN_NONFATAL_ASSERTIONS pattern appeared in
stdout/stderr -- *before* the crash-signal and crash-pattern checks
ran. So a fuzz run that produced a known parser-assertion message
AND a SIGSEGV or AddressSanitizer report had its crash silently
swallowed and the reproducer deleted.

Reorder the checks so crash signals and patterns come first; the
known-nonfatal allowlist now only applies to otherwise-clean exits.

Refs redis#408

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

  • Hotfix commits reference Cursor bugbot explicitly: Third commit ("check crash markers before known-nonfatal assertion allowlist") opens with "Cursor Bugbot finding (medium severity)" and clearly explains the verdict-check reordering bug. The fix is precisely attributed.
  • Refs #408 correctly stated in PR body ("Fixes #408"); first commit message also references #408. Both mention the parent issues (#404, #405, #406, #407, #409) in context.
  • CI wiring intentionally deferred: PR body explicitly explains "Why CI wiring is not in this PR" — fuzzer surfaces real bugs needing separate fixes; phased CI plan documented (smoke on every PR post-#405/#406/#407/#409 merge, nightly post-landing).
  • No missing issue refs: hotfix properly links findings back to #408.

Verdict: clear docs; hotfix bugbot attribution explicit; CI deferral well-justified.

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

Python subprocess overhead per iteration:

  • Fuzzer driver: subprocess.run([memtier, ...]) spawned 50 times (default FUZZ_ITER). Per spawn: ~80–120 ms (fork + exec + binary startup + libevent initialization).
  • Total fuzz runtime: 50 iterations × 2-3 sec per run = ~150 sec (2.5 min at default FUZZ_ITER=50). Cost is dominated by memtier's startup and I/O, not subprocess overhead.
  • Mutator chain (bitflip, chop, dup, grow, crlf, quote-storm): ~1 ms per seed (in-memory byte operations, negligible).

Memory profile:

  • Fuzzer itself: ~15 MiB steady (corpus in RAM, one mutated payload at a time).
  • Subprocess: each memtier run allocates per its normal working set (~5–50 MiB depending on --data-size). Max observed at FUZZ_ITER=200: ~500 MiB (capped in code at 32 MiB per mutated payload to prevent OOM).

Crash detection cost:

  • Subprocess polling + stdout/stderr capture: negligible (blocking on already-exited process).
  • Regex matching against crash patterns (7 strings): O(n) in stderr size, typically <1 KB per run.

Verdict: Subprocess overhead is sub-dominant; cold-start domination is expected for fuzz harnesses. The 50-iteration smoke run (~2.5 min) is acceptable for local contributors. Nightly fuzzing would benefit from warm-cache binary caching or in-process fuzzing (out of scope here). No hot-path 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 v2: design & API (sonnet 4.6)

  • Corpus duplication with merged #421 is the main design concern. #421 merged tests/fuzz/corpus/monitor/ (10 libFuzzer seeds: 01_basic_monitor through 10_comment_then_cmd). This PR adds tests/fuzz/monitor_input_corpus/ (18 Python-driver seeds: 01_empty through 20_pathological_quotes). The two sets overlap significantly — unterminated quotes, embedded NUL, proxy preamble, and no-trailing-newline appear in both. Two separate corpus directories for the same parser will drift independently. The PR description should add a TODO: converge monitor_input_corpus/ with fuzz/corpus/monitor/ once #421's libFuzzer CI runs are stable so future contributors know this is a known split rather than an intentional design choice.
  • KNOWN_NONFATAL_ASSERTIONS allowlist is an unbounded escape hatch. The tuple currently has one entry (run_stats::print_type_column assertion). There is no mechanism to prevent the list from growing as new parser assertions are added — each new entry silently reduces the fuzzer's detection surface. A comment capping the list ("if this grows beyond 3 entries, open an issue to fix the underlying assertions rather than allowlisting them") would act as a soft process gate.
  • FUZZ_GROW_MAX = 256 KiB default will miss the #405 regression class post-fix. The comment explains this: once #405 lands, the default should be 8 MiB. But the change requires editing the source. FUZZ_GROW_MAX is already env-overridable, so the follow-up CI wiring PR should set FUZZ_GROW_MAX=8388608 in the nightly job definition — and that intent should be noted here as a TODO so the follow-up author knows to do it.
  • FUZZ_TIMEOUT default is 60 s in the env docstring but 30 in the code. os.environ.get("FUZZ_TIMEOUT", "60") → the docstring says "default 30" and the source says "60". One is wrong. At 60 s/run × 50 iterations × 18 seeds = 54 000 s theoretical max per local run, which is obviously not the intended behavior. Clarify whether the timeout is per-mutation or per-seed-set, and align the docstring.
  • No CI wiring is explicitly a design choice, but the PR body's stated reason ("would turn CI red on master") has a shelf life. Once #405/#406/#407/#409 merge, nothing prevents CI wiring from landing — but this PR will be merged by then, and the follow-up intent lives only in the PR body text, not in a tracked issue or a # TODO(follow-up PR) in the workflow directory. Adding a skeleton .github/workflows/fuzz-monitor-nightly.yml.disabled with a comment "re-enable after #405/#406/#409 merge" would make the intent discoverable without adding a live workflow.

Verdict: the seed set and mutator design are solid. The corpus duplication with #421 is the live concern; the PR description needs the convergence TODO, and the FUZZ_TIMEOUT discrepancy is a correctness issue that should be fixed 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: security (opus 4.7)

  • (load-bearing) fuzz driver never invokes memtier through a shell. subprocess.run(cmd, stdin=DEVNULL, stdout=PIPE, stderr=PIPE, env=env, timeout=FUZZ_TIMEOUT) with cmd built as a Python list of ["--monitor-input=<path>", "--command=__monitor_line@__", "--server=<host>", "--port=<port>", ...]. No shell=True. mpath is tempfile.NamedTemporaryFile(...).name — driver-controlled, not attacker-influenced. REDIS_HOST/REDIS_PORT come from env but flow into argv positional values, not through shell metacharacter expansion. Clean.
  • MEMTIER path is constructed from os.environ["MEMTIER"] with no validation beyond exists(). A caller setting MEMTIER=/usr/bin/env;rm would still be safe because of list-form, but consider asserting MEMTIER.is_file() and os.access(MEMTIER, os.X_OK) to catch typos rather than silently launching a directory.
  • Mutated payloads can include embedded NULs, binary, and (intentionally) gigabyte-scale grow output capped at 32 MiB by mutate() — but the 15_huge_single_line synthetic seed is 17 MiB and can itself be mutated upward toward the 32 MiB cap. On a stripped CI runner with 7 GiB RAM that's fine; on a heavily-parallelized soak host this could stack with other jobs. Cap is in place, just flagging.
  • Tempfile cleanup is asymmetric. Clean runs os.unlink(mpath); timeout/crash branches deliberately keep the file (repro). Good. But KeyboardInterrupt between iterations leaks every retained mfuzz_*.txt in /tmp. Driver could atexit.register a cleanup of unflagged tmpfiles to keep /tmp from filling on a long fuzz session.
  • KNOWN_NONFATAL_ASSERTIONS allowlist. The comment correctly notes "check crash signals BEFORE the allowlist" and the code does so. Good — that order matters because the column.column_size < 100 assertion can co-occur with a SIGSEGV in the same run.
  • No CI wiring (deliberate, documented). When the wiring lands per the PR description, the smoke FUZZ_ITER=50 value running ./memtier_benchmark against a live local redis means the workflow needs to spin up a server. Recommend treating the redis fixture as an artifact of the fuzz job (not a network reach-out) — the current driver defaults 127.0.0.1:6379 which is fine.

Verdict: ship. No shell-injection surface; cleanup polish only.

@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. GROW_MAX default is 256 KiB with a comment saying "bump once #405 lands" — #405 has already merged (per PR description context). The default should now be raised to the intended 8 MiB, or the comment updated to FUZZ_GROW_MAX=8388608 if the intent is to keep it conservative until the soak suite validates the fix.

  2. KNOWN_NONFATAL_ASSERTIONS tuple with a bare-string reason ("tracked separately; flagging them here would make every fuzz run noisy") is good rationale but the comment says "See PR discussion at #408" — after PR merge, PR discussions are harder to find than issues. The allowlist entry should reference the downstream issue number (if one was filed for Assertion \column.column_size < 100`) instead.

  3. run_one IMPORTANT comment ("check crash signals / sanitizer patterns BEFORE the known-nonfatal allowlist") correctly cites the cursor bugbot finding. As with #419 and #420, drop the external attribution; the reasoning itself is clear and valuable.

  4. generate_synthetic_seeds docstring says "Gated behind FUZZ_INCLUDE_HUGE=1 until PR #405 … lands on master." Since #405 has merged, this gate should either be removed or the docstring updated to explain why large synthetic seeds remain opt-in (e.g. CI runner OOM risk).

  5. Commit message "check crash markers before known-nonfatal assertion allowlist" is accurate and explains the consequence. Good hygiene; no changes needed.

Verdict: two stale references to #405 as "not yet landed" (items 1 and 4) are the main readability issues; the core logic is sound.

Adds .github/workflows/monitor-fuzz.yml so the in-tree driver
tests/fuzz/fuzz_monitor_input.py actually runs in CI:

  * nightly cron at 03:37 UTC with FUZZ_ITER=2000 (~30 min budget)
  * workflow_dispatch with optional iterations override
  * PR with `run-fuzz` label, with reduced FUZZ_ITER=300 for ~3-4 min
    feedback when the PR touches the monitor-input parser, the
    arbitrary-command splitter, or the RESP-encoded request path:

        gh pr edit <num> --add-label run-fuzz

Build uses --enable-sanitizers --enable-ubsan so silent memory
corruptions caught by ASAN/UBSan are not masked by happy-path memtier
output. Reproducers from any FAIL iterations are uploaded as artifacts
for 14 days.

Refs redis#408

@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: 238c82b. Pure test-only — 18 corpus seeds + python fuzzer driver. Limited correctness surface; focused on harness fidelity.

  • fuzz_monitor_input.py::run_one (line ~167): tempfile.NamedTemporaryFile(prefix="mfuzz_", suffix=".txt", delete=False) creates a file in $TMPDIR and only os.unlink(mpath) on the success path (post crash-needle checks). On a crash, the file is preserved as a repro — intentional. But the "known-nonfatal allowlist" branch (if any(p in blob for p in KNOWN_NONFATAL_ASSERTIONS): os.unlink(mpath); return True) also deletes the repro on success. So far so good. The problem: BaseException handler at the bottom does raise without unlink, which is correct behavior. But the subprocess.TimeoutExpired branch returns False without unlinking — the repro file is preserved, good. At FUZZ_ITER=20000 (the nightly setting in the description) with the documented ~3.5% crash rate, that's 700 repro files per run, ~22 GB at the 32-MiB cap. No rotation / cleanup. Either cap repro files (rotate at N), or move them under a single mkdtemp() per run so artifact upload is bounded.

  • CRASH_SIGNALS = {-11, -6, -7, -8, -4} — -7 is SIGBUS on x86/Linux but is SIGEMT on some other ABIs; -4 is SIGILL on Linux, but the magic-number style means a future runner on a non-Linux glibc will silently classify the wrong signals as fatal. Use -int(signal.SIGSEGV) etc. — same style PR #419's harness uses.

  • inject_nul (line 96): arr.insert(random.randrange(len(arr) + 1), 0). When arr is empty (seed 01_empty.txt), random.randrange(1) == 0, so arr.insert(0, 0) works. But the loop runs random.randint(1, 8) times and each iteration recomputes len(arr) + 1; arr grows by 1 each iter, fine. No bug, just confirming.

  • dup (line 87) uses chunk = b[: random.randint(1, min(len(b), 4096))] and returns b + chunk * random.randint(1, 4). For the 17_all_command_types.txt seed (~5 KiB), this can produce ~25 KiB. Combined with grow later in the mutator chain (up to 256 KiB by default), total can hit ~280 KiB per file. The if len(out) > 32 * 1024 * 1024: out = out[:32 * 1024 * 1024] cap kicks in only on extreme runs; nothing wrong.

  • KNOWN_NONFATAL_ASSERTIONS allows b"Assertion \column.column_size < 100". The comment says it's reachable from malformed monitor input but is "not the memory-safety class issue #408 is hunting." That assertion fires from glibc __assert_fail, which calls abort()— i.e. exit code-6(SIGABRT). The order-of-checks fix you applied (crash signals FIRST, allowlist SECOND) is correct: if the assertion fires *and* the process is killed by SIGABRT, the SIGABRT short-circuits and you mark it a fail. But re-read your code path:proc.returncode in CRASH_SIGNALS` (which includes -6) returns False before the allowlist check — wait, you do check it first. So the assertion-then-abort case will be flagged as a FAIL, not allowlisted. That's actually wrong relative to the stated intent ("nonfatal" means "skip"). Either remove the allowlist (the assertion is a real bug worth flagging) or also filter out -6 specifically when this assertion text is present.

  • FUZZ_TIMEOUT = int(os.environ.get("FUZZ_TIMEOUT", "60")) but the docstring says "default 30". Inconsistency between doc and code. Per the description claim "30 s timeout", default should be 30.

  • The 15_huge_single_line and 16_million_tiny_lines synthetic seeds are gated behind FUZZ_INCLUDE_HUGE=1. Fine. But generate_synthetic_seeds() allocates 17 MiB then (38 bytes) * 1_000_000 = 38 MiB strings in Python unconditionally — wait, only when INCLUDE_HUGE_SYNTHETIC is true. Good. The 1M-line seed sent through mutate() could grow to 32 MiB then be written to disk for each iteration (50 by default). 50 * 38 MiB tempfile churn = 1.9 GB of disk write per nightly run. Worth noting.

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 — check order against TimeoutExpired is correct; few smaller concerns remain.

  • proc.returncode is None is unreachable on the path that checks proc.returncode in CRASH_SIGNALS. Walked the chain: subprocess.TimeoutExpired raises before proc is even bound; the except block at the diff line "FAIL ... timed out" returns False before touching proc.returncode. After subprocess.run() returns normally, proc.returncode is guaranteed non-None (CPython docs). So proc.returncode in CRASH_SIGNALS is safe. The reordering note in the PR description holds. Nothing new here.
  • CRASH_SIGNALS = {-11, -6, -7, -8, -4} — but -9 (SIGKILL) is NOT in the set. If memtier is killed by OOM-killer or by an external kill -9 during fuzz (the harness itself doesn't do this, but the OOM-killer can on a 32 MiB-capped mutated input), proc.returncode = -9 → falls through both crash-signal and == 42 checks → counted as success. The repro is unlinked. Add SIGKILL to CRASH_SIGNALS, or at minimum log "unexpected non-signal exit" for any returncode < 0 not in the set so OOM events are visible.
  • KNOWN_NONFATAL_ASSERTIONS short-circuit after crash checks is correct (the cursor-bugbot fix landed cleanly). Re-walked: if assertion text AND a sanitizer needle both appear, the sanitizer needle wins (checked first). Good. But the allowlist only covers print_type_column — issue #408 mentions this is a separate bug worth tracking. Please add an inline TODO/issue link so the allowlist gets revisited.
  • os.unlink(mpath) runs at the bottom of the success path but NOT after the timeout-return-False path. Timeout is "saved at mpath" — intentional. Same for crash returns. But on a clean run where the assertion-allowlist branch is taken, os.unlink(mpath) runs once. On a clean run where assertion-allowlist is NOT taken, the second os.unlink(mpath) runs. Good. However: the except BaseException at the bottom re-raises after logging — mpath survives. That's intended for harness errors. But under signal interruption (Ctrl-C → KeyboardInterrupt), all in-flight mpaths since the previous successful unlink leak in /tmp. Minor.
  • Module-level constants are fine for THIS file (FUZZ_ITER etc. are read once at process start, not test discovery — this is a __main__ script, not a pytest module). No collection-time hazard like in #418/#423. Good.
  • generate_synthetic_seeds allocates a 17 MiB bytes object and a 33 MiB bytes object eagerly when FUZZ_INCLUDE_HUGE=1. Combined with mutate() doing b + chunk * random.randint(1, 4) and bytes([random.randrange(256)]) * pad_len, peak Python heap can hit ~100 MiB per seed. The 32 MiB cap in mutate() clamps the result but not the intermediates. On a memory-constrained runner this OOMs the harness, not memtier — getting reported as "harness error". Worth a gc.collect() between iterations and/or moving the synthetic generator behind a lazy yield.

(File: tests/fuzz/fuzz_monitor_input.py.)

@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 8071430. Configure here.

uses: actions/upload-artifact@v4
with:
name: monitor-fuzz-repros
path: /tmp/fuzz_monitor_*

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Artifact upload glob never matches reproducer temp files

Medium Severity

The "Upload reproducers on failure" step uses the glob path: /tmp/fuzz_monitor_*, but run_one creates temp files with tempfile.NamedTemporaryFile(prefix="mfuzz_", suffix=".txt"), producing paths like /tmp/mfuzz_XXXX.txt. These prefixes never overlap, so no reproducer file will ever be uploaded on CI crash. Because if-no-files-found: ignore is set, this mismatch fails silently — the step succeeds but produces an empty artifact, defeating the whole purpose of preserving crash reproducers.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 8071430. Configure here.

PR authors need to know the label exists and when to use it. Add a new
"On-demand fuzzers and soak tests (PR labels)" subsection under
## Testing that explains:
  * which workflow the label triggers (monitor-fuzz.yml)
  * what it runs (FUZZ_ITER=300, ASAN+UBSan build, ~3-4 min budget)
  * when to apply it (parser / splitter / RESP-encoded request path)
  * how to apply (gh pr edit --add-label run-fuzz)
  * how to run locally

Sibling PRs (redis#420, redis#423) will extend this table with their own labels
(run-differential, run-soak).

Refs redis#408
@fcostaoliveira
fcostaoliveira merged commit 2b86126 into redis:master Jun 1, 2026
69 checks passed
fcostaoliveira added a commit to filipecosta90/memtier_benchmark that referenced this pull request Jun 1, 2026
Fold the run-soak label into the consolidated on-demand-suites table
that the now-merged differential (redis#420) and monitor-fuzz (redis#422) PRs
established. One table covers all three labels.
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
fcostaoliveira added a commit that referenced this pull request Jun 2, 2026
…443)

Both were "temporary until #405 lands" guards added by PR #422. PR
#405 (heap-vector fix for split_command_to_args) has been merged for
weeks. The stale defaults meant the very regression path the fuzzer
was built to cover -- multi-MB monitor lines -- was never actually
exercised in the nightly run. Lifting the guards restores the
intended coverage.

Refs: 2.4 review #21 (Review 8).

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 fuzzed-corpus coverage for --monitor-input parser

1 participant