Repository navigation
fix(opts): validate --run-count (Refs #426 phase 2a) - #429
fcostaoliveira merged 1 commit into
Conversation
Closes items 4 and 5 of redis#426: ``--run-count=-1`` and ``--run-count=2147483647`` both triggered SIGABRT (std::bad_alloc) on master because the parser cast straight to unsigned (so -1 wrapped to ~4.3B) and never enforced an upper bound, so the per-run vectors allocated in main() blew up the allocator before any work started. The parser now: - reads via signed strtol so negatives are caught explicitly, - rejects empty / non-numeric input, - rejects zero, - caps at MAX_RUN_COUNT = 1024 (well above any realistic benchmarking use case; the default is 1, and even 1024 keeps the per-run bookkeeping under ~100 MiB on memory-constrained hosts). Each rejection prints a readable error to stderr and bubbles up through the existing -1-return -> usage() -> exit(2) path, matching the style of every other option-parsing error in the file. Regression coverage lives in tests/test_cli_validation_run_count.py (RLTest-compatible, mirrors tests/test_monitor_input.py and tests/test_mget_validation.py): - --run-count=-1 -> non-zero exit + "must be greater than zero" - --run-count=0 -> non-zero exit + "must be greater than zero" - --run-count=2147483647 -> non-zero exit + "must be <=" - --run-count=2 -> end-to-end run, mb.json shows BEST/WORST sections The cli_fuzz.py strategy exclusion entry for --run-count is left in place; removing it is the follow-up tracked in redis#426. Refs redis#426 Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
|
Review: docs & commit message (haiku 4.5)
Verdict: Commits clean; DEVELOPMENT.md needs run-count validation bounds. |
|
Review: performance (haiku 4.5) verdict: pre-run validation, zero steady-state impact ✓ • run_count parsing: Uses strtol() (signed) instead of strtoul() to catch negatives before unsigned cast. Single parse-time check with errno and range bounds. Zero hot-path involvement. ✓ • Per-run vector allocation: run_count cap (MAX_RUN_COUNT=1024) prevents pre-run allocations in main() from exploding. The aggregation path reserves run_stats/cmd_stats vectors proportional to run_count; cap at 1024 keeps this under ~100MiB even on memory-constrained hosts. This fires once at startup before any request is sent. ✓ • No per-request overhead: run_count is read at startup for aggregation mode logic, not in the request loop. Zero steady-state cost. ✓ • Allocation safety: By rejecting run_count > MAX_RUN_COUNT, we prevent vector::reserve() throwing std::bad_alloc, which would crash or abort the benchmark before any work is done. This is a failure mode fix, not a hot-loop change. ✓ Summary: Pre-benchmark validation with linear but one-time memory cost (per-run metadata vectors). Cap prevents OOM without affecting the actual request/response loop. No per-request allocation churn introduced. |
|
Review: design & API (sonnet 4.6) Verdict: Correct fix, cleanly scoped; the
|
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: security (opus 4.7)
- LOAD-BEARING: this is the cleanest of the phase-2 PRs from a validation correctness lens.
errno = 0;+ signedstrtol+ explicitERANGEcheck +parsed_run_count <= 0reject +MAX_RUN_COUNTcap correctly closes both reported repros:-1no longer wraps to~4.3B, andINT_MAXis rejected by the upper bound before allocator OOM. No signed-to-unsigned cast sneaks through because the bounds (0 < parsed <= 1024) are checked on thelongbefore the narrow tounsigned intat the end. MAX_RUN_COUNT = 1024is a sane cap and the rationale (pre-run per-run vectors growing linearly) is correct —main()allocatesrun_stats[run_count]and HDR per-run state up front, so this is the right place to bound it.endptrcheck:optarg[0] == '\0' || !endptr || *endptr != '\0'correctly rejects empty and trailing-junk inputs. Note:strtolnever setsendptrto NULL on standards-conformant glibc, so!endptris defensive but unreachable — fine.errno == ERANGEis checked buterrno == EINVALisn't — glibc'sstrtoldoesn't set EINVAL on no-conversion, the empty-string case is caught by the explicitoptarg[0] == '\0'check, so no gap.- No format-string risk in
fprintf(stderr, "error: run count must be <= %d (got %ld).\n", ...). The%ldmatcheslong parsed_run_count. Clean. - Test coverage exercises
-1,0,INT_MAX, and a happy path of2confirmingBEST/WORST RUN RESULTSare emitted; coverage is appropriate.
Verdict: LGTM. No security findings. The pattern in this PR (signed parse + ERANGE + range check + final narrow) is the template the other phase-2 PRs (427, 428) should converge on.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: correctness & latent bugs (opus 4.7)
memtier_benchmark.cpp:1058-1067clean: signedstrtol,errno=0pre-set,ERANGE-checked,endptrvalidated, both lower and upper bounds enforced. No off-by-one in the upper-bound message either (uses<= MAX_RUN_COUNT).memtier_benchmark.cpp:1058optarg[0] == '\0'correctly catches the empty-string case. Whitespace-only inputs are caught by*endptr != '\0'becausestrtolskips leading whitespace andendptrstops at the first non-converted character.memtier_benchmark.cpp:1062parsed_run_count <= 0covers both 0 and negatives in one branch. Good.memtier_benchmark.cpp:1067(unsigned int) parsed_run_count—parsed_run_countislong(potentially 64-bit) cast tounsigned int. Cap of1024keeps this trivially in range; defensive but fine.- One minor inconsistency with phase 2b (#428) and 2c (#427): no
optarg == NULLguard. getopt won't handNULLfor a required-arg option, so this is theoretical, but the other PRs in the series do guard for it. Consistency for grep-ability. - Nit:
MAX_RUN_COUNTis a#define(intliteral). Adjacent caps in PR #428 are also#defines (unsigned). Cross-PR, consider a singlenamespace memtier::limitsor at least matching widths/styles to keep the merge tidy.
Verdict: Approve (no functional concerns)
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: edge cases & failure modes (opus 4.7)
Verdict: LGTM; cleanest of the phase-2 batch.
- Invocation paths: only the long-option case
'x'exists;parse_uri()does not touchrun_count, no config-file feature. All paths covered. - Cap boundary:
parsed_run_count > MAX_RUN_COUNTcorrectly admits 1024 and rejects 1025. Edge:--run-count=1024(cap) and--run-count=1023(cap-1) are not in the test suite — happy path only tests2. A regression to>=would slip past CI; one cap-value-accepted assertion would close that. errno = 0beforestrtolanderrno == ERANGEcheck is correctly sequenced — handles--run-count=99999999999999999999(overflows LONG_MAX) cleanly. This is the right pattern; please port it to PR #428's pipeline/data-size parsing.parsed_run_count <= 0correctly catches0and any negative valuestrtolproduces.--run-count=-9223372036854775808(LONG_MIN) → ERANGE on some libcs, otherwise returns LONG_MIN, both rejected. Good.(unsigned int) parsed_run_countcast happens only after the cap check (≤1024), so no truncation surprises.- Empty optarg guard:
optarg[0] == '\0'check is correct, but note that getopt_long with1(required argument) will not pass an empty string from--run-count=(it usually rejects argv earlier or treats the next argv as the value). Defensive but harmless. The check usesoptarg[0]after thestrtolcall which already deref'doptarg— order is fine because strtol(NULL) is UB and optarg is guaranteed non-NULL by getopt for required-arg options.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: style & readability (sonnet 4.6)
Verdict: clean; one structural note.
-
Two different error messages for the same conceptual rejection (
memtier_benchmark.cpp): empty/non-numeric input prints "run count must be a positive integer" while zero/negative prints "run count must be greater than zero". Both messages are accurate but a user who passes--run-count=-1(the primary repro from #426) gets the second message, not the first — becausestrtol("-1")succeeds and the parse branch reaches the<= 0check. The two-message split is only needed if you want to distinguish "not a number" from "number but invalid range"; if that distinction isn't important to users, collapsing to one message ("must be a positive integer <= 1024") would simplify both the code and the test expectations. -
Inline comment in the
case 'x'block explains what the code does (memtier_benchmark.cpp): "Parse via signed strtol so negative values do not silently wrap" is partially why — good. The part that explains why strtoul was wrong (not that it wraps, but that the wrapped value then passed the!cfg->run_countzero-check unchanged) is the load-bearing insight; make it explicit. -
MAX_RUN_COUNT#defineat global scope is consistent with project convention — well-placed near line 90 with the other globals. Good. -
Python test:
test_run_count_valid_runs_normallyusesenv.skipOnCluster()— appropriate since the BEST/WORST JSON sections are a standalone-specific layout, but this is worth a one-line comment explaining why the test is standalone-only (cluster mode produces different JSON shapes). -
Commit message: single-commit, Conventional Commits-clean (
fix(opts): validate --run-count); body is exemplary — itemises both repros, explains the cap rationale, and notes the intentional non-removal of the fuzz exclusion.
…/0 (#436) * fix(opts): reject negative -c/-t/-n/--test-time; guard Hits/sec from /0 Same crash class as merged phases #428/#429 (--pipeline, --data-size, --run-count): strtoul("-1") wraps to UINT_MAX and -c -1 then tries to spawn ~4B clients. The four count flags missed the phase-2 sweep. Also adds a > 0 guard to run_stats.cpp summarize() for the legacy GET Hits/sec / Misses/sec computation (the only summarize site without one); sub-microsecond runs were emitting +Inf / nan into the JSON. Refs: 2.4 review findings #24 + #19 Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(stats): guard all summarize() rate computations from /0; standardize error wording Reviewers R3+R4 flagged that the prior commit only guarded m_hits_sec and m_misses_sec in summarize(); six sibling rate computations (m_ops_sec, m_bytes_sec, m_bytes_sec_rx, m_bytes_sec_tx, m_moved_sec, m_ask_sec, m_connection_errors_sec) still divided by test_duration_usec with no guard. All now use the (test_duration_usec > 0 ? ... : 0.0) ternary, consistent with sites at lines 1300, 1311, 1317, 1344, 1354, 1360, 1627, 1629. R5 also flagged that the four new error messages mixed "must be a positive integer" and "must be greater than zero". Standardized to match the phase-2 convention. Refs: 2.4 review of PR #436 (R3/R4/R5). Co-Authored-By: Claude Sonnet 4.6 <[email protected]> --------- 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
--run-count=-1and--run-count=2147483647previously triggered SIGABRT (std::bad_alloc): the parser cast straight tounsigned int(so-1wrapped to ~4.3B) and had no upper bound, so the per-run vectors allocated inmain()blew up the allocator before any work started.strtol, rejects empty/non-numeric input, rejects zero/negative, and caps atMAX_RUN_COUNT = 1024(default is 1; the cap keeps per-run bookkeeping well under ~100 MiB even on memory-constrained hosts and covers every realistic benchmarking use case).-1 -> usage() -> exit(2)path, matching the style of every other option-parsing error inmemtier_benchmark.cpp.Items closed from #426
--run-count -1-> SIGABRT,std::bad_alloc--run-count 2147483647(INT_MAX) -> SIGABRT,std::bad_allocThe
tests/cli_fuzz.pystrategy exclusion for--run-countis intentionally left in place; flipping it back on is the follow-up tracked in #426.Test plan
New regression coverage in
tests/test_cli_validation_run_count.py(RLTest-compatible, mirrorstests/test_monitor_input.pyandtests/test_mget_validation.py):--run-count=-1-> non-zero exit, stderr containsrun count must be greater than zero--run-count=0-> non-zero exit, stderr containsrun count must be greater than zero--run-count=2147483647-> non-zero exit, stderr containsrun count must be <=--run-count=2-> end-to-end run,mb.jsoncontainsBEST RUN RESULTSandWORST RUN RESULTSsectionsRun:
Also verified:
make -jclean build on the changed file.make format-checkclean on the changed file (clang-format --dry-run --Werror memtier_benchmark.cppexits 0).make format-check-staged) passed on commit.Refs #426
Note
Low Risk
CLI-only validation before benchmark startup; no change to runtime benchmarking logic beyond rejecting previously dangerous inputs.
Overview
--run-countis validated at CLI parse time so invalid values no longer crash the process withstd::bad_allocbefore benchmarking starts (issue #426).Parsing now uses signed
strtolinstead ofstrtoul, so negative values (e.g.-1) are rejected instead of wrapping to a hugeunsignedand forcing massive per-run vector reservations inmain(). Zero, non-numeric input, and overflow get clear stderr errors. A newMAX_RUN_COUNT(1024) caps huge values (e.g.INT_MAX) that previously OOM’d while reserving run bookkeeping.Regression tests in
tests/test_cli_validation_run_count.pycover rejections for-1,0, and2147483647, plus an end-to-end run with--run-count=2that checksBEST/WORSTJSON sections.Reviewed by Cursor Bugbot for commit a66a38d. Bugbot is set up for automated code reviews on this repo. Configure here.