Repository navigation
fix(opts): validate --command / --command-ratio at parse time (Refs #426 phase 2c) - #427
Conversation
Three redis#426 fuzz reproducers (items 12, 13, 14) trip on missing parse-time validation: 12. --command __key__ SIGABRT at protocol.cpp:774 assert 13. --command '' hangs (worker loop spins on 0 argv tokens) 14. --command-ratio 0 hangs (ratio sampler never picks the cmd) This commit moves all three checks to argument-parsing time so the user gets a readable error and exit code 2 instead of a crash or unbounded hang. set_ratio() is also tightened to reject empty / whitespace / leading sign / zero input - strtoul() previously accepted "" as 0 and wrapped negatives to UINT_MAX. Monitor-placeholder commands (handled via the existing MONITOR_PLACEHOLDER_PREFIX branch) are unaffected. Refs redis#426 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 3 potential issues.
Reviewed by Cursor Bugbot for commit 667eb08. Configure here.
| first++; | ||
| } | ||
| if (*first == '\0' || *first == '-' || *first == '+') { | ||
| return false; |
There was a problem hiding this comment.
Valid + prefixed ratios incorrectly rejected
Low Severity
set_ratio rejects a leading + sign alongside - and empty strings, but + is a standard prefix for positive integers. strtoul("+5", &q, 10) correctly returns 5, so "--command-ratio +5" was valid before this change and is now incorrectly rejected. The comments and PR description mention rejecting "negative" input but don't mention rejecting +, suggesting this was unintentional.
Reviewed by Cursor Bugbot for commit 667eb08. Configure here.
|
Review: performance (haiku 4.5) verdict: parse-time only, zero steady-state impact ✓ • Validation firing: Runs once at argv parsing before any connections are established. All checks are string prefix matching and integer comparisons (first_arg_is_placeholder, split_command_to_args validation). Zero hot-path involvement. ✓ • Error messages: Clear parse-time exits (fprintf + return -1) prevent hang/SIGABRT. These run once and are user-facing, not instrumentation that fires repeatedly. ✓ • No rate-limiting: The ratio validation (set_ratio()) rejects empty/negative/zero inputs at parse time; no per-request sampling overhead introduced. Rejects pathological configs that would spin in worker loops. ✓ • Net improvement: By rejecting zero-ratio and placeholder-first-arg at parse time, we prevent infinite loops and asserts that would have eaten CPU and latency. This is a net performance gain for invalid configs (fast failure vs. hang). ✓ Summary: Pure parse-time safety, zero request-loop overhead. No steady-state allocations, syscalls, or lock contention. Prevents bugs that would have degraded performance (spinning workers, SIGABRT restarts). |
|
Review: docs & commit message (haiku 4.5)
Verdict: Commits clean; DEVELOPMENT.md needs CLI option ranges and placeholder rules. |
|
Review: design & API (sonnet 4.6) Verdict: Correct fixes for the three #426 items; the bespoke per-flag validation pattern is the main design question for this series.
|
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: security (opus 4.7)
- LOAD-BEARING:
set_ratio()correctly hardens against the strtoul negative-wrap path — explicit reject of leading-/+, empty, whitespace-only, andparsed == 0after the trailing-junk check. Theunsigned long->unsigned intnarrow at the end is unchecked: input"4294967296"(= 2^32) overflows on 64-bitunsigned long-> truncates to 0 inunsigned int, and the priorparsed == 0check fires only on theunsigned longvalue, not the narrowed one. Bigger inputs like"8589934593"(2^33 + 1) narrow to 1 silently. Tighten withif (parsed > UINT_MAX) return false;or checkerrno == ERANGE. errnois not checked afterstrtoul— input"99999999999999999999"setserrno = ERANGEand returnsULONG_MAX, which passes theparsed != 0and*q == '\0'checks and then narrows. Same fix: adderrno = 0;before the call and reject onERANGE.first_arg_is_placeholder()correctly handles the bare-placeholder case at the literal command-name slot; theMONITOR_PLACEHOLDER_PREFIXstartswith check is defensive enough (a real Redis command would never start with__).--command ''and whitespace-only correctly land in thecommand_args.empty()branch (viasplit_command_to_args's zero-token return). Good.isspace((unsigned char) *first)cast is correct (avoids UB on negativechar); the surrounding code usesisspace(*p)unguarded in config_types.cpp:525,581,601 — pre-existing, not a regression here, but worth a separate hardening pass.- No format-string / injection surface: error messages use literal format specifiers;
optarg's content is only printed via%s. No shell exposure.
Verdict: NEEDS MINOR FIX. The unsigned long -> unsigned int narrow + missing errno = ERANGE check is a real (low-severity) bypass — --command-ratio 4294967296 would still be accepted as ratio=0 today.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: correctness & latent bugs (opus 4.7)
memtier_benchmark.cpp:746-757first_arg_is_placeholderonly catches exact-match tokens, but the assert atprotocol.cpp:774fires whenever the first arg contains__key__,__data__, or equalsSCAN_CURSOR_PLACEHOLDER.--command "FOO__key__",--command "SET__key__",--command "x__data__y"all still setcurrent_arg->type = key_type/data_typefor i==0 and hit the SIGABRT this PR was supposed to close. Either mirrorprotocol.cpp'sdata.find(PLACEHOLDER) != npossemantics, or move the check to immediately before the assert informat_arbitrary_commandand convert the assert to a graceful error.config_types.cpp:506-525isspace((unsigned char) *first)—<ctype.h>is not directly#included inconfig_types.cpp(it comes in transitively today through other STL headers, but that's fragile). Add an explicit#include <ctype.h>so a future header reshuffle doesn't break the build silently.memtier_benchmark.cpp:1463-1467placeholder rejection message reads the placeholder viacmd.command_args[0].data.c_str()—split_command_to_args()may have stripped surrounding quotes/whitespace before the check, so the printed token can differ from the raw user input. Cosmetic, but the error message becomes harder to grep for a fuzz harness that quotes its inputs.config_types.cpp:524unsigned long parsed = strtoul(...)followed by(unsigned int) parsed— no> UINT_MAXcheck.--command-ratio 4294967296on 64-bit silently truncates to 0 and then theparsed == 0guard rejects, so the user-visible behavior is fine here, but values like4294967297truncate to 1 and pass. Low impact but inconsistent with the strictness of the other phase-2 PRs (#428, #429) which both added> MAXcaps.- Cursor-flagged leading
+rejected andstrtoultruncation bypass — acknowledged, not repeated.
Verdict: Request changes (the placeholder-substring bypass re-opens the SIGABRT this PR claims to fix)
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: edge cases & failure modes (opus 4.7)
Verdict: LGTM with one paths-coverage note.
- Invocation paths: there is no config-file feature and
parse_uri()does not handle--commandor--command-ratio, so the long-option case is the only entry — validation correctly fires on every path. (Confirmed by readingparse_uriandconfig_parse_args.) - Cap boundary for ratio:
set_ratio()rejects 0, accepts every positive value up toULONG_MAX, then truncates tounsigned int. So--command-ratio 4294967296(UINT_MAX+1) truncates to1silently — not catastrophic, but inconsistent with the new "positive integer" promise. Consider rejectingparsed > UINT_MAX. - First-arg placeholder check uses
==forKEY_PLACEHOLDER/DATA_PLACEHOLDER/SCAN_CURSOR_PLACEHOLDERbutcompare(0, strlen(PREFIX), PREFIX) == 0for the monitor prefix. That asymmetry means--command __key__suffix(a literal token that happens to start with__key__but isn't the placeholder) is accepted, while--command __monitor_lineXXX__(anything starting with the monitor prefix) is rejected. Probably intentional — the monitor prefix is a family — but worth a comment so this doesn't drift. - Multiple
--commandinvocations: each one goes throughfirst_arg_is_placeholder()independently — good. But theset_ratiorejection branch referencescmd.command_name.c_str()fromget_last_command()— if the user passes--command-ratio 0before any--command,get_last_command()returns the implicit/default command (or whateverarbitrary_commands_listinitialises with). Worth a quick check that no crash/UB occurs in that argv order; the existing code likely already handles it but the new error path didn't add a guard. - Whitespace handling in
set_ratio: rejects leading+and-after stripping spaces, but" 5 "(trailing whitespace) — strtoul stops at the space,*q != '\0'triggers rejection. Good."\t5"—isspace((unsigned char) '\t')is true so the leading-sign check works correctly. Good. split_command_to_args()returningtruewithcmd.command_args.empty()is now caught at parse time — good. But the second branch (first_arg_is_placeholder(cmd.command_args[0].data)) reads[0]immediately after; if a future refactor letssplit_command_to_args()return true with zero args without the empty-check above it, this becomes an OOB read. The two checks are sequenced correctly today, just brittle to reorder.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: style & readability (sonnet 4.6)
Verdict: clean; two minor notes.
-
first_arg_is_placeholdercomment explains what the function checks, not why the first-arg slot is special (memtier_benchmark.cpp): the block comment describes what each placeholder token is, but the why — thatformat_arbitrary_command()inprotocol.cppunconditionally forwardsargv[0]as the Redis command name without a placeholder expansion step, making a placeholder there structurally unformattable — is absent. One sentence on that invariant would make the guard self-documenting. -
set_ratiowhitespace skip usesisspace();optarg_is_negativein PR #428 (same series) uses literal' ' || '\t'(config_types.cpp): these are sister functions added in consecutive PRs. Usingisspace((unsigned char))in one and manual space/tab in the other is a style inconsistency. Since they're both in the same fix series, aligning them (either direction) before merge would avoid future "which one is canonical?" confusion. -
Error message phrasing differs from the PR-428 companion (
memtier_benchmark.cpp): the new--command-ratiorejection reads "must be a positive integer (got '...')"; the analogous--pipelinemessage in #428 reads "must be greater than zero." Both are correct but the extra(got 'X')parenthetical is not applied consistently. Either style is fine — pick one for the series. -
Python test:
_run_memtierdocstring says "A timeout guards against regressions" — this is a why comment and reads well. Consistent with the project style. -
Commit message: single-commit, Conventional Commits-clean (
fix(opts): validate --command / --command-ratio at parse time); body enumerates all three items, which is good.
…eview fixes) Two review findings from the 7-lens review pass on redis#427. 1) (correctness reviewer, load-bearing) first_arg_is_placeholder used exact equality on the token but the runtime assert at protocol.cpp:774 fires on substring containment via memmem(). A literal like `FOO__key__` or `setkey__key__` therefore still SIGABRT'd. Switched to std::string::find() so the substring contract matches at parse time. 2) (security reviewer) set_ratio's strtoul parse missed the ERANGE overflow path. On x86_64 strtoul("4294967296") returns 4294967296 without ERANGE (unsigned long is 64-bit), and the narrow cast to unsigned int silently produced ratio=0, re-introducing the very hang redis#427 was meant to prevent. Added an `errno = 0` before strtoul and reject on ERANGE / parsed > UINT_MAX. Refs redis#426 phase 2c.
PR redis#402 added PARALLELISM=2 to the sanitizer (ASAN/UBSan/TSAN) cluster cells because cluster bootstrap + serial RLTest pass routinely hit the workflow's 15-minute step ceiling. The regular Test workflow's OSS-CLUSTER cells were not updated at the time and have been a known master flake ever since (~3/8 master runs fail at the same 15-minute mark; deep-CI investigators on PRs redis#425 / redis#427 / redis#430 / redis#431 all confirmed the pattern). Add PARALLELISM=2 to the two affected cells: - OSS-CLUSTER API: TCP Plaintext - OSS-CLUSTER API: TCP TLS The 49/99-shard mega-cluster cells already use a single targeted test (TEST=test_rate_limited_completion_no_hang), so they're under budget without parallelism. Bundled with PR redis#430 because that PR was being blocked by exactly this flake on its final CI run.
…--key-pattern=G:G) (Refs #426 phase 3) (#430) * fix(opts): validate sampler configs (--data-size-list, --key-stddev, --key-pattern=G:G) Reject sampler configurations that can never produce a value at parse / construction time instead of hanging the worker loop or tripping the Gaussian assert: - --data-size-list entries with weight 0: the size sampler would skip them and (if every bucket is zero-weight) spin forever picking nothing. Issue #426 item 10. - --key-stddev must be finite and > 0: NaN compared false against the previous "<= 0" guard, and +/-inf produced a Gaussian rejection sampler that never satisfied its range constraint. Issue #426 item 15. - --key-pattern=G requires key-maximum - key-minimum >= 2: the Gaussian distribution asserts median > min && median < max, which is impossible on a 1-key range. SIGABRT before the fix. Issue #426 item 16. All three paths now emit a readable error and exit with code 2 (the parser-error convention used elsewhere in memtier_benchmark.cpp). Regression coverage in tests/test_cli_validation_sampler.py exercises each rejection plus a healthy G:G config to guard against false positives. Refs #426 Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(opts): relax G-range cutoff to max <= min, add median bounds check Review fix on #430 (correctness reviewer): the original `(max - min) < 2` cutoff rejected the perfectly valid 2-key Gaussian case (min=1, max=2). The sampler computes a default median of `(max - min)/2.0 + min + 0.5` which for that case is 1.5 -- strictly inside (1, 2), passes the `assert(median > min && median < max)`. The actual SIGABRT path was a user passing a `--key-median` that lands outside (min, max). Fix: * Reject only `max <= min` for --key-pattern=G (the truly-degenerate single-key case). * Additionally validate that any user-supplied `--key-median` lands strictly inside `(min, max)`. Default median=0 means "auto-compute" and is always safe. Refs #426 phase 3. * test(sampler): harden valid-G:G happy path against TLS connection-reset flake ASAN TLS cells under CI load dropped the first connection mid- handshake on the happy-path test (3 cells failed identically with 'Connection reset by peer / Maximum reconnection attempts (0) exceeded'). Make the workload a deterministic 10-request smoke and add --reconnect-on-error so the rc==0 assertion measures the parser path that the test exists to verify, not TLS flake. Refs #426 phase 3. * test(sampler): make valid-G:G happy path TLS-environment agnostic The previous hotfix (--reconnect-on-error + --max-reconnect-attempts=5) still relied on a successful TCP/TLS connection, but the test harness does not inject --tls/--cert flags here, so on TLS-only CI cells (ASAN/TSAN/UBSan TCP TLS, OSS TCP TLS v1.2/v1.3) the workload cannot connect at all and the rc==0 assertion always tripped. Restructure the assertion to match the test's documented purpose: verify only that the *parser* accepts the valid G:G config. The workload's runtime outcome is intentionally ignored. - Assert rc != 2 (parser did not reject). - Assert none of the Items 10/15/16 rejection diagnostics appear in stderr. - Bound the run with --connection-timeout=1 and --max-reconnect-attempts=1 so a TLS-only environment can't keep the subprocess alive past _run_memtier's 10s timeout. Refs #426 phase 3. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(opts): reject 2-key G:G range that SIGABRTs auto-computed median The d5b882c relaxation of the G-range cutoff from `(max - min) < 2` to `key_maximum <= key_minimum` was based on a wrong arithmetic claim in the accompanying comment: for (min=1, max=2) the auto-computed median in gaussian_distribution_range is median = (max - min) / 2.0 + min + 0.5 = 1/2.0 + 1 + 0.5 = 2.0 so the subsequent `assert(median > min && median < max)` fires (2.0 < 2 is false) and the process SIGABRTs -- exactly the regression Item 16 was supposed to prevent. Confirmed locally: with min=1, max=2 the previous build hit the crash-handler bug-report dump. Restore the original `(max - min) < 2` cutoff (and keep the unsigned- wrap-safe explicit `key_maximum < key_minimum` clause that d5b882c added), and rewrite the comment with the correct arithmetic so the choice of cutoff is auditable. The smallest accepted range is now (max - min) == 2 (e.g. min=1, max=3 -> auto-median = 2.5). This re-tightens the parser-reject path picked up by cursor[bot] on the previous commit; the negative test `test_key_pattern_g_one_key_range_rejected` continues to pass because the new diagnostic still contains the substring `key-pattern=G`. Refs #426 phase 3. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * ci: re-trigger workflows after master-flake noise The prior run hit the pre-existing master flakes `Test OSS-CLUSTER API: TCP {Plaintext,TLS}` (15-min step timeout) and the older workflow can't be partial-reran. Empty commit to force a fresh run. * ci: parallelize Test OSS-CLUSTER API cluster cells (mirror PR #402) PR #402 added PARALLELISM=2 to the sanitizer (ASAN/UBSan/TSAN) cluster cells because cluster bootstrap + serial RLTest pass routinely hit the workflow's 15-minute step ceiling. The regular Test workflow's OSS-CLUSTER cells were not updated at the time and have been a known master flake ever since (~3/8 master runs fail at the same 15-minute mark; deep-CI investigators on PRs #425 / #427 / #430 / #431 all confirmed the pattern). Add PARALLELISM=2 to the two affected cells: - OSS-CLUSTER API: TCP Plaintext - OSS-CLUSTER API: TCP TLS The 49/99-shard mega-cluster cells already use a single targeted test (TEST=test_rate_limited_completion_no_hang), so they're under budget without parallelism. Bundled with PR #430 because that PR was being blocked by exactly this flake on its final CI run. --------- Co-authored-by: Claude Sonnet 4.6 <[email protected]>
…445) The fuzzer excluded flags/inputs (--cluster-mode against standalone, --authenticate empty, --wait-ratio, G:G degenerate, --data-size-list zero-weight/zero-size, negative count flags) because they used to crash or hang. The phase-1-3 parser fixes (#427/#428/#429/#430) plus the connection-stage-timeout supervisor (#431) now bound all of those. Removed the exclusions and wired the fuzzer into CI so it runs nightly. Also fix .githooks/pre-commit to work from linked worktrees: locate the Makefile via git-common-dir and export GIT_INDEX_FILE so that `git diff --cached` inside the Makefile rule sees the worktree-local index rather than the main worktree's index. Refs: 2.4 review #20 (Review 8 + Review 17). Co-authored-by: Claude Sonnet 4.6 <[email protected]>


Summary
Three CLI-fuzz reproducers from #426 share the same root cause: missing
parse-time validation lets bad
--command/--command-ratioinputthrough into the worker loop where it either trips a runtime assert or
hangs forever ignoring
--test-time. This PR moves the checks to theargument-parsing path so the user gets a readable error and exit 2
instead of a crash or unbounded hang.
--command __key__(and other bare placeholders) is rejected at parsetime instead of SIGABRTing inside
protocol.cpp::format_arbitrary_commandat the
first arg is not command name?assert.--command ''(or whitespace-only) is rejected; previouslysplit_command_to_args()returned true with zero argv tokens and theworker loop spun forever.
--command-ratio 0(also empty / whitespace / negative) is rejected;set_ratio()is tightened sostrtoul("")==0and negative wrap-aroundno longer slip through.
Monitor-placeholder commands (handled via the existing
MONITOR_PLACEHOLDER_PREFIXbranch ino_command) are unaffected. Theexisting
test_arbitrary_command_misses/test_monitor_input/test_scansuites still pass.Items closed (from #426)
--command __key__SIGABRT atprotocol.cpp:774--command ''hangs--command-ratio 0hangs (also empty / whitespace / negative)Test plan
(SIGABRT / hang) and the fixed binary (clean exit 2 with readable
stderr).
tests/test_cli_validation_command.py(4 cases: items 12, 13, 14 plus a happy-path
--command-ratio 1end-to-end run); each guarded by a subprocess timeout so a future
regression that re-introduces the hang fails the test loudly.
make format-checkclean.makeclean.test_arbitrary_command_misses(12/12),test_monitor_input(11/11),test_scan(15/15).Refs #426
Co-Authored-By: Claude Sonnet 4.6 [email protected]
Note
Low Risk
CLI-only validation and stricter ratio parsing; monitor-placeholder
--commandpaths are unchanged, with new subprocess tests guarding regressions.Overview
Adds parse-time validation for
--commandand--command-ratioso bad CLI input fails with readable stderr instead of SIGABRT or an infinite worker hang (issue #426 items 12–14).For
--command, empty or whitespace-only strings are rejected after parsing (zero argv tokens). The first token must be a real command name: placeholders such as__key__,__data__,__scan_cursor__, and monitor markers are detected with the same substring rules asprotocol.cpp, so values likeFOO__key__are caught too.For
--command-ratio,set_ratio()now rejects null/empty/whitespace, signs, non-integers, zero,ERANGEoverflow, and values aboveUINT_MAXbefore they can truncate or wrap and starve the ratio sampler.New regression tests in
tests/test_cli_validation_command.pycover the three rejection cases plus a happy-path run with--command-ratio 1(subprocess timeouts guard against reintroduced hangs).Reviewed by Cursor Bugbot for commit 30b1898. Bugbot is set up for automated code reviews on this repo. Configure here.